answer
stringlengths
17
10.2M
package coderefactory.net.popmovies; import android.app.Activity; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; public class MovieAdapter extends ArrayAdapter<Movie> { private ViewHolder viewHolder; public MovieAdapter(final Activity context, final List<Movie> movies) { super(context, 0, movies); } @NonNull @Override public View getView(final int position, final View convertView, final ViewGroup parent) { final View itemView; if (convertView == null) { itemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_movie, parent, false); viewHolder = new ViewHolder(itemView); itemView.setTag(viewHolder); } else { itemView = convertView; viewHolder = (ViewHolder) convertView.getTag(); } populateView(position); return itemView; } private void populateView(final int position) { final Movie movie = getItem(position); viewHolder.titleView.setText(movie.getTitle()); viewHolder.releaseView.setText(String.valueOf(movie.getReleased())); } private static class ViewHolder { private final TextView titleView; private final TextView releaseView; private ViewHolder(final View itemView) { titleView = (TextView) itemView.findViewById(R.id.movie_title); releaseView = (TextView) itemView.findViewById(R.id.movie_released); } } }
package com.cmput301f16t11.a2b; import com.google.android.gms.maps.model.LatLng; import java.util.ArrayList; public class RequestController { public static ArrayList<Request> getRequestNear(String address, Number radius){ return new ArrayList<Request>(); } public static ArrayList<Request> getRequestNear(LatLng location, Number radius) { return new ArrayList<Request>(); } // TEMPORARY POPULATION OF RANDOM REQUESTS!!! public static ArrayList<Request> tempFakeRequestList() { ArrayList<Request> returnValue = new ArrayList<Request>(); returnValue.add(new Request(new LatLng(53.5443890, -113.4909270), new LatLng(54.07777, -113.50192), new User("test", "test@email.com"))); returnValue.add(new Request(new LatLng(54.07777, -113.50192), new LatLng(53.5443890, -113.4909270), new User("test", "test@email.com"))); returnValue.add(new Request(new LatLng(54.07777, -113.50192), new LatLng(53.5443890, -113.4909270), new User("test2", "test2@email.com"))); return returnValue; } public static ArrayList<Request> getNearbyRequests(LatLng location) { //TODO: actual logic ArrayList<Request> temp = new ArrayList<Request>(); temp.add(RequestController.tempFakeRequestList().get(0)); return temp; } public static ArrayList<Request> getOwnRequests(User user) { // TODO: actual logic ArrayList<Request> temp = new ArrayList<Request>(); temp.add(RequestController.tempFakeRequestList().get(1)); return temp; } public static ArrayList<Request> getAcceptedByDrivers(User user) { //TODO: actual logic return new ArrayList<Request>(); } public static ArrayList<Request> getConfirmedByRiders(User user) { //TODO: actual logic // (get request accepted by the current user as a driver, that are also accepted by the user // who originally made the request ArrayList<Request> temp = new ArrayList<Request>(); temp.add(RequestController.tempFakeRequestList().get(2)); return temp; } }
package com.example.ysm0622.app_when.login; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.PorterDuff; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.ysm0622.app_when.R; import com.example.ysm0622.app_when.group.GroupList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.util.ArrayList; import java.util.List; public class Login extends AppCompatActivity implements TextWatcher, View.OnClickListener { public static final int PROGRESS_DIALOG = 1001; public ProgressDialog progressDialog; private static final String TAG = "Login"; private static final int mInputNum = 2; private EditText mEditText[]; private FloatingActionButton mFab; private Button mButton; private String mURL; private String mAddress; private String mResult; private BackgroundTask mTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.login_main); initialize(); } private void initialize() { // Array allocation mEditText = new EditText[mInputNum]; // Create instance // View allocation mEditText[0] = (EditText) findViewById(R.id.EditText0); // Email mEditText[1] = (EditText) findViewById(R.id.EditText1); // Password mFab = (FloatingActionButton) findViewById(R.id.Fab0); // Login Button mButton = (Button) findViewById(R.id.Button0); // Sign up Button // Add listener for (int i = 0; i < mInputNum; i++) { mEditText[i].addTextChangedListener(this); } mFab.setOnClickListener(this); mButton.setOnClickListener(this); // Default setting for (int i = 0; i < mInputNum; i++) { mEditText[i].getBackground().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP); } mFab.setVisibility(View.INVISIBLE); mURL = "http://52.79.132.35:8080/JSP_test.jsp"; mAddress = ""; mResult = ""; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { int cnt = 0; for (int i = 0; i < mInputNum; i++) { if (mEditText[i].getText().toString().length() > 0) { cnt++; } } if (cnt == mInputNum) { mFab.setVisibility(View.VISIBLE); } else { mFab.setVisibility(View.INVISIBLE); } } @Override public void afterTextChanged(Editable s) { } @Override public void onClick(View v) { if (v.getId() == mFab.getId()) { // Email, password validation // Query - Select USER_CODE, USER_MAIL, USER_PSWD, USER_NAME from ACCOUNT ( intent ) // Query - Select * from ACCOUNT-GROUPS WHERE USER_CODE = @@ ( / Intent ) mTask = new BackgroundTask(); mTask.execute(); } if (v.getId() == mButton.getId()) { startActivity(new Intent(Login.this, SignUp.class)); } } class BackgroundTask extends AsyncTask<Integer, Integer, Integer> { protected void onPreExecute() { mAddress = mURL; showDialog(PROGRESS_DIALOG); } @Override protected Integer doInBackground(Integer... arg0) { // TODO Auto-generated method stub mResult = request(mAddress); return null; } protected void onPostExecute(Integer a) { Toast.makeText(getApplicationContext(), mResult, Toast.LENGTH_SHORT).show(); Log.w(TAG, mResult); if (progressDialog != null) progressDialog.dismiss(); if (mResult != "") startActivity(new Intent(Login.this, GroupList.class)); else Toast.makeText(getApplicationContext(), " ", Toast.LENGTH_SHORT).show(); } } private String request(String urlStr) { try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(mURL); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("msg", mEditText[0].getText().toString())); //params.add(new BasicNameValuePair("pass", "xyz")); UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8); post.setEntity(ent); HttpResponse responsePOST = client.execute(post); HttpEntity resEntity = responsePOST.getEntity(); if (resEntity != null) { mResult = EntityUtils.toString(resEntity); } } catch (Exception e) { e.printStackTrace(); } return mResult; } public Dialog onCreateDialog(int id) { if (id == PROGRESS_DIALOG) { progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setMessage(" ."); return progressDialog; } return null; } }
package com.mooo.ziggypop.candconline; import android.app.Activity; import android.app.Fragment; import android.os.AsyncTask; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class JsonGetter extends AsyncTask<URL, Integer, JSONObject> { String TAG = "JSON"; static JSONObject jobj = null; static String json = ""; MainActivity myActivity; public JsonGetter(MainActivity activity){ myActivity = activity; } public static JSONObject getJSONFromUrl() { try { URL url = new URL("http", "online.the3rdage.net", 29998, "index.html"); Log.v("URL",url.toString()); InputStream is = null; try{ is = url.openStream(); } catch (IOException e){ Log.e("InputStream", "Could not open stream" ); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while((line = reader.readLine()) != null){ sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result: " + e.toString()); } try { jobj = new JSONObject(json); } catch (JSONException e){ Log.e("JSON Parser", "Error parsing data: " + e.toString()); } } catch (MalformedURLException e) { Log.e("????", "Malformed URL"); } //Log.v("JSON", jobj.toString()); return jobj; } @Override public JSONObject doInBackground(URL... params) { JSONObject json = getJSONFromUrl(); return json; } public ArrayList<GameInLobby> getGames(JSONObject gameClasses, String typeOfGame) { ArrayList<GameInLobby> returnArr = new ArrayList<>(); try { JSONArray lobbies = gameClasses.getJSONArray(typeOfGame); //Log.v(TAG, lobbies.toString()); for (int i = 0; i < lobbies.length(); i++) { JSONObject lobby = lobbies.getJSONObject(i); String title = lobby.get("title").toString(); String slots = "(" + lobby.get("numRealPlayers").toString() + "/" + lobby.get("maxRealPlayers").toString() + ")"; JSONArray playersJSON = lobby.getJSONArray("players"); ArrayList<String> players = new ArrayList<>(); for (int j = 0; j < playersJSON.length(); j++) { players.add(playersJSON.getJSONObject(j).get("nickname").toString()); } //get the map name and remove all characters before the last "/" String map = lobby.get("map").toString(); map = map.substring(map.lastIndexOf('/')); /* TODO: add locked status */ String lock = lobby.get("pw").toString(); boolean isLocked = false; if (lock.equals("1")){ isLocked = true;} returnArr.add(new GameInLobby(title, slots, players, isLocked, map)); } } catch (JSONException e) { e.printStackTrace(); } return returnArr; } @Override public void onPostExecute(JSONObject result){ try { JSONObject game = result.getJSONObject("cnc3kw"); //Log.v(TAG, game.toString()); JSONObject usersForGame = game.getJSONObject("users"); //Log.v(TAG, usersForGame.toString()); ArrayList<String> usersArray = new ArrayList<>(); Iterator<String> iter = usersForGame.keys(); while (iter.hasNext()) { String key = iter.next(); try { JSONObject value = (JSONObject) usersForGame.get(key); usersArray.add(key); //Log.v(TAG, key); //Log.v(TAG, value.getJSONObject("nickname").toString()); } catch (JSONException e){ e.printStackTrace(); } } JSONObject gameClasses = game.getJSONObject("games"); ArrayList<GameInLobby> gamesInLobbyArrList = getGames(gameClasses, "staging"); ArrayList<GameInLobby> gamesInProgressArrList = getGames(gameClasses, "playing"); PlayersFragment playerFrag = myActivity.mSectionsPagerAdapter.player; playerFrag.refreshData(usersArray); GamesFragment gamesFrag = myActivity.mSectionsPagerAdapter.lobby; gamesFrag.refreshData(gamesInLobbyArrList); GamesInProgressFragment progressFrag = myActivity.mSectionsPagerAdapter.inGame; progressFrag.refreshData(gamesInProgressArrList); }catch (JSONException e){ e.printStackTrace(); } } }
package com.noprestige.kanaquiz; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; class KanaQuestionBank extends ArrayList<KanaQuestion> { private KanaQuestion currentQuestion; private Random rng = new Random(); private static final int MAX_MULTIPLE_CHOICE_ANSWERS = 6; private QuestionRecord previousQuestions = null; KanaQuestionBank() { super(); } void newQuestion() throws NoQuestionsException { if (this.size() > 1) { if (previousQuestions == null) previousQuestions = new QuestionRecord(Math.min(this.size(), OptionsControl.getInt(R.string.prefid_repetition))); do currentQuestion = this.get(rng.nextInt(this.size())); while (!previousQuestions.add(currentQuestion)); } else throw new NoQuestionsException(); } String getCurrentKana() { return currentQuestion.getKana(); } boolean checkCurrentAnswer(String response) { return currentQuestion.checkAnswer(response); } String fetchCorrectAnswer() { return currentQuestion.fetchCorrectAnswer(); } boolean addQuestions(KanaQuestion[] questions) { previousQuestions = null; return super.addAll(Arrays.asList(questions)); } boolean addQuestions(KanaQuestion[] questions1, KanaQuestion[] questions2) { previousQuestions = null; return (super.addAll(Arrays.asList(questions1)) && super.addAll(Arrays.asList(questions2))); } boolean addQuestions(KanaQuestionBank questions) { previousQuestions = null; return super.addAll(questions); } String[] getPossibleAnswers() { ArrayList<String> fullAnswerList = new ArrayList<>(); for (int i = 0; i < size(); i++) if (!fullAnswerList.contains(get(i).fetchCorrectAnswer())) fullAnswerList.add(get(i).fetchCorrectAnswer()); ArrayList<String> possibleAnswerStrings = new ArrayList<>(); possibleAnswerStrings.add(fetchCorrectAnswer()); while (possibleAnswerStrings.size() < Math.min(fullAnswerList.size(), MAX_MULTIPLE_CHOICE_ANSWERS)) { int rand = rng.nextInt(fullAnswerList.size()); if (!possibleAnswerStrings.contains(fullAnswerList.get(rand))) possibleAnswerStrings.add(fullAnswerList.get(rand)); } Collections.shuffle(possibleAnswerStrings); String[] returnValue = new String[possibleAnswerStrings.size()]; possibleAnswerStrings.toArray(returnValue); return returnValue; } }
package com.troy.xifan.activity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import butterknife.BindView; import butterknife.ButterKnife; import com.chenenyu.router.Router; import com.chenenyu.router.annotation.Route; import com.google.gson.Gson; import com.troy.xifan.App; import com.troy.xifan.BuildConfig; import com.troy.xifan.R; import com.troy.xifan.config.Constants; import com.troy.xifan.manage.UserHolder; import com.troy.xifan.model.response.AppVersionInfoRes; import com.troy.xifan.service.DownLoadApkService; import com.troy.xifan.util.UIUtils; import com.troy.xifan.util.Utils; import im.fir.sdk.FIR; import im.fir.sdk.VersionCheckCallback; @Route(Constants.Router.SETTINGS) public class SettingsActivity extends BaseActivity { private static final String FIR_TOKEN = "2def92fc28bb812a895538fa54ed38d3"; @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.layout_logout) View mViewLogout; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); ButterKnife.bind(this); initViews(); } @Override protected void initViews() { mToolbar.setTitle(getString(R.string.title_settings)); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); initFragment(); initListeners(); } private void initListeners() { mViewLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UIUtils.showDialog(SettingsActivity.this, getString(R.string.title_tips), getString(R.string.text_logout_tips), new UIUtils.OnDialogListener() { @Override public void onConfirm() { UserHolder.getInstance().cleanUser(); Router.build(Constants.Router.LOGIN).go(SettingsActivity.this); App.getInstance().cleanActivityList(); } @Override public void onCancel() { } }); } }); } private void initFragment() { getFragmentManager().beginTransaction() .replace(R.id.content, new SettingsFragment()) .commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; } return super.onOptionsItemSelected(item); } public static class SettingsFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener { private Resources mResources; private Preference mCleanCachePre; private Preference mFeedbackPre; private Preference mCheckUpdatePre; private Preference mAboutPre; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initPreference(); } private void initPreference() { mResources = getResources(); addPreferencesFromResource(R.xml.preference); //mCleanCachePre = findPreference(mResources.getString(R.string.text_clean_cache)); //mFeedbackPre = findPreference(mResources.getString(R.string.text_feedback)); mCheckUpdatePre = findPreference(mResources.getString(R.string.text_check_update)); mCheckUpdatePre.setOnPreferenceClickListener(this); mAboutPre = findPreference(getString(R.string.text_about)); mAboutPre.setOnPreferenceClickListener(this); } @Override public boolean onPreferenceClick(Preference preference) { String key = preference.getKey(); if (getString(R.string.text_check_update).equals(key)) { checkUpdate(); } else if (getString(R.string.text_about).equals(key)) { UIUtils.showToast(getActivity(), Utils.getVersionName()); } return false; } private void checkUpdate() { FIR.checkForUpdateInFIR(FIR_TOKEN, new VersionCheckCallback() { @Override public void onSuccess(String versionJson) { AppVersionInfoRes appVersionInfo = new Gson().fromJson(versionJson, AppVersionInfoRes.class); String firVersion = appVersionInfo.getVersionShort().replaceAll("[.]", ""); String currentVersion = BuildConfig.VERSION_NAME.replaceAll("[.]", ""); if (Integer.parseInt(firVersion) > Integer.parseInt(currentVersion)) { showAppUpdateDialog(appVersionInfo); } else { UIUtils.showOkDialog(getActivity(), getString(R.string.title_check_upate), getString(R.string.text_not_need_update)); } } @Override public void onFail(Exception exception) { UIUtils.showToast(getActivity(), getString(R.string.text_check_update_fail)); } @Override public void onStart() { UIUtils.showToast(getActivity(), getString(R.string.text_checking_update)); } @Override public void onFinish() { } }); } private void showAppUpdateDialog(final AppVersionInfoRes appVersionInfo) { UIUtils.showDialog(getActivity(), getString(R.string.title_check_upate), appVersionInfo.getChangelog(), new UIUtils.OnDialogListener() { @Override public void onConfirm() { Intent serviceIntent = new Intent(getActivity(), DownLoadApkService.class); serviceIntent.putExtra(DownLoadApkService.EXTRA_URL, appVersionInfo.getInstallUrl()); getActivity().startService(serviceIntent); } @Override public void onCancel() { } }); } } }
package de.bitdroid.flooding.map; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider; import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import de.bitdroid.flooding.R; import de.bitdroid.flooding.dataselection.Extras; import de.bitdroid.flooding.pegelonline.PegelOnlineSource; import de.bitdroid.flooding.utils.AbstractLoaderCallbacks; import de.bitdroid.flooding.utils.BaseActivity; import de.bitdroid.utils.StringUtils; import static de.bitdroid.flooding.pegelonline.PegelOnlineSource.COLUMN_LEVEL_TYPE; import static de.bitdroid.flooding.pegelonline.PegelOnlineSource.COLUMN_STATION_LAT; import static de.bitdroid.flooding.pegelonline.PegelOnlineSource.COLUMN_STATION_LONG; import static de.bitdroid.flooding.pegelonline.PegelOnlineSource.COLUMN_STATION_NAME; import static de.bitdroid.flooding.pegelonline.PegelOnlineSource.COLUMN_WATER_NAME; public abstract class BaseMapActivity extends BaseActivity implements Extras { private static final int LOADER_ID = 43; private MyLocationNewOverlay locationOverlay; private FixedMapView mapView; private StationsOverlay stationsOverlay; protected String waterName, stationName; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map); waterName = getIntent().getStringExtra(EXTRA_WATER_NAME); stationName = getIntent().getStringExtra(EXTRA_STATION_NAME); // enable action bar back button if (waterName != null) setTitle(StringUtils.toProperCase(waterName)); else if (stationName != null) setTitle(StringUtils.toProperCase(stationName)); // map view mapView = (FixedMapView) findViewById(R.id.map); mapView.setMultiTouchControls(true); // location overlay locationOverlay = new MyLocationNewOverlay( getApplicationContext(), new GpsMyLocationProvider(getApplicationContext()), mapView); mapView.getOverlays().add(locationOverlay); // load station data AbstractLoaderCallbacks loaderCallback = new AbstractLoaderCallbacks(LOADER_ID) { @Override protected void onLoadFinishedHelper(Loader<Cursor> loader, Cursor cursor) { cursor.moveToFirst(); if (cursor.getCount() == 0) return; List<Station> stations = new ArrayList<Station>(); int latIdx = cursor.getColumnIndex(COLUMN_STATION_LAT); int longIdx = cursor.getColumnIndex(COLUMN_STATION_LONG); int nameIdx = cursor.getColumnIndex(COLUMN_STATION_NAME); int riverIdx = cursor.getColumnIndex(COLUMN_WATER_NAME); do { String stationName = cursor.getString(nameIdx); double lat = cursor.getDouble(latIdx); double lon = cursor.getDouble(longIdx); String riverName = cursor.getString(riverIdx); stations.add(new Station(stationName, riverName, lat, lon)); } while (cursor.moveToNext()); // filter stations with invalid coordinates filterInvalidStations(stations); // add to overlays if (stationsOverlay != null) mapView.getOverlays().remove(stationsOverlay); stationsOverlay = new StationsOverlay( getApplicationContext(), stations, getStationClickListener()); mapView.getOverlays().add(stationsOverlay); GeoPoint point = getCenter(stations); mapView.getController().setCenter(point); if (waterName != null || stationName != null) mapView.getController().setZoom(8); else mapView.getController().setZoom(7); } @Override protected void onLoaderResetHelper(Loader<Cursor> loader) { } @Override protected Loader<Cursor> getCursorLoader() { String selection = COLUMN_LEVEL_TYPE + "=?"; String[] selectionParams = null; if (waterName != null) { selection += " AND " + COLUMN_WATER_NAME + "=?"; selectionParams = new String[] { "W", waterName }; } else if (stationName != null) { selection += " AND " + COLUMN_STATION_NAME + "=?"; selectionParams = new String[] { "W", stationName }; } else { selectionParams = new String[] { "W" }; } return new CursorLoader( getApplicationContext(), PegelOnlineSource.INSTANCE.toUri(), new String[] { COLUMN_STATION_LAT, COLUMN_STATION_LONG, COLUMN_STATION_NAME, COLUMN_WATER_NAME }, selection, selectionParams, null); } }; getLoaderManager().initLoader( StationsOverlay.LOADER_ID, null, loaderCallback); } @Override public void onResume() { super.onResume(); locationOverlay.enableMyLocation(); } @Override public void onPause() { super.onPause(); locationOverlay.disableMyLocation(); } private static final String EXTRA_SCROLL_X = "EXTRA_SCROLL_X", EXTRA_SCROLL_Y = "EXTRA_SCROLL_Y", EXTRA_ZOOM_LEVEL = "EXTRA_ZOOM_LEVEL"; @Override protected void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putInt(EXTRA_SCROLL_X, mapView.getScrollX()); state.putInt(EXTRA_SCROLL_Y, mapView.getScrollY()); state.putInt(EXTRA_ZOOM_LEVEL, mapView.getZoomLevel()); } @Override protected void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); mapView.getController().setZoom(state.getInt(EXTRA_ZOOM_LEVEL, 1)); mapView.scrollTo( state.getInt(EXTRA_SCROLL_X, 0), state.getInt(EXTRA_SCROLL_Y, 0)); } protected abstract StationClickListener getStationClickListener(); private GeoPoint getCenter(List<Station> stations) { double minX = Double.MAX_VALUE, maxX = Double.MIN_VALUE, minY = Double.MAX_VALUE, maxY = Double.MIN_VALUE; for (Station station : stations) { minX = Math.min(station.getLat(), minX); maxX = Math.max(station.getLat(), maxX); minY = Math.min(station.getLon(), minY); maxY = Math.max(station.getLon(), maxY); } return new GeoPoint((minX + maxX) / 2.0f, (minY + maxY) / 2.0f); } private void filterInvalidStations(List<Station> stations) { Iterator<Station> iter = stations.iterator(); while (iter.hasNext()) { Station s = iter.next(); if (s.getLat() == 0 && s.getLon() == 0) iter.remove(); } } }
package nu.yona.app.ui.settings; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import nu.yona.app.R; import nu.yona.app.YonaApplication; import nu.yona.app.analytics.AnalyticsConstant; import nu.yona.app.analytics.YonaAnalytics; import nu.yona.app.api.manager.APIManager; import nu.yona.app.api.manager.impl.DeviceManagerImpl; import nu.yona.app.api.model.AppMetaInfo; import nu.yona.app.api.model.ErrorMessage; import nu.yona.app.customview.CustomAlertDialog; import nu.yona.app.customview.YonaFontTextView; import nu.yona.app.enums.IntentEnum; import nu.yona.app.listener.DataLoadListener; import nu.yona.app.state.EventChangeManager; import nu.yona.app.ui.BaseFragment; import nu.yona.app.ui.LaunchActivity; import nu.yona.app.ui.YonaActivity; import nu.yona.app.ui.pincode.PinActivity; import nu.yona.app.utils.AppConstant; import nu.yona.app.utils.AppUtils; import static nu.yona.app.YonaApplication.getSharedAppPreferences; public class SettingsFragment extends BaseFragment { private DeviceManagerImpl deviceManager; private SettingListViewAdaptor settingsListViewAdaptor; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View settingsLayoutView = inflater.inflate(R.layout.settings_fragment, null); settingsLayoutView = configureSettingsListView(settingsLayoutView); setupToolbar(settingsLayoutView); configureAppMetaInfoDisplay(settingsLayoutView); return settingsLayoutView; } public class SettingListViewAdaptor extends ArrayAdapter<String> { public SettingListViewAdaptor(Context context, int resource, int textViewResourceId, String[] list) { super(context, resource, textViewResourceId, list); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); convertView = inflater.inflate(R.layout.settings_list_item, parent, false); } setUpListItemView(convertView, position); return convertView; } private View setUpListItemView(View convertView, int position) { RelativeLayout listRelativeLayout = convertView.findViewById(R.id.list_relative_layout); YonaFontTextView yonaFontTextView = listRelativeLayout.findViewById(R.id.list_title); String title = getItem(position); yonaFontTextView.setText(title); CheckBox checkBox = listRelativeLayout.findViewById(R.id.list_check_box); if ((title.equals(getString(R.string.showopenvpnlog)))) { checkBox.setVisibility(View.VISIBLE); setUpListItemViewCheckBox(checkBox); } else { checkBox.setVisibility(View.GONE); } return convertView; } private CheckBox setUpListItemViewCheckBox(CheckBox checkBox) { boolean showOpenVpnLog = getSharedAppPreferences().getBoolean(AppConstant.SHOW_VPN_WINDOW, false); checkBox.setChecked(showOpenVpnLog); checkBox.setOnCheckedChangeListener((CompoundButton buttonView, boolean isChecked) -> { toggleVPNLogWindowDisplay(); }); return checkBox; } } private View configureSettingsListView(View settingsLayoutView) { ListView settingsListView = (ListView) settingsLayoutView.findViewById(R.id.list_view); deviceManager = new DeviceManagerImpl(getActivity()); String[] listArray = new String[]{ getString(R.string.changepin), getString(R.string.privacy), getString(R.string.adddevice), getString(R.string.showopenvpnlog), getString(R.string.contact_us), getString(R.string.deleteuser)}; settingsListViewAdaptor = new SettingListViewAdaptor(getActivity(), R.layout.settings_list_item, R.id.list_title, listArray); settingsListView.setAdapter(settingsListViewAdaptor); setUpListItemOnClickListener(settingsListView); configureAppMetaInfoDisplay(settingsLayoutView); return settingsLayoutView; } private ListView setUpListItemOnClickListener(ListView settingsListView) { settingsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { RelativeLayout listRelativeLayout = view.findViewById(R.id.list_relative_layout); YonaFontTextView yonaFontTextView = listRelativeLayout.findViewById(R.id.list_title); String listItemTitle = yonaFontTextView.getText().toString(); if (listItemTitle.equals(getString(R.string.changepin))) { showChangePin(); } else if (listItemTitle.equals(getString(R.string.privacy))) { showPrivacy(); } else if (listItemTitle.equals(getString(R.string.adddevice))) { addDevice(AppUtils.getRandomString(AppConstant.ADD_DEVICE_PASSWORD_CHAR_LIMIT)); } else if (listItemTitle.equals(getString(R.string.deleteuser))) { unsubscribeUser(); } else if (listItemTitle.equals(getString(R.string.contact_us))) { openEmail(); } else if (listItemTitle.equals(getString(R.string.showopenvpnlog))) { toggleVPNLogWindowDisplay(); } } }); return settingsListView; } private View configureAppMetaInfoDisplay(View settingsLayoutView) { AppMetaInfo appMetaInfo = AppMetaInfo.getInstance(); ((TextView) settingsLayoutView.findViewById(R.id.label_version)).setText(getString(R.string.version) + appMetaInfo.getAppVersion() + getString(R.string.space) + appMetaInfo.getAppVersionCode()); setHook(new YonaAnalytics.BackHook(AnalyticsConstant.BACK_FROM_SCREEN_SETTINGS)); return settingsLayoutView; } private void showChangePin() { YonaAnalytics.createTapEvent(getString(R.string.changepin)); YonaActivity.getActivity().setSkipVerification(true); APIManager.getInstance().getPasscodeManager().resetWrongCounter(); Intent intent = new Intent(getActivity(), PinActivity.class); Bundle bundle = new Bundle(); bundle.putBoolean(AppConstant.FROM_SETTINGS, true); bundle.putString(AppConstant.SCREEN_TYPE, AppConstant.PIN_RESET_VERIFICATION); bundle.putInt(AppConstant.PROGRESS_DRAWABLE, R.drawable.pin_reset_progress_bar); bundle.putString(AppConstant.SCREEN_TITLE, getString(R.string.changepin)); bundle.putInt(AppConstant.COLOR_CODE, ContextCompat.getColor(YonaActivity.getActivity(), R.color.mango)); bundle.putInt(AppConstant.TITLE_BACKGROUND_RESOURCE, R.drawable.triangle_shadow_mango); bundle.putInt(AppConstant.PASSCODE_TEXT_BACKGROUND, R.drawable.passcode_edit_bg_mango); intent.putExtras(bundle); startActivity(intent); } private void toggleVPNLogWindowDisplay() { boolean showOpenVpnLog = getSharedAppPreferences().getBoolean(AppConstant.SHOW_VPN_WINDOW, false); getSharedAppPreferences().edit().putBoolean(AppConstant.SHOW_VPN_WINDOW, !showOpenVpnLog).commit(); settingsListViewAdaptor.notifyDataSetChanged(); } private void showPrivacy() { YonaAnalytics.createTapEvent(getString(R.string.privacy)); Intent friendIntent = new Intent(IntentEnum.ACTION_PRIVACY_POLICY.getActionString()); YonaActivity.getActivity().replaceFragment(friendIntent); } private void unsubscribeUser() { YonaAnalytics.createTapEvent(getString(R.string.deleteuser)); CustomAlertDialog.show(YonaActivity.getActivity(), getString(R.string.deleteuser), getString(R.string.deleteusermessage), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); YonaAnalytics.createTapEvent(getString(R.string.ok)); doUnsubscribe(); } }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { YonaAnalytics.createTapEvent(getString(R.string.cancel)); dialog.dismiss(); } }); } private void doUnsubscribe() { YonaActivity.getActivity().showLoadingView(true, null); APIManager.getInstance().getAuthenticateManager().deleteUser(new DataLoadListener() { @Override public void onDataLoad(Object result) { YonaApplication.getEventChangeManager().notifyChange(EventChangeManager.EVENT_CLEAR_ACTIVITY_LIST, null); YonaApplication.getEventChangeManager().notifyChange(EventChangeManager.EVENT_USER_NOT_EXIST, null); YonaActivity.getActivity().showLoadingView(false, null); startActivity(new Intent(YonaActivity.getActivity(), LaunchActivity.class)); YonaApplication.getEventChangeManager().notifyChange(EventChangeManager.EVENT_CLOSE_ALL_ACTIVITY_EXCEPT_LAUNCH, null); } @Override public void onError(Object errorMessage) { YonaActivity.getActivity().showLoadingView(false, null); Snackbar snackbar = Snackbar.make(YonaActivity.getActivity().findViewById(android.R.id.content), ((ErrorMessage) errorMessage).getMessage(), Snackbar.LENGTH_SHORT); TextView textView = ((TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text)); textView.setMaxLines(5); snackbar.show(); } }); } @Override public void onResume() { super.onResume(); setTitleAndIcon(); YonaActivity.getActivity().setSkipVerification(false); } private void setTitleAndIcon() { toolbarTitle.setText(R.string.settings); } private void addDevice(final String pin) { YonaAnalytics.createTapEvent(getString(R.string.adddevice)); YonaActivity.getActivity().showLoadingView(true, null); try { deviceManager.addDevice(pin, new DataLoadListener() { @Override public void onDataLoad(Object result) { showAlert(getString(R.string.yonaadddevicemessage, pin), true); } @Override public void onError(Object errorMessage) { showAlert(((ErrorMessage) errorMessage).getMessage(), false); } }); } catch (Exception e) { showAlert(e.toString(), false); } } private void showAlert(String message, final boolean doDelete) { try { if (YonaActivity.getActivity() != null) { YonaActivity.getActivity().showLoadingView(false, null); Snackbar.make(YonaActivity.getActivity().findViewById(android.R.id.content), message, Snackbar.LENGTH_INDEFINITE) .setAction(getString(R.string.ok), new View.OnClickListener() { @Override public void onClick(View v) { if (doDelete) { doDeleteDeviceRequest(); } } }) .show(); } } catch (Exception e) { AppUtils.reportException(SettingsFragment.class.getSimpleName(), e, Thread.currentThread()); } } private void doDeleteDeviceRequest() { try { deviceManager.deleteDevice(new DataLoadListener() { @Override public void onDataLoad(Object result) { //do nothing if server response success } @Override public void onError(Object errorMessage) { showAlert(((ErrorMessage) errorMessage).getMessage(), false); } }); } catch (Exception e) { AppUtils.reportException(SettingsFragment.class.getSimpleName(), e, Thread.currentThread()); } } private void openEmail() { CustomAlertDialog.show(YonaActivity.getActivity(), getString(R.string.usercredential), getString(R.string.usercredentialmsg), getString(R.string.yes), getString(R.string.no), (dialog, which) -> { showEmailClient(getTextForSupportMail(true)); }, (dialog, which) -> showEmailClient(getTextForSupportMail(false))); } private void showEmailClient(String userCredential) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.parse("mailto:support@yona.nu?subject=" + getString(R.string.support_mail_subject) + "&body=" + userCredential); intent.setData(data); startActivity(intent); } private String getTextForSupportMail(Boolean isYonaPasswordToBeAdded) { AppMetaInfo appMetaInfo = AppMetaInfo.getInstance(); String baseURL = " Base URL: " + Uri.encode(YonaApplication.getEventChangeManager().getDataState().getUser().getLinks().getSelf().getHref()); String yonaPassword = ""; if (isYonaPasswordToBeAdded) { yonaPassword = Uri.encode("Password: " + YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword()) + "<br><br>"; } String appVersion = "App version: " + appMetaInfo.getAppVersion(); String appBuild = "App version code: " + appMetaInfo.getAppVersionCode(); String androidVersion = "Android version: " + Build.VERSION.RELEASE; String deviceBrand = "Device brand: " + Build.MANUFACTURER; String deviceModel = "Device model: " + Build.MODEL; return Html.fromHtml("<html>" + baseURL + "<br><br>" + yonaPassword + appVersion + "<br>" + appBuild + "<br>" + androidVersion + "<br>" + deviceBrand + "<br>" + deviceModel + "</html>").toString(); } @Override public String getAnalyticsCategory() { return AnalyticsConstant.SCREEN_SETTINGS; } }
package org.openlmis.core.service; import com.google.inject.Singleton; import org.joda.time.DateTime; import org.openlmis.core.LMISApp; import org.openlmis.core.R; import org.openlmis.core.model.Period; import org.openlmis.core.utils.AutoUpdateApk; @Singleton public class UpgradeManager { private String upgradeServerUrl = LMISApp.getContext().getResources().getString(R.string.upgrade_server_url); private AutoUpdateApk autoUpdateApk = new AutoUpdateApk(LMISApp.getContext(), "", upgradeServerUrl); public void triggerUpgrade() { // if (Period.isWithinSubmissionWindow(DateTime.now())) { // return; //skip self auto upgrade if it's within 18th-25th of a month autoUpdateApk.checkUpdatesManually(); } }
package bj.discogsbrowser.main; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import com.mikepenz.materialdrawer.Drawer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import bj.discogsbrowser.R; import bj.discogsbrowser.greendao.DaoInteractor; import bj.discogsbrowser.greendao.ViewedRelease; import bj.discogsbrowser.model.listing.Listing; import bj.discogsbrowser.model.order.Order; import bj.discogsbrowser.model.search.SearchResult; import bj.discogsbrowser.model.user.UserDetails; import bj.discogsbrowser.network.DiscogsInteractor; import bj.discogsbrowser.testmodels.TestRootSearchResponse; import bj.discogsbrowser.testmodels.TestViewedRelease; import bj.discogsbrowser.utils.AnalyticsTracker; import bj.discogsbrowser.utils.NavigationDrawerBuilder; import bj.discogsbrowser.utils.SharedPrefsManager; import bj.discogsbrowser.utils.schedulerprovider.TestSchedulerProvider; import bj.discogsbrowser.wrappers.LogWrapper; import edu.emory.mathcs.backport.java.util.Collections; import io.reactivex.Single; import io.reactivex.schedulers.TestScheduler; import static junit.framework.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class MainPresenterTest { private String username = "BJLairy"; private MainPresenter mainPresenter; private TestScheduler testScheduler; private UserDetails testUserDetails; @Mock Context context; @Mock MainContract.View mView; @Mock DiscogsInteractor discogsInteractor; @Mock NavigationDrawerBuilder navigationDrawerBuilder; @Mock MainController mainController; @Mock RecyclerView recyclerView; @Mock SharedPrefsManager sharedPrefsManager; @Mock LogWrapper logWrapper; @Mock DaoInteractor daoInteractor; @Mock AnalyticsTracker tracker; @Mock MainActivity mainActivity; @Mock Toolbar toolbar; @Mock Drawer drawer; @Before public void setUp() { MockitoAnnotations.initMocks(this); testUserDetails = new UserDetails(); testUserDetails.setUsername(username); testScheduler = new TestScheduler(); mainPresenter = new MainPresenter(context, mView, discogsInteractor, new TestSchedulerProvider(testScheduler), navigationDrawerBuilder, mainController, sharedPrefsManager, logWrapper, daoInteractor, tracker); } @After public void tearDown() { verifyNoMoreInteractions(mView, discogsInteractor, navigationDrawerBuilder, mainController, sharedPrefsManager, logWrapper, daoInteractor, tracker); } @Test public void buildNavigationDrawer_succeeds() { List<Order> listOrders = new ArrayList(); List<Listing> listSelling = new ArrayList(); when(sharedPrefsManager.getUsername()).thenReturn(username); when(discogsInteractor.fetchUserDetails()).thenReturn(Single.just(testUserDetails)); when(context.getString(R.string.main_activity)).thenReturn("MainActivity"); when(context.getString(R.string.logged_in)).thenReturn("logged in"); when(discogsInteractor.fetchOrders()).thenReturn(Single.just(listOrders)); when(discogsInteractor.fetchSelling(username)).thenReturn(Single.just(listSelling)); when(navigationDrawerBuilder.buildNavigationDrawer(mainActivity, toolbar)).thenReturn(drawer); mainPresenter.connectAndBuildNavigationDrawer(mainActivity, toolbar); testScheduler.triggerActions(); verify(mView, times(1)).showLoading(true); verify(sharedPrefsManager, times(1)).storeUserDetails(testUserDetails); verify(discogsInteractor, times(1)).fetchUserDetails(); verify(tracker).send("MainActivity", "MainActivity", "logged in", testUserDetails.getUsername(), 1L); verify(discogsInteractor, times(1)).fetchOrders(); verify(sharedPrefsManager, times(1)).getUsername(); verify(mainController, times(1)).setOrders(listOrders); verify(discogsInteractor, times(1)).fetchSelling(username); verify(mainController, times(1)).setSelling(listSelling); verify(mView, times(1)).setDrawer(drawer); verify(navigationDrawerBuilder, times(1)).buildNavigationDrawer(mainActivity, toolbar); verify(mView, times(1)).setupRecyclerView(); verify(mainController, times(1)).setLoadingMorePurchases(true); } @Test public void buildNavigationDrawerUserDetailsError_handles() throws UnknownHostException { when(discogsInteractor.fetchUserDetails()).thenReturn(Single.error(new UnknownHostException())); when(navigationDrawerBuilder.buildNavigationDrawer(mainActivity, toolbar)).thenReturn(drawer); mainPresenter.connectAndBuildNavigationDrawer(mainActivity, toolbar); testScheduler.triggerActions(); verify(mView, times(1)).showLoading(true); verify(discogsInteractor, times(1)).fetchUserDetails(); verify(mainController).setOrdersError(true); verify(navigationDrawerBuilder, times(1)).buildNavigationDrawer(mainActivity, toolbar); verify(mView).setDrawer(drawer); verify(mView).setupRecyclerView(); verify(logWrapper).e(any(String.class), any(String.class)); } @Test public void setupRecyclerView_setsUpRecyclerView() { mainPresenter.setupRecyclerView(mainActivity, recyclerView); verify(mainController, times(1)).getAdapter(); verify(mainController, times(1)).requestModelBuild(); } @Test public void retrySuccessful_displaysInfo() { List<Order> listOrders = new ArrayList(); List<Listing> listSelling = new ArrayList(); when(sharedPrefsManager.getUsername()).thenReturn(username); when(context.getString(R.string.main_activity)).thenReturn("MainActivity"); when(context.getString(R.string.logged_in)).thenReturn("logged in"); when(discogsInteractor.fetchUserDetails()).thenReturn(Single.just(testUserDetails)); when(discogsInteractor.fetchOrders()).thenReturn(Single.just(listOrders)); when(discogsInteractor.fetchSelling(username)).thenReturn(Single.just(listSelling)); mainPresenter.retry(); testScheduler.triggerActions(); verify(discogsInteractor, times(1)).fetchUserDetails(); verify(discogsInteractor, times(1)).fetchOrders(); verify(sharedPrefsManager, times(1)).getUsername(); verify(tracker).send("MainActivity", "MainActivity", "logged in", testUserDetails.getUsername(), 1L); verify(sharedPrefsManager, times(1)).storeUserDetails(testUserDetails); verify(mainController, times(1)).setLoadingMorePurchases(true); verify(mainController, times(1)).setOrders(listOrders); verify(discogsInteractor, times(1)).fetchSelling(username); verify(mainController, times(1)).setSelling(listSelling); } @Test public void retryError_displaysError() throws Exception { when(discogsInteractor.fetchUserDetails()).thenReturn(Single.error(new Exception())); mainPresenter.retry(); testScheduler.triggerActions(); verify(discogsInteractor, times(1)).fetchUserDetails(); verify(mainController, times(1)).setOrdersError(true); } @Test public void buildRecommendationsEmptyList_ControllerEmptyList() { List list = Collections.emptyList(); when(daoInteractor.getViewedReleases()).thenReturn(list); mainPresenter.buildRecommendations(); verify(daoInteractor, times(1)).getViewedReleases(); verify(mainController).setRecommendations(list); } @Test public void buildRecommendationsError_ControllerError() { ArrayList<ViewedRelease> viewedReleases = new ArrayList<>(); viewedReleases.add(new TestViewedRelease()); when(daoInteractor.getViewedReleases()).thenReturn(viewedReleases); when(discogsInteractor.searchByStyle(viewedReleases.get(0).getStyle(), "1", false)).thenReturn(Single.error(new Throwable())); when(discogsInteractor.searchByLabel(viewedReleases.get(0).getLabelName())).thenReturn(Single.error(new Throwable())); mainPresenter.buildRecommendations(); testScheduler.triggerActions(); assertEquals(daoInteractor.getViewedReleases(), viewedReleases); verify(daoInteractor, times(2)).getViewedReleases(); verify(discogsInteractor, times(1)).searchByStyle(viewedReleases.get(0).getStyle(), "1", false); verify(discogsInteractor, times(1)).searchByLabel(viewedReleases.get(0).getLabelName()); verify(mainController, times(1)).setRecommendationsError(true); } @Test public void buildRecommendationsOver24_ControllerDisplaysTruncatedLists() { final ArgumentCaptor searchResultCaptor = ArgumentCaptor.forClass(List.class); ArrayList<ViewedRelease> viewedReleases = new ArrayList<>(); viewedReleases.add(new TestViewedRelease()); when(daoInteractor.getViewedReleases()).thenReturn(viewedReleases); // TestSearchResponse contains 20 entries each when(discogsInteractor.searchByStyle(viewedReleases.get(0).getStyle(), "1", false)).thenReturn(Single.just(new TestRootSearchResponse())); when(discogsInteractor.searchByStyle(viewedReleases.get(0).getStyle(), String.valueOf(1), true)).thenReturn(Single.just(new TestRootSearchResponse())); when(discogsInteractor.searchByLabel(viewedReleases.get(0).getLabelName())).thenReturn(Single.just(new TestRootSearchResponse().getSearchResults())); mainPresenter.buildRecommendations(); testScheduler.triggerActions(); verify(daoInteractor, times(1)).getViewedReleases(); verify(discogsInteractor, times(1)).searchByStyle(viewedReleases.get(0).getStyle(), "1", false); verify(discogsInteractor, times(1)).searchByStyle(viewedReleases.get(0).getStyle(), "1", true); verify(discogsInteractor, times(1)).searchByLabel(viewedReleases.get(0).getLabelName()); verify(mainController, times(1)).setRecommendations((List<SearchResult>) searchResultCaptor.capture()); // Truncated 40 to 24 assertEquals(((List<SearchResult>) searchResultCaptor.getAllValues().get(0)).size(), 24); } }
package <%=packageName%>.web.rest; import com.codahale.metrics.annotation.Timed; import <%=packageName%>.domain.User; import <%=packageName%>.repository.UserRepository; import <%=packageName%>.security.AuthoritiesConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory;<% if (javaVersion == '8') { %> import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity;<% } %> import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.security.RolesAllowed; import javax.inject.Inject;<% if (javaVersion == '8') { %> import java.util.Optional;<% } else { %> import javax.servlet.http.HttpServletResponse;<% } %> /** * REST controller for managing users. */ @RestController @RequestMapping("/app") public class UserResource { private final Logger log = LoggerFactory.getLogger(UserResource.class); @Inject private UserRepository userRepository; /** * GET /rest/users/:login -> get the "login" user. */ @RequestMapping(value = "/rest/users/{login}", method = RequestMethod.GET, produces = "application/json") @Timed @RolesAllowed(AuthoritiesConstants.ADMIN)<% if (javaVersion == '8') { %> ResponseEntity<User> getUser(@PathVariable String login) { log.debug("REST request to get User : {}", login); return Optional.ofNullable(userRepository.findOne(login)) .map(user -> new ResponseEntity<>(user, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); }<% } else { %> public User getUser(@PathVariable String login, HttpServletResponse response) { log.debug("REST request to get User : {}", login); User user = userRepository.findOne(login); if (user == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } return user; }<% } %> }
package configuration; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.*; public class ErrorCheck { private HashMap<String, String> commandMap; private final String onenum = "\\s\\d+"; //one parameter only exactly one space between parameters private final String twonum = "\\s\\d+\\s\\d+"; //two parameter private final String com_regix = "\\[(.*?)\\]"; //[command] private final String variable = ":\\w+"; private final String constant = "-?\\d+.?\\d*"; private final String commandname = "\\w+[?]?"; private final String[] command = new String[]{"fd", "forward", "back", "bk", "towards", "tw", "setxy", "sum", "+", "difference","-", "product","*", "quotient","remainder", "%", "/","#","left", "lf", "right", "rt", "setheading", "seth", "sin", "cos", "tan", "atan", "repeat", "dotimes"}; private final String[] regix = new String[]{ "^fd"+ onenum,"^foward" + onenum, "^back" +onenum, "^bk"+ onenum, "^towards"+twonum, "^tw" + twonum, "^setxy" + twonum, "^sum" + twonum, "^+" + twonum, "^difference"+ twonum, "^-" + twonum, "^product" + twonum, "^*" + twonum, "^quotient" + twonum, "^remainder" + twonum, "^%" + twonum, "^/" + twonum, "^#.*", "^left" +onenum,"^lt" +onenum, "^right" +onenum,"^rt" +onenum, "setheading" +onenum, "^seth" +onenum,"^sin" +onenum,"^cos" +onenum, "^tan" +onenum, "^atan" +onenum, "repeat"+onenum+"\\s" +com_regix, "dotimes"+ "\\s\\[\\s"+variable+"\\s\\d+\\s\\]\\s"+com_regix}; /* public boolean validateInput(String in){ String s = in.trim().toLowerCase(); String command = s.split(" ")[0]; System.out.println(in); } */ //non-nested command validation public boolean validateBasicCommands(String in){ String s = in.trim().toLowerCase(); String command = s.split(" ")[0]; System.out.println(in); String commandRegix = commandMap.get(command); if(commandRegix != null){ return s.matches(commandRegix); //call parser here. } return false; } public boolean validateInput(String in){ String s = in.trim().toLowerCase();//sanitized input String command = s.split(" ")[0]; System.out.println(in); String commandRegix = commandMap.get(command); if(commandRegix != null){ //undefined commands return validateLoop(commandRegix, s); } return false; } public boolean validateLoop(String regix, String in){ Pattern p = Pattern.compile(regix); Matcher m = p.matcher(in); while(m.find()) return validateBasicCommands(m.group(1)); return false; } public ErrorCheck(){ commandMap = new HashMap(); //what if new commands added for(int i=0; i < command.length; i++){ commandMap.put(command[i],regix[i]); } } public static void main(String[] args) { ErrorCheck example = new ErrorCheck(); String s1 = "fd a"; String s2= "sum 50 50"; String s4 = "# ignore this is just comment!"; //broken when no space after # String s3 = "sum a b"; String s5 = "REmainder 50 50"; String s6 = " rt 50 "; String s7= "setheading 30"; String repeat = "repeat 10 [ fd 50 ]"; String dotimes = "dotimes [ :name 200 ] [ rt 50 ]"; //System.out.println(example.validateBasicCommands(s1)); //System.out.println(example.validateBasicCommands(s2)); //System.out.println(example.validateBasicCommands(s3)); //System.out.println(example.validateBasicCommands(s4)); //System.out.println(example.validateBasicCommands(s5)); //System.out.println(example.validateBasicCommands(s6)); //System.out.println(example.validateBasicCommands(s7)); System.out.println(example.validateInput(repeat)); //System.out.println(example.validateInput(dotimes)); } }
package bisq.asset.coins; import bisq.asset.Coin; import bisq.asset.RegexAddressValidator; public class TurtleCoin extends Coin { public TurtleCoin() { super("TurtleCoin", "TRTL", new RegexAddressValidator("^TRTL[1-9A-Za-z^OIl]{95}")); } }
package net.domesdaybook.automata.trie; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import net.domesdaybook.automata.base.BaseAutomata; import net.domesdaybook.automata.State; import net.domesdaybook.automata.Transition; import net.domesdaybook.automata.base.BaseStateFactory; import net.domesdaybook.automata.StateFactory; import net.domesdaybook.automata.base.ByteMatcherTransitionFactory; import net.domesdaybook.automata.TransitionFactory; import net.domesdaybook.bytes.ByteUtilities; /** * * @author Matt Palmer */ public abstract class AbstractTrie<T> extends BaseAutomata<T> implements Trie<T> { private final StateFactory<T> stateFactory; private final TransitionFactory transitionFactory; private final List<T> sequences; private int minimumLength = -1; private int maximumLength = 0; public AbstractTrie() { this(new BaseStateFactory<T>(), null); } public AbstractTrie(final StateFactory<T> stateFactory) { this(stateFactory, null); } public AbstractTrie(final TransitionFactory transitionFactory) { this(new BaseStateFactory(), transitionFactory); } public AbstractTrie(final StateFactory<T> stateFactory, final TransitionFactory transitionFactory) { super(stateFactory.create(State.NON_FINAL)); this.stateFactory = stateFactory; if (transitionFactory == null) { this.transitionFactory = new ByteMatcherTransitionFactory(); } else { this.transitionFactory = transitionFactory; } this.sequences = new ArrayList<T>(); } public int getMinimumLength() { return minimumLength == -1 ? 0 : minimumLength; } public int getMaximumLength() { return maximumLength; } public Collection<T> getSequences() { return new ArrayList<T>(sequences); } public void add(final T sequence) { List<State<T>> currentStates = new ArrayList<State<T>>(); currentStates.add(initialState); final int length = getSequenceLength(sequence); for (int position = 0; position < length; position++) { final byte[] matchingBytes = getBytesForPosition(sequence, position); final boolean isFinal = position == length - 1; currentStates = nextStates(currentStates, matchingBytes, isFinal); } for (final State<T> finalState : currentStates) { finalState.addAssociation(sequence); } setMinMaxLength(length); sequences.add(sequence); } public void addAll(final Collection<? extends T> sequences) { for (final T sequence : sequences) { add(sequence); } } public void addReversed(final T sequence) { List<State<T>> currentStates = new ArrayList<State<T>>(); currentStates.add(initialState); final int length = getSequenceLength(sequence); for (int position = length - 1; position >= 0; position final byte[] matchingBytes = getBytesForPosition(sequence, position); final boolean isFinal = position == 0; currentStates = nextStates(currentStates, matchingBytes, isFinal); } for (final State<T> finalState : currentStates) { finalState.addAssociation(sequence); } setMinMaxLength(length); sequences.add(sequence); } public void addAllReversed(final Collection<? extends T> sequences) { for (final T sequence : sequences) { addReversed(sequence); } } protected abstract int getSequenceLength(T sequence); protected abstract byte[] getBytesForPosition(T sequence, int position); private void setMinMaxLength(final int length) { if (length > maximumLength) { maximumLength = length; } if (length < minimumLength || minimumLength == -1) { minimumLength = length; } } /** * * @param currentStates * @param bytes * @param isFinal * @return */ private List<State<T>> nextStates(final List<State<T>> currentStates, final byte[] bytes, final boolean isFinal) { final List<State<T>> nextStates = new ArrayList<State<T>>(); final Set<Byte> allBytesToTransitionOn = ByteUtilities.toSet(bytes); for (final State currentState : currentStates) { // make a defensive copy of the transitions of the current state: final List<Transition> transitions = new ArrayList<Transition>(currentState.getTransitions()); final Set<Byte> bytesToTransitionOn = new HashSet<Byte>(allBytesToTransitionOn); for (final Transition transition : transitions) { final Set<Byte> originalTransitionBytes = ByteUtilities.toSet(transition.getBytes()); final int originalTransitionBytesSize = originalTransitionBytes.size(); final Set<Byte> bytesInCommon = ByteUtilities.subtract(originalTransitionBytes, bytesToTransitionOn); // If the existing transition is the same or a subset of the new transition bytes: final int numberOfBytesInCommon = bytesInCommon.size(); if (numberOfBytesInCommon == originalTransitionBytesSize) { final State toState = transition.getToState(); // Ensure that the state is final if necessary: if (isFinal) { toState.setIsFinal(true); } // Add this state to the states we have to process next. nextStates.add((State<T>) toState); } else if (numberOfBytesInCommon > 0) { // Only some bytes are in common. // We will have to split the existing transition to // two states, and recreate the transitions to them: final State originalToState = transition.getToState(); if (isFinal) { originalToState.setIsFinal(true); } final State newToState = originalToState.deepCopy(); // Add a transition to the bytes which are not in common: final Transition bytesNotInCommonTransition = transitionFactory.createSetTransition(originalTransitionBytes, false, originalToState); currentState.addTransition(bytesNotInCommonTransition); // Add a transition to the bytes in common: final Transition bytesInCommonTransition = transitionFactory.createSetTransition(bytesInCommon, false, newToState); currentState.addTransition(bytesInCommonTransition); // Add the bytes in common state to the next states to process: nextStates.add((State<T>) newToState); // Remove the original transition from the current state: currentState.removeTransition(transition); } // If we have no further bytes to process, just break out. final int numberOfBytesLeft = bytesToTransitionOn.size(); if (numberOfBytesLeft == 0) { break; } } // If there are any bytes left over, create a transition to a new state: final int numberOfBytesLeft = bytesToTransitionOn.size(); if (numberOfBytesLeft > 0) { final State<T> newState = stateFactory.create(isFinal); final Transition newTransition = transitionFactory.createSetTransition(bytesToTransitionOn, false, newState); currentState.addTransition(newTransition); nextStates.add(newState); } } return nextStates; } }
package net.java.sip.communicator.util; import java.net.*; import java.text.*; import java.util.*; import net.java.sip.communicator.service.dns.*; import net.java.sip.communicator.util.SRVRecord; import org.xbill.DNS.*; /** * Utility methods and fields to use when working with network addresses. * * @author Emil Ivov * @author Damian Minkov * @author Vincent Lucas * @author Alan Kelly */ public class NetworkUtils { /** * The <tt>Logger</tt> used by the <tt>NetworkUtils</tt> class for logging * output. */ private static final Logger logger = Logger.getLogger(NetworkUtils.class); /** * A string containing the "any" local address for IPv6. */ public static final String IN6_ADDR_ANY = "::0"; /** * A string containing the "any" local address for IPv4. */ public static final String IN4_ADDR_ANY = "0.0.0.0"; /** * A string containing the "any" local address. */ public static final String IN_ADDR_ANY = determineAnyAddress(); /** * The length of IPv6 addresses. */ private final static int IN6_ADDR_SIZE = 16; /** * The size of the tokens in a <tt>String</tt> representation of IPv6 * addresses. */ private final static int IN6_ADDR_TOKEN_SIZE = 2; /** * The length of IPv4 addresses. */ private final static int IN4_ADDR_SIZE = 4; /** * The maximum int value that could correspond to a port number. */ public static final int MAX_PORT_NUMBER = 65535; /** * The minimum int value that could correspond to a port number bindable * by the SIP Communicator. */ public static final int MIN_PORT_NUMBER = 1024; /** * The random port number generator that we use in getRandomPortNumer() */ private static Random portNumberGenerator = new Random(); /** * The name of the boolean property that defines whether all domain names * looked up from Jitsi should be treated as absolute. */ public static final String PNAME_DNS_ALWAYS_ABSOLUTE = "net.java.sip.communicator.util.dns.DNSSEC_ALWAYS_ABSOLUTE"; /** * Default value of {@link #PNAME_DNS_ALWAYS_ABSOLUTE}. */ public static final boolean PDEFAULT_DNS_ALWAYS_ABSOLUTE = false; /** * A random number generator. */ private static final Random random = new Random(); /** * Determines whether the address is the result of windows auto configuration. * (i.e. One that is in the 169.254.0.0 network) * @param add the address to inspect * @return true if the address is autoconfigured by windows, false otherwise. */ public static boolean isWindowsAutoConfiguredIPv4Address(InetAddress add) { return (add.getAddress()[0] & 0xFF) == 169 && (add.getAddress()[1] & 0xFF) == 254; } /** * Determines whether the address is an IPv4 link local address. IPv4 link * local addresses are those in the following networks: * * 10.0.0.0 to 10.255.255.255 * 172.16.0.0 to 172.31.255.255 * 192.168.0.0 to 192.168.255.255 * * @param add the address to inspect * @return true if add is a link local ipv4 address and false if not. */ public static boolean isLinkLocalIPv4Address(InetAddress add) { if (add instanceof Inet4Address) { byte address[] = add.getAddress(); if ( (address[0] & 0xFF) == 10) return true; if ( (address[0] & 0xFF) == 172 && (address[1] & 0xFF) >= 16 && address[1] <= 31) return true; if ( (address[0] & 0xFF) == 192 && (address[1] & 0xFF) == 168) return true; return false; } return false; } /** * Returns a random local port number that user applications could bind to. * (i.e. above 1024). * @return a random int located between 1024 and 65 535. */ public static int getRandomPortNumber() { return getRandomPortNumber(MIN_PORT_NUMBER, MAX_PORT_NUMBER); } /** * Returns a random local port number, greater than min and lower than max. * * @param min the minimum allowed value for the returned port number. * @param max the maximum allowed value for the returned port number. * * @return a random int located between greater than min and lower than max. */ public static int getRandomPortNumber(int min, int max) { return portNumberGenerator.nextInt(max - min) + min; } /** * Returns a random local port number, greater than min and lower than max. * If the pair flag is set to true, then the returned port number is * guaranteed to be pair. This is useful for protocols that require this * such as RTP * * @param min the minimum allowed value for the returned port number. * @param max the maximum allowed value for the returned port number. * @param pair specifies whether the caller would like the returned port to * be pair. * * @return a random int located between greater than min and lower than max. */ public static int getRandomPortNumber(int min, int max, boolean pair) { if(pair) { int delta = max - min; delta /= 2; int port = getRandomPortNumber(min, min + delta); return port * 2; } else { return getRandomPortNumber(min, max); } } /** * Verifies whether <tt>address</tt> could be an IPv4 address string. * * @param address the String that we'd like to determine as an IPv4 address. * * @return true if the address contained by <tt>address</tt> is an IPv4 * address and false otherwise. */ public static boolean isIPv4Address(String address) { return strToIPv4(address) != null; } /** * Verifies whether <tt>address</tt> could be an IPv6 address string. * * @param address the String that we'd like to determine as an IPv6 address. * * @return true if the address contained by <tt>address</tt> is an IPv6 * address and false otherwise. */ public static boolean isIPv6Address(String address) { return strToIPv6(address) != null; } /** * Checks whether <tt>address</tt> is a valid IP address string. * * @param address the address that we'd like to check * @return true if address is an IPv4 or IPv6 address and false otherwise. */ public static boolean isValidIPAddress(String address) { // empty string if (address == null || address.length() == 0) { return false; } // look for IPv6 brackets and remove brackets for parsing boolean ipv6Expected = false; if (address.charAt(0) == '[') { // This is supposed to be an IPv6 literal if (address.length() > 2 && address.charAt(address.length() - 1) == ']') { // remove brackets from IPv6 address = address.substring(1, address.length() - 1); ipv6Expected = true; } else { return false; } } // look for IP addresses if (Character.digit(address.charAt(0), 16) != -1 || (address.charAt(0) == ':')) { byte[] addr = null; // see if it is IPv4 address addr = strToIPv4(address); // if not, see if it is IPv6 address if (addr == null) { addr = strToIPv6(address); } // if IPv4 is found when IPv6 is expected else if (ipv6Expected) { // invalid address: IPv4 address surrounded with brackets! return false; } // if an IPv4 or IPv6 address is found if (addr != null) { // is an IP address return true; } } // no matches found return false; } /** * Creates a byte array containing the specified <tt>ipv4AddStr</tt>. * * @param ipv4AddrStr a <tt>String</tt> containing an IPv4 address. * * @return a byte array containing the four bytes of the address represented * by ipv4AddrStr or <tt>null</tt> if <tt>ipv4AddrStr</tt> does not contain * a valid IPv4 address string. */ public static byte[] strToIPv4(String ipv4AddrStr) { if (ipv4AddrStr == null || ipv4AddrStr.length() == 0) return null; byte[] address = new byte[IN4_ADDR_SIZE]; String[] tokens = ipv4AddrStr.split("\\.", -1); long currentTkn; try { switch(tokens.length) { case 1: //If the address was specified as a single String we can //directly copy it into the byte array. currentTkn = Long.parseLong(tokens[0]); if (currentTkn < 0 || currentTkn > 0xffffffffL) return null; address[0] = (byte) ((currentTkn >> 24) & 0xff); address[1] = (byte) (((currentTkn & 0xffffff) >> 16) & 0xff); address[2] = (byte) (((currentTkn & 0xffff) >> 8) & 0xff); address[3] = (byte) (currentTkn & 0xff); break; case 2: // If the address was passed in two parts (e.g. when dealing // with a Class A address representation), we place the // first one in the leftmost byte and the rest in the three // remaining bytes of the address array. currentTkn = Integer.parseInt(tokens[0]); if (currentTkn < 0 || currentTkn > 0xff) return null; address[0] = (byte) (currentTkn & 0xff); currentTkn = Integer.parseInt(tokens[1]); if (currentTkn < 0 || currentTkn > 0xffffff) return null; address[1] = (byte) ((currentTkn >> 16) & 0xff); address[2] = (byte) (((currentTkn & 0xffff) >> 8) &0xff); address[3] = (byte) (currentTkn & 0xff); break; case 3: // If the address was passed in three parts (e.g. when // dealing with a Class B address representation), we place // the first two parts in the two leftmost bytes and the // rest in the two remaining bytes of the address array. for (int i = 0; i < 2; i++) { currentTkn = Integer.parseInt(tokens[i]); if (currentTkn < 0 || currentTkn > 0xff) return null; address[i] = (byte) (currentTkn & 0xff); } currentTkn = Integer.parseInt(tokens[2]); if (currentTkn < 0 || currentTkn > 0xffff) return null; address[2] = (byte) ((currentTkn >> 8) & 0xff); address[3] = (byte) (currentTkn & 0xff); break; case 4: // And now for the most common - four part case. This time // there's a byte for every part :). Yuppiee! :) for (int i = 0; i < 4; i++) { currentTkn = Integer.parseInt(tokens[i]); if (currentTkn < 0 || currentTkn > 0xff) return null; address[i] = (byte) (currentTkn & 0xff); } break; default: return null; } } catch(NumberFormatException e) { return null; } return address; } /** * Creates a byte array containing the specified <tt>ipv6AddStr</tt>. * * @param ipv6AddrStr a <tt>String</tt> containing an IPv6 address. * * @return a byte array containing the four bytes of the address represented * by <tt>ipv6AddrStr</tt> or <tt>null</tt> if <tt>ipv6AddrStr</tt> does * not contain a valid IPv6 address string. */ public static byte[] strToIPv6(String ipv6AddrStr) { // Bail out if the string is shorter than "::" if (ipv6AddrStr == null || ipv6AddrStr.length() < 2) return null; int colonIndex; char currentChar; boolean sawtDigit; int currentTkn; char[] addrBuff = ipv6AddrStr.toCharArray(); byte[] dst = new byte[IN6_ADDR_SIZE]; int srcb_length = addrBuff.length; int scopeID = ipv6AddrStr.indexOf ("%"); if (scopeID == srcb_length -1) return null; if (scopeID != -1) srcb_length = scopeID; colonIndex = -1; int i = 0, j = 0; // Starting : mean we need to have at least one more. if (addrBuff[i] == ':') if (addrBuff[++i] != ':') return null; int curtok = i; sawtDigit = false; currentTkn = 0; while (i < srcb_length) { currentChar = addrBuff[i++]; int chval = Character.digit(currentChar, 16); if (chval != -1) { currentTkn <<= 4; currentTkn |= chval; if (currentTkn > 0xffff) return null; sawtDigit = true; continue; } if (currentChar == ':') { curtok = i; if (!sawtDigit) { if (colonIndex != -1) return null; colonIndex = j; continue; } else if (i == srcb_length) { return null; } if (j + IN6_ADDR_TOKEN_SIZE > IN6_ADDR_SIZE) return null; dst[j++] = (byte) ((currentTkn >> 8) & 0xff); dst[j++] = (byte) (currentTkn & 0xff); sawtDigit = false; currentTkn = 0; continue; } if (currentChar == '.' && ((j + IN4_ADDR_SIZE) <= IN6_ADDR_SIZE)) { String ia4 = ipv6AddrStr.substring(curtok, srcb_length); // check this IPv4 address has 3 dots, ie. A.B.C.D int dot_count = 0, index=0; while ((index = ia4.indexOf ('.', index)) != -1) { dot_count ++; index ++; } if (dot_count != 3) return null; byte[] v4addr = strToIPv4(ia4); if (v4addr == null) return null; for (int k = 0; k < IN4_ADDR_SIZE; k++) { dst[j++] = v4addr[k]; } sawtDigit = false; break; /* '\0' was seen by inet_pton4(). */ } return null; } if (sawtDigit) { if (j + IN6_ADDR_TOKEN_SIZE > IN6_ADDR_SIZE) return null; dst[j++] = (byte) ((currentTkn >> 8) & 0xff); dst[j++] = (byte) (currentTkn & 0xff); } if (colonIndex != -1) { int n = j - colonIndex; if (j == IN6_ADDR_SIZE) return null; for (i = 1; i <= n; i++) { dst[IN6_ADDR_SIZE - i] = dst[colonIndex + n - i]; dst[colonIndex + n - i] = 0; } j = IN6_ADDR_SIZE; } if (j != IN6_ADDR_SIZE) return null; byte[] newdst = mappedIPv4ToRealIPv4(dst); if (newdst != null) { return newdst; } else { return dst; } } /** * Returns array of hosts from the SRV record of the specified domain. * The records are ordered against the SRV record priority * @param domain the name of the domain we'd like to resolve (_proto._tcp * included). * @return an array of SRVRecord containing records returned by the DNS * server - address and port . * @throws ParseException if <tt>domain</tt> is not a valid domain name. * @throws DnssecException when a DNSSEC validation failure occurred. */ public static SRVRecord[] getSRVRecords(String domain) throws ParseException, DnssecException { Record[] records = null; try { Lookup lookup = createLookup(domain, Type.SRV); records = lookup.run(); } catch (TextParseException tpe) { logger.error("Failed to parse domain=" + domain, tpe); throw new ParseException(tpe.getMessage(), 0); } catch(DnssecRuntimeException e) { throw new DnssecException(e); } if (records == null) { return null; } //String[][] pvhn = new String[records.length][4]; SRVRecord srvRecords[] = new SRVRecord[records.length]; for (int i = 0; i < records.length; i++) { org.xbill.DNS.SRVRecord srvRecord = (org.xbill.DNS.SRVRecord) records[i]; srvRecords[i] = new SRVRecord(srvRecord); } // Sort the SRV RRs by priority (lower is preferred) and weight. sortSrvRecord(srvRecords); if (logger.isTraceEnabled()) { logger.trace("DNS SRV query for domain " + domain + " returned:"); for (int i = 0; i < srvRecords.length; i++) { if (logger.isTraceEnabled()) logger.trace(srvRecords[i]); } } return srvRecords; } /** * Returns an <tt>InetSocketAddress</tt> representing the first SRV * record available for the specified domain or <tt>null</tt> if there are * not SRV records for <tt>domain</tt>. * * @param domain the name of the domain we'd like to resolve. * @param service the service that we are trying to get a record for. * @param proto the protocol that we'd like <tt>service</tt> on. * * @return the first InetSocketAddress containing records returned by the * DNS server - address and port . * @throws ParseException if <tt>domain</tt> is not a valid domain name. * @throws DnssecException when a DNSSEC validation failure occurred. */ public static SRVRecord getSRVRecord(String service, String proto, String domain) throws ParseException, DnssecException { SRVRecord[] records = getSRVRecords("_" + service + "._" + proto + "." + domain); if(records == null || records.length == 0) return null; return records[0]; } /** * Returns an <tt>InetSocketAddress</tt> representing the first SRV * record available for the specified domain or <tt>null</tt> if there are * not SRV records for <tt>domain</tt>. * * @param domain the name of the domain we'd like to resolve. * @param service the service that we are trying to get a record for. * @param proto the protocol that we'd like <tt>service</tt> on. * * @return the InetSocketAddress[] containing records returned by the * DNS server - address and port . * @throws ParseException if <tt>domain</tt> is not a valid domain name. * @throws DnssecException when a DNSSEC validation failure occurred. */ public static SRVRecord[] getSRVRecords(String service, String proto, String domain) throws ParseException, DnssecException { SRVRecord[] records = getSRVRecords("_" + service + "._" + proto + "." + domain); if(records == null || records.length == 0) return null; return records; } /** * Makes a NAPTR query and returns the result. The returned records are an * array of [Order, Service(Transport) and Replacement * (the srv to query for servers and ports)] this all for supplied * <tt>domain</tt>. * * @param domain the name of the domain we'd like to resolve. * @return an array with the values or null if no records found. * * @throws ParseException if <tt>domain</tt> is not a valid domain name. * @throws DnssecException when a DNSSEC validation failure occurred. */ public static String[][] getNAPTRRecords(String domain) throws ParseException, DnssecException { Record[] records = null; try { Lookup lookup = createLookup(domain, Type.NAPTR); records = lookup.run(); } catch (TextParseException tpe) { logger.error("Failed to parse domain="+domain, tpe); throw new ParseException(tpe.getMessage(), 0); } catch(DnssecRuntimeException e) { throw new DnssecException(e); } if (records == null) { if(logger.isTraceEnabled()) logger.trace("No NAPTRs found for " + domain); return null; } String[][] recVals = new String[records.length][4]; for (int i = 0; i < records.length; i++) { NAPTRRecord r = (NAPTRRecord)records[i]; // todo - check here for broken records as missing transport recVals[i][0] = "" + r.getOrder(); recVals[i][1] = getProtocolFromNAPTRRecords(r.getService()); String replacement = r.getReplacement().toString(); if (replacement.endsWith(".")) { recVals[i][2] = replacement.substring(0, replacement.length() - 1); } else { recVals[i][2] = replacement; } recVals[i][3] = "" + r.getPreference(); } // sort the SRV RRs by RR value (lower is preferred) Arrays.sort(recVals, new Comparator<String[]>() { // Sorts NAPTR records by ORDER (low number first), PREFERENCE (low // number first) and PROTOCOL (0-TLS, 1-TCP, 2-UDP). public int compare(String array1[], String array2[]) { // First tries to define the priority with the NAPTR order. int order = Integer.parseInt(array1[0]) - Integer.parseInt(array2[0]); if(order != 0) { return order; } // Second tries to define the priority with the NAPTR // preference. int preference = Integer.parseInt(array1[3]) - Integer.parseInt(array2[3]); if(preference != 0) { return preference; } // Finally defines the priority with the NAPTR protocol. int protocol = getProtocolPriority(array1[1]) - getProtocolPriority(array2[1]); return protocol; } }); if(logger.isTraceEnabled()) logger.trace("NAPTRs for " + domain + "=" + Arrays.toString(recVals)); return recVals; } /** * Returns the mapping from rfc3263 between service and the protocols. * * @param service the service from NAPTR record. * @return the protocol TCP, UDP or TLS. */ private static String getProtocolFromNAPTRRecords(String service) { if(service.equalsIgnoreCase("SIP+D2U")) return "UDP"; else if(service.equalsIgnoreCase("SIP+D2T")) return "TCP"; else if(service.equalsIgnoreCase("SIPS+D2T")) return "TLS"; else return null; } /** * Returns the priority of a protocol. The lowest priority is the highest: * 0-TLS, 1-TCP, 2-UDP. * * @param protocol The protocol name: "TLS", "TCP" or "UDP". * * @return The priority of a protocol. The lowest priority is the highest: * 0-TLS, 1-TCP, 2-UDP. */ private static int getProtocolPriority(String protocol) { if(protocol.equals("TLS")) return 0; else if(protocol.equals("TCP")) return 1; return 2; // "UDP". } /** * Creates an InetAddress from the specified <tt>hostAddress</tt>. The point * of using the method rather than creating the address by yourself is that * it would first check whether the specified <tt>hostAddress</tt> is indeed * a valid ip address. It this is the case, the method would create the * <tt>InetAddress</tt> using the <tt>InetAddress.getByAddress()</tt> * method so that no DNS resolution is attempted by the JRE. Otherwise * it would simply use <tt>InetAddress.getByName()</tt> so that we would an * <tt>InetAddress</tt> instance even at the cost of a potential DNS * resolution. * * @param hostAddress the <tt>String</tt> representation of the address * that we would like to create an <tt>InetAddress</tt> instance for. * * @return an <tt>InetAddress</tt> instance corresponding to the specified * <tt>hostAddress</tt>. * * @throws UnknownHostException if any of the <tt>InetAddress</tt> methods * we are using throw an exception. */ public static InetAddress getInetAddress(String hostAddress) throws UnknownHostException { //is null if (hostAddress == null || hostAddress.length() == 0) { throw new UnknownHostException( hostAddress + " is not a valid host address"); } //transform IPv6 literals into normal addresses if (hostAddress.charAt(0) == '[') { // This is supposed to be an IPv6 literal if (hostAddress.length() > 2 && hostAddress.charAt(hostAddress.length()-1) == ']') { hostAddress = hostAddress.substring(1, hostAddress.length() -1); } else { // This was supposed to be a IPv6 address, but it's not! throw new UnknownHostException(hostAddress); } } if (NetworkUtils.isValidIPAddress(hostAddress)) { byte[] addr = null; // attempt parse as IPv4 address addr = strToIPv4(hostAddress); // if not IPv4, parse as IPv6 address if (addr == null) { addr = strToIPv6(hostAddress); } return InetAddress.getByAddress(hostAddress, addr); } else { return InetAddress.getByName(hostAddress); } } /** * Returns array of hosts from the A and AAAA records of the specified * domain. The records are ordered against the IPv4/IPv6 protocol priority * * @param domain the name of the domain we'd like to resolve. * @param port the port number of the returned <tt>InetSocketAddress</tt> * @return an array of InetSocketAddress containing records returned by the * DNS server - address and port . * @throws ParseException if <tt>domain</tt> is not a valid domain name. * @throws DnssecException when a DNSSEC validation failure occurred. */ public static InetSocketAddress[] getAandAAAARecords(String domain, int port) throws ParseException, DnssecException { byte[] address = null; if((address = strToIPv4(domain)) != null || (address = strToIPv6(domain)) != null) { try { return new InetSocketAddress[] { new InetSocketAddress( InetAddress.getByAddress(domain, address), port) }; } catch (UnknownHostException e) { //should not happen logger.error( "Unable to create InetAddress for <" + domain + ">", e); return null; } } List<InetSocketAddress> addresses = new LinkedList<InetSocketAddress>(); boolean v6lookup = Boolean.getBoolean("java.net.preferIPv6Addresses"); for(int i = 0; i < 2; i++) { Lookup lookup; try { lookup = createLookup(domain, v6lookup ? Type.AAAA : Type.A); } catch (TextParseException tpe) { logger.error("Failed to parse domain <" + domain + ">", tpe); throw new ParseException(tpe.getMessage(), 0); } Record[] records = null; try { records = lookup.run(); } catch(DnssecRuntimeException e) { throw new DnssecException(e); } if(records != null) { for(Record r : records) { try { addresses.add( new InetSocketAddress( // create a new InetAddress filled with the // domain name to avoid PTR queries InetAddress.getByAddress( domain, v6lookup ? ((AAAARecord)r).getAddress().getAddress() : ((ARecord)r).getAddress().getAddress() ), port ) ); } catch (UnknownHostException e) { logger.error("Invalid record returned from DNS", e); } } } v6lookup = !v6lookup; } if(logger.isTraceEnabled()) logger.trace("A or AAAA addresses: " + addresses); return addresses.toArray(new InetSocketAddress[0]); } /** * Returns array of hosts from the A record of the specified domain. * The records are ordered against the A record priority * @param domain the name of the domain we'd like to resolve. * @param port the port number of the returned <tt>InetSocketAddress</tt> * @return an array of InetSocketAddress containing records returned by the * DNS server - address and port . * @throws ParseException if <tt>domain</tt> is not a valid domain name. * @throws DnssecException when a DNSSEC validation failure occurred. */ public static InetSocketAddress getARecord(String domain, int port) throws ParseException, DnssecException { byte[] address; if((address = strToIPv4(domain)) != null) { try { return new InetSocketAddress( InetAddress.getByAddress(domain, address), port); } catch (UnknownHostException e) { //should not happen logger.error( "Unable to create InetAddress for <" + domain + ">", e); return null; } } Record[] records; try { //note that we intentionally do not use our parallel resolver here. //for starters we'd like to make sure that it works well enough //with SRV and NAPTR queries. We may then also adopt it for As //and AAAAs once it proves to be reliable (posted on: 2010-11-24) Lookup lookup = createLookup(domain, Type.A); records = lookup.run(); } catch (TextParseException tpe) { logger.error("Failed to parse domain="+domain, tpe); throw new ParseException(tpe.getMessage(), 0); } catch(DnssecRuntimeException e) { throw new DnssecException(e); } if (records != null && records.length > 0) { if(logger.isTraceEnabled()) logger.trace("A record for " + domain + "=" + ((ARecord)records[0]).getAddress()); try { return new InetSocketAddress( InetAddress.getByAddress(domain, ((ARecord)records[0]).getAddress().getAddress()), port); } catch (UnknownHostException e) { return null; } } else { if(logger.isTraceEnabled()) logger.trace("No A record found for " + domain); return null; } } /** * Returns array of hosts from the AAAA record of the specified domain. * The records are ordered against the AAAA record priority * @param domain the name of the domain we'd like to resolve. * @param port the port number of the returned <tt>InetSocketAddress</tt> * @return an array of InetSocketAddress containing records returned by the * DNS server - address and port . * @throws ParseException if <tt>domain</tt> is not a valid domain name. * @throws DnssecException */ public static InetSocketAddress getAAAARecord(String domain, int port) throws ParseException, DnssecException { byte[] address; if((address = strToIPv6(domain)) != null) { try { return new InetSocketAddress( InetAddress.getByAddress(domain, address), port); } catch (UnknownHostException e) { //should not happen logger.error( "Unable to create InetAddress for <" + domain + ">", e); return null; } } Record[] records; try { //note that we intentionally do not use our parallel resolver here. //for starters we'd like to make sure that it works well enough //with SRV and NAPTR queries. We may then also adopt it for As //and AAAAs once it proves to be reliable (posted on: 2010-11-24) Lookup lookup = createLookup(domain, Type.AAAA); records = lookup.run(); } catch (TextParseException tpe) { logger.error("Failed to parse domain="+domain, tpe); throw new ParseException(tpe.getMessage(), 0); } catch(DnssecRuntimeException e) { throw new DnssecException(e); } if (records != null && records.length > 0) { if(logger.isTraceEnabled()) logger.trace("AAAA record for " + domain + "=" + ((AAAARecord)records[0]).getAddress()); try { return new InetSocketAddress( InetAddress.getByAddress(domain, ((AAAARecord)records[0]).getAddress().getAddress()), port); } catch (UnknownHostException e) { return null; } } else { if(logger.isTraceEnabled()) logger.trace("No AAAA record found for " + domain); return null; } } /** * Tries to determine if this host supports IPv6 addresses (i.e. has at * least one IPv6 address) and returns IN6_ADDR_ANY or IN4_ADDR_ANY * accordingly. This method is only used to initialize IN_ADDR_ANY so that * it could be used when binding sockets. The reason we need it is because * on mac (contrary to lin or win) binding a socket on 0.0.0.0 would make * it deaf to IPv6 traffic. Binding on ::0 does the trick but that would * fail on hosts that have no IPv6 support. Using the result of this method * provides an easy way to bind sockets in cases where we simply want any * IP packets coming on the port we are listening on (regardless of IP * version). * * @return IN6_ADDR_ANY or IN4_ADDR_ANY if this host supports or not IPv6. */ private static String determineAnyAddress() { Enumeration<NetworkInterface> ifaces; try { ifaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { if (logger.isDebugEnabled()) logger.debug("Couldn't retrieve local interfaces.", e); return IN4_ADDR_ANY; } while(ifaces.hasMoreElements()) { Enumeration<InetAddress> addrs = ifaces.nextElement().getInetAddresses(); while (addrs.hasMoreElements()) { if(addrs.nextElement() instanceof Inet6Address) return IN6_ADDR_ANY; } } return IN4_ADDR_ANY; } /** * Determines whether <tt>port</tt> is a valid port number bindable by an * application (i.e. an integer between 1024 and 65535). * * @param port the port number that we'd like verified. * * @return <tt>true</tt> if port is a valid and bindable port number and * <tt>alse</tt> otherwise. */ public static boolean isValidPortNumber(int port) { return MIN_PORT_NUMBER < port && port < MAX_PORT_NUMBER; } /** * Returns an IPv4 address matching the one mapped in the IPv6 * <tt>addr</tt>. Both input and returned value are in network order. * * @param addr a String representing an IPv4-Mapped address in textual * format * * @return a byte array numerically representing the IPv4 address */ public static byte[] mappedIPv4ToRealIPv4(byte[] addr) { if (isMappedIPv4Addr(addr)) { byte[] newAddr = new byte[IN4_ADDR_SIZE]; System.arraycopy(addr, 12, newAddr, 0, IN6_ADDR_SIZE); return newAddr; } return null; } /** * Utility method to check if the specified <tt>address</tt> is an IPv4 * mapped IPv6 address. * * @param address the address that we'd like to determine as an IPv4 mapped * one or not. * * @return <tt>true</tt> if address is an IPv4 mapped IPv6 address and * <tt>false</tt> otherwise. */ private static boolean isMappedIPv4Addr(byte[] address) { if (address.length < IN6_ADDR_SIZE) { return false; } if ((address[0] == 0x00) && (address[1] == 0x00) && (address[2] == 0x00) && (address[3] == 0x00) && (address[4] == 0x00) && (address[5] == 0x00) && (address[6] == 0x00) && (address[7] == 0x00) && (address[8] == 0x00) && (address[9] == 0x00) && (address[10] == (byte)0xff) && (address[11] == (byte)0xff)) { return true; } return false; } /** * Creates a new {@link Lookup} instance using our own {@link * ParallelResolverImpl} if it is enabled and DNSSEC is not active. * * @param domain the domain we will be resolving * @param type the type of the record we will be trying to obtain. * * @return the newly created {@link Lookup} instance. * * @throws TextParseException if <tt>domain</tt> is not a valid domain name. */ private static Lookup createLookup(String domain, int type) throws TextParseException { // make domain name absolute if requested if(UtilActivator.getConfigurationService().getBoolean( PNAME_DNS_ALWAYS_ABSOLUTE, PDEFAULT_DNS_ALWAYS_ABSOLUTE)) { if(!Name.fromString(domain).isAbsolute()) domain = domain + "."; } Lookup lookup = new Lookup(domain, type); if(logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Active DNS servers in default resolver: "); for(String s : ResolverConfig.getCurrentConfig().servers()) { sb.append(s); sb.append(", "); } logger.trace(sb.toString()); } return lookup; } /** * Compares two DNS names against each other. Helper method to avoid the * export of DNSJava. * @param dns1 The first DNS name * @param dns2 The DNS name that is compared against dns1 * @return The value 0 if dns2 is a name equivalent to dns1; * a value less than 0 if dns2 is less than dns1 in the canonical ordering, * and a value greater than 0 if dns2 is greater than dns1 in the canonical * ordering. * @throws ParseException if the dns1 or dns2 is not a DNS Name */ public static int compareDnsNames(String dns1, String dns2) throws ParseException { try { return Name.fromString(dns1).compareTo(Name.fromString(dns2)); } catch(TextParseException e) { throw new ParseException(e.getMessage(), 0); } } /** * Sorts the SRV record list by priority and weight. * * @param srvRecords The list of SRV records. */ private static void sortSrvRecord(SRVRecord[] srvRecords) { // Sort the SRV RRs by priority (lower is preferred). Arrays.sort(srvRecords, new Comparator<SRVRecord>() { public int compare(SRVRecord obj1, SRVRecord obj2) { return (obj1.getPriority() - obj2.getPriority()); } }); // Sort the SRV RRs by weight (larger weight has a proportionately // higher probability of being selected). sortSrvRecordByWeight(srvRecords); } /** * Sorts each priority of the SRV record list. Each priority is sorted with * the probabilty given by the weight attribute. * * @param srvRecords The list of SRV records already sorted by priority. */ private static void sortSrvRecordByWeight(SRVRecord[] srvRecords) { int currentPriority = srvRecords[0].getPriority(); int startIndex = 0; for(int i = 0; i < srvRecords.length; ++i) { if(currentPriority != srvRecords[i].getPriority()) { // Sort the current priority. sortSrvRecordPriorityByWeight(srvRecords, startIndex, i); // Reinit variables for the next priority. startIndex = i; currentPriority = srvRecords[i].getPriority(); } } } /** * Sorts SRV record list for a given priority: this priority is sorted with * the probabilty given by the weight attribute. * * @param srvRecords The list of SRV records already sorted by priority. * @param startIndex The first index (included) for the current priority. * @param endIndex The last index (excluded) for the current priority. */ private static void sortSrvRecordPriorityByWeight( SRVRecord[] srvRecords, int startIndex, int endIndex) { int randomWeight; // Loops over the items of the current priority. while(startIndex < endIndex) { // Compute a random number in [0...totalPriorityWeight]. randomWeight = getRandomWeight(srvRecords, startIndex, endIndex); // Move the selected item on top of the unsorted items for this // priority. moveSelectedSRVRecord( srvRecords, startIndex, endIndex, randomWeight); // Move to next index. ++startIndex; } } /** * Compute a random number in [0...totalPriorityWeight] with * totalPriorityWeight the sum of all weight for the current priority. * * @param srvRecords The list of SRV records already sorted by priority. * @param startIndex The first index (included) for the current priority. * @param endIndex The last index (excluded) for the current priority. * * @return A random number in [0...totalPriorityWeight] with * totalPriorityWeight the sum of all weight for the current priority. */ private static int getRandomWeight( SRVRecord[] srvRecords, int startIndex, int endIndex) { int totalPriorityWeight = 0; // Compute the max born. for(int i = startIndex; i < endIndex; ++i) { totalPriorityWeight += srvRecords[i].getWeight(); } // Compute a random number in [0...totalPriorityWeight]. return random.nextInt(totalPriorityWeight + 1); } /** * Moves the selected SRV record in top of the unsorted items for this * priority. * * @param srvRecords The list of SRV records already sorted by priority. * @param startIndex The first unsorted index (included) for the current * priority. * @param endIndex The last unsorted index (excluded) for the current * priority. * @param selectedWeight The selected weight used to design the selected * item to move. */ private static void moveSelectedSRVRecord( SRVRecord[] srvRecords, int startIndex, int endIndex, int selectedWeight) { SRVRecord tmpSrvRecord; int totalPriorityWeight = 0; for(int i = startIndex; i < endIndex; ++i) { totalPriorityWeight += srvRecords[i].getWeight(); // If we found the selecting record. if(totalPriorityWeight >= selectedWeight) { // Switch between startIndex and j. tmpSrvRecord = srvRecords[startIndex]; srvRecords[startIndex] = srvRecords[i]; srvRecords[i] = tmpSrvRecord; // Break the loop; return; } } } }
package net.kevxu.purdueassist.course; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.kevxu.purdueassist.course.elements.Predefined.Subject; import net.kevxu.purdueassist.course.elements.Predefined.Term; import net.kevxu.purdueassist.course.elements.Predefined.Type; import net.kevxu.purdueassist.course.shared.CourseNotFoundException; import net.kevxu.purdueassist.course.shared.HttpParseException; import net.kevxu.purdueassist.shared.httpclient.BasicHttpClientAsync; import net.kevxu.purdueassist.shared.httpclient.BasicHttpClientAsync.OnRequestFinishedListener; import net.kevxu.purdueassist.shared.httpclient.HttpClientAsync.HttpMethod; import net.kevxu.purdueassist.shared.httpclient.MethodNotPostException; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.message.BasicNameValuePair; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class CatalogDetail implements OnRequestFinishedListener { private static final String URL_HEAD = "https://selfservice.mypurdue.purdue.edu/prod/" + "bzwsrch.p_catalog_detail"; private Term term; private Subject subject; private int cnbr; private OnCatalogDetailFinishedListener mListener; private BasicHttpClientAsync httpClient; public interface OnCatalogDetailFinishedListener { public void onCatalogDetailFinished(CatalogDetailEntry entry); public void onCatalogDetailFinished(IOException e); public void onCatalogDetailFinished(HttpParseException e); public void onCatalogDetailFinished(CourseNotFoundException e); } public CatalogDetail(Subject subject, int cnbr, OnCatalogDetailFinishedListener onCatalogDetailFinishedListener) { this(Term.CURRENT, subject, cnbr, onCatalogDetailFinishedListener); } public CatalogDetail(Term term, Subject subject, int cnbr, OnCatalogDetailFinishedListener onCatalogDetailFinishedListener) { if (term != null) this.term = term; else this.term = Term.CURRENT; this.subject = subject; this.cnbr = cnbr; this.mListener = onCatalogDetailFinishedListener; } public void getResult() { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("term", term.getLinkName())); parameters.add(new BasicNameValuePair("subject", subject.name())); parameters.add(new BasicNameValuePair("cnbr", Integer.toString(cnbr))); httpClient = new BasicHttpClientAsync(URL_HEAD, HttpMethod.POST, this); try { httpClient.setParameters(parameters); httpClient.getResponse(); } catch (MethodNotPostException e) { e.printStackTrace(); } } @Override public void onRequestFinished(HttpResponse httpResponse) { try { InputStream stream = httpResponse.getEntity().getContent(); Header encoding = httpResponse.getEntity().getContentEncoding(); Document document; if (encoding == null) { document = Jsoup.parse(stream, null, URL_HEAD); } else { document = Jsoup.parse(stream, encoding.getValue(), URL_HEAD); } stream.close(); CatalogDetailEntry entry = parseDocument(document); mListener.onCatalogDetailFinished(entry); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { mListener.onCatalogDetailFinished(e); } catch (HttpParseException e) { mListener.onCatalogDetailFinished(e); } catch (CourseNotFoundException e) { mListener.onCatalogDetailFinished(e); } catch (Exception e) { e.printStackTrace(); } } @Override public void onRequestFinished(ClientProtocolException e) { e.printStackTrace(); } @Override public void onRequestFinished(IOException e) { mListener.onCatalogDetailFinished(e); } private CatalogDetailEntry parseDocument(Document document) throws HttpParseException, CourseNotFoundException, IOException { CatalogDetailEntry entry = new CatalogDetailEntry(subject, cnbr); Elements tableElements = document.getElementsByAttributeValue("summary", "This table lists the course detail for the selected term."); if (tableElements.isEmpty() != true) { // get name try { Element body = tableElements.first().select("tbody").first(); String nameBlock = body.select("tr td.nttitle").first().text(); String[] temp = nameBlock.split(subject.name() + " " + String.valueOf(cnbr)); String name = temp[temp.length - 1].substring(3); entry.setName(name); // get description body = body.select(".ntdefault").first(); String text = body.text(); int split = text.indexOf("Levels:"); String description = text.substring(0, split); description = description.substring(20); entry.setDescription(description); // get levels int begin = split; int end = text.indexOf("Schedule Types:"); String levels = text.substring(begin + 8, end); temp = levels.split("[ ,]"); List<String> lvs = new ArrayList<String>(); for (String s : temp) if (!s.equals("")) { lvs.add(s); } entry.setLevels(lvs); // get type and prerequisites List<Type> types = new ArrayList<Type>(); List<String> preq = new ArrayList<String>(); Elements parsing_A = body.select("a"); for (Element e : parsing_A) { if (e.attr("href").contains("schd_in") && !(e.attr("href").contains("%"))) { try { types.add(Type.valueOf(e.text().replace(" ", ""))); } catch (Exception exception) { throw new HttpParseException(); } } else if (e.attr("href").contains("sel_attr=")) { preq.add(e.text()); } } if (types.size() > 0) entry.setType(types); if (preq.size() > 0) entry.setPrerequisites(preq); // get offered by begin = text.indexOf("Offered By:"); end = text.indexOf("Department:"); if (end < 0) end = text.indexOf("Course Attributes:"); if(end>0){ entry.setOfferedBy(text.substring(begin + 12, end - 1)); } // get department begin = text.indexOf("Department:"); if (begin > 0) { end = text.indexOf("Course Attributes:"); entry.setDepartment((text.substring(begin + 12, end - 1))); } // get campus begin = text.indexOf("May be offered at any of the following campuses:"); String campuses; end = text.indexOf("Repeatable for Additional Credit:"); if (end < 0) end = text.indexOf("Learning Objectives:"); if (end < 0) end = text.indexOf("Restrictions:"); if (end < 0) end = text.indexOf("Corequisites:"); if (end < 0) end = text.indexOf("Prerequisites:"); if (end < 0) { campuses = text.substring(begin + "May be offered at any of the following campuses:".length() + 5); } else { campuses = text.substring(begin + "May be offered at any of the following campuses:".length() + 5, end - 1); } temp = campuses.replace(" ", "#").split("#"); List<String> camps = new ArrayList<String>(); for (String s : temp) { if (s.length() > 1) { camps.add(s); } } entry.setCampuses(camps); // get restrictions begin = text.indexOf("Restrictions:"); end=text.indexOf("Corequisites:"); if(end<0) end = text.indexOf("Prerequisites:"); if (begin > 0 && end < 0) { entry.setRestrictions(text.substring(begin + "Restrictions:".length()) .replace(" ", "\n")); } else if (begin > 0) { entry.setRestrictions(text.substring(begin + "Restrictions:".length(), end).replace(" ", "\n")); } } catch (StringIndexOutOfBoundsException e) { //no type, not available // System.out.println("Error for cnbr = " + cnbr); } } else { throw new CourseNotFoundException(); } return entry; } public class CatalogDetailEntry { private Subject searchSubject; private int searchCnbr; public CatalogDetailEntry(Subject subject, int cnbr) { this.searchSubject = subject; this.searchCnbr = cnbr; this.cnbr = cnbr; this.subject = subject; name = null; description = null; levels = null; type = null; offeredBy = null; department = null; campuses = null; restrictions = null; prerequisites = null; } private Subject subject; private int cnbr; private String name; private String description; private List<String> levels; private List<Type> type; private String offeredBy; private String department; private List<String> campuses; private String restrictions; private List<String> prerequisites; public String toString() { String myStr = ""; myStr += "Subject: " + subject.toString() + "\n"; myStr += "CNBR: " + cnbr + "\n"; if (name != null) myStr += "Name: " + name + "\n"; if (description != null) myStr += "Description: " + description + "\n"; if (levels != null) { myStr += "Level: "; for (String s : levels) myStr += s + " ; "; myStr += "\n"; } if (type != null) { myStr += "Type: "; for (Type t : type) myStr += t.toString() + " ; "; myStr += "\n"; } if (offeredBy != null) myStr += "OfferedBy: " + offeredBy + "\n"; if (department != null) myStr += "Department: " + department + "\n"; if (campuses != null) { myStr += "Campuses: "; for (String s : campuses) myStr += s + " ; "; myStr += "\n"; } if (restrictions != null) myStr += "Restrictions: " + restrictions + "\n"; if (prerequisites != null) { myStr += "Prerequisites: "; for (String s : prerequisites) myStr += s + " ; "; myStr += "\n"; } return myStr; } private Subject getSearchSubject() { return searchSubject; } private int getSearchCnbr() { return searchCnbr; } public Subject getSubject() { return subject; } public int getCnbr() { return cnbr; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<String> getLevels() { return levels; } public void setLevels(List<String> levels) { this.levels = levels; } public List<Type> getType() { return type; } public void setType(List<Type> type) { this.type = type; } public String getOfferedBy() { return offeredBy; } public void setOfferedBy(String offeredBy) { this.offeredBy = offeredBy; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public List<String> getCampuses() { return campuses; } public void setCampuses(List<String> campuses) { this.campuses = campuses; } public String getRestrictions() { return restrictions; } public void setRestrictions(String restrictions) { this.restrictions = restrictions; } public List<String> getPrerequisites() { return prerequisites; } public void setPrerequisites(List<String> prerequisites) { this.prerequisites = prerequisites; } } }
package net.maizegenetics.tassel; import net.maizegenetics.baseplugins.TableDisplayPlugin; import net.maizegenetics.baseplugins.TreeDisplayPlugin; import net.maizegenetics.baseplugins.Grid2dDisplayPlugin; import net.maizegenetics.baseplugins.LinkageDiseqDisplayPlugin; import net.maizegenetics.baseplugins.chart.ChartDisplayPlugin; import net.maizegenetics.baseplugins.QQDisplayPlugin; import net.maizegenetics.baseplugins.ManhattanDisplayPlugin; public class ResultControlPanel extends AbstractControlPanel { public ResultControlPanel(TASSELMainFrame theQAF, DataTreePanel theDTP) { super(theQAF, theDTP); try { addPlugin(new TableDisplayPlugin(theTASSELMainFrame, true)); addPlugin(new TreeDisplayPlugin(theTASSELMainFrame, true)); addPlugin(new Grid2dDisplayPlugin(theTASSELMainFrame, true)); addPlugin(new LinkageDiseqDisplayPlugin(theTASSELMainFrame, true)); addPlugin(new ChartDisplayPlugin(theTASSELMainFrame, true)); addPlugin(new QQDisplayPlugin(theTASSELMainFrame, true)); addPlugin(new ManhattanDisplayPlugin(theTASSELMainFrame, true)); } catch (Exception ex) { ex.printStackTrace(); } } }
package net.wurstclient.features.mods; import net.wurstclient.events.listeners.UpdateListener; @Mod.Info(description = "Allows you to see in the dark.", name = "Fullbright", tags = "NightVision, full bright, brightness, night vision", help = "Mods/Fullbright") @Mod.Bypasses public final class FullbrightMod extends Mod implements UpdateListener { public FullbrightMod() { wurst.events.add(UpdateListener.class, this); } @Override public void onDisable() { if(wurst.mods.panicMod.isActive()) mc.gameSettings.gammaSetting = 0.5F; } @Override public void onUpdate() { if(isEnabled() || wurst.mods.xRayMod.isActive()) { if(mc.gameSettings.gammaSetting < 16F) mc.gameSettings.gammaSetting += 0.5F; }else if(mc.gameSettings.gammaSetting > 0.5F) if(mc.gameSettings.gammaSetting < 1F) mc.gameSettings.gammaSetting = 0.5F; else mc.gameSettings.gammaSetting -= 0.5F; } }
package org.biojava.bio.gui.sequence; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.*; import java.util.List; import org.biojava.utils.*; import org.biojava.utils.cache.*; import org.biojava.bio.*; import org.biojava.bio.gui.*; import org.biojava.bio.symbol.*; import org.biojava.bio.seq.*; public class BumpedRenderer extends SequenceRendererWrapper { private int leadingPixles; private int trailingPixles; public BumpedRenderer() {} public BumpedRenderer(SequenceRenderer renderer) { super(renderer); } public BumpedRenderer(SequenceRenderer renderer, int leading, int trailing) { super(renderer); this.leadingPixles = leading; this.trailingPixles = trailing; } public int getLeadingPixles() { return leadingPixles; } public void setLeadingPixles(int leading) { this.leadingPixles = leading; } public int getTrailingPixles() { return trailingPixles; } public void setTrailingPixles(int trailing) { this.trailingPixles = trailing; } protected boolean hasListeners() { return super.hasListeners(); } protected ChangeSupport getChangeSupport(ChangeType ct) { return super.getChangeSupport(ct); } public double getDepth(SequenceRenderContext src) { List layers = layer(src); return LayeredRenderer.INSTANCE.getDepth( layers, Collections.nCopies(layers.size(), getRenderer()) ); } public double getMinimumLeader(SequenceRenderContext src) { List layers = layer(src); return LayeredRenderer.INSTANCE.getMinimumLeader( layers, Collections.nCopies(layers.size(), getRenderer()) ); } public double getMinimumTrailer(SequenceRenderContext src) { List layers = layer(src); return LayeredRenderer.INSTANCE.getMinimumTrailer( layers, Collections.nCopies(layers.size(), getRenderer()) ); } public void paint( Graphics2D g, SequenceRenderContext src ) { List layers = layer(src); LayeredRenderer.INSTANCE.paint( g, layers, Collections.nCopies(layers.size(), getRenderer()) ); } public SequenceViewerEvent processMouseEvent( SequenceRenderContext src, MouseEvent me, List path ) { path.add(this); List layers = layer(src); SequenceViewerEvent sve = LayeredRenderer.INSTANCE.processMouseEvent( layers, me, path, Collections.nCopies(layers.size(), getRenderer()) ); if(sve == null) { sve = new SequenceViewerEvent( this, null, src.graphicsToSequence(me.getPoint()), me, path ); } return sve; } private CacheMap contextCache = new FixedSizeMap(5); private Set flushers = new HashSet(); protected List layer(SequenceRenderContext src) { FeatureFilter filt = new FeatureFilter.OverlapsLocation(src.getRange()); CtxtFilt gopher = new CtxtFilt(src, filt, false); List layers = (List) contextCache.get(gopher); if(layers == null) { layers = doLayer(src, filt); contextCache.put(gopher, layers); CacheFlusher cf = new CacheFlusher(gopher); ((Changeable) src.getSymbols()).addChangeListener(cf, FeatureHolder.FEATURES); flushers.add(cf); } return layers; } protected List doLayer(SequenceRenderContext src, FeatureFilter filt) { FeatureHolder features = src.getFeatures(); List layers = new ArrayList(); List layerLocs = new ArrayList(); int lead = (int) (leadingPixles / src.getScale()); int trail = (int) (trailingPixles / src.getScale()); for( Iterator fi = features.filter( filt, false ).features(); fi.hasNext(); ) { Feature f = (Feature) fi.next(); try { Location fLoc = f.getLocation(); fLoc = new RangeLocation(fLoc.getMin() - lead, fLoc.getMax() + trail); Iterator li = layerLocs.iterator(); Iterator fhI = layers.iterator(); SimpleFeatureHolder fhLayer = null; List listLayer = null; LAYER: while(li.hasNext()) { List l = (List) li.next(); SimpleFeatureHolder fh = (SimpleFeatureHolder) fhI.next(); for(Iterator locI = l.iterator(); locI.hasNext(); ) { Location loc = (Location) locI.next(); if(loc.overlaps(fLoc)) { continue LAYER; } } listLayer = l; fhLayer = fh; break; } if(listLayer == null) { layerLocs.add(listLayer = new ArrayList()); layers.add(fhLayer = new SimpleFeatureHolder()); } listLayer.add(fLoc); fhLayer.addFeature(f); } catch (ChangeVetoException cve) { throw new BioError(cve, "Pants"); } catch (Throwable t) { throw new NestedError(t, "Could not bump feature: " + f); } } List contexts = new ArrayList(layers.size()); for(Iterator i = layers.iterator(); i.hasNext(); ) { FeatureHolder layer = (FeatureHolder) i.next(); contexts.add(new SubSequenceRenderContext( src, null, layer, null )); } return contexts; } private class CacheFlusher implements ChangeListener { private CtxtFilt ctxtFilt; public CacheFlusher(CtxtFilt ctxtFilt) { this.ctxtFilt = ctxtFilt; } public void preChange(ChangeEvent ce) { } public void postChange(ChangeEvent ce) { contextCache.remove(ctxtFilt); flushers.remove(this); if(hasListeners()) { ChangeSupport cs = getChangeSupport(SequenceRenderContext.LAYOUT); synchronized(cs) { ChangeEvent ce2 = new ChangeEvent( BumpedRenderer.this, SequenceRenderContext.LAYOUT ); cs.firePostChangeEvent(ce2); } } } } private class CtxtFilt { private SequenceRenderContext src; private FeatureFilter filter; private boolean recurse; public CtxtFilt(SequenceRenderContext src, FeatureFilter filter, boolean recurse) { this.src = src; this.filter = filter; this.recurse = recurse; } public boolean equals(Object o) { if(! (o instanceof CtxtFilt) ) { return false; } CtxtFilt that = (CtxtFilt) o; return src.equals(that.src) && filter.equals(that.filter) && (recurse == that.recurse); } public int hashCode() { return src.hashCode() ^ filter.hashCode(); } } }
package org.broad.igv.ui.panel; import org.broad.igv.track.AttributeManager; import org.broad.igv.ui.FontManager; import org.broad.igv.ui.IGV; import javax.swing.*; import javax.swing.event.MouseInputAdapter; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.util.*; import java.util.List; /** * @author jrobinso */ public class AttributeHeaderPanel extends JPanel { final static int MAXIMUM_FONT_SIZE = 10; public final static int ATTRIBUTE_COLUMN_WIDTH = 10; public final static int COLUMN_BORDER_WIDTH = 2; Map<String, Boolean> sortOrder = new HashMap(); public AttributeHeaderPanel() { setBorder(javax.swing.BorderFactory.createLineBorder(Color.black)); setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); addMouseListener(); } public int getAttributeColumnWidth() { return ATTRIBUTE_COLUMN_WIDTH; } private String getAttributeHeading(int x) { int idx = x / (ATTRIBUTE_COLUMN_WIDTH + COLUMN_BORDER_WIDTH); List<String> keys = AttributeManager.getInstance().getVisibleAttributes(); if (idx < keys.size()) { return keys.get(idx); } else { return null; } } @Override protected void paintComponent(final Graphics graphics) { super.paintComponent(graphics); final List<String> keys = AttributeManager.getInstance().getVisibleAttributes(); if (keys.size() > 0) { final Graphics2D graphics2 = (Graphics2D) graphics.create(); // Divide the remaining space to get column widths int columnWidth = getAttributeColumnWidth(); // Create font and font size int fontSize = (int) (0.9 * columnWidth); if (fontSize > MAXIMUM_FONT_SIZE) { fontSize = MAXIMUM_FONT_SIZE; } Font font = FontManager.getFont(fontSize); // Change the origin for the text AffineTransform transform = AffineTransform.getTranslateInstance(0, getHeight() - COLUMN_BORDER_WIDTH); graphics2.transform(transform); // Now rotate text counter-clockwise 90 degrees transform = AffineTransform.getRotateInstance(-Math.PI / 2); graphics2.transform(transform); graphics2.setFont(font); FontMetrics fm = graphics2.getFontMetrics(); int fontAscent = fm.getHeight(); int i = 1; int x; for (String key : keys) { int columnLeftEdge = ((COLUMN_BORDER_WIDTH + ATTRIBUTE_COLUMN_WIDTH) * i++); x = columnLeftEdge + ((COLUMN_BORDER_WIDTH + ATTRIBUTE_COLUMN_WIDTH) - fontAscent) / 2; graphics2.drawString(key, 0, x); } } } private void addMouseListener() { setToolTipText("Click attribute heading to sort"); MouseInputAdapter listener = new MouseInputAdapter() { @Override public void mouseClicked(MouseEvent e) { String attKey = getAttributeHeading(e.getX()); if (attKey != null) { Boolean tmp = sortOrder.get(attKey); boolean sortAscending = tmp == null ? true : tmp.booleanValue(); sortTrackByAttribute(attKey, sortAscending); sortOrder.put(attKey, !sortAscending); } } @Override public void mouseMoved(MouseEvent e) { String attKey = getAttributeHeading(e.getX()); if (attKey == null) { setToolTipText("Click attribute heading to sort"); } else { setToolTipText("<html>" + attKey + "<br>Click to sort"); } } }; addMouseMotionListener(listener); addMouseListener(listener); } final public void sortTrackByAttribute(String sortKey, boolean isSortAscending) { if (sortKey != null) { IGV.getInstance().getTrackManager().sortAllTracksByAttributes(new String[]{sortKey}, new boolean[]{isSortAscending}); IGV.getMainFrame().repaint(); } } }
package com.el1t.iolite; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.View; import com.el1t.iolite.item.EighthActivity; import com.el1t.iolite.parser.EighthActivityJsonParser; import org.json.JSONException; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import javax.net.ssl.HttpsURLConnection; public class SignupActivity extends AppCompatActivity implements SignupFragment.OnFragmentInteractionListener { private static final String TAG = "Signup Activity"; private SignupFragment mSignupFragment; private int BID; private String mAuthKey; private boolean fake; private ArrayList<AsyncTask> mTasks; public enum Response { SUCCESS, CAPACITY, RESTRICTED, CANCELLED, PRESIGN, ATTENDANCE_TAKEN, FAIL } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); final Intent intent = getIntent(); BID = intent.getIntExtra("BID", -1); mTasks = new ArrayList<>(); // Check if restoring from previously destroyed instance that matches the BID if (savedInstanceState == null || BID != savedInstanceState.getInt("BID")) { // Check if fake information should be used if (fake = intent.getBooleanExtra("fake", false)) { Log.d(TAG, "Loading fake info"); // Pretend fake list was received postRequest(getList()); } } else { fake = savedInstanceState.getBoolean("fake"); mSignupFragment = (SignupFragment) getFragmentManager().getFragment(savedInstanceState, "fragment"); } // Retrieve authKey from shared preferences if (!fake) { final SharedPreferences preferences = getSharedPreferences(LoginActivity.PREFS_NAME, MODE_PRIVATE); mAuthKey = Utils.getAuthKey(preferences); } // Use material design toolbar final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); } getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override protected void onResume() { super.onResume(); // Load list of blocks from web refresh(); } @Override protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putInt("BID", BID); savedInstanceState.putBoolean("fake", fake); getFragmentManager().putFragment(savedInstanceState, "fragment", mSignupFragment); } @Override public void onDestroy() { // Try to cancel tasks when destroying for (AsyncTask a : mTasks) { a.cancel(true); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.eighth_signup, menu); final SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search)); if (searchView != null) { searchView.setSearchableInfo(manager.getSearchableInfo(getComponentName())); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String query) { if (mSignupFragment != null) { mSignupFragment.filter(query); } return true; } @Override public boolean onQueryTextSubmit(String query) { return true; } }); } return super.onCreateOptionsMenu(menu); } public void refresh() { if (!fake) { // Set loading fragment, if necessary if (mSignupFragment == null) { // Set loading fragment getFragmentManager().beginTransaction() .add(R.id.container, new LoadingFragment()) .commit(); } // Retrieve list for bid using cookies mTasks.add(new ActivityListRequest(BID).execute()); } else { // Reload offline list postRequest(getList()); } } // Try signing up for an activity public void submit(EighthActivity item) { // Perform checks before submission // Note that server performs checks as well if (item.isCancelled()) { showSnackbar(Response.CANCELLED); } else if (item.isFull()) { showSnackbar(Response.CAPACITY); } else if (item.isRestricted()) { showSnackbar(Response.RESTRICTED); } else { mTasks.add(new SignupRequest(item.getAID(), item.getBID()).execute()); } } // Display details for activity public void viewDetails(EighthActivity activityItem) { final Intent intent = new Intent(this, DetailActivity.class); intent.putExtra("activity", activityItem); intent.putExtra("fake", fake); startActivity(intent); } // Notify the user of server response void showSnackbar(Response result) { switch(result) { case SUCCESS: // TODO: Pass success to home activity Log.d(TAG, "Sign up success"); finish(); break; case CAPACITY: Snackbar.make(findViewById(R.id.container), "Capacity exceeded", Snackbar.LENGTH_SHORT).show(); Log.d(TAG, "Capacity exceeded"); break; case RESTRICTED: Snackbar.make(findViewById(R.id.container), "Activity restricted", Snackbar.LENGTH_SHORT).show(); Log.d(TAG, "Restricted activity"); break; case CANCELLED: Snackbar.make(findViewById(R.id.container), "Activity cancelled", Snackbar.LENGTH_SHORT).show(); Log.d(TAG, "Cancelled activity"); break; case PRESIGN: Snackbar.make(findViewById(R.id.container), "Activity signup not open yet", Snackbar.LENGTH_SHORT).show(); Log.d(TAG, "Presign activity"); break; case ATTENDANCE_TAKEN: Snackbar.make(findViewById(R.id.container), "Signup closed", Snackbar.LENGTH_SHORT).show(); Log.d(TAG, "Attendance taken"); break; case FAIL: // TODO: Make this error message reflect the actual error Snackbar.make(findViewById(R.id.container), "Fatal error", Snackbar.LENGTH_SHORT).show(); Log.w(TAG, "Sign up failure"); break; } } // Do after getting list of activities private void postRequest(EighthActivity[] result) { if (mSignupFragment == null) { // Create the content view mSignupFragment = new SignupFragment(); // Add ArrayList to the ListView in BlockFragment final Bundle args = new Bundle(); args.putParcelableArray("list", result); mSignupFragment.setArguments(args); // Switch to BlockFragment view, remove LoadingFragment getFragmentManager().beginTransaction() .replace(R.id.container, mSignupFragment) .commit(); } else { mSignupFragment.setListItems(result); } } // Favorite an activity public void favorite(final int AID, final int BID, final EighthActivity item) { // Note: the server uses the UID field as the AID in its API // Sending the BID is useless, but it is required by the server mTasks.add(new ServerRequest("eighth/vcp_schedule/favorite/uid/" + AID + "/bids/" + BID).execute()); if (item.changeFavorite()) { Snackbar.make(findViewById(R.id.container), "Favorited", Snackbar.LENGTH_SHORT) .setAction("Undo", new View.OnClickListener() { @Override public void onClick(View view) { mTasks.add(new ServerRequest("eighth/vcp_schedule/favorite/uid/" + AID + "/bids/" + BID) .execute()); item.changeFavorite(); mSignupFragment.updateAdapter(); } }).show(); } else { Snackbar.make(findViewById(R.id.container), "Unfavorited", Snackbar.LENGTH_SHORT) .setAction("Undo", new View.OnClickListener() { @Override public void onClick(View view) { mTasks.add(new ServerRequest("eighth/vcp_schedule/favorite/uid/" + AID + "/bids/" + BID) .execute()); item.changeFavorite(); mSignupFragment.updateAdapter(); } }).show(); } Log.d(TAG, "Favorited AID " + AID); } // Get a fake list of activities for debugging private EighthActivity[] getList() { try { return EighthActivityJsonParser.parseAll(getAssets().open("testActivityList.json")); } catch (Exception e) { Log.e(TAG, "Error parsing activity xml", e); } return null; } // Retrieve activity list for BID from server using HttpURLConnection private class ActivityListRequest extends AsyncTask<Void, Void, EighthActivity[]> { private static final String TAG = "ActivityListRequest"; private static final String URL = "https://ion.tjhsst.edu/api/blocks/"; private int BID; public ActivityListRequest(int BID) { this.BID = BID; } @Override protected EighthActivity[] doInBackground(Void... params) { final HttpsURLConnection urlConnection; EighthActivity[] response = null; try { urlConnection = (HttpsURLConnection) new URL(URL + BID).openConnection(); // Add authKey to header urlConnection.setRequestProperty("Authorization", mAuthKey); // Begin connection urlConnection.connect(); // Parse xml from server response = EighthActivityJsonParser.parseAll(urlConnection.getInputStream()); // Close connection urlConnection.disconnect(); } catch (JSONException | ParseException e) { Log.e(TAG, "Parsing error.", e); } catch (IOException e) { Log.e(TAG, "Connection error.", e); } return response; } @Override protected void onPostExecute(EighthActivity[] result) { super.onPostExecute(result); mTasks.remove(this); // Add ArrayList to the ListView in SignupFragment postRequest(result); } } // Web request for activity signup using HttpClient private class SignupRequest extends AsyncTask<Void, Void, Boolean> { private static final String TAG = "Signup Connection"; private static final String URL = "https://ion.tjhsst.edu/api/signups/user"; private final String AID; private final String BID; public SignupRequest(int AID, int BID) { this.AID = Integer.toString(AID); this.BID = Integer.toString(BID); } @Override protected Boolean doInBackground(Void... params) { final HttpsURLConnection urlConnection; try { urlConnection = (HttpsURLConnection) new URL(URL).openConnection(); // Add auth token urlConnection.setRequestProperty("Authorization", mAuthKey); // Add parameters urlConnection.addRequestProperty("block", BID); urlConnection.addRequestProperty("activity", AID); // Send request urlConnection.connect(); urlConnection.getInputStream(); urlConnection.disconnect(); return true; } catch (IOException e) { Log.e(TAG, "Connection error.", e); } return false; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); mTasks.remove(this); if (result) { showSnackbar(Response.SUCCESS); } else { showSnackbar(Response.FAIL); } } } // Ping the server, discard response and do nothing afterwards private class ServerRequest extends AsyncTask<Void, Void, Boolean> { private static final String TAG = "Server Ping"; private static final String URL = "https://iodine.tjhsst.edu/"; private final String domain; public ServerRequest(String domain) { this.domain = domain; } @Override protected Boolean doInBackground(Void... params) { final HttpsURLConnection urlConnection; try { urlConnection = (HttpsURLConnection) new URL(URL + domain).openConnection(); // Add auth token urlConnection.setRequestProperty("Authorization", mAuthKey); // Begin connection urlConnection.connect(); urlConnection.getInputStream(); // Close connection urlConnection.disconnect(); return true; } catch (IOException e) { Log.e(TAG, "Connection error.", e); } return false; } @Override protected void onPostExecute(Boolean result) { mTasks.remove(this); } } }
package org.fife.ui.rsyntaxtextarea; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Window; import java.awt.datatransfer.Clipboard; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.font.FontRenderContext; import java.io.File; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.event.CaretEvent; import javax.swing.event.EventListenerList; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.Highlighter; import org.fife.ui.rsyntaxtextarea.focusabletip.FocusableTip; import org.fife.ui.rsyntaxtextarea.folding.Fold; import org.fife.ui.rsyntaxtextarea.folding.FoldManager; import org.fife.ui.rsyntaxtextarea.parser.Parser; import org.fife.ui.rsyntaxtextarea.parser.ParserNotice; import org.fife.ui.rsyntaxtextarea.parser.ToolTipInfo; import org.fife.ui.rtextarea.Gutter; import org.fife.ui.rtextarea.RTextArea; import org.fife.ui.rtextarea.RTextAreaUI; import org.fife.ui.rtextarea.RTextScrollPane; import org.fife.ui.rtextarea.RecordableTextAction; /** * An extension of <code>RTextArea</code> that adds syntax highlighting * of certain programming languages to its list of features. Languages * currently supported include: * * <table> * <tr> * <td style="vertical-align: top"> * <ul> * <li>ActionScript * <li>Assembler (X86) * <li>BBCode * <li>C * <li>C++ * <li>CSS * <li>C# * <li>Clojure * <li>Delphi * <li>DTD * <li>Fortran * <li>Groovy * <li>HTML * <li>htaccess * <li>Java * <li>JavaScript * <li>JSP * </ul> * </td> * <td style="vertical-align: top"> * <ul> * <li>LaTeX * <li>Lisp * <li>Lua * <li>Make * <li>MXML * <li>NSIS * <li>Perl * <li>PHP * <li>Ruby * <li>SAS * <li>Scala * <li>SQL * <li>Tcl * <li>UNIX shell scripts * <li>Windows batch * <li>XML files * </ul> * </td> * </tr> * </table> * * Other added features include: * <ul style="columns: 2 12em; column-gap: 1em"> * <li>Code folding * <li>Bracket matching * <li>Auto-indentation * <li>Copy as RTF * <li>Clickable hyperlinks (if the language scanner being used supports it) * <li>A pluggable "parser" system that can be used to implement syntax * validation, spell checking, etc. * </ul> * * It is recommended that you use an instance of * {@link org.fife.ui.rtextarea.RTextScrollPane} instead of a regular * <code>JScrollPane</code> as this class allows you to add line numbers and * bookmarks easily to your text area. * * @author Robert Futrell * @version 2.5.2 * @see TextEditorPane */ public class RSyntaxTextArea extends RTextArea implements SyntaxConstants { public static final String ANIMATE_BRACKET_MATCHING_PROPERTY = "RSTA.animateBracketMatching"; public static final String ANTIALIAS_PROPERTY = "RSTA.antiAlias"; public static final String AUTO_INDENT_PROPERTY = "RSTA.autoIndent"; public static final String BRACKET_MATCHING_PROPERTY = "RSTA.bracketMatching"; public static final String CLEAR_WHITESPACE_LINES_PROPERTY = "RSTA.clearWhitespaceLines"; public static final String CLOSE_CURLY_BRACES_PROPERTY = "RSTA.closeCurlyBraces"; public static final String CLOSE_MARKUP_TAGS_PROPERTY = "RSTA.closeMarkupTags"; public static final String CODE_FOLDING_PROPERTY = "RSTA.codeFolding"; public static final String EOL_VISIBLE_PROPERTY = "RSTA.eolMarkersVisible"; public static final String FOCUSABLE_TIPS_PROPERTY = "RSTA.focusableTips"; public static final String FRACTIONAL_FONTMETRICS_PROPERTY = "RSTA.fractionalFontMetrics"; public static final String HIGHLIGHT_SECONDARY_LANGUAGES_PROPERTY = "RSTA.highlightSecondaryLanguages"; public static final String HYPERLINKS_ENABLED_PROPERTY = "RSTA.hyperlinksEnabled"; public static final String MARK_OCCURRENCES_PROPERTY = "RSTA.markOccurrences"; public static final String MARKED_OCCURRENCES_CHANGED_PROPERTY = "RSTA.markedOccurrencesChanged"; public static final String PAINT_MATCHED_BRACKET_PAIR_PROPERTY = "RSTA.paintMatchedBracketPair"; public static final String PARSER_NOTICES_PROPERTY = "RSTA.parserNotices"; public static final String SYNTAX_SCHEME_PROPERTY = "RSTA.syntaxScheme"; public static final String SYNTAX_STYLE_PROPERTY = "RSTA.syntaxStyle"; public static final String TAB_LINE_COLOR_PROPERTY = "RSTA.tabLineColor"; public static final String TAB_LINES_PROPERTY = "RSTA.tabLines"; public static final String USE_SELECTED_TEXT_COLOR_PROPERTY = "RSTA.useSelectedTextColor"; public static final String VISIBLE_WHITESPACE_PROPERTY = "RSTA.visibleWhitespace"; private static final Color DEFAULT_BRACKET_MATCH_BG_COLOR = new Color(234,234,255); private static final Color DEFAULT_BRACKET_MATCH_BORDER_COLOR = new Color(0,0,128); private static final Color DEFAULT_SELECTION_COLOR = new Color(200,200,255); private static final String MSG = "org.fife.ui.rsyntaxtextarea.RSyntaxTextArea"; private JMenu foldingMenu; private static RecordableTextAction toggleCurrentFoldAction; private static RecordableTextAction collapseAllCommentFoldsAction; private static RecordableTextAction collapseAllFoldsAction; private static RecordableTextAction expandAllFoldsAction; /** The key for the syntax style to be highlighting. */ private String syntaxStyleKey; /** The colors used for syntax highlighting. */ private SyntaxScheme syntaxScheme; /** Handles code templates. */ private static CodeTemplateManager codeTemplateManager; /** Whether or not templates are enabled. */ private static boolean templatesEnabled; /** * The rectangle surrounding the "matched bracket" if bracket matching * is enabled. */ private Rectangle match; /** * The rectangle surrounding the current offset if both bracket matching and * "match both brackets" are enabled. */ private Rectangle dotRect; /** * Used to store the location of the bracket at the caret position (either * just before or just after it) and the location of its match. */ private Point bracketInfo; /** * Colors used for the "matched bracket" if bracket matching is enabled. */ private Color matchedBracketBGColor; private Color matchedBracketBorderColor; /** The location of the last matched bracket. */ private int lastBracketMatchPos; /** Whether or not bracket matching is enabled. */ private boolean bracketMatchingEnabled; /** Whether or not bracket matching is animated. */ private boolean animateBracketMatching; /** Whether <b>both</b> brackets are highlighted when bracket matching. */ private boolean paintMatchedBracketPair; private BracketMatchingTimer bracketRepaintTimer; private boolean metricsNeverRefreshed; /** * Whether or not auto-indent is on. */ private boolean autoIndentEnabled; /** * Whether curly braces should be closed on Enter key presses, (if the * current language supports it). */ private boolean closeCurlyBraces; /** * Whether closing markup tags should be automatically completed when * "<code>&lt;/</code>" is typed (if the current language is a markup * language). */ private boolean closeMarkupTags; /** * Whether or not lines with nothing but whitespace are "made empty." */ private boolean clearWhitespaceLines; /** Whether we are displaying visible whitespace (spaces and tabs). */ private boolean whitespaceVisible; /** Whether EOL markers should be visible at the end of each line. */ private boolean eolMarkersVisible; /** Whether tab lines are enabled. */ private boolean paintTabLines; /** The color to use when painting tab lines. */ private Color tabLineColor; /** * Whether hyperlinks are enabled (must be supported by the syntax * scheme being used). */ private boolean hyperlinksEnabled; /** The color to use when painting hyperlinks. */ private Color hyperlinkFG; /** * Mask used to determine if the correct key is being held down to scan * for hyperlinks (ctrl, meta, etc.). */ private int linkScanningMask; /** Whether secondary languages have their backgrounds colored. */ private boolean highlightSecondaryLanguages; /** Whether the "selected text" color should be used with selected text. */ private boolean useSelectedTextColor; /** Handles "mark occurrences" support. */ private MarkOccurrencesSupport markOccurrencesSupport; /** The color used to render "marked occurrences." */ private Color markOccurrencesColor; /** Whether a border should be painted around marked occurrences. */ private boolean paintMarkOccurrencesBorder; /** Metrics of the text area's font. */ private FontMetrics defaultFontMetrics; /** Manages running the parser. */ private ParserManager parserManager; /** * Whether the editor is currently scanning for hyperlinks on mouse * movement. */ private boolean isScanningForLinks; private int hoveredOverLinkOffset; private LinkGenerator linkGenerator; private LinkGeneratorResult linkGeneratorResult; private int rhsCorrection; private FoldManager foldManager; /** Whether "focusable" tool tips are used instead of standard ones. */ private boolean useFocusableTips; /** The last focusable tip displayed. */ private FocusableTip focusableTip; /** Cached desktop anti-aliasing hints, if anti-aliasing is enabled. */ private Map<?,?> aaHints; /** Renders tokens. */ private TokenPainter tokenPainter; private int lineHeight; // Height of a line of text; same for default, bold & italic. private int maxAscent; private boolean fractionalFontMetricsEnabled; private Color[] secondaryLanguageBackgrounds; /** * Constructor. */ public RSyntaxTextArea() { } /** * Constructor. * * @param doc The document for the editor. */ public RSyntaxTextArea(RSyntaxDocument doc) { super(doc); } /** * Constructor. * * @param text The initial text to display. */ public RSyntaxTextArea(String text) { super(text); } public RSyntaxTextArea(int rows, int cols) { super(rows, cols); } public RSyntaxTextArea(String text, int rows, int cols) { super(text, rows, cols); } public RSyntaxTextArea(RSyntaxDocument doc, String text,int rows,int cols) { super(doc, text, rows, cols); } /** * Creates a new <code>RSyntaxTextArea</code>. * * @param textMode Either <code>INSERT_MODE</code> or * <code>OVERWRITE_MODE</code>. */ public RSyntaxTextArea(int textMode) { super(textMode); } /** * Adds an "active line range" listener to this text area. * * @param l The listener to add. * @see #removeActiveLineRangeListener(ActiveLineRangeListener) */ public void addActiveLineRangeListener(ActiveLineRangeListener l) { listenerList.add(ActiveLineRangeListener.class, l); } /** * Adds a hyperlink listener to this text area. * * @param l The listener to add. * @see #removeHyperlinkListener(HyperlinkListener) */ public void addHyperlinkListener(HyperlinkListener l) { listenerList.add(HyperlinkListener.class, l); } /** * Updates the font metrics the first time we're displayed. */ @Override public void addNotify() { super.addNotify(); // Some LookAndFeels (e.g. WebLaF) for some reason have a 0x0 parent // window initially (perhaps something to do with them fading in?), // which will cause an exception from getGraphics(), so we must be // careful here. if (metricsNeverRefreshed) { Window parent = SwingUtilities.getWindowAncestor(this); if (parent!=null && parent.getWidth()>0 && parent.getHeight()>0) { refreshFontMetrics(getGraphics2D(getGraphics())); metricsNeverRefreshed = false; } } // Re-start parsing if we were removed from one container and added // to another if (parserManager!=null) { parserManager.restartParsing(); } } /** * Adds the parser to "validate" the source code in this text area. This * can be anything from a spell checker to a "compiler" that verifies * source code. * * @param parser The new parser. A value of <code>null</code> will * do nothing. * @see #getParser(int) * @see #getParserCount() * @see #removeParser(Parser) */ public void addParser(Parser parser) { if (parserManager==null) { parserManager = new ParserManager(this); } parserManager.addParser(parser); } /** * Appends a submenu with code folding options to this text component's * popup menu. * * @param popup The popup menu to append to. * @see #createPopupMenu() */ protected void appendFoldingMenu(JPopupMenu popup) { popup.addSeparator(); ResourceBundle bundle = ResourceBundle.getBundle(MSG); foldingMenu = new JMenu(bundle.getString("ContextMenu.Folding")); foldingMenu.add(createPopupMenuItem(toggleCurrentFoldAction)); foldingMenu.add(createPopupMenuItem(collapseAllCommentFoldsAction)); foldingMenu.add(createPopupMenuItem(collapseAllFoldsAction)); foldingMenu.add(createPopupMenuItem(expandAllFoldsAction)); popup.add(foldingMenu); } /** * Recalculates the height of a line in this text area and the * maximum ascent of all fonts displayed. */ private void calculateLineHeight() { lineHeight = maxAscent = 0; // Each token style. for (int i=0; i<syntaxScheme.getStyleCount(); i++) { Style ss = syntaxScheme.getStyle(i); if (ss!=null && ss.font!=null) { FontMetrics fm = getFontMetrics(ss.font); int height = fm.getHeight(); if (height>lineHeight) lineHeight = height; int ascent = fm.getMaxAscent(); if (ascent>maxAscent) maxAscent = ascent; } } // The text area's (default) font). Font temp = getFont(); FontMetrics fm = getFontMetrics(temp); int height = fm.getHeight(); if (height>lineHeight) { lineHeight = height; } int ascent = fm.getMaxAscent(); if (ascent>maxAscent) { maxAscent = ascent; } } /** * Removes all parsers from this text area. * * @see #removeParser(Parser) */ public void clearParsers() { if (parserManager!=null) { parserManager.clearParsers(); } } /** * Clones a token list. This is necessary as tokens are reused in * {@link RSyntaxDocument}, so we can't simply use the ones we * are handed from it. * * @param t The token list to clone. * @return The clone of the token list. */ private TokenImpl cloneTokenList(Token t) { if (t==null) { return null; } TokenImpl clone = new TokenImpl(t); TokenImpl cloneEnd = clone; while ((t=t.getNextToken())!=null) { TokenImpl temp = new TokenImpl(t); cloneEnd.setNextToken(temp); cloneEnd = temp; } return clone; } /** * Overridden to toggle the enabled state of various * RSyntaxTextArea-specific menu items. * * If you set the popup menu via {@link #setPopupMenu(JPopupMenu)}, you * will want to override this method, especially if you removed any of the * menu items in the default popup menu. * * @param popupMenu The popup menu. This will never be <code>null</code>. * @see #createPopupMenu() * @see #setPopupMenu(JPopupMenu) */ @Override protected void configurePopupMenu(JPopupMenu popupMenu) { super.configurePopupMenu(popupMenu); // They may have overridden createPopupMenu()... if (popupMenu!=null && popupMenu.getComponentCount()>0 && foldingMenu!=null) { foldingMenu.setEnabled(foldManager. isCodeFoldingSupportedAndEnabled()); } } /** * Copies the currently selected text to the system clipboard, with * any necessary style information (font, foreground color and background * color). Does nothing for <code>null</code> selections. */ public void copyAsRtf() { int selStart = getSelectionStart(); int selEnd = getSelectionEnd(); if (selStart==selEnd) { return; } // Make sure there is a system clipboard, and that we can write // to it. SecurityManager sm = System.getSecurityManager(); if (sm!=null) { try { sm.checkSystemClipboardAccess(); } catch (SecurityException se) { UIManager.getLookAndFeel().provideErrorFeedback(null); return; } } Clipboard cb = getToolkit().getSystemClipboard(); // Create the RTF selection. RtfGenerator gen = new RtfGenerator(); Token tokenList = getTokenListFor(selStart, selEnd); for (Token t=tokenList; t!=null; t=t.getNextToken()) { if (t.isPaintable()) { if (t.length()==1 && t.charAt(0)=='\n') { gen.appendNewline(); } else { Font font = getFontForTokenType(t.getType()); Color bg = getBackgroundForToken(t); boolean underline = getUnderlineForToken(t); // Small optimization - don't print fg color if this // is a whitespace color. Saves on RTF size. if (t.isWhitespace()) { gen.appendToDocNoFG(t.getLexeme(), font, bg, underline); } else { Color fg = getForegroundForToken(t); gen.appendToDoc(t.getLexeme(), font, fg, bg, underline); } } } } // Set the system clipboard contents to the RTF selection. RtfTransferable contents = new RtfTransferable(gen.getRtf().getBytes()); try { cb.setContents(contents, null); } catch (IllegalStateException ise) { UIManager.getLookAndFeel().provideErrorFeedback(null); return; } } /** * Returns the document to use for an <code>RSyntaxTextArea</code> * * @return The document. */ @Override protected Document createDefaultModel() { return new RSyntaxDocument(SYNTAX_STYLE_NONE); } /** * Returns the caret event/mouse listener for <code>RTextArea</code>s. * * @return The caret event/mouse listener. */ @Override protected RTAMouseListener createMouseListener() { return new RSyntaxTextAreaMutableCaretEvent(this); } /** * Overridden to add menu items related to cold folding. * * @return The popup menu. * @see #appendFoldingMenu(JPopupMenu) */ @Override protected JPopupMenu createPopupMenu() { JPopupMenu popup = super.createPopupMenu(); appendFoldingMenu(popup); return popup; } /** * See createPopupMenuActions() in RTextArea. * TODO: Remove these horrible hacks and move localizing of actions into * the editor kits, where it should be! The context menu should contain * actions from the editor kits. */ private static void createRstaPopupMenuActions() { ResourceBundle msg = ResourceBundle.getBundle(MSG); toggleCurrentFoldAction = new RSyntaxTextAreaEditorKit. ToggleCurrentFoldAction(); toggleCurrentFoldAction.setProperties(msg, "Action.ToggleCurrentFold"); collapseAllCommentFoldsAction = new RSyntaxTextAreaEditorKit. CollapseAllCommentFoldsAction(); collapseAllCommentFoldsAction.setProperties(msg, "Action.CollapseCommentFolds"); collapseAllFoldsAction = new RSyntaxTextAreaEditorKit.CollapseAllFoldsAction(true); expandAllFoldsAction = new RSyntaxTextAreaEditorKit.ExpandAllFoldsAction(true); } /** * Returns the a real UI to install on this text area. * * @return The UI. */ @Override protected RTextAreaUI createRTextAreaUI() { return new RSyntaxTextAreaUI(this); } /** * If the caret is on a bracket, this method finds the matching bracket, * and if it exists, highlights it. */ protected final void doBracketMatching() { // We always need to repaint the "matched bracket" highlight if it // exists. if (match!=null) { repaint(match); if (dotRect!=null) { repaint(dotRect); } } // If a matching bracket is found, get its bounds and paint it! int lastCaretBracketPos = bracketInfo==null ? -1 : bracketInfo.x; bracketInfo = RSyntaxUtilities.getMatchingBracketPosition(this, bracketInfo); if (bracketInfo.y>-1 && (bracketInfo.y!=lastBracketMatchPos || bracketInfo.x!=lastCaretBracketPos)) { try { match = modelToView(bracketInfo.y); if (match!=null) { // Happens if we're not yet visible if (getPaintMatchedBracketPair()) { dotRect = modelToView(bracketInfo.x); } else { dotRect = null; } if (getAnimateBracketMatching()) { bracketRepaintTimer.restart(); } repaint(match); if (dotRect!=null) { repaint(dotRect); } } } catch (BadLocationException ble) { ble.printStackTrace(); // Shouldn't happen. } } else if (bracketInfo.y==-1) { // Set match to null so the old value isn't still repainted. match = null; dotRect = null; bracketRepaintTimer.stop(); } lastBracketMatchPos = bracketInfo.y; } /** * Notifies all listeners that a caret change has occurred. * * @param e The caret event. */ @Override protected void fireCaretUpdate(CaretEvent e) { super.fireCaretUpdate(e); if (isBracketMatchingEnabled()) { doBracketMatching(); } } /** * Notifies all listeners that the active line range has changed. * * @param min The minimum "active" line, or <code>-1</code>. * @param max The maximum "active" line, or <code>-1</code>. */ private void fireActiveLineRangeEvent(int min, int max) { ActiveLineRangeEvent e = null; // Lazily created // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==ActiveLineRangeListener.class) { if (e==null) { e = new ActiveLineRangeEvent(this, min, max); } ((ActiveLineRangeListener)listeners[i+1]).activeLineRangeChanged(e); } } } /** * Notifies all listeners that have registered interest for notification * on this event type. The listener list is processed last to first. * * @param e The event to fire. * @see EventListenerList */ private void fireHyperlinkUpdate(HyperlinkEvent e) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==HyperlinkListener.class) { ((HyperlinkListener)listeners[i+1]).hyperlinkUpdate(e); } } } /** * Notifies listeners that the marked occurrences for this text area * have changed. */ void fireMarkedOccurrencesChanged() { firePropertyChange(RSyntaxTextArea.MARKED_OCCURRENCES_CHANGED_PROPERTY, null, null); } /** * Fires a notification that the parser notices for this text area have * changed. */ void fireParserNoticesChange() { firePropertyChange(PARSER_NOTICES_PROPERTY, null, null); } /** * Called whenever a fold is collapsed or expanded. This causes the * text editor to revalidate. This method is here because of poor design * and should be removed. * * @param fold The fold that was collapsed or expanded. */ public void foldToggled(Fold fold) { match = null; // TODO: Update the bracket rect rather than hide it dotRect = null; if (getLineWrap()) { // NOTE: Without doing this later, the caret position is out of // sync with the Element structure when word wrap is enabled, and // causes BadLocationExceptions when an entire folded region is // deleted (see GitHub issue SwingUtilities.invokeLater(new Runnable() { public void run() { possiblyUpdateCurrentLineHighlightLocation(); } }); } else { possiblyUpdateCurrentLineHighlightLocation(); } revalidate(); repaint(); } /** * Forces the given {@link Parser} to re-parse the content of this text * area.<p> * * This method can be useful when a <code>Parser</code> can be configured * as to what notices it returns. For example, if a Java language parser * can be configured to set whether no serialVersionUID is a warning, * error, or ignored, this method can be called after changing the expected * notice type to have the document re-parsed. * * @param parser The index of the <code>Parser</code> to re-run. * @see #getParser(int) */ public void forceReparsing(int parser) { parserManager.forceReparsing(parser); } /** * Forces re-parsing with a specific parser. Note that if this parser is * not installed on this text area, nothing will happen. * * @param parser The parser that should re-parse this text area's contents. * This should be installed on this text area. * @return Whether the parser was installed on this text area. * @see #forceReparsing(int) */ public boolean forceReparsing(Parser parser) { for (int i=0; i<getParserCount(); i++) { if (getParser(i)==parser) { forceReparsing(i); return true; } } return false; } /** * Returns whether bracket matching should be animated. * * @return Whether bracket matching should be animated. * @see #setAnimateBracketMatching(boolean) */ public boolean getAnimateBracketMatching() { return animateBracketMatching; } /** * Returns whether anti-aliasing is enabled in this editor. * * @return Whether anti-aliasing is enabled in this editor. * @see #setAntiAliasingEnabled(boolean) * @see #getFractionalFontMetricsEnabled() */ public boolean getAntiAliasingEnabled() { return aaHints!=null; } /** * Returns the background color for a token. * * @param token The token. * @return The background color to use for that token. If this value is * is <code>null</code> then this token has no special background * color. * @see #getForegroundForToken(Token) */ public Color getBackgroundForToken(Token token) { Color c = null; if (getHighlightSecondaryLanguages()) { // 1-indexed, since 0 == main language. int languageIndex = token.getLanguageIndex() - 1; if (languageIndex>=0 && languageIndex<secondaryLanguageBackgrounds.length) { c = secondaryLanguageBackgrounds[languageIndex]; } } if (c==null) { c = syntaxScheme.getStyle(token.getType()).background; } // Don't default to this.getBackground(), as Tokens simply don't // paint a background if they get a null Color. return c; } /** * Returns whether curly braces should be automatically closed when a * newline is entered after an opening curly brace. Note that this * property is only honored for languages that use curly braces to denote * code blocks. * * @return Whether curly braces should be automatically closed. * @see #setCloseCurlyBraces(boolean) */ public boolean getCloseCurlyBraces() { return closeCurlyBraces; } /** * Returns whether closing markup tags should be automatically completed * when "<code>&lt;/</code>" is typed. Note that this property is only * honored for markup languages, such as HTML, XML and PHP. * * @return Whether closing markup tags should be automatically completed. * @see #setCloseMarkupTags(boolean) */ public boolean getCloseMarkupTags() { return closeMarkupTags; } /** * Returns the code template manager for all instances of * <code>RSyntaxTextArea</code>. The manager is lazily created. * * @return The code template manager. * @see #setTemplatesEnabled(boolean) */ public static synchronized CodeTemplateManager getCodeTemplateManager() { if (codeTemplateManager==null) { codeTemplateManager = new CodeTemplateManager(); } return codeTemplateManager; } /** * Returns the default bracket-match background color. * * @return The color. * @see #getDefaultBracketMatchBorderColor */ public static final Color getDefaultBracketMatchBGColor() { return DEFAULT_BRACKET_MATCH_BG_COLOR; } /** * Returns the default bracket-match border color. * * @return The color. * @see #getDefaultBracketMatchBGColor */ public static final Color getDefaultBracketMatchBorderColor() { return DEFAULT_BRACKET_MATCH_BORDER_COLOR; } /** * Returns the default selection color for this text area. This * color was chosen because it's light and <code>RSyntaxTextArea</code> * does not change text color between selected/unselected text for * contrast like regular <code>JTextArea</code>s do. * * @return The default selection color. */ public static Color getDefaultSelectionColor() { return DEFAULT_SELECTION_COLOR; } /** * Returns the "default" syntax highlighting color scheme. The colors * used are somewhat standard among syntax highlighting text editors. * * @return The default syntax highlighting color scheme. * @see #restoreDefaultSyntaxScheme() * @see #getSyntaxScheme() * @see #setSyntaxScheme(SyntaxScheme) */ public SyntaxScheme getDefaultSyntaxScheme() { return new SyntaxScheme(getFont()); } /** * Returns whether an EOL marker should be drawn at the end of each line. * * @return Whether EOL markers should be visible. * @see #setEOLMarkersVisible(boolean) * @see #isWhitespaceVisible() */ public boolean getEOLMarkersVisible() { return eolMarkersVisible; } /** * Returns the fold manager for this text area. * * @return The fold manager. */ public FoldManager getFoldManager() { return foldManager; } /** * Returns the font for tokens of the specified type. * * @param type The type of token. * @return The font to use for that token type. * @see #getFontMetricsForTokenType(int) */ public Font getFontForTokenType(int type) { Font f = syntaxScheme.getStyle(type).font; return f!=null ? f : getFont(); } /** * Returns the font metrics for tokens of the specified type. * * @param type The type of token. * @return The font metrics to use for that token type. * @see #getFontForTokenType(int) */ public FontMetrics getFontMetricsForTokenType(int type) { FontMetrics fm = syntaxScheme.getStyle(type).fontMetrics; return fm!=null ? fm : defaultFontMetrics; } /** * Returns the foreground color to use when painting a token. * * @param t The token. * @return The foreground color to use for that token. This * value is never <code>null</code>. * @see #getBackgroundForToken(Token) */ public Color getForegroundForToken(Token t) { if (getHyperlinksEnabled() && hoveredOverLinkOffset==t.getOffset() && (t.isHyperlink() || linkGeneratorResult!=null)) { return hyperlinkFG; } return getForegroundForTokenType(t.getType()); } /** * Returns the foreground color to use when painting a token. This does * not take into account whether the token is a hyperlink. * * @param type The token type. * @return The foreground color to use for that token. This * value is never <code>null</code>. * @see #getForegroundForToken(Token) */ public Color getForegroundForTokenType(int type) { Color fg = syntaxScheme.getStyle(type).foreground; return fg!=null ? fg : getForeground(); } /** * Returns whether fractional font metrics are enabled for this text area. * * @return Whether fractional font metrics are enabled. * @see #setFractionalFontMetricsEnabled * @see #getAntiAliasingEnabled() */ public boolean getFractionalFontMetricsEnabled() { return fractionalFontMetricsEnabled; } /** * Returns a <code>Graphics2D</code> version of the specified graphics * that has been initialized with the proper rendering hints. * * @param g The graphics context for which to get a * <code>Graphics2D</code>. * @return The <code>Graphics2D</code>. */ private final Graphics2D getGraphics2D(Graphics g) { Graphics2D g2d = (Graphics2D)g; if (aaHints!=null) { g2d.addRenderingHints(aaHints); } if (fractionalFontMetricsEnabled) { g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } return g2d; } /** * Returns whether "secondary" languages should have their backgrounds * colored differently to visually differentiate them. This feature * imposes a fair performance penalty. * * @return Whether secondary languages have their backgrounds colored * differently. * @see #setHighlightSecondaryLanguages(boolean) * @see #getSecondaryLanguageBackground(int) * @see #getSecondaryLanguageCount() * @see #setSecondaryLanguageBackground(int, Color) */ public boolean getHighlightSecondaryLanguages() { return highlightSecondaryLanguages; } /** * Returns the color to use when painting hyperlinks. * * @return The color to use when painting hyperlinks. * @see #setHyperlinkForeground(Color) * @see #getHyperlinksEnabled() */ public Color getHyperlinkForeground() { return hyperlinkFG; } /** * Returns whether hyperlinks are enabled for this text area. * * @return Whether hyperlinks are enabled for this text area. * @see #setHyperlinksEnabled(boolean) */ public boolean getHyperlinksEnabled() { return hyperlinksEnabled; } /** * Returns the last visible offset in this text area. This may not be the * length of the document if code folding is enabled. * * @return The last visible offset in this text area. */ public int getLastVisibleOffset() { if (isCodeFoldingEnabled()) { int lastVisibleLine = foldManager.getLastVisibleLine(); if (lastVisibleLine<getLineCount()-1) { // Not the last line try { return getLineEndOffset(lastVisibleLine) - 1; } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); } } } return getDocument().getLength(); } /** * Returns the height to use for a line of text in this text area. * * @return The height of a line of text in this text area. */ @Override public int getLineHeight() { //System.err.println("... getLineHeight() returning " + lineHeight); return lineHeight; } public LinkGenerator getLinkGenerator() { return linkGenerator; } /** * Returns a list of "mark all" highlights in the text area. If there are * no such highlights, this will be an empty list. * * @return The list of "mark all" highlight ranges. */ public List<DocumentRange> getMarkAllHighlightRanges() { return ((RSyntaxTextAreaHighlighter)getHighlighter()). getMarkAllHighlightRanges(); } /** * Returns a list of "marked occurrences" in the text area. If there are * no marked occurrences, this will be an empty list. * * @return The list of marked occurrences. */ public List<DocumentRange> getMarkedOccurrences() { return ((RSyntaxTextAreaHighlighter)getHighlighter()). getMarkedOccurrences(); } /** * Returns whether "Mark Occurrences" is enabled. * * @return Whether "Mark Occurrences" is enabled. * @see #setMarkOccurrences(boolean) */ public boolean getMarkOccurrences() { return markOccurrencesSupport!=null; } /** * Returns the color used to "mark occurrences." * * @return The mark occurrences color. * @see #setMarkOccurrencesColor(Color) */ public Color getMarkOccurrencesColor() { return markOccurrencesColor; } /** * Returns whether tokens of the specified type should have "mark * occurrences" enabled for the current programming language. * * @param type The token type. * @return Whether tokens of this type should have "mark occurrences" * enabled. */ boolean getMarkOccurrencesOfTokenType(int type) { RSyntaxDocument doc = (RSyntaxDocument)getDocument(); return doc.getMarkOccurrencesOfTokenType(type); } /** * Gets the color used as the background for a matched bracket. * * @return The color used. If this is <code>null</code>, no special * background is painted behind a matched bracket. * @see #setMatchedBracketBGColor * @see #getMatchedBracketBorderColor */ public Color getMatchedBracketBGColor() { return matchedBracketBGColor; } /** * Gets the color used as the border for a matched bracket. * * @return The color used. * @see #setMatchedBracketBorderColor * @see #getMatchedBracketBGColor */ public Color getMatchedBracketBorderColor() { return matchedBracketBorderColor; } /** * Returns the caret's offset's rectangle, or <code>null</code> if there * is currently no matched bracket, bracket matching is disabled, or "paint * both matched brackets" is disabled. This should never be called by the * programmer directly. * * @return The rectangle surrounding the matched bracket. * @see #getMatchRectangle() */ Rectangle getDotRectangle() { return dotRect; } /** * Returns the matched bracket's rectangle, or <code>null</code> if there * is currently no matched bracket. This should never be called by the * programmer directly. * * @return The rectangle surrounding the matched bracket. * @see #getDotRectangle() */ Rectangle getMatchRectangle() { return match; } /** * Overridden to return the max ascent for any font used in the editor. * * @return The max ascent value. */ @Override public int getMaxAscent() { return maxAscent; } /** * Returns whether the bracket at the caret position is painted as a * "match" when a matched bracket is found. Note that this property does * nothing if {@link #isBracketMatchingEnabled()} returns * <code>false</code>. * * @return Whether both brackets in a bracket pair are highlighted when * bracket matching is enabled. * @see #setPaintMatchedBracketPair(boolean) * @see #isBracketMatchingEnabled() * @see #setBracketMatchingEnabled(boolean) */ public boolean getPaintMatchedBracketPair() { return paintMatchedBracketPair; } /** * Returns whether tab lines are painted. * * @return Whether tab lines are painted. * @see #setPaintTabLines(boolean) * @see #getTabLineColor() */ public boolean getPaintTabLines() { return paintTabLines; } /** * Returns the specified parser. * * @param index The {@link Parser} to retrieve. * @return The <code>Parser</code>. * @see #getParserCount() * @see #addParser(Parser) */ public Parser getParser(int index) { return parserManager.getParser(index); } /** * Returns the number of parsers operating on this text area. * * @return The parser count. * @see #addParser(Parser) */ public int getParserCount() { return parserManager==null ? 0 : parserManager.getParserCount(); } /** * Returns a list of the current parser notices for this text area. * This method (like most Swing methods) should only be called on the * EDT. * * @return The list of notices. This will be an empty list if there are * none. */ public List<ParserNotice> getParserNotices() { if (parserManager==null) { return Collections.emptyList(); } return parserManager.getParserNotices(); } /** * Workaround for JTextComponents allowing the caret to be rendered * entirely off-screen if the entire "previous" character fit entirely. * * @return The amount of space to add to the x-axis preferred span. * @see #setRightHandSideCorrection(int) */ public int getRightHandSideCorrection() { return rhsCorrection; } /** * If auto-indent is enabled, this method returns whether a new line after * this one should be indented (based on the standard indentation rules for * the current programming language). For example, in Java, for a line * containing: * * <pre> * for (int i=0; i<10; i++) { * </pre> * * the following line should be indented. * * @param line The line to check. * @return Whether a line inserted after this one should be auto-indented. * If auto-indentation is disabled, this will always return * <code>false</code>. * @see #isAutoIndentEnabled() */ public boolean getShouldIndentNextLine(int line) { if (isAutoIndentEnabled()) { RSyntaxDocument doc = (RSyntaxDocument)getDocument(); return doc.getShouldIndentNextLine(line); } return false; } /** * Returns what type of syntax highlighting this editor is doing. * * @return The style being used, such as * {@link SyntaxConstants#SYNTAX_STYLE_JAVA}. * @see #setSyntaxEditingStyle(String) * @see SyntaxConstants */ public String getSyntaxEditingStyle() { return syntaxStyleKey; } /** * Returns all of the colors currently being used in syntax highlighting * by this text component. * * @return An instance of <code>SyntaxScheme</code> that represents * the colors currently being used for syntax highlighting. * @see #setSyntaxScheme(SyntaxScheme) */ public SyntaxScheme getSyntaxScheme() { return syntaxScheme; } /** * Returns the color used to paint tab lines. * * @return The color used to paint tab lines. * @see #setTabLineColor(Color) * @see #getPaintTabLines() * @see #setPaintTabLines(boolean) */ public Color getTabLineColor() { return tabLineColor; } /** * Returns whether a border is painted around marked occurrences. * * @return Whether a border is painted. * @see #setPaintMarkOccurrencesBorder(boolean) * @see #getMarkOccurrencesColor() * @see #getMarkOccurrences() */ public boolean getPaintMarkOccurrencesBorder() { return paintMarkOccurrencesBorder; } /** * Returns the background color for the specified secondary language. * * @param index The language index. Note that these are 1-based, not * 0-based, and should be in the range * <code>1-getSecondaryLanguageCount()</code>, inclusive. * @return The color, or <code>null</code> if none. * @see #getSecondaryLanguageCount() * @see #setSecondaryLanguageBackground(int, Color) * @see #getHighlightSecondaryLanguages() */ public Color getSecondaryLanguageBackground(int index) { return secondaryLanguageBackgrounds[index]; } /** * Returns the number of secondary language backgrounds. * * @return The number of secondary language backgrounds. * @see #getSecondaryLanguageBackground(int) * @see #setSecondaryLanguageBackground(int, Color) * @see #getHighlightSecondaryLanguages() */ public int getSecondaryLanguageCount() { return secondaryLanguageBackgrounds.length; } public static synchronized boolean getTemplatesEnabled() { return templatesEnabled; } /** * Returns a token list for the given range in the document. * * @param startOffs The starting offset in the document. * @param endOffs The end offset in the document. * @return The first token in the token list. */ private Token getTokenListFor(int startOffs, int endOffs) { TokenImpl tokenList = null; TokenImpl lastToken = null; Element map = getDocument().getDefaultRootElement(); int startLine = map.getElementIndex(startOffs); int endLine = map.getElementIndex(endOffs); for (int line=startLine; line<=endLine; line++) { TokenImpl t = (TokenImpl)getTokenListForLine(line); t = cloneTokenList(t); if (tokenList==null) { tokenList = t; lastToken = tokenList; } else { lastToken.setNextToken(t); } while (lastToken.getNextToken()!=null && lastToken.getNextToken().isPaintable()) { lastToken = (TokenImpl)lastToken.getNextToken(); } if (line<endLine) { // Document offset MUST be correct to prevent exceptions // in getTokenListFor() int docOffs = map.getElement(line).getEndOffset()-1; t = new TokenImpl(new char[] { '\n' }, 0,0, docOffs, Token.WHITESPACE); lastToken.setNextToken(t); lastToken = t; } } // Trim the beginning and end of the token list so that it starts // at startOffs and ends at endOffs. // Be careful and check that startOffs is actually in the list. // startOffs can be < the token list's start if the end "newline" // character of a line is the first character selected (the token // list returned for that line will be null, so the first token in // the final token list will be from the next line and have a // starting offset > startOffs?). if (startOffs>=tokenList.getOffset()) { while (!tokenList.containsPosition(startOffs)) { tokenList = (TokenImpl)tokenList.getNextToken(); } tokenList.makeStartAt(startOffs); } TokenImpl temp = tokenList; // Be careful to check temp for null here. It is possible that no // token contains endOffs, if endOffs is at the end of a line. while (temp!=null && !temp.containsPosition(endOffs)) { temp = (TokenImpl)temp.getNextToken(); } if (temp!=null) { temp.textCount = endOffs - temp.getOffset(); temp.setNextToken(null); } return tokenList; } /** * Returns a list of tokens representing the given line. * * @param line The line number to get tokens for. * @return A linked list of tokens representing the line's text. */ public Token getTokenListForLine(int line) { return ((RSyntaxDocument)getDocument()).getTokenListForLine(line); } /** * Returns the painter to use for rendering tokens. * * @return The painter to use for rendering tokens. */ TokenPainter getTokenPainter() { return tokenPainter; } /** * Returns the tool tip to display for a mouse event at the given * location. This method is overridden to give a registered parser a * chance to display a tool tip (such as an error description when the * mouse is over an error highlight). * * @param e The mouse event. */ @Override public String getToolTipText(MouseEvent e) { // Check parsers for tool tips first. String text = null; URL imageBase = null; if (parserManager!=null) { ToolTipInfo info = parserManager.getToolTipText(e); if (info!=null) { // Should always be true text = info.getToolTipText(); // May be null imageBase = info.getImageBase(); // May be null } } if (text==null) { text = super.getToolTipText(e); } // Do we want to use "focusable" tips? if (getUseFocusableTips()) { if (text!=null) { if (focusableTip==null) { focusableTip = new FocusableTip(this, parserManager); } focusableTip.setImageBase(imageBase); focusableTip.toolTipRequested(e, text); } // No tool tip text at new location - hide tip window if one is // currently visible else if (focusableTip!=null) { focusableTip.possiblyDisposeOfTipWindow(); } return null; } return text; // Standard tool tips } /** * Returns whether the specified token should be underlined. * A token is underlined if its syntax style includes underlining, * or if it is a hyperlink and hyperlinks are enabled. * * @param t The token. * @return Whether the specified token should be underlined. */ public boolean getUnderlineForToken(Token t) { return (getHyperlinksEnabled() && (t.isHyperlink() || (linkGeneratorResult!=null && linkGeneratorResult.getSourceOffset()==t.getOffset()))) || syntaxScheme.getStyle(t.getType()).underline; } /** * Returns whether "focusable" tool tips are used instead of standard * ones. Focusable tool tips are tool tips that the user can click on, * resize, copy from, and click links in. * * @return Whether to use focusable tool tips. * @see #setUseFocusableTips(boolean) * @see FocusableTip */ public boolean getUseFocusableTips() { return useFocusableTips; } /** * Returns whether selected text should use the "selected text color" * property set via {@link #setSelectedTextColor(Color)}. This is the * typical behavior of text components. By default, RSyntaxTextArea does * not do this, so that token styles are visible even in selected regions * of text. * * @return Whether the "selected text" color is used when painting text * in selected regions. * @see #setUseSelectedTextColor(boolean) */ public boolean getUseSelectedTextColor() { return useSelectedTextColor; } /** * Called by constructors to initialize common properties of the text * editor. */ @Override protected void init() { super.init(); metricsNeverRefreshed = true; tokenPainter = new DefaultTokenPainter(); // NOTE: Our actions are created here instead of in a static block // so they are only created when the first RTextArea is instantiated, // not before. There have been reports of users calling static getters // (e.g. RSyntaxTextArea.getDefaultBracketMatchBGColor()) which would // cause these actions to be created and (possibly) incorrectly // localized, if they were in a static block. if (toggleCurrentFoldAction==null) { createRstaPopupMenuActions(); } // Set some RSyntaxTextArea default values. syntaxStyleKey = SYNTAX_STYLE_NONE; setMatchedBracketBGColor(getDefaultBracketMatchBGColor()); setMatchedBracketBorderColor(getDefaultBracketMatchBorderColor()); setBracketMatchingEnabled(true); setAnimateBracketMatching(true); lastBracketMatchPos = -1; setSelectionColor(getDefaultSelectionColor()); setTabLineColor(null); setMarkOccurrencesColor(MarkOccurrencesSupport.DEFAULT_COLOR); foldManager = new FoldManager(this); // Set auto-indent related stuff. setAutoIndentEnabled(true); setCloseCurlyBraces(true); setCloseMarkupTags(true); setClearWhitespaceLinesEnabled(true); setHyperlinksEnabled(true); setLinkScanningMask(InputEvent.CTRL_DOWN_MASK); setHyperlinkForeground(Color.BLUE); isScanningForLinks = false; setUseFocusableTips(true); //setAntiAliasingEnabled(true); setDefaultAntiAliasingState(); restoreDefaultSyntaxScheme(); setHighlightSecondaryLanguages(true); secondaryLanguageBackgrounds = new Color[3]; secondaryLanguageBackgrounds[0] = new Color(0xfff0cc); secondaryLanguageBackgrounds[1] = new Color(0xdafeda); secondaryLanguageBackgrounds[2] = new Color(0xffe0f0); setRightHandSideCorrection(0); } /** * Returns whether or not auto-indent is enabled. * * @return Whether or not auto-indent is enabled. * @see #setAutoIndentEnabled(boolean) */ public boolean isAutoIndentEnabled() { return autoIndentEnabled; } /** * Returns whether or not bracket matching is enabled. * * @return <code>true</code> iff bracket matching is enabled. * @see #setBracketMatchingEnabled */ public final boolean isBracketMatchingEnabled() { return bracketMatchingEnabled; } /** * Returns whether or not lines containing nothing but whitespace are made * into blank lines when Enter is pressed in them. * * @return Whether or not whitespace-only lines are cleared when * the user presses Enter on them. * @see #setClearWhitespaceLinesEnabled(boolean) */ public boolean isClearWhitespaceLinesEnabled() { return clearWhitespaceLines; } /** * Returns whether code folding is enabled. Note that only certain * languages support code folding; those that do not will ignore this * property. * * @return Whether code folding is enabled. * @see #setCodeFoldingEnabled(boolean) */ public boolean isCodeFoldingEnabled() { return foldManager.isCodeFoldingEnabled(); } /** * Returns whether whitespace (spaces and tabs) is visible. * * @return Whether whitespace is visible. * @see #setWhitespaceVisible(boolean) * @see #getEOLMarkersVisible() */ public boolean isWhitespaceVisible() { return whitespaceVisible; } /** * Returns the token at the specified position in the model. * * @param offs The position in the model. * @return The token, or <code>null</code> if no token is at that * position. * @see #viewToToken(Point) */ public Token modelToToken(int offs) { if (offs>=0) { try { int line = getLineOfOffset(offs); Token t = getTokenListForLine(line); return RSyntaxUtilities.getTokenAtOffset(t, offs); } catch (BadLocationException ble) { ble.printStackTrace(); // Never happens } } return null; } /** * The <code>paintComponent</code> method is overridden so we * apply any necessary rendering hints to the Graphics object. */ @Override protected void paintComponent(Graphics g) { // A call to refreshFontMetrics() used to be in addNotify(), but // unfortunately we cannot always get the graphics context there. If // the parent frame/dialog is LAF-decorated, there is a chance that the // window's width and/or height is still == 0 at addNotify() (e.g. // WebLaF). So unfortunately it's safest to do this here, with a flag // to only allow it to happen once. if (metricsNeverRefreshed) { refreshFontMetrics(getGraphics2D(getGraphics())); metricsNeverRefreshed = false; } super.paintComponent(getGraphics2D(g)); } private void refreshFontMetrics(Graphics2D g2d) { // It is assumed that any rendering hints are already applied to g2d. defaultFontMetrics = g2d.getFontMetrics(getFont()); syntaxScheme.refreshFontMetrics(g2d); if (getLineWrap()==false) { // HORRIBLE HACK! The un-wrapped view needs to refresh its cached // longest line information. SyntaxView sv = (SyntaxView)getUI().getRootView(this).getView(0); sv.calculateLongestLine(); } } /** * Removes an "active line range" listener from this text area. * * @param l The listener to remove. * @see #removeActiveLineRangeListener(ActiveLineRangeListener) */ public void removeActiveLineRangeListener(ActiveLineRangeListener l) { listenerList.remove(ActiveLineRangeListener.class, l); } /** * Removes a hyperlink listener from this text area. * * @param l The listener to remove. * @see #addHyperlinkListener(HyperlinkListener) */ public void removeHyperlinkListener(HyperlinkListener l) { listenerList.remove(HyperlinkListener.class, l); } /** * Overridden so we stop this text area's parsers, if any. */ @Override public void removeNotify() { if (parserManager!=null) { parserManager.stopParsing(); } super.removeNotify(); } /** * Removes a parser from this text area. * * @param parser The {@link Parser} to remove. * @return Whether the parser was found and removed. * @see #clearParsers() * @see #addParser(Parser) * @see #getParser(int) */ public boolean removeParser(Parser parser) { boolean removed = false; if (parserManager!=null) { removed = parserManager.removeParser(parser); } return removed; } /** * Sets the colors used for syntax highlighting to their defaults. * * @see #setSyntaxScheme(SyntaxScheme) * @see #getSyntaxScheme() * @see #getDefaultSyntaxScheme() */ public void restoreDefaultSyntaxScheme() { setSyntaxScheme(getDefaultSyntaxScheme()); } /** * Attempts to save all currently-known templates to the current template * directory, as set by <code>setTemplateDirectory</code>. Templates * will be saved as XML files with names equal to their abbreviations; for * example, a template that expands on the word "forb" will be saved as * <code>forb.xml</code>. * * @return Whether or not the save was successful. The save will * be unsuccessful if the template directory does not exist or * if it has not been set (i.e., you have not yet called * <code>setTemplateDirectory</code>). * @see #getTemplatesEnabled * @see #setTemplateDirectory * @see #setTemplatesEnabled */ public static synchronized boolean saveTemplates() { if (!getTemplatesEnabled()) { return false; } return getCodeTemplateManager().saveTemplates(); } public void setActiveLineRange(int min, int max) { if (min==-1) { max = -1; // Force max to be -1 if min is. } fireActiveLineRangeEvent(min, max); } /** * Sets whether bracket matching should be animated. This fires a property * change event of type {@link #ANIMATE_BRACKET_MATCHING_PROPERTY}. * * @param animate Whether to animate bracket matching. * @see #getAnimateBracketMatching() */ public void setAnimateBracketMatching(boolean animate) { if (animate!=animateBracketMatching) { animateBracketMatching = animate; if (animate && bracketRepaintTimer==null) { bracketRepaintTimer = new BracketMatchingTimer(); } firePropertyChange(ANIMATE_BRACKET_MATCHING_PROPERTY, !animate, animate); } } /** * Sets whether anti-aliasing is enabled in this editor. This method * fires a property change event of type {@link #ANTIALIAS_PROPERTY}. * * @param enabled Whether anti-aliasing is enabled. * @see #getAntiAliasingEnabled() */ public void setAntiAliasingEnabled(boolean enabled) { boolean currentlyEnabled = aaHints!=null; if (enabled!=currentlyEnabled) { if (enabled) { aaHints = RSyntaxUtilities.getDesktopAntiAliasHints(); // If the desktop query method comes up empty, use the standard // Java2D greyscale method. Note this will likely NOT be as // nice as what would be used if the getDesktopAntiAliasHints() // call worked. if (aaHints==null) { Map<RenderingHints.Key, Object> temp = new HashMap<RenderingHints.Key, Object>(); temp.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); aaHints = temp; } } else { aaHints = null; } // We must be connected to a screen resource for our graphics // to be non-null. if (isDisplayable()) { refreshFontMetrics(getGraphics2D(getGraphics())); } firePropertyChange(ANTIALIAS_PROPERTY, !enabled, enabled); repaint(); } } /** * Sets whether or not auto-indent is enabled. This fires a property * change event of type {@link #AUTO_INDENT_PROPERTY}. * * @param enabled Whether or not auto-indent is enabled. * @see #isAutoIndentEnabled() */ public void setAutoIndentEnabled(boolean enabled) { if (autoIndentEnabled!=enabled) { autoIndentEnabled = enabled; firePropertyChange(AUTO_INDENT_PROPERTY, !enabled, enabled); } } /** * Sets whether bracket matching is enabled. This fires a property change * event of type {@link #BRACKET_MATCHING_PROPERTY}. * * @param enabled Whether or not bracket matching should be enabled. * @see #isBracketMatchingEnabled() */ public void setBracketMatchingEnabled(boolean enabled) { if (enabled!=bracketMatchingEnabled) { bracketMatchingEnabled = enabled; repaint(); firePropertyChange(BRACKET_MATCHING_PROPERTY, !enabled, enabled); } } /** * Sets whether or not lines containing nothing but whitespace are made * into blank lines when Enter is pressed in them. This method fires * a property change event of type {@link #CLEAR_WHITESPACE_LINES_PROPERTY}. * * @param enabled Whether or not whitespace-only lines are cleared when * the user presses Enter on them. * @see #isClearWhitespaceLinesEnabled() */ public void setClearWhitespaceLinesEnabled(boolean enabled) { if (enabled!=clearWhitespaceLines) { clearWhitespaceLines = enabled; firePropertyChange(CLEAR_WHITESPACE_LINES_PROPERTY, !enabled, enabled); } } /** * Toggles whether curly braces should be automatically closed when a * newline is entered after an opening curly brace. Note that this * property is only honored for languages that use curly braces to denote * code blocks.<p> * * This method fires a property change event of type * {@link #CLOSE_CURLY_BRACES_PROPERTY}. * * @param close Whether curly braces should be automatically closed. * @see #getCloseCurlyBraces() */ public void setCloseCurlyBraces(boolean close) { if (close!=closeCurlyBraces) { closeCurlyBraces = close; firePropertyChange(CLOSE_CURLY_BRACES_PROPERTY, !close, close); } } /** * Sets whether closing markup tags should be automatically completed * when "<code>&lt;/</code>" is typed. Note that this property is only * honored for markup languages, such as HTML, XML and PHP.<p> * * This method fires a property change event of type * {@link #CLOSE_MARKUP_TAGS_PROPERTY}. * * @param close Whether closing markup tags should be automatically * completed. * @see #getCloseMarkupTags() */ public void setCloseMarkupTags(boolean close) { if (close!=closeMarkupTags) { closeMarkupTags = close; firePropertyChange(CLOSE_MARKUP_TAGS_PROPERTY, !close, close); } } /** * Sets whether code folding is enabled. Note that only certain * languages will support code folding out of the box. Those languages * which do not support folding will ignore this property.<p> * This method fires a property change event of type * {@link #CODE_FOLDING_PROPERTY}. * * @param enabled Whether code folding should be enabled. * @see #isCodeFoldingEnabled() */ public void setCodeFoldingEnabled(boolean enabled) { if (enabled!=foldManager.isCodeFoldingEnabled()) { foldManager.setCodeFoldingEnabled(enabled); firePropertyChange(CODE_FOLDING_PROPERTY, !enabled, enabled); } } /** * Sets anti-aliasing to whatever the user's desktop value is. * * @see #getAntiAliasingEnabled() */ private final void setDefaultAntiAliasingState() { // Most accurate technique, but not available on all OSes. aaHints = RSyntaxUtilities.getDesktopAntiAliasHints(); if (aaHints==null) { Map<RenderingHints.Key, Object> temp = new HashMap<RenderingHints.Key, Object>(); // In Java 6+, you can figure out what text AA hint Swing uses for // JComponents... JLabel label = new JLabel(); FontMetrics fm = label.getFontMetrics(label.getFont()); Object hint = null; //FontRenderContext frc = fm.getFontRenderContext(); //hint = fm.getAntiAliasingHint(); try { Method m = FontMetrics.class.getMethod("getFontRenderContext"); FontRenderContext frc = (FontRenderContext)m.invoke(fm); m = FontRenderContext.class.getMethod("getAntiAliasingHint"); hint = m.invoke(frc); } catch (RuntimeException re) { throw re; // FindBugs } catch (Exception e) { // Swallow, either Java 1.5, or running in an applet } // If not running Java 6+, default to AA enabled on Windows where // the software AA is pretty fast, and default (e.g. disabled) on // non-Windows. Note that OS X always uses AA no matter what // rendering hints you give it, so this is a moot point there. //System.out.println("Rendering hint: " + hint); if (hint==null) { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("windows")) { hint = RenderingHints.VALUE_TEXT_ANTIALIAS_ON; } else { hint = RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT; } } temp.put(RenderingHints.KEY_TEXT_ANTIALIASING, hint); aaHints = temp; } // We must be connected to a screen resource for our graphics // to be non-null. if (isDisplayable()) { refreshFontMetrics(getGraphics2D(getGraphics())); } repaint(); } @Override public void setDocument(Document document) { if (!(document instanceof RSyntaxDocument)) throw new IllegalArgumentException("Documents for " + "RSyntaxTextArea must be instances of " + "RSyntaxDocument!"); super.setDocument(document); } /** * Sets whether EOL markers are visible at the end of each line. This * method fires a property change of type {@link #EOL_VISIBLE_PROPERTY}. * * @param visible Whether EOL markers are visible. * @see #getEOLMarkersVisible() * @see #setWhitespaceVisible(boolean) */ public void setEOLMarkersVisible(boolean visible) { if (visible!=eolMarkersVisible) { eolMarkersVisible = visible; repaint(); firePropertyChange(EOL_VISIBLE_PROPERTY, !visible, visible); } } /** * Sets the font used by this text area. Note that if some token styles * are using a different font, they will not be changed by calling this * method. To set different fonts on individual token types, use the * text area's <code>SyntaxScheme</code>. * * @param font The font. * @see SyntaxScheme#getStyle(int) */ @Override public void setFont(Font font) { Font old = super.getFont(); super.setFont(font); // Do this first. // Usually programmers keep a single font for all token types, but // may use bold or italic for styling some. SyntaxScheme scheme = getSyntaxScheme(); if (scheme!=null && old!=null) { scheme.changeBaseFont(old, font); calculateLineHeight(); } // We must be connected to a screen resource for our // graphics to be non-null. if (isDisplayable()) { refreshFontMetrics(getGraphics2D(getGraphics())); // Updates the margin line. updateMarginLineX(); // Force the current line highlight to be repainted, even // though the caret's location hasn't changed. forceCurrentLineHighlightRepaint(); // Get line number border in text area to repaint again // since line heights have updated. firePropertyChange("font", old, font); // So parent JScrollPane will have its scrollbars updated. revalidate(); } } /** * Sets whether fractional font metrics are enabled. This method fires * a property change event of type {@link #FRACTIONAL_FONTMETRICS_PROPERTY}. * * @param enabled Whether fractional font metrics are enabled. * @see #getFractionalFontMetricsEnabled() */ public void setFractionalFontMetricsEnabled(boolean enabled) { if (fractionalFontMetricsEnabled!=enabled) { fractionalFontMetricsEnabled = enabled; // We must be connected to a screen resource for our graphics to be // non-null. if (isDisplayable()) { refreshFontMetrics(getGraphics2D(getGraphics())); } firePropertyChange(FRACTIONAL_FONTMETRICS_PROPERTY, !enabled, enabled); } } @Override public void setHighlighter(Highlighter h) { if (!(h instanceof RSyntaxTextAreaHighlighter)) { throw new IllegalArgumentException("RSyntaxTextArea requires " + "an RSyntaxTextAreaHighlighter for its Highlighter"); } super.setHighlighter(h); } /** * Sets whether "secondary" languages should have their backgrounds * colored differently to visually differentiate them. This feature * imposes a fair performance penalty. This method fires a property change * event of type {@link #HIGHLIGHT_SECONDARY_LANGUAGES_PROPERTY}. * * @see #getHighlightSecondaryLanguages() * @see #setSecondaryLanguageBackground(int, Color) * @see #getSecondaryLanguageCount() */ public void setHighlightSecondaryLanguages(boolean highlight) { if (this.highlightSecondaryLanguages!=highlight) { highlightSecondaryLanguages = highlight; repaint(); firePropertyChange(HIGHLIGHT_SECONDARY_LANGUAGES_PROPERTY, !highlight, highlight); } } /** * Sets the color to use when painting hyperlinks. * * @param fg The color to use when painting hyperlinks. * @throws NullPointerException If <code>fg</code> is <code>null</code>. * @see #getHyperlinkForeground() * @see #setHyperlinksEnabled(boolean) */ public void setHyperlinkForeground(Color fg) { if (fg==null) { throw new NullPointerException("fg cannot be null"); } hyperlinkFG = fg; } /** * Sets whether hyperlinks are enabled for this text area. This method * fires a property change event of type * {@link #HYPERLINKS_ENABLED_PROPERTY}. * * @param enabled Whether hyperlinks are enabled. * @see #getHyperlinksEnabled() */ public void setHyperlinksEnabled(boolean enabled) { if (this.hyperlinksEnabled!=enabled) { this.hyperlinksEnabled = enabled; repaint(); firePropertyChange(HYPERLINKS_ENABLED_PROPERTY, !enabled, enabled); } } public void setLinkGenerator(LinkGenerator generator) { this.linkGenerator = generator; } /** * Sets the mask for the key used to toggle whether we are scanning for * hyperlinks with mouse hovering. The default value is * <code>CTRL_DOWN_MASK</code>. * * @param mask The mask to use. This should be some bitwise combination of * {@link InputEvent#CTRL_DOWN_MASK}, * {@link InputEvent#ALT_DOWN_MASK}, * {@link InputEvent#SHIFT_DOWN_MASK} or * {@link InputEvent#META_DOWN_MASK}. * For invalid values, behavior is undefined. * @see InputEvent */ public void setLinkScanningMask(int mask) { mask &= (InputEvent.CTRL_DOWN_MASK|InputEvent.META_DOWN_MASK| InputEvent.ALT_DOWN_MASK|InputEvent.SHIFT_DOWN_MASK); if (mask==0) { throw new IllegalArgumentException("mask argument should be " + "some combination of InputEvent.*_DOWN_MASK fields"); } linkScanningMask = mask; } /** * Toggles whether "mark occurrences" is enabled. This method fires a * property change event of type {@link #MARK_OCCURRENCES_PROPERTY}. * * @param markOccurrences Whether "Mark Occurrences" should be enabled. * @see #getMarkOccurrences() * @see #setMarkOccurrencesColor(Color) */ public void setMarkOccurrences(boolean markOccurrences) { if (markOccurrences) { if (markOccurrencesSupport==null) { markOccurrencesSupport = new MarkOccurrencesSupport(); markOccurrencesSupport.install(this); firePropertyChange(MARK_OCCURRENCES_PROPERTY, false, true); } } else { if (markOccurrencesSupport!=null) { markOccurrencesSupport.uninstall(); markOccurrencesSupport = null; firePropertyChange(MARK_OCCURRENCES_PROPERTY, true, false); } } } /** * Sets the "mark occurrences" color. * * @param color The new color. This cannot be <code>null</code>. * @see #getMarkOccurrencesColor() * @see #setMarkOccurrences(boolean) */ public void setMarkOccurrencesColor(Color color) { markOccurrencesColor = color; if (markOccurrencesSupport!=null) { markOccurrencesSupport.setColor(color); } } /** * Sets the color used as the background for a matched bracket. * * @param color The color to use. If this is <code>null</code>, then no * special background is painted behind a matched bracket. * @see #getMatchedBracketBGColor * @see #setMatchedBracketBorderColor * @see #setPaintMarkOccurrencesBorder(boolean) */ public void setMatchedBracketBGColor(Color color) { matchedBracketBGColor = color; if (match!=null) { repaint(); } } /** * Sets the color used as the border for a matched bracket. * * @param color The color to use. * @see #getMatchedBracketBorderColor * @see #setMatchedBracketBGColor */ public void setMatchedBracketBorderColor(Color color) { matchedBracketBorderColor = color; if (match!=null) { repaint(); } } /** * Toggles whether a border should be painted around marked occurrences. * * @param paintBorder Whether to paint a border. * @see #getPaintMarkOccurrencesBorder() * @see #setMarkOccurrencesColor(Color) * @see #setMarkOccurrences(boolean) */ public void setPaintMarkOccurrencesBorder(boolean paintBorder) { paintMarkOccurrencesBorder = paintBorder; if (markOccurrencesSupport!=null) { markOccurrencesSupport.setPaintBorder(paintBorder); } } /** * Sets whether the bracket at the caret position is painted as a "match" * when a matched bracket is found. Note that this property does nothing * if {@link #isBracketMatchingEnabled()} returns <code>false</code>.<p> * * This method fires a property change event of type * {@link #PAINT_MATCHED_BRACKET_PAIR_PROPERTY}. * * @param paintPair Whether both brackets in a bracket pair should be * highlighted when bracket matching is enabled. * @see #getPaintMatchedBracketPair() * @see #isBracketMatchingEnabled() * @see #setBracketMatchingEnabled(boolean) */ public void setPaintMatchedBracketPair(boolean paintPair) { if (paintPair!=paintMatchedBracketPair) { paintMatchedBracketPair = paintPair; doBracketMatching(); repaint(); firePropertyChange(PAINT_MATCHED_BRACKET_PAIR_PROPERTY, !paintMatchedBracketPair, paintMatchedBracketPair); } } /** * Toggles whether tab lines are painted. This method fires a property * change event of type {@link #TAB_LINES_PROPERTY}. * * @param paint Whether tab lines are painted. * @see #getPaintTabLines() * @see #setTabLineColor(Color) */ public void setPaintTabLines(boolean paint) { if (paint!=paintTabLines) { paintTabLines = paint; repaint(); firePropertyChange(TAB_LINES_PROPERTY, !paint, paint); } } /** * Applications typically have no need to modify this value.<p> * * Workaround for JTextComponents allowing the caret to be rendered * entirely off-screen if the entire "previous" character fit entirely. * * @param rhsCorrection The amount of space to add to the x-axis preferred * span. This should be non-negative. * @see #getRightHandSideCorrection() */ public void setRightHandSideCorrection(int rhsCorrection) { if (rhsCorrection<0) { throw new IllegalArgumentException("correction should be > 0"); } if (rhsCorrection!=this.rhsCorrection) { this.rhsCorrection = rhsCorrection; revalidate(); repaint(); } } /** * Sets the background color to use for a secondary language. * * @param index The language index. Note that these are 1-based, not * 0-based, and should be in the range * <code>1-getSecondaryLanguageCount()</code>, inclusive. * @param color The new color, or <code>null</code> for none. * @see #getSecondaryLanguageBackground(int) * @see #getSecondaryLanguageCount() */ public void setSecondaryLanguageBackground(int index, Color color) { index Color old = secondaryLanguageBackgrounds[index]; if ((color==null && old!=null) || (color!=null && !color.equals(old))) { secondaryLanguageBackgrounds[index] = color; if (getHighlightSecondaryLanguages()) { repaint(); } } } /** * Sets what type of syntax highlighting this editor is doing. This method * fires a property change of type {@link #SYNTAX_STYLE_PROPERTY}. * * @param styleKey The syntax editing style to use, for example, * {@link SyntaxConstants#SYNTAX_STYLE_NONE} or * {@link SyntaxConstants#SYNTAX_STYLE_JAVA}. * @see #getSyntaxEditingStyle() * @see SyntaxConstants */ public void setSyntaxEditingStyle(String styleKey) { if (styleKey==null) { styleKey = SYNTAX_STYLE_NONE; } if (!styleKey.equals(syntaxStyleKey)) { String oldStyle = syntaxStyleKey; syntaxStyleKey = styleKey; ((RSyntaxDocument)getDocument()).setSyntaxStyle(styleKey); firePropertyChange(SYNTAX_STYLE_PROPERTY, oldStyle, styleKey); setActiveLineRange(-1, -1); } } /** * Sets all of the colors used in syntax highlighting to the colors * specified. This uses a shallow copy of the color scheme so that * multiple text areas can share the same color scheme and have their * properties changed simultaneously.<p> * * This method fires a property change event of type * {@link #SYNTAX_SCHEME_PROPERTY}. * * @param scheme The instance of <code>SyntaxScheme</code> to use. * @see #getSyntaxScheme() */ public void setSyntaxScheme(SyntaxScheme scheme) { // NOTE: We don't check whether colorScheme is the same as the // current scheme because DecreaseFontSizeAction and // IncreaseFontSizeAction need it this way. // FIXME: Find a way around this. SyntaxScheme old = this.syntaxScheme; this.syntaxScheme = scheme; // Recalculate the line height. We do this here instead of in // refreshFontMetrics() as this method is called less often and we // don't need the rendering hints to get the font's height. calculateLineHeight(); if (isDisplayable()) { refreshFontMetrics(getGraphics2D(getGraphics())); } // Updates the margin line. updateMarginLineX(); // Force the current line highlight to be repainted, even though // the caret's location hasn't changed. forceCurrentLineHighlightRepaint(); // So encompassing JScrollPane will have its scrollbars updated. revalidate(); firePropertyChange(SYNTAX_SCHEME_PROPERTY, old, this.syntaxScheme); } /** * If templates are enabled, all currently-known templates are forgotten * and all templates are loaded from all files in the specified directory * ending in "*.xml". If templates aren't enabled, nothing happens. * * @param dir The directory containing files ending in extension * <code>.xml</code> that contain templates to load. * @return <code>true</code> if the load was successful; * <code>false</code> if either templates aren't currently * enabled or the load failed somehow (most likely, the * directory doesn't exist). * @see #getTemplatesEnabled * @see #setTemplatesEnabled * @see #saveTemplates */ public static synchronized boolean setTemplateDirectory(String dir) { if (getTemplatesEnabled() && dir!=null) { File directory = new File(dir); if (directory.isDirectory()) { return getCodeTemplateManager(). setTemplateDirectory(directory)>-1; } boolean created = directory.mkdir(); if (created) { return getCodeTemplateManager(). setTemplateDirectory(directory)>-1; } } return false; } public static synchronized void setTemplatesEnabled(boolean enabled) { templatesEnabled = enabled; } /** * Sets the color use to paint tab lines. This method fires a property * change event of type {@link #TAB_LINE_COLOR_PROPERTY}. * * @param c The color. If this value is <code>null</code>, the default * (gray) is used. * @see #getTabLineColor() * @see #setPaintTabLines(boolean) * @see #getPaintTabLines() */ public void setTabLineColor(Color c) { if (c==null) { c = Color.gray; } if (!c.equals(tabLineColor)) { Color old = tabLineColor; tabLineColor = c; if (getPaintTabLines()) { repaint(); } firePropertyChange(TAB_LINE_COLOR_PROPERTY, old, tabLineColor); } } /** * Sets whether "focusable" tool tips are used instead of standard ones. * Focusable tool tips are tool tips that the user can click on, * resize, copy from, and clink links in. This method fires a property * change event of type {@link #FOCUSABLE_TIPS_PROPERTY}. * * @param use Whether to use focusable tool tips. * @see #getUseFocusableTips() * @see FocusableTip */ public void setUseFocusableTips(boolean use) { if (use!=useFocusableTips) { useFocusableTips = use; firePropertyChange(FOCUSABLE_TIPS_PROPERTY, !use, use); } } /** * Sets whether selected text should use the "selected text color" property * (set via {@link #setSelectedTextColor(Color)}). This is the typical * behavior of text components. By default, RSyntaxTextArea does not do * this, so that token styles are visible even in selected regions of text. * This method fires a property change event of type * {@link #USE_SELECTED_TEXT_COLOR_PROPERTY}. * * @param use Whether to use the "selected text" color when painting text * in selected regions. * @see #getUseSelectedTextColor() */ public void setUseSelectedTextColor(boolean use) { if (use!=useSelectedTextColor) { useSelectedTextColor = use; firePropertyChange(USE_SELECTED_TEXT_COLOR_PROPERTY, !use, use); } } /** * Sets whether whitespace is visible. This method fires a property change * of type {@link #VISIBLE_WHITESPACE_PROPERTY}. * * @param visible Whether whitespace should be visible. * @see #isWhitespaceVisible() */ public void setWhitespaceVisible(boolean visible) { if (whitespaceVisible!=visible) { this.whitespaceVisible = visible; tokenPainter = visible ? new VisibleWhitespaceTokenPainter() : (TokenPainter)new DefaultTokenPainter(); repaint(); firePropertyChange(VISIBLE_WHITESPACE_PROPERTY, !visible, visible); } } /** * Resets the editor state after the user clicks on a hyperlink or releases * the hyperlink modifier. */ private void stopScanningForLinks() { if (isScanningForLinks) { Cursor c = getCursor(); isScanningForLinks = false; linkGeneratorResult = null; hoveredOverLinkOffset = -1; if (c!=null && c.getType()==Cursor.HAND_CURSOR) { setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); repaint(); // TODO: Repaint just the affected line. } } } /** * Returns the token at the specified position in the view. * * @param p The position in the view. * @return The token, or <code>null</code> if no token is at that * position. * @see #modelToToken(int) */ /* * TODO: This is a little inefficient. This should convert view * coordinates to the underlying token (if any). The way things currently * are, we're calling getTokenListForLine() twice (once in viewToModel() * and once here). */ public Token viewToToken(Point p) { return modelToToken(viewToModel(p)); } /** * A timer that animates the "bracket matching" animation. */ private class BracketMatchingTimer extends Timer implements ActionListener { private int pulseCount; public BracketMatchingTimer() { super(20, null); addActionListener(this); setCoalesce(false); } public void actionPerformed(ActionEvent e) { if (isBracketMatchingEnabled()) { if (match!=null) { updateAndInvalidate(match); } if (dotRect!=null && getPaintMatchedBracketPair()) { updateAndInvalidate(dotRect); } if (++pulseCount==8) { pulseCount = 0; stop(); } } } private void init(Rectangle r) { r.x += 3; r.y += 3; r.width -= 6; r.height -= 6; // So animation can "grow" match } @Override public void start() { init(match); if (dotRect!=null && getPaintMatchedBracketPair()) { init(dotRect); } pulseCount = 0; super.start(); } private void updateAndInvalidate(Rectangle r) { if (pulseCount<5) { r.x r.y r.width += 2; r.height += 2; repaint(r.x,r.y, r.width,r.height); } else if (pulseCount<7) { r.x++; r.y++; r.width -= 2; r.height -= 2; repaint(r.x-2,r.y-2, r.width+5,r.height+5); } } } /** * Handles hyperlinks. */ private class RSyntaxTextAreaMutableCaretEvent extends RTextAreaMutableCaretEvent { private Insets insets; protected RSyntaxTextAreaMutableCaretEvent(RTextArea textArea) { super(textArea); insets = new Insets(0, 0, 0, 0); } private HyperlinkEvent createHyperlinkEvent() { HyperlinkEvent he = null; if (linkGeneratorResult!=null) { he = linkGeneratorResult.execute(); linkGeneratorResult = null; } else { Token t = modelToToken(hoveredOverLinkOffset); URL url = null; String desc = null; try { String temp = t.getLexeme(); if (temp.startsWith("www.")) { temp = "http://" + temp; } url = new URL(temp); } catch (MalformedURLException mue) { desc = mue.getMessage(); } he = new HyperlinkEvent(RSyntaxTextArea.this, HyperlinkEvent.EventType.ACTIVATED, url, desc); } return he; } private final boolean equal(LinkGeneratorResult e1, LinkGeneratorResult e2) { return e1.getSourceOffset()==e2.getSourceOffset(); } @Override public void mouseClicked(MouseEvent e) { if (getHyperlinksEnabled() && isScanningForLinks && hoveredOverLinkOffset>-1) { HyperlinkEvent he = createHyperlinkEvent(); if (he!=null) { fireHyperlinkUpdate(he); } stopScanningForLinks(); } } @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); if (!getHyperlinksEnabled()) { return; } // If our link scanning mask is pressed... if ((e.getModifiersEx()&linkScanningMask)==linkScanningMask) { // GitHub issue #25 - links identified at "edges" of editor // should not be activated if mouse is in margin insets. insets = getInsets(insets); if (insets!=null) { int x = e.getX(); int y = e.getY(); if (x<=insets.left || y<insets.top) { if (isScanningForLinks) { stopScanningForLinks(); } return; } } isScanningForLinks = true; Token t = viewToToken(e.getPoint()); if (t!=null) { // Copy token, viewToModel() unfortunately modifies Token t = new TokenImpl(t); } Cursor c2 = null; if (t!=null && t.isHyperlink()) { if (hoveredOverLinkOffset==-1 || hoveredOverLinkOffset!=t.getOffset()) { hoveredOverLinkOffset = t.getOffset(); repaint(); } c2 = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } else if (t!=null && linkGenerator!=null) { int offs = viewToModel(e.getPoint()); LinkGeneratorResult newResult = linkGenerator. isLinkAtOffset(RSyntaxTextArea.this, offs); if (newResult!=null) { // Repaint if we're at a new link now. if (linkGeneratorResult==null || !equal(newResult, linkGeneratorResult)) { repaint(); } linkGeneratorResult = newResult; hoveredOverLinkOffset = t.getOffset(); c2 = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } else { // Repaint if we've moved off of a link. if (linkGeneratorResult!=null) { repaint(); } c2 = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); hoveredOverLinkOffset = -1; linkGeneratorResult = null; } } else { c2 = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); hoveredOverLinkOffset = -1; linkGeneratorResult = null; } if (getCursor()!=c2) { setCursor(c2); // TODO: Repaint just the affected line(s). repaint(); // Link either left or went into. } } else { if (isScanningForLinks) { stopScanningForLinks(); } } } } }
package local.tomo.login; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import local.tomo.login.database.DatabaseHandler; import local.tomo.login.json.MedicamentsDbJSON; import local.tomo.login.model.MedicamentDb; import local.tomo.login.model.User; import local.tomo.login.network.RestIntefrace; import local.tomo.login.network.RetrofitBuilder; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class LoginActivity extends Activity { private static String PREF_NAME = "tomo_pref"; private static String PREF_USER = "username"; private static String PREF_PASSWORD = "password"; private static String PREF_UNIQUE_ID = "uniqueId"; public static String uniqueId; String userName; DatabaseHandler databaseHandler; MedicamentsDbJSON medicamentsDbJSON; private EditText editTextLoginUserName; private EditText editTextLoginPassword; private class Background extends AsyncTask<Void, Void, Void> { Resources resources; LoginActivity loginActivity; private ProgressDialog progressDialog; public Background(Context applicationContext, Resources resources) { this.resources = resources; this.progressDialog = new ProgressDialog(applicationContext); } @Override protected Void doInBackground(Void... params) { medicamentsDbJSON = new MedicamentsDbJSON(getResources()); InputStream inputStream = resources.openRawResource(R.raw.medicount); String s = ""; try { s = IOUtils.toString(inputStream); } catch (IOException e) { e.printStackTrace(); } int medicamentsDbCountFile = Integer.parseInt(s); //if(medicamentsDbCountFile > medicamentDbDAO.count()) { //if(medicamentsDbCountFile > databaseHandler.getMedicamentDbDAO().count()) { if(medicamentsDbCountFile > databaseHandler.getMedicamentsDbCount()) { List<MedicamentDb> medicamentsDbFromFile = medicamentsDbJSON.getMedicamentsDbFromFile(); //List<MedicamentDb> medicamentsDbs = medicamentDbDAO.getAll(); //List<MedicamentDb> medicamentsDbs = databaseHandler.getMedicamentDbDAO().getAll(); List<MedicamentDb> medicamentsDbs = databaseHandler.getMedicamentsDb(); List<MedicamentDb> list = new LinkedList<MedicamentDb>(medicamentsDbFromFile); List<MedicamentDb> toRemove = new ArrayList<MedicamentDb>(); for (MedicamentDb medicamentDb : list) { for (MedicamentDb medicamentDb1 : medicamentsDbs) { if(medicamentDb.getPackageID() == medicamentDb1.getPackageID()) { toRemove.add(medicamentDb); break; } } } list.removeAll(toRemove); medicamentsDbFromFile = new ArrayList<MedicamentDb>(list); if(medicamentsDbFromFile.size() > 0) //medicamentDbDAO.addAll(medicamentsDbFromFile); //databaseHandler.getMedicamentDbDAO().addAll(medicamentsDbFromFile); databaseHandler.putAllMedicamentsDb(medicamentsDbFromFile); } return null; } @Override protected void onPreExecute() { progressDialog = ProgressDialog.show(LoginActivity.this, "Synchronizacja...", "Trwa synchronizacja", true, false); } @Override protected void onPostExecute(Void aVoid) { progressDialog.dismiss(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); databaseHandler = new DatabaseHandler(getApplicationContext(), null, null, 1); editTextLoginUserName = (EditText) findViewById(R.id.editTextLoginUserName); editTextLoginPassword = (EditText) findViewById(R.id.editTextLoginPassword); Background background = new Background(getApplicationContext(), getResources()); background.execute(); Log.d("tomo", "2222"); SharedPreferences preference = getSharedPreferences(PREF_NAME, MODE_PRIVATE); userName = preference.getString(PREF_USER, null); String password = preference.getString(PREF_PASSWORD, null); uniqueId = preference.getString(PREF_UNIQUE_ID, null); if (userName != null & password != null & uniqueId != null) { login(); } } private void login() { Toast.makeText(this, "Zalogowano jako " + userName, Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } public void loginClick(View view) { String user = editTextLoginUserName.getText().toString(); String password = editTextLoginPassword.getText().toString(); RestIntefrace restIntefrace = RetrofitBuilder.getRestIntefrace(); Call<User> call = restIntefrace.user(user, password); try { User u = call.execute().body(); if (u != null) { userName = u.getName(); uniqueId = u.getUniqueID(); getSharedPreferences(PREF_NAME, MODE_PRIVATE).edit() .putString(PREF_USER, u.getName()) .putString(PREF_PASSWORD, u.getPassword()) .putString(PREF_UNIQUE_ID, u.getUniqueID()) .commit(); login(); } else Toast.makeText(getApplicationContext(), "Błędny login lub hasło", Toast.LENGTH_SHORT).show(); } catch (SocketTimeoutException e) { Toast.makeText(getApplicationContext(), "Brak połączenia z Internetem", Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); } } public void registerClick(View view) { Intent intent = new Intent(this, RegisterActivity.class); startActivity(intent); } }
package org.myrobotlab.service; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import org.myrobotlab.framework.Service; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.Python.Script; import org.slf4j.Logger; /** * based on _TemplateService */ /** * * @author LunDev (github), Ma. Vo. (MyRobotlab) */ public class InMoovGestureCreator extends Service { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory .getLogger(InMoovGestureCreator.class); ServoItemHolder[][] servoitemholder; ArrayList<FrameItemHolder> frameitemholder; ArrayList<PythonItemHolder> pythonitemholder; boolean[] tabs_main_checkbox_states; boolean moverealtime = false; InMoov i01; String pythonscript; public InMoovGestureCreator(String n) { super(n); // intializing variables servoitemholder = new ServoItemHolder[6][]; frameitemholder = new ArrayList<FrameItemHolder>(); pythonitemholder = new ArrayList<PythonItemHolder>(); tabs_main_checkbox_states = new boolean[6]; } @Override public void startService() { super.startService(); } @Override public void stopService() { super.stopService(); } @Override public String getDescription() { return "an easier way to create gestures for InMoov"; } public void tabs_main_checkbox_states_changed( boolean[] tabs_main_checkbox_states2) { // checkbox states (on the main site) (for the services) changed tabs_main_checkbox_states = tabs_main_checkbox_states2; } public void control_connect(JButton control_connect) { // Connect / Disconnect to / from the InMoov service (button // bottom-left) if (control_connect.getText().equals("Connect")) { i01 = (InMoov) Runtime.getService("i01"); control_connect.setText("Disconnect"); } else { i01 = null; control_connect.setText("Connect"); } } public void control_loadscri(JList control_list) { // Load the Python-Script (out Python-Service) (button bottom-left) Python python = (Python) Runtime.getService("python"); Script script = python.getScript(); pythonscript = script.getCode(); parsescript(control_list); } public void control_savescri() { // Save the Python-Script (in Python-Service) (button bottom-left) JFrame frame = new JFrame(); JTextArea textarea = new JTextArea(); textarea.setText(pythonscript); textarea.setEditable(false); textarea.setLineWrap(true); JScrollPane scrollpane = new JScrollPane(textarea); scrollpane .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollpane .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); frame.add(scrollpane); frame.setVisible(true); } public void control_loadgest(JList control_list, JList framelist, JTextField control_gestname, JTextField control_funcname) { // Load the current gesture from the script (button bottom-left) int posl = control_list.getSelectedIndex(); if (posl != -1) { if (pythonitemholder.get(posl).modifyable) { frameitemholder.clear(); String defname = null; String code = pythonitemholder.get(posl).code; String[] codesplit = code.split("\n"); FrameItemHolder fih = null; boolean ismove = false; boolean isspeed = false; boolean head = false; boolean rhand = false; boolean lhand = false; boolean rarm = false; boolean larm = false; boolean torso = false; boolean keepgoing = true; int pos = 0; while (keepgoing) { if (fih == null) { fih = new FrameItemHolder(); } String line; if (pos < codesplit.length) { line = codesplit[pos]; } else { line = "pweicmfh - only one run"; keepgoing = false; } String linewithoutspace = line.replace(" ", ""); if (linewithoutspace.equals("")) { pos++; continue; } String line2 = line.replace(" ", ""); if (!(ismove) && !(isspeed)) { if (line2.startsWith("def")) { String defn = line.substring(line.indexOf(" ") + 1, line.lastIndexOf("():")); defname = defn; pos++; } else if (line2.startsWith("sleep")) { String sleeptime = line.substring( line.indexOf("(") + 1, line.lastIndexOf(")")); fih.sleep = Integer.parseInt(sleeptime); fih.speech = null; fih.name = null; frameitemholder.add(fih); fih = null; pos++; } else if (line2.startsWith("i01")) { if (line2.startsWith("i01.mouth.speak")) { fih.sleep = -1; fih.speech = line.substring( line.indexOf("(") + 1, line.lastIndexOf(")")); fih.name = null; frameitemholder.add(fih); fih = null; pos++; } else if (line2.startsWith("i01.move")) { ismove = true; String good = line2.substring( line2.indexOf("(") + 1, line2.lastIndexOf(")")); String[] goodsplit = good.split(","); if (line2.startsWith("i01.moveHead")) { fih.neck = Integer.parseInt(goodsplit[0]); fih.rothead = Integer .parseInt(goodsplit[1]); if (goodsplit.length > 2) { fih.eyeX = Integer .parseInt(goodsplit[2]); fih.eyeY = Integer .parseInt(goodsplit[3]); fih.jaw = Integer .parseInt(goodsplit[4]); } else { fih.eyeX = 90; fih.eyeY = 90; fih.jaw = 90; } head = true; pos++; } else if (line2.startsWith("i01.moveHand")) { String gs = goodsplit[0]; String side = gs.substring( gs.indexOf("\"") + 1, gs.lastIndexOf("\"")); if (side.equals("right")) { fih.rthumb = Integer .parseInt(goodsplit[1]); fih.rindex = Integer .parseInt(goodsplit[2]); fih.rmajeure = Integer .parseInt(goodsplit[3]); fih.rringfinger = Integer .parseInt(goodsplit[4]); fih.rpinky = Integer .parseInt(goodsplit[5]); if (goodsplit.length > 6) { fih.rwrist = Integer .parseInt(goodsplit[6]); } else { fih.rwrist = 90; } rhand = true; pos++; } else if (side.equals("left")) { fih.lthumb = Integer .parseInt(goodsplit[1]); fih.lindex = Integer .parseInt(goodsplit[2]); fih.lmajeure = Integer .parseInt(goodsplit[3]); fih.lringfinger = Integer .parseInt(goodsplit[4]); fih.lpinky = Integer .parseInt(goodsplit[5]); if (goodsplit.length > 6) { fih.lwrist = Integer .parseInt(goodsplit[6]); } else { fih.lwrist = 90; } lhand = true; pos++; } } else if (line2.startsWith("i01.moveArm")) { String gs = goodsplit[0]; String side = gs.substring( gs.indexOf("\"") + 1, gs.lastIndexOf("\"")); if (side.equals("right")) { fih.rbicep = Integer .parseInt(goodsplit[1]); fih.rrotate = Integer .parseInt(goodsplit[2]); fih.rshoulder = Integer .parseInt(goodsplit[3]); fih.romoplate = Integer .parseInt(goodsplit[4]); rarm = true; pos++; } else if (side.equals("left")) { fih.lbicep = Integer .parseInt(goodsplit[1]); fih.lrotate = Integer .parseInt(goodsplit[2]); fih.lshoulder = Integer .parseInt(goodsplit[3]); fih.lomoplate = Integer .parseInt(goodsplit[4]); larm = true; pos++; } } else if (line2.startsWith("i01.moveTorso")) { fih.topStom = Integer .parseInt(goodsplit[0]); fih.midStom = Integer .parseInt(goodsplit[1]); fih.lowStom = Integer .parseInt(goodsplit[2]); torso = true; pos++; } } else if (line2.startsWith("i01.set")) { isspeed = true; String good = line2.substring( line2.indexOf("(") + 1, line2.lastIndexOf(")")); String[] goodsplit = good.split(","); if (line2.startsWith("i01.setHeadSpeed")) { fih.neckspeed = Float .parseFloat(goodsplit[0]); fih.rotheadspeed = Float .parseFloat(goodsplit[1]); if (goodsplit.length > 2) { fih.eyeXspeed = Float .parseFloat(goodsplit[2]); fih.eyeYspeed = Float .parseFloat(goodsplit[3]); fih.jawspeed = Float .parseFloat(goodsplit[4]); } else { fih.eyeXspeed = 1.0f; fih.eyeYspeed = 1.0f; fih.jawspeed = 1.0f; } head = true; pos++; } else if (line2.startsWith("i01.setHandSpeed")) { String gs = goodsplit[0]; String side = gs.substring( gs.indexOf("\"") + 1, gs.lastIndexOf("\"")); if (side.equals("right")) { fih.rthumbspeed = Float .parseFloat(goodsplit[1]); fih.rindexspeed = Float .parseFloat(goodsplit[2]); fih.rmajeurespeed = Float .parseFloat(goodsplit[3]); fih.rringfingerspeed = Float .parseFloat(goodsplit[4]); fih.rpinkyspeed = Float .parseFloat(goodsplit[5]); if (goodsplit.length > 6) { fih.rwristspeed = Float .parseFloat(goodsplit[6]); } else { fih.rwristspeed = 1.0f; } rhand = true; pos++; } else if (side.equals("left")) { fih.lthumbspeed = Float .parseFloat(goodsplit[1]); fih.lindexspeed = Float .parseFloat(goodsplit[2]); fih.lmajeurespeed = Float .parseFloat(goodsplit[3]); fih.lringfingerspeed = Float .parseFloat(goodsplit[4]); fih.lpinkyspeed = Float .parseFloat(goodsplit[5]); if (goodsplit.length > 6) { fih.lwristspeed = Float .parseFloat(goodsplit[6]); } else { fih.lwristspeed = 1.0f; } lhand = true; pos++; } } else if (line2.startsWith("i01.setArmSpeed")) { String gs = goodsplit[0]; String side = gs.substring( gs.indexOf("\"") + 1, gs.lastIndexOf("\"")); if (side.equals("right")) { fih.rbicepspeed = Float .parseFloat(goodsplit[1]); fih.rrotatespeed = Float .parseFloat(goodsplit[2]); fih.rshoulderspeed = Float .parseFloat(goodsplit[3]); fih.romoplatespeed = Float .parseFloat(goodsplit[4]); rarm = true; pos++; } else if (side.equals("left")) { fih.lbicepspeed = Float .parseFloat(goodsplit[1]); fih.lrotatespeed = Float .parseFloat(goodsplit[2]); fih.lshoulderspeed = Float .parseFloat(goodsplit[3]); fih.lomoplatespeed = Float .parseFloat(goodsplit[4]); larm = true; pos++; } } else if (line2 .startsWith("i01.setTorsoSpeed")) { fih.topStomspeed = Float .parseFloat(goodsplit[0]); fih.midStomspeed = Float .parseFloat(goodsplit[1]); fih.lowStomspeed = Float .parseFloat(goodsplit[2]); torso = true; pos++; } } } } else if (ismove && !(isspeed)) { if (line2.startsWith("i01.move")) { String good = line2.substring( line2.indexOf("(") + 1, line2.lastIndexOf(")")); String[] goodsplit = good.split(","); if (line2.startsWith("i01.moveHead")) { fih.neck = Integer.parseInt(goodsplit[0]); fih.rothead = Integer.parseInt(goodsplit[1]); if (goodsplit.length > 2) { fih.eyeX = Integer.parseInt(goodsplit[2]); fih.eyeY = Integer.parseInt(goodsplit[3]); fih.jaw = Integer.parseInt(goodsplit[4]); } else { fih.eyeX = 90; fih.eyeY = 90; fih.jaw = 90; } head = true; pos++; } else if (line2.startsWith("i01.moveHand")) { String gs = goodsplit[0]; String side = gs.substring( gs.indexOf("\"") + 1, gs.lastIndexOf("\"")); if (side.equals("right")) { fih.rthumb = Integer.parseInt(goodsplit[1]); fih.rindex = Integer.parseInt(goodsplit[2]); fih.rmajeure = Integer .parseInt(goodsplit[3]); fih.rringfinger = Integer .parseInt(goodsplit[4]); fih.rpinky = Integer.parseInt(goodsplit[5]); if (goodsplit.length > 6) { fih.rwrist = Integer .parseInt(goodsplit[6]); } else { fih.rwrist = 90; } rhand = true; pos++; } else if (side.equals("left")) { fih.lthumb = Integer.parseInt(goodsplit[1]); fih.lindex = Integer.parseInt(goodsplit[2]); fih.lmajeure = Integer .parseInt(goodsplit[3]); fih.lringfinger = Integer .parseInt(goodsplit[4]); fih.lpinky = Integer.parseInt(goodsplit[5]); if (goodsplit.length > 6) { fih.lwrist = Integer .parseInt(goodsplit[6]); } else { fih.lwrist = 90; } lhand = true; pos++; } } else if (line2.startsWith("i01.moveArm")) { String gs = goodsplit[0]; String side = gs.substring( gs.indexOf("\"") + 1, gs.lastIndexOf("\"")); if (side.equals("right")) { fih.rbicep = Integer.parseInt(goodsplit[1]); fih.rrotate = Integer .parseInt(goodsplit[2]); fih.rshoulder = Integer .parseInt(goodsplit[3]); fih.romoplate = Integer .parseInt(goodsplit[4]); rarm = true; pos++; } else if (side.equals("left")) { fih.lbicep = Integer.parseInt(goodsplit[1]); fih.lrotate = Integer .parseInt(goodsplit[2]); fih.lshoulder = Integer .parseInt(goodsplit[3]); fih.lomoplate = Integer .parseInt(goodsplit[4]); larm = true; pos++; } } else if (line2.startsWith("i01.moveTorso")) { fih.topStom = Integer.parseInt(goodsplit[0]); fih.midStom = Integer.parseInt(goodsplit[1]); fih.lowStom = Integer.parseInt(goodsplit[2]); torso = true; pos++; } } else { if (!head) { fih.neck = 90; fih.rothead = 90; fih.eyeX = 90; fih.eyeY = 90; fih.jaw = 90; } if (!rhand) { fih.rthumb = 90; fih.rindex = 90; fih.rmajeure = 90; fih.rringfinger = 90; fih.rpinky = 90; fih.rwrist = 90; } if (!lhand) { fih.lthumb = 90; fih.lindex = 90; fih.lmajeure = 90; fih.lringfinger = 90; fih.lpinky = 90; fih.lwrist = 90; } if (!rarm) { fih.rbicep = 90; fih.rrotate = 90; fih.rshoulder = 90; fih.romoplate = 90; } if (!larm) { fih.lbicep = 90; fih.lrotate = 90; fih.lshoulder = 90; fih.lomoplate = 90; } if (!torso) { fih.topStom = 90; fih.midStom = 90; fih.lowStom = 90; } fih.sleep = -1; fih.speech = null; fih.name = "SEQ"; frameitemholder.add(fih); fih = null; ismove = false; head = false; rhand = false; lhand = false; rarm = false; larm = false; torso = false; } } else if (!(ismove) && isspeed) { if (line2.startsWith("i01.set")) { String good = line2.substring( line2.indexOf("(") + 1, line2.lastIndexOf(")")); String[] goodsplit = good.split(","); if (line2.startsWith("i01.setHeadSpeed")) { fih.neckspeed = Float.parseFloat(goodsplit[0]); fih.rotheadspeed = Float .parseFloat(goodsplit[1]); if (goodsplit.length > 2) { fih.eyeXspeed = Float .parseFloat(goodsplit[2]); fih.eyeYspeed = Float .parseFloat(goodsplit[3]); fih.jawspeed = Float .parseFloat(goodsplit[4]); } else { fih.eyeXspeed = 1.0f; fih.eyeYspeed = 1.0f; fih.jawspeed = 1.0f; } head = true; pos++; } else if (line2.startsWith("i01.setHandSpeed")) { String gs = goodsplit[0]; String side = gs.substring( gs.indexOf("\"") + 1, gs.lastIndexOf("\"")); if (side.equals("right")) { fih.rthumbspeed = Float .parseFloat(goodsplit[1]); fih.rindexspeed = Float .parseFloat(goodsplit[2]); fih.rmajeurespeed = Float .parseFloat(goodsplit[3]); fih.rringfingerspeed = Float .parseFloat(goodsplit[4]); fih.rpinkyspeed = Float .parseFloat(goodsplit[5]); if (goodsplit.length > 6) { fih.rwristspeed = Float .parseFloat(goodsplit[6]); } else { fih.rwristspeed = 1.0f; } rhand = true; pos++; } else if (side.equals("left")) { fih.lthumbspeed = Float .parseFloat(goodsplit[1]); fih.lindexspeed = Float .parseFloat(goodsplit[2]); fih.lmajeurespeed = Float .parseFloat(goodsplit[3]); fih.lringfingerspeed = Float .parseFloat(goodsplit[4]); fih.lpinkyspeed = Float .parseFloat(goodsplit[5]); if (goodsplit.length > 6) { fih.lwristspeed = Float .parseFloat(goodsplit[6]); } else { fih.lwristspeed = 1.0f; } lhand = true; pos++; } } else if (line2.startsWith("i01.setArmSpeed")) { String gs = goodsplit[0]; String side = gs.substring( gs.indexOf("\"") + 1, gs.lastIndexOf("\"")); if (side.equals("right")) { fih.rbicepspeed = Float .parseFloat(goodsplit[1]); fih.rrotatespeed = Float .parseFloat(goodsplit[2]); fih.rshoulderspeed = Float .parseFloat(goodsplit[3]); fih.romoplatespeed = Float .parseFloat(goodsplit[4]); rarm = true; pos++; } else if (side.equals("left")) { fih.lbicepspeed = Float .parseFloat(goodsplit[1]); fih.lrotatespeed = Float .parseFloat(goodsplit[2]); fih.lshoulderspeed = Float .parseFloat(goodsplit[3]); fih.lomoplatespeed = Float .parseFloat(goodsplit[4]); larm = true; pos++; } } else if (line2.startsWith("i01.setTorsoSpeed")) { fih.topStomspeed = Float .parseFloat(goodsplit[0]); fih.midStomspeed = Float .parseFloat(goodsplit[1]); fih.lowStomspeed = Float .parseFloat(goodsplit[2]); torso = true; pos++; } } else { if (!head) { fih.neckspeed = 1.0f; fih.rotheadspeed = 1.0f; fih.eyeXspeed = 1.0f; fih.eyeYspeed = 1.0f; fih.jawspeed = 1.0f; } if (!rhand) { fih.rthumbspeed = 1.0f; fih.rindexspeed = 1.0f; fih.rmajeurespeed = 1.0f; fih.rringfingerspeed = 1.0f; fih.rpinkyspeed = 1.0f; fih.rwristspeed = 1.0f; } if (!lhand) { fih.lthumbspeed = 1.0f; fih.lindexspeed = 1.0f; fih.lmajeurespeed = 1.0f; fih.lringfingerspeed = 1.0f; fih.lpinkyspeed = 1.0f; fih.lwristspeed = 1.0f; } if (!rarm) { fih.rbicepspeed = 1.0f; fih.rrotatespeed = 1.0f; fih.rshoulderspeed = 1.0f; fih.romoplatespeed = 1.0f; } if (!larm) { fih.lbicepspeed = 1.0f; fih.lrotatespeed = 1.0f; fih.lshoulderspeed = 1.0f; fih.lomoplatespeed = 1.0f; } if (!torso) { fih.topStomspeed = 1.0f; fih.midStomspeed = 1.0f; fih.lowStomspeed = 1.0f; } fih.sleep = -1; fih.speech = null; fih.name = null; frameitemholder.add(fih); fih = null; isspeed = false; head = false; rhand = false; lhand = false; rarm = false; larm = false; torso = false; } } else { // this shouldn't be reached // ismove & isspeed true // wrong } } framelistact(framelist); int defnamepos = pythonscript.indexOf(defname); int earpos1 = pythonscript.lastIndexOf("\n", defnamepos); int earpos2 = pythonscript.indexOf("\n", defnamepos); String earline = pythonscript.substring(earpos1 + 1, earpos2); if (earline.startsWith("ear.addCommand")) { String good = earline.substring(earline.indexOf("("), earline.lastIndexOf(")")); String[] goodsplit = good.split(","); String funcnamedirty = goodsplit[0]; String funcname = funcnamedirty.substring( funcnamedirty.indexOf("\"") + 1, funcnamedirty.lastIndexOf("\"")); control_gestname.setText(funcname); control_funcname.setText(defname); } } } } public void control_addgest(JList control_list, JTextField control_gestname, JTextField control_funcname) { // Add the current gesture to the script (button bottom-left) String defname = control_funcname.getText(); String gestname = control_gestname.getText(); String code = ""; for (FrameItemHolder fih : frameitemholder) { String code1; if (fih.sleep != -1) { code1 = " sleep(" + fih.sleep + ")\n"; } else if (fih.speech != null) { code1 = " i01.mouth.speakBlocking(\"" + fih.speech + "\")\n"; } else if (fih.name != null) { String code11 = ""; String code12 = ""; String code13 = ""; String code14 = ""; String code15 = ""; String code16 = ""; if (tabs_main_checkbox_states[0]) { code11 = " i01.moveHead(" + fih.neck + "," + fih.rothead + "," + fih.eyeX + "," + fih.eyeY + "," + fih.jaw + ")\n"; } if (tabs_main_checkbox_states[1]) { code12 = " i01.moveArm(\"left\"," + fih.lbicep + "," + fih.lrotate + "," + fih.lshoulder + "," + fih.lomoplate + ")\n"; } if (tabs_main_checkbox_states[2]) { code13 = " i01.moveArm(\"right\"," + fih.rbicep + "," + fih.rrotate + "," + fih.rshoulder + "," + fih.romoplate + ")\n"; } if (tabs_main_checkbox_states[3]) { code14 = " i01.moveHand(\"left\"," + fih.lthumb + "," + fih.lindex + "," + fih.lmajeure + "," + fih.lringfinger + "," + fih.lpinky + "," + fih.lwrist + ")\n"; } if (tabs_main_checkbox_states[4]) { code15 = " i01.moveHand(\"right\"," + fih.rthumb + "," + fih.rindex + "," + fih.rmajeure + "," + fih.rringfinger + "," + fih.rpinky + "," + fih.rwrist + ")\n"; } if (tabs_main_checkbox_states[5]) { code16 = " i01.moveTorso(" + fih.topStom + "," + fih.midStom + "," + fih.lowStom + ")\n"; } code1 = code11 + code12 + code13 + code14 + code15 + code16; } else { String code11 = ""; String code12 = ""; String code13 = ""; String code14 = ""; String code15 = ""; String code16 = ""; if (tabs_main_checkbox_states[0]) { code11 = " i01.setHeadSpeed(" + fih.neckspeed + "," + fih.rotheadspeed + "," + fih.eyeXspeed + "," + fih.eyeYspeed + "," + fih.jawspeed + ")\n"; } if (tabs_main_checkbox_states[1]) { code12 = " i01.setArmSpeed(\"left\"," + fih.lbicepspeed + "," + fih.lrotatespeed + "," + fih.lshoulderspeed + "," + fih.lomoplatespeed + ")\n"; } if (tabs_main_checkbox_states[2]) { code13 = " i01.setArmSpeed(\"right\"," + fih.rbicepspeed + "," + fih.rrotatespeed + "," + fih.rshoulderspeed + "," + fih.romoplatespeed + ")\n"; } if (tabs_main_checkbox_states[3]) { code14 = " i01.setHandSpeed(\"left\"," + fih.lthumbspeed + "," + fih.lindexspeed + "," + fih.lmajeurespeed + "," + fih.lringfingerspeed + "," + fih.lpinkyspeed + "," + fih.lwristspeed + ")\n"; } if (tabs_main_checkbox_states[4]) { code15 = " i01.setHandSpeed(\"right\"," + fih.rthumbspeed + "," + fih.rindexspeed + "," + fih.rmajeurespeed + "," + fih.rringfingerspeed + "," + fih.rpinkyspeed + "," + fih.rwristspeed + ")\n"; } if (tabs_main_checkbox_states[5]) { code16 = " i01.setTorsoSpeed(" + fih.topStomspeed + "," + fih.midStomspeed + "," + fih.lowStomspeed + ")\n"; } code1 = code11 + code12 + code13 + code14 + code15 + code16; } code = code + code1; } String finalcode = "def " + defname + "():\n" + code; String insert = "ear.addCommand(\"" + gestname + "\", \"python\", \"" + defname + "\")"; int posear = pythonscript.lastIndexOf("ear.addCommand"); int pos = pythonscript.indexOf("\n", posear); pythonscript = pythonscript.substring(0, pos) + "\n" + insert + pythonscript.substring(pos, pythonscript.length()); pythonscript = pythonscript + "\n" + finalcode; parsescript(control_list); } public void control_updategest(JList control_list, JTextField control_gestname, JTextField control_funcname) { // Update the current gesture in the script (button bottom-left) int posl = control_list.getSelectedIndex(); if (posl != -1) { if (pythonitemholder.get(posl).function && !pythonitemholder.get(posl).notfunction) { String codeold = pythonitemholder.get(posl).code; String defnameold = codeold.substring( codeold.indexOf("def ") + 4, codeold.indexOf("():")); String defname = control_funcname.getText(); String gestname = control_gestname.getText(); String code = ""; for (FrameItemHolder fih : frameitemholder) { String code1; if (fih.sleep != -1) { code1 = " sleep(" + fih.sleep + ")\n"; } else if (fih.speech != null) { code1 = " i01.mouth.speakBlocking(\"" + fih.speech + "\")\n"; } else if (fih.name != null) { String code11 = ""; String code12 = ""; String code13 = ""; String code14 = ""; String code15 = ""; String code16 = ""; if (tabs_main_checkbox_states[0]) { code11 = " i01.moveHead(" + fih.neck + "," + fih.rothead + "," + fih.eyeX + "," + fih.eyeY + "," + fih.jaw + ")\n"; } if (tabs_main_checkbox_states[1]) { code12 = " i01.moveArm(\"left\"," + fih.lbicep + "," + fih.lrotate + "," + fih.lshoulder + "," + fih.lomoplate + ")\n"; } if (tabs_main_checkbox_states[2]) { code13 = " i01.moveArm(\"right\"," + fih.rbicep + "," + fih.rrotate + "," + fih.rshoulder + "," + fih.romoplate + ")\n"; } if (tabs_main_checkbox_states[3]) { code14 = " i01.moveHand(\"left\"," + fih.lthumb + "," + fih.lindex + "," + fih.lmajeure + "," + fih.lringfinger + "," + fih.lpinky + "," + fih.lwrist + ")\n"; } if (tabs_main_checkbox_states[4]) { code15 = " i01.moveHand(\"right\"," + fih.rthumb + "," + fih.rindex + "," + fih.rmajeure + "," + fih.rringfinger + "," + fih.rpinky + "," + fih.rwrist + ")\n"; } if (tabs_main_checkbox_states[5]) { code16 = " i01.moveTorso(" + fih.topStom + "," + fih.midStom + "," + fih.lowStom + ")\n"; } code1 = code11 + code12 + code13 + code14 + code15 + code16; } else { String code11 = ""; String code12 = ""; String code13 = ""; String code14 = ""; String code15 = ""; String code16 = ""; if (tabs_main_checkbox_states[0]) { code11 = " i01.setHeadSpeed(" + fih.neckspeed + "," + fih.rotheadspeed + "," + fih.eyeXspeed + "," + fih.eyeYspeed + "," + fih.jawspeed + ")\n"; } if (tabs_main_checkbox_states[1]) { code12 = " i01.setArmSpeed(\"left\"," + fih.lbicepspeed + "," + fih.lrotatespeed + "," + fih.lshoulderspeed + "," + fih.lomoplatespeed + ")\n"; } if (tabs_main_checkbox_states[2]) { code13 = " i01.setArmSpeed(\"right\"," + fih.rbicepspeed + "," + fih.rrotatespeed + "," + fih.rshoulderspeed + "," + fih.romoplatespeed + ")\n"; } if (tabs_main_checkbox_states[3]) { code14 = " i01.setHandSpeed(\"left\"," + fih.lthumbspeed + "," + fih.lindexspeed + "," + fih.lmajeurespeed + "," + fih.lringfingerspeed + "," + fih.lpinkyspeed + "," + fih.lwristspeed + ")\n"; } if (tabs_main_checkbox_states[4]) { code15 = " i01.setHandSpeed(\"right\"," + fih.rthumbspeed + "," + fih.rindexspeed + "," + fih.rmajeurespeed + "," + fih.rringfingerspeed + "," + fih.rpinkyspeed + "," + fih.rwristspeed + ")\n"; } if (tabs_main_checkbox_states[5]) { code16 = " i01.setTorsoSpeed(" + fih.topStomspeed + "," + fih.midStomspeed + "," + fih.lowStomspeed + ")\n"; } code1 = code11 + code12 + code13 + code14 + code15 + code16; } code = code + code1; } String finalcode = "def " + defname + "():\n" + code; String insert = "ear.addCommand(\"" + gestname + "\", \"python\", \"" + defname + "\")"; int olddefpos = pythonscript.indexOf(defnameold); int pos1 = pythonscript.lastIndexOf("\n", olddefpos); int pos2 = pythonscript.indexOf("\n", olddefpos); pythonscript = pythonscript.substring(0, pos1) + "\n" + insert + pythonscript.substring(pos2, pythonscript.length()); int posscript = pythonscript.lastIndexOf(defnameold); int posscriptnextdef = pythonscript.indexOf("def", posscript); if (posscriptnextdef == -1) { posscriptnextdef = pythonscript.length(); } pythonscript = pythonscript.substring(0, posscript - 4) + "\n" + finalcode + pythonscript.substring(posscriptnextdef - 1, pythonscript.length()); parsescript(control_list); } } } public void control_removegest(JList control_list) { // Remove the selected gesture from the script (button bottom-left) int posl = control_list.getSelectedIndex(); if (posl != -1) { if (pythonitemholder.get(posl).function && !pythonitemholder.get(posl).notfunction) { String codeold = pythonitemholder.get(posl).code; String defnameold = codeold.substring( codeold.indexOf("def ") + 4, codeold.indexOf("():")); int olddefpos = pythonscript.indexOf(defnameold); int pos1 = pythonscript.lastIndexOf("\n", olddefpos); int pos2 = pythonscript.indexOf("\n", olddefpos); pythonscript = pythonscript.substring(0, pos1) + pythonscript.substring(pos2, pythonscript.length()); int posscript = pythonscript.lastIndexOf(defnameold); int posscriptnextdef = pythonscript.indexOf("def", posscript); if (posscriptnextdef == -1) { posscriptnextdef = pythonscript.length(); } pythonscript = pythonscript.substring(0, posscript - 4) + pythonscript.substring(posscriptnextdef - 1, pythonscript.length()); parsescript(control_list); } } } public void control_testgest() { // test (execute) the created gesture (button bottom-left) if (i01 != null) { for (FrameItemHolder fih : frameitemholder) { if (fih.sleep != -1) { sleep(fih.sleep); } else if (fih.speech != null) { i01.mouth.speakBlocking(fih.speech); } else if (fih.name != null) { if (tabs_main_checkbox_states[0]) { i01.moveHead(fih.neck, fih.rothead, fih.eyeX, fih.eyeY, fih.jaw); } if (tabs_main_checkbox_states[1]) { i01.moveArm("left", fih.lbicep, fih.lrotate, fih.lshoulder, fih.lomoplate); } if (tabs_main_checkbox_states[2]) { i01.moveArm("right", fih.rbicep, fih.rrotate, fih.rshoulder, fih.romoplate); } if (tabs_main_checkbox_states[3]) { i01.moveHand("left", fih.lthumb, fih.lindex, fih.lmajeure, fih.lringfinger, fih.lpinky, fih.lwrist); } if (tabs_main_checkbox_states[4]) { i01.moveHand("right", fih.rthumb, fih.rindex, fih.rmajeure, fih.rringfinger, fih.rpinky, fih.rwrist); } if (tabs_main_checkbox_states[5]) { i01.moveTorso(fih.topStom, fih.midStom, fih.lowStom); } } else { if (tabs_main_checkbox_states[0]) { i01.setHeadSpeed(fih.neckspeed, fih.rotheadspeed, fih.eyeXspeed, fih.eyeYspeed, fih.jawspeed); } if (tabs_main_checkbox_states[1]) { i01.setArmSpeed("left", fih.lbicepspeed, fih.lrotatespeed, fih.lshoulderspeed, fih.lomoplatespeed); } if (tabs_main_checkbox_states[2]) { i01.setArmSpeed("right", fih.rbicepspeed, fih.rrotatespeed, fih.rshoulderspeed, fih.romoplatespeed); } if (tabs_main_checkbox_states[3]) { i01.setHandSpeed("left", fih.lthumbspeed, fih.lindexspeed, fih.lmajeurespeed, fih.lringfingerspeed, fih.lpinkyspeed, fih.lwristspeed); } if (tabs_main_checkbox_states[4]) { i01.setHandSpeed("right", fih.rthumbspeed, fih.rindexspeed, fih.rmajeurespeed, fih.rringfingerspeed, fih.rpinkyspeed, fih.rwristspeed); } if (tabs_main_checkbox_states[5]) { i01.setTorsoSpeed(fih.topStomspeed, fih.midStomspeed, fih.lowStomspeed); } } } } } public void controllistact(JList control_list) { String[] listdata = new String[pythonitemholder.size()]; for (int i = 0; i < pythonitemholder.size(); i++) { PythonItemHolder pih = pythonitemholder.get(i); String pre; if (!(pih.modifyable)) { pre = "X "; } else { pre = " "; } int he = 21; if (pih.code.length() < he) { he = pih.code.length(); } String des = pih.code.substring(0, he); String displaytext = pre + des; listdata[i] = displaytext; } control_list.setListData(listdata); } public void frame_add(JList framelist, JTextField frame_add_textfield) { // Add a servo movement frame to the framelist (button bottom-right) FrameItemHolder fih = new FrameItemHolder(); fih.rthumb = servoitemholder[0][0].sli.getValue(); fih.rindex = servoitemholder[0][1].sli.getValue(); fih.rmajeure = servoitemholder[0][2].sli.getValue(); fih.rringfinger = servoitemholder[0][3].sli.getValue(); fih.rpinky = servoitemholder[0][4].sli.getValue(); fih.rwrist = servoitemholder[0][5].sli.getValue(); fih.rbicep = servoitemholder[1][0].sli.getValue(); fih.rrotate = servoitemholder[1][1].sli.getValue(); fih.rshoulder = servoitemholder[1][2].sli.getValue(); fih.romoplate = servoitemholder[1][3].sli.getValue(); fih.lthumb = servoitemholder[2][0].sli.getValue(); fih.lindex = servoitemholder[2][1].sli.getValue(); fih.lmajeure = servoitemholder[2][2].sli.getValue(); fih.lringfinger = servoitemholder[2][3].sli.getValue(); fih.lpinky = servoitemholder[2][4].sli.getValue(); fih.lwrist = servoitemholder[2][5].sli.getValue(); fih.lbicep = servoitemholder[3][0].sli.getValue(); fih.lrotate = servoitemholder[3][1].sli.getValue(); fih.lshoulder = servoitemholder[3][2].sli.getValue(); fih.lomoplate = servoitemholder[3][3].sli.getValue(); fih.neck = servoitemholder[4][0].sli.getValue(); fih.rothead = servoitemholder[4][1].sli.getValue(); fih.eyeX = servoitemholder[4][2].sli.getValue(); fih.eyeY = servoitemholder[4][3].sli.getValue(); fih.jaw = servoitemholder[4][4].sli.getValue(); fih.topStom = servoitemholder[5][0].sli.getValue(); fih.midStom = servoitemholder[5][1].sli.getValue(); fih.lowStom = servoitemholder[5][2].sli.getValue(); fih.sleep = -1; fih.speech = null; fih.name = frame_add_textfield.getText(); frameitemholder.add(fih); framelistact(framelist); } public void frame_addspeed(JList framelist) { // Add a speed setting frame to the framelist (button bottom-right) FrameItemHolder fih = new FrameItemHolder(); fih.rthumbspeed = Float.parseFloat(servoitemholder[0][0].spe.getText()); fih.rindexspeed = Float.parseFloat(servoitemholder[0][1].spe.getText()); fih.rmajeurespeed = Float.parseFloat(servoitemholder[0][2].spe .getText()); fih.rringfingerspeed = Float.parseFloat(servoitemholder[0][3].spe .getText()); fih.rpinkyspeed = Float.parseFloat(servoitemholder[0][4].spe.getText()); fih.rwristspeed = Float.parseFloat(servoitemholder[0][5].spe.getText()); fih.rbicepspeed = Float.parseFloat(servoitemholder[1][0].spe.getText()); fih.rrotatespeed = Float .parseFloat(servoitemholder[1][1].spe.getText()); fih.rshoulderspeed = Float.parseFloat(servoitemholder[1][2].spe .getText()); fih.romoplatespeed = Float.parseFloat(servoitemholder[1][3].spe .getText()); fih.lthumbspeed = Float.parseFloat(servoitemholder[2][0].spe.getText()); fih.lindexspeed = Float.parseFloat(servoitemholder[2][1].spe.getText()); fih.lmajeurespeed = Float.parseFloat(servoitemholder[2][2].spe .getText()); fih.lringfingerspeed = Float.parseFloat(servoitemholder[2][3].spe .getText()); fih.lpinkyspeed = Float.parseFloat(servoitemholder[2][4].spe.getText()); fih.lwristspeed = Float.parseFloat(servoitemholder[2][5].spe.getText()); fih.lbicepspeed = Float.parseFloat(servoitemholder[3][0].spe.getText()); fih.lrotatespeed = Float .parseFloat(servoitemholder[3][1].spe.getText()); fih.lshoulderspeed = Float.parseFloat(servoitemholder[3][2].spe .getText()); fih.lomoplatespeed = Float.parseFloat(servoitemholder[3][3].spe .getText()); fih.neckspeed = Float.parseFloat(servoitemholder[4][0].spe.getText()); fih.rotheadspeed = Float .parseFloat(servoitemholder[4][1].spe.getText()); fih.eyeXspeed = Float.parseFloat(servoitemholder[4][2].spe.getText()); fih.eyeYspeed = Float.parseFloat(servoitemholder[4][3].spe.getText()); fih.jawspeed = Float.parseFloat(servoitemholder[4][4].spe.getText()); fih.topStomspeed = Float .parseFloat(servoitemholder[5][0].spe.getText()); fih.midStomspeed = Float .parseFloat(servoitemholder[5][1].spe.getText()); fih.lowStomspeed = Float .parseFloat(servoitemholder[5][2].spe.getText()); fih.sleep = -1; fih.speech = null; fih.name = null; frameitemholder.add(fih); framelistact(framelist); } public void frame_addsleep(JList framelist, JTextField frame_addsleep_textfield) { // Add a sleep frame to the framelist (button bottom-right) FrameItemHolder fih = new FrameItemHolder(); fih.sleep = Integer.parseInt(frame_addsleep_textfield.getText()); fih.speech = null; fih.name = null; frameitemholder.add(fih); framelistact(framelist); } public void frame_addspeech(JList framelist, JTextField frame_addspeech_textfield) { // Add a speech frame to the framelist (button bottom-right) FrameItemHolder fih = new FrameItemHolder(); fih.sleep = -1; fih.speech = frame_addspeech_textfield.getText(); fih.name = null; frameitemholder.add(fih); framelistact(framelist); } public void frame_importminresmax() { // Import the Min- / Res- / Max- settings of your InMoov for (int i1 = 0; i1 < servoitemholder.length; i1++) { for (int i2 = 0; i2 < servoitemholder[i1].length; i2++) { InMoovHand inmhand = null; InMoovArm inmarm = null; InMoovHead inmhead = null; InMoovTorso inmtorso = null; if (i1 == 0) { inmhand = i01.rightHand; } else if (i1 == 1) { inmarm = i01.rightArm; } else if (i1 == 2) { inmhand = i01.leftHand; } else if (i1 == 3) { inmarm = i01.rightArm; } else if (i1 == 4) { inmhead = i01.head; } else if (i1 == 5) { inmtorso = i01.torso; } Servo servo = null; if (i1 == 0 || i1 == 2) { if (i2 == 0) { servo = inmhand.thumb; } else if (i2 == 1) { servo = inmhand.index; } else if (i2 == 2) { servo = inmhand.majeure; } else if (i2 == 3) { servo = inmhand.ringFinger; } else if (i2 == 4) { servo = inmhand.pinky; } else if (i2 == 5) { servo = inmhand.wrist; } } else if (i1 == 1 || i1 == 3) { if (i2 == 0) { servo = inmarm.bicep; } else if (i2 == 1) { servo = inmarm.rotate; } else if (i2 == 2) { servo = inmarm.shoulder; } else if (i2 == 3) { servo = inmarm.omoplate; } } else if (i1 == 4) { if (i2 == 0) { servo = inmhead.neck; } else if (i2 == 1) { servo = inmhead.rothead; } else if (i2 == 2) { servo = inmhead.eyeX; } else if (i2 == 3) { servo = inmhead.eyeY; } else if (i2 == 4) { servo = inmhead.jaw; } } else if (i1 == 5) { if (i2 == 0) { servo = inmtorso.topStom; } else if (i2 == 1) { servo = inmtorso.midStom; } else if (i2 == 2) { servo = inmtorso.lowStom; } } int min = servo.getMin(); int res = servo.getRest(); int max = servo.getMax(); servoitemholder[i1][i2].min.setText(min + ""); servoitemholder[i1][i2].res.setText(res + ""); servoitemholder[i1][i2].max.setText(max + ""); servoitemholder[i1][i2].sli.setMinimum(min); servoitemholder[i1][i2].sli.setMaximum(max); servoitemholder[i1][i2].sli.setValue(res); } } } public void frame_remove(JList framelist) { // Remove this frame from the framelist (button bottom-right) int pos = framelist.getSelectedIndex(); if (pos != -1) { frameitemholder.remove(pos); framelistact(framelist); } } public void frame_load(JList framelist, JTextField frame_add_textfield, JTextField frame_addsleep_textfield, JTextField frame_addspeech_textfield) { // Load this frame from the framelist (button bottom-right) int pos = framelist.getSelectedIndex(); if (pos != -1) { // sleep || speech || servo movement || speed setting if (frameitemholder.get(pos).sleep != -1) { frame_addsleep_textfield.setText(frameitemholder.get(pos).sleep + ""); } else if (frameitemholder.get(pos).speech != null) { frame_addspeech_textfield .setText(frameitemholder.get(pos).speech); } else if (frameitemholder.get(pos).name != null) { servoitemholder[0][0].sli .setValue(frameitemholder.get(pos).rthumb); servoitemholder[0][1].sli .setValue(frameitemholder.get(pos).rindex); servoitemholder[0][2].sli .setValue(frameitemholder.get(pos).rmajeure); servoitemholder[0][3].sli .setValue(frameitemholder.get(pos).rringfinger); servoitemholder[0][4].sli .setValue(frameitemholder.get(pos).rpinky); servoitemholder[0][5].sli .setValue(frameitemholder.get(pos).rwrist); servoitemholder[1][0].sli .setValue(frameitemholder.get(pos).rbicep); servoitemholder[1][1].sli .setValue(frameitemholder.get(pos).rrotate); servoitemholder[1][2].sli .setValue(frameitemholder.get(pos).rshoulder); servoitemholder[1][3].sli .setValue(frameitemholder.get(pos).romoplate); servoitemholder[2][0].sli .setValue(frameitemholder.get(pos).lthumb); servoitemholder[2][1].sli .setValue(frameitemholder.get(pos).lindex); servoitemholder[2][2].sli .setValue(frameitemholder.get(pos).lmajeure); servoitemholder[2][3].sli .setValue(frameitemholder.get(pos).lringfinger); servoitemholder[2][4].sli .setValue(frameitemholder.get(pos).lpinky); servoitemholder[2][5].sli .setValue(frameitemholder.get(pos).lwrist); servoitemholder[3][0].sli .setValue(frameitemholder.get(pos).lbicep); servoitemholder[3][1].sli .setValue(frameitemholder.get(pos).lrotate); servoitemholder[3][2].sli .setValue(frameitemholder.get(pos).lshoulder); servoitemholder[3][3].sli .setValue(frameitemholder.get(pos).lomoplate); servoitemholder[4][0].sli .setValue(frameitemholder.get(pos).neck); servoitemholder[4][1].sli .setValue(frameitemholder.get(pos).rothead); servoitemholder[4][2].sli .setValue(frameitemholder.get(pos).eyeX); servoitemholder[4][3].sli .setValue(frameitemholder.get(pos).eyeY); servoitemholder[4][4].sli .setValue(frameitemholder.get(pos).jaw); servoitemholder[5][0].sli .setValue(frameitemholder.get(pos).topStom); servoitemholder[5][1].sli .setValue(frameitemholder.get(pos).midStom); servoitemholder[5][2].sli .setValue(frameitemholder.get(pos).lowStom); frame_add_textfield.setText(frameitemholder.get(pos).name); } else { servoitemholder[0][0].spe .setText(frameitemholder.get(pos).rthumbspeed + ""); servoitemholder[0][1].spe .setText(frameitemholder.get(pos).rindexspeed + ""); servoitemholder[0][2].spe .setText(frameitemholder.get(pos).rmajeurespeed + ""); servoitemholder[0][3].spe .setText(frameitemholder.get(pos).rringfingerspeed + ""); servoitemholder[0][4].spe .setText(frameitemholder.get(pos).rpinkyspeed + ""); servoitemholder[0][5].spe .setText(frameitemholder.get(pos).rwristspeed + ""); servoitemholder[1][0].spe .setText(frameitemholder.get(pos).rbicepspeed + ""); servoitemholder[1][1].spe .setText(frameitemholder.get(pos).rrotatespeed + ""); servoitemholder[1][2].spe .setText(frameitemholder.get(pos).rshoulderspeed + ""); servoitemholder[1][3].spe .setText(frameitemholder.get(pos).romoplatespeed + ""); servoitemholder[2][0].spe .setText(frameitemholder.get(pos).lthumbspeed + ""); servoitemholder[2][1].spe .setText(frameitemholder.get(pos).lindexspeed + ""); servoitemholder[2][2].spe .setText(frameitemholder.get(pos).lmajeurespeed + ""); servoitemholder[2][3].spe .setText(frameitemholder.get(pos).lringfingerspeed + ""); servoitemholder[2][4].spe .setText(frameitemholder.get(pos).lpinkyspeed + ""); servoitemholder[2][5].spe .setText(frameitemholder.get(pos).lwristspeed + ""); servoitemholder[3][0].spe .setText(frameitemholder.get(pos).lbicepspeed + ""); servoitemholder[3][1].spe .setText(frameitemholder.get(pos).lrotatespeed + ""); servoitemholder[3][2].spe .setText(frameitemholder.get(pos).lshoulderspeed + ""); servoitemholder[3][3].spe .setText(frameitemholder.get(pos).lomoplatespeed + ""); servoitemholder[4][0].spe .setText(frameitemholder.get(pos).neckspeed + ""); servoitemholder[4][1].spe .setText(frameitemholder.get(pos).rotheadspeed + ""); servoitemholder[4][2].spe .setText(frameitemholder.get(pos).eyeXspeed + ""); servoitemholder[4][3].spe .setText(frameitemholder.get(pos).eyeYspeed + ""); servoitemholder[4][4].spe .setText(frameitemholder.get(pos).jawspeed + ""); servoitemholder[5][0].spe .setText(frameitemholder.get(pos).topStomspeed + ""); servoitemholder[5][1].spe .setText(frameitemholder.get(pos).midStomspeed + ""); servoitemholder[5][2].spe .setText(frameitemholder.get(pos).lowStomspeed + ""); } } } public void frame_update(JList framelist, JTextField frame_add_textfield, JTextField frame_addsleep_textfield, JTextField frame_addspeech_textfield) { // Update this frame on the framelist (button bottom-right) int pos = framelist.getSelectedIndex(); if (pos != -1) { FrameItemHolder fih = new FrameItemHolder(); // sleep || speech || servo movement || speed setting if (frameitemholder.get(pos).sleep != -1) { fih.sleep = Integer .parseInt(frame_addsleep_textfield.getText()); fih.speech = null; fih.name = null; } else if (frameitemholder.get(pos).speech != null) { fih.sleep = -1; fih.speech = frame_addspeech_textfield.getText(); fih.name = null; } else if (frameitemholder.get(pos).name != null) { fih.rthumb = servoitemholder[0][0].sli.getValue(); fih.rindex = servoitemholder[0][1].sli.getValue(); fih.rmajeure = servoitemholder[0][2].sli.getValue(); fih.rringfinger = servoitemholder[0][3].sli.getValue(); fih.rpinky = servoitemholder[0][4].sli.getValue(); fih.rwrist = servoitemholder[0][5].sli.getValue(); fih.rbicep = servoitemholder[1][0].sli.getValue(); fih.rrotate = servoitemholder[1][1].sli.getValue(); fih.rshoulder = servoitemholder[1][2].sli.getValue(); fih.romoplate = servoitemholder[1][3].sli.getValue(); fih.lthumb = servoitemholder[2][0].sli.getValue(); fih.lindex = servoitemholder[2][1].sli.getValue(); fih.lmajeure = servoitemholder[2][2].sli.getValue(); fih.lringfinger = servoitemholder[2][3].sli.getValue(); fih.lpinky = servoitemholder[2][4].sli.getValue(); fih.lwrist = servoitemholder[2][5].sli.getValue(); fih.lbicep = servoitemholder[3][0].sli.getValue(); fih.lrotate = servoitemholder[3][1].sli.getValue(); fih.lshoulder = servoitemholder[3][2].sli.getValue(); fih.lomoplate = servoitemholder[3][3].sli.getValue(); fih.neck = servoitemholder[4][0].sli.getValue(); fih.rothead = servoitemholder[4][1].sli.getValue(); fih.eyeX = servoitemholder[4][2].sli.getValue(); fih.eyeY = servoitemholder[4][3].sli.getValue(); fih.jaw = servoitemholder[4][4].sli.getValue(); fih.topStom = servoitemholder[5][0].sli.getValue(); fih.midStom = servoitemholder[5][1].sli.getValue(); fih.lowStom = servoitemholder[5][2].sli.getValue(); fih.sleep = -1; fih.speech = null; fih.name = frame_add_textfield.getText(); } else { fih.rthumbspeed = Float.parseFloat(servoitemholder[0][0].spe .getText()); fih.rindexspeed = Float.parseFloat(servoitemholder[0][1].spe .getText()); fih.rmajeurespeed = Float.parseFloat(servoitemholder[0][2].spe .getText()); fih.rringfingerspeed = Float .parseFloat(servoitemholder[0][3].spe.getText()); fih.rpinkyspeed = Float.parseFloat(servoitemholder[0][4].spe .getText()); fih.rwristspeed = Float.parseFloat(servoitemholder[0][5].spe .getText()); fih.rbicepspeed = Float.parseFloat(servoitemholder[1][0].spe .getText()); fih.rrotatespeed = Float.parseFloat(servoitemholder[1][1].spe .getText()); fih.rshoulderspeed = Float.parseFloat(servoitemholder[1][2].spe .getText()); fih.romoplatespeed = Float.parseFloat(servoitemholder[1][3].spe .getText()); fih.lthumbspeed = Float.parseFloat(servoitemholder[2][0].spe .getText()); fih.lindexspeed = Float.parseFloat(servoitemholder[2][1].spe .getText()); fih.lmajeurespeed = Float.parseFloat(servoitemholder[2][2].spe .getText()); fih.lringfingerspeed = Float .parseFloat(servoitemholder[2][3].spe.getText()); fih.lpinkyspeed = Float.parseFloat(servoitemholder[2][4].spe .getText()); fih.lwristspeed = Float.parseFloat(servoitemholder[2][5].spe .getText()); fih.lbicepspeed = Float.parseFloat(servoitemholder[3][0].spe .getText()); fih.lrotatespeed = Float.parseFloat(servoitemholder[3][1].spe .getText()); fih.lshoulderspeed = Float.parseFloat(servoitemholder[3][2].spe .getText()); fih.lomoplatespeed = Float.parseFloat(servoitemholder[3][3].spe .getText()); fih.neckspeed = Float.parseFloat(servoitemholder[4][0].spe .getText()); fih.rotheadspeed = Float.parseFloat(servoitemholder[4][1].spe .getText()); fih.eyeXspeed = Float.parseFloat(servoitemholder[4][2].spe .getText()); fih.eyeYspeed = Float.parseFloat(servoitemholder[4][3].spe .getText()); fih.jawspeed = Float.parseFloat(servoitemholder[4][4].spe .getText()); fih.topStomspeed = Float.parseFloat(servoitemholder[5][0].spe .getText()); fih.midStomspeed = Float.parseFloat(servoitemholder[5][1].spe .getText()); fih.lowStomspeed = Float.parseFloat(servoitemholder[5][2].spe .getText()); fih.sleep = -1; fih.speech = null; fih.name = null; } frameitemholder.set(pos, fih); framelistact(framelist); } } public void frame_copy(JList framelist) { // Copy this frame on the framelist (button bottom-right) int pos = framelist.getSelectedIndex(); if (pos != -1) { FrameItemHolder fih = frameitemholder.get(pos); frameitemholder.add(fih); framelistact(framelist); } } public void frame_up(JList framelist) { // Move this frame one up on the framelist (button bottom-right) int pos = framelist.getSelectedIndex(); if (pos != -1) { FrameItemHolder fih = frameitemholder.remove(pos); frameitemholder.add(pos - 1, fih); framelistact(framelist); } } public void frame_down(JList framelist) { // Move this frame one down on the framelist (button bottom-right) int pos = framelist.getSelectedIndex(); if (pos != -1) { FrameItemHolder fih = frameitemholder.remove(pos); frameitemholder.add(pos + 1, fih); framelistact(framelist); } } public void frame_test(JList framelist) { // Test this frame (execute) int pos = framelist.getSelectedIndex(); if (i01 != null && pos != -1) { FrameItemHolder fih = frameitemholder.get(pos); // sleep || speech || servo movement || speed setting if (fih.sleep != -1) { sleep(fih.sleep); } else if (fih.speech != null) { i01.mouth.speakBlocking(fih.speech); } else if (fih.name != null) { if (tabs_main_checkbox_states[0]) { i01.moveHead(fih.neck, fih.rothead, fih.eyeX, fih.eyeY, fih.jaw); } if (tabs_main_checkbox_states[1]) { i01.moveArm("left", fih.lbicep, fih.lrotate, fih.lshoulder, fih.lomoplate); } if (tabs_main_checkbox_states[2]) { i01.moveArm("right", fih.rbicep, fih.rrotate, fih.rshoulder, fih.romoplate); } if (tabs_main_checkbox_states[3]) { i01.moveHand("left", fih.lthumb, fih.lindex, fih.lmajeure, fih.lringfinger, fih.lpinky, fih.lwrist); } if (tabs_main_checkbox_states[4]) { i01.moveHand("right", fih.rthumb, fih.rindex, fih.rmajeure, fih.rringfinger, fih.rpinky, fih.rwrist); } if (tabs_main_checkbox_states[5]) { i01.moveTorso(fih.topStom, fih.midStom, fih.lowStom); } } else { if (tabs_main_checkbox_states[0]) { i01.setHeadSpeed(fih.neckspeed, fih.rotheadspeed, fih.eyeXspeed, fih.eyeYspeed, fih.jawspeed); } if (tabs_main_checkbox_states[1]) { i01.setArmSpeed("left", fih.lbicepspeed, fih.lrotatespeed, fih.lshoulderspeed, fih.lomoplatespeed); } if (tabs_main_checkbox_states[2]) { i01.setArmSpeed("right", fih.rbicepspeed, fih.rrotatespeed, fih.rshoulderspeed, fih.romoplatespeed); } if (tabs_main_checkbox_states[3]) { i01.setHandSpeed("left", fih.lthumbspeed, fih.lindexspeed, fih.lmajeurespeed, fih.lringfingerspeed, fih.lpinkyspeed, fih.lwristspeed); } if (tabs_main_checkbox_states[4]) { i01.setHandSpeed("right", fih.rthumbspeed, fih.rindexspeed, fih.rmajeurespeed, fih.rringfingerspeed, fih.rpinkyspeed, fih.rwristspeed); } if (tabs_main_checkbox_states[5]) { i01.setTorsoSpeed(fih.topStomspeed, fih.midStomspeed, fih.lowStomspeed); } } } } public void framelistact(JList framelist) { // Re-Build the framelist String[] listdata = new String[frameitemholder.size()]; for (int i = 0; i < frameitemholder.size(); i++) { FrameItemHolder fih = frameitemholder.get(i); String displaytext = ""; // servo movement || sleep || speech || speed setting if (fih.sleep != -1) { displaytext = "SLEEP " + fih.sleep; } else if (fih.speech != null) { displaytext = "SPEECH " + fih.speech; } else if (fih.name != null) { String displaytext1 = ""; String displaytext2 = ""; String displaytext3 = ""; String displaytext4 = ""; String displaytext5 = ""; String displaytext6 = ""; if (tabs_main_checkbox_states[0]) { displaytext1 = fih.rthumb + " " + fih.rindex + " " + fih.rmajeure + " " + fih.rringfinger + " " + fih.rpinky + " " + fih.rwrist; } if (tabs_main_checkbox_states[1]) { displaytext2 = fih.rbicep + " " + fih.rrotate + " " + fih.rshoulder + " " + fih.romoplate; } if (tabs_main_checkbox_states[2]) { displaytext3 = fih.lthumb + " " + fih.lindex + " " + fih.lmajeure + " " + fih.lringfinger + " " + fih.lpinky + " " + fih.lwrist; } if (tabs_main_checkbox_states[3]) { displaytext4 = fih.lbicep + " " + fih.lrotate + " " + fih.lshoulder + " " + fih.lomoplate; } if (tabs_main_checkbox_states[4]) { displaytext5 = fih.neck + " " + fih.rothead + " " + fih.eyeX + " " + fih.eyeY + " " + fih.jaw; } if (tabs_main_checkbox_states[5]) { displaytext6 = fih.topStom + " " + fih.midStom + " " + fih.lowStom; } displaytext = fih.name + ": " + displaytext1 + " | " + displaytext2 + " | " + displaytext3 + " | " + displaytext4 + " | " + displaytext5 + " | " + displaytext6; } else { String displaytext1 = ""; String displaytext2 = ""; String displaytext3 = ""; String displaytext4 = ""; String displaytext5 = ""; String displaytext6 = ""; if (tabs_main_checkbox_states[0]) { displaytext1 = fih.rthumbspeed + " " + fih.rindexspeed + " " + fih.rmajeurespeed + " " + fih.rringfingerspeed + " " + fih.rpinkyspeed + " " + fih.rwristspeed; } if (tabs_main_checkbox_states[1]) { displaytext2 = fih.rbicepspeed + " " + fih.rrotatespeed + " " + fih.rshoulderspeed + " " + fih.romoplatespeed; } if (tabs_main_checkbox_states[2]) { displaytext3 = fih.lthumbspeed + " " + fih.lindexspeed + " " + fih.lmajeurespeed + " " + fih.lringfingerspeed + " " + fih.lpinkyspeed + " " + fih.lwristspeed; } if (tabs_main_checkbox_states[3]) { displaytext4 = fih.lbicepspeed + " " + fih.lrotatespeed + " " + fih.lshoulderspeed + " " + fih.lomoplatespeed; } if (tabs_main_checkbox_states[4]) { displaytext5 = fih.neckspeed + " " + fih.rotheadspeed + " " + fih.eyeXspeed + " " + fih.eyeYspeed + " " + fih.jawspeed; } if (tabs_main_checkbox_states[5]) { displaytext6 = fih.topStomspeed + " " + fih.midStomspeed + " " + fih.lowStomspeed; } displaytext = "SPEED " + displaytext1 + " | " + displaytext2 + " | " + displaytext3 + " | " + displaytext4 + " | " + displaytext5 + " | " + displaytext6; } listdata[i] = displaytext; } framelist.setListData(listdata); } public void frame_moverealtime(JCheckBox frame_moverealtime) { moverealtime = frame_moverealtime.isSelected(); } public void servoitemholder_slider_changed(int t1, int t2) { // One slider were adjusted servoitemholder[t1][t2].akt.setText(servoitemholder[t1][t2].sli .getValue() + ""); // Move the Servos in "Real-Time" if (moverealtime && i01 != null) { FrameItemHolder fih = new FrameItemHolder(); fih.rthumb = servoitemholder[0][0].sli.getValue(); fih.rindex = servoitemholder[0][1].sli.getValue(); fih.rmajeure = servoitemholder[0][2].sli.getValue(); fih.rringfinger = servoitemholder[0][3].sli.getValue(); fih.rpinky = servoitemholder[0][4].sli.getValue(); fih.rwrist = servoitemholder[0][5].sli.getValue(); fih.rbicep = servoitemholder[1][0].sli.getValue(); fih.rrotate = servoitemholder[1][1].sli.getValue(); fih.rshoulder = servoitemholder[1][2].sli.getValue(); fih.romoplate = servoitemholder[1][3].sli.getValue(); fih.lthumb = servoitemholder[2][0].sli.getValue(); fih.lindex = servoitemholder[2][1].sli.getValue(); fih.lmajeure = servoitemholder[2][2].sli.getValue(); fih.lringfinger = servoitemholder[2][3].sli.getValue(); fih.lpinky = servoitemholder[2][4].sli.getValue(); fih.lwrist = servoitemholder[2][5].sli.getValue(); fih.lbicep = servoitemholder[3][0].sli.getValue(); fih.lrotate = servoitemholder[3][1].sli.getValue(); fih.lshoulder = servoitemholder[3][2].sli.getValue(); fih.lomoplate = servoitemholder[3][3].sli.getValue(); fih.neck = servoitemholder[4][0].sli.getValue(); fih.rothead = servoitemholder[4][1].sli.getValue(); fih.eyeX = servoitemholder[4][2].sli.getValue(); fih.eyeY = servoitemholder[4][3].sli.getValue(); fih.jaw = servoitemholder[4][4].sli.getValue(); fih.topStom = servoitemholder[5][0].sli.getValue(); fih.midStom = servoitemholder[5][1].sli.getValue(); fih.lowStom = servoitemholder[5][2].sli.getValue(); if (tabs_main_checkbox_states[0]) { i01.moveHead(fih.neck, fih.rothead, fih.eyeX, fih.eyeY, fih.jaw); } if (tabs_main_checkbox_states[1]) { i01.moveArm("left", fih.lbicep, fih.lrotate, fih.lshoulder, fih.lomoplate); } if (tabs_main_checkbox_states[2]) { i01.moveArm("right", fih.rbicep, fih.rrotate, fih.rshoulder, fih.romoplate); } if (tabs_main_checkbox_states[3]) { i01.moveHand("left", fih.lthumb, fih.lindex, fih.lmajeure, fih.lringfinger, fih.lpinky, fih.lwrist); } if (tabs_main_checkbox_states[4]) { i01.moveHand("right", fih.rthumb, fih.rindex, fih.rmajeure, fih.rringfinger, fih.rpinky, fih.rwrist); } if (tabs_main_checkbox_states[5]) { i01.moveTorso(fih.topStom, fih.midStom, fih.lowStom); } } } public void servoitemholder_set_sih1(int i1, ServoItemHolder[] sih1) { // Setting references servoitemholder[i1] = sih1; } public void parsescript(JList control_list) { pythonitemholder.clear(); if (true) { String pscript = pythonscript; String[] pscriptsplit = pscript.split("\n"); PythonItemHolder pih = null; boolean keepgoing = true; int pos = 0; while (keepgoing) { if (pih == null) { pih = new PythonItemHolder(); } if (pos >= pscriptsplit.length) { keepgoing = false; break; } String line = pscriptsplit[pos]; String linewithoutspace = line.replace(" ", ""); if (linewithoutspace.equals("")) { pos++; continue; } if (linewithoutspace.startsWith(" pih.code = pih.code + "\n" + line; pos++; continue; } line = line.replace(" ", " "); // 2 -> 4 line = line.replace(" ", " "); // 3 -> 4 line = line.replace(" ", " "); // 5 -> 4 line = line.replace(" ", " "); // 6 -> 4 if (!(pih.function) && !(pih.notfunction)) { if (line.startsWith("def")) { pih.function = true; pih.notfunction = false; pih.modifyable = false; pih.code = line; pos++; } else { pih.notfunction = true; pih.function = false; pih.modifyable = false; pih.code = line; pos++; } } else if (pih.function && !(pih.notfunction)) { if (line.startsWith(" ")) { pih.code = pih.code + "\n" + line; pos++; } else { pythonitemholder.add(pih); pih = null; } } else if (!(pih.function) && pih.notfunction) { if (!(line.startsWith("def"))) { pih.code = pih.code + "\n" + line; pos++; } else { pythonitemholder.add(pih); pih = null; } } else { // it should never end here ... // .function & .notfunction true ... // would be wrong ... } } pythonitemholder.add(pih); } if (true) { ArrayList<PythonItemHolder> pythonitemholder1 = pythonitemholder; pythonitemholder = new ArrayList<PythonItemHolder>(); for (PythonItemHolder pih : pythonitemholder1) { if (pih.function && !(pih.notfunction)) { String code = pih.code; String[] codesplit = code.split("\n"); String code2 = ""; for (String line : codesplit) { line = line.replace(" ", ""); if (line.startsWith("def")) { line = ""; } else if (line.startsWith("sleep")) { line = ""; } else if (line.startsWith("i01")) { if (line.startsWith("i01.move")) { if (line.startsWith("i01.moveHead")) { line = ""; } else if (line.startsWith("i01.moveHand")) { line = ""; } else if (line.startsWith("i01.moveArm")) { line = ""; } else if (line.startsWith("i01.moveTorso")) { line = ""; } } else if (line.startsWith("i01.set")) { if (line.startsWith("i01.setHeadSpeed")) { line = ""; } else if (line.startsWith("i01.setHandSpeed")) { line = ""; } else if (line.startsWith("i01.setArmSpeed")) { line = ""; } else if (line.startsWith("i01.setTorsoSpeed")) { line = ""; } } else if (line.startsWith("i01.mouth.speak")) { line = ""; } } code2 = code2 + line; } if (code2.length() > 0) { pih.modifyable = false; } else { pih.modifyable = true; } } else if (!(pih.function) && pih.notfunction) { pih.modifyable = false; } else { // shouldn't get here // both true or both false // wrong } pythonitemholder.add(pih); } } controllistact(control_list); } public static class ServoItemHolder { public JLabel fin; public JLabel min; public JLabel res; public JLabel max; public JSlider sli; public JLabel akt; public JTextField spe; } public static class FrameItemHolder { int rthumb, rindex, rmajeure, rringfinger, rpinky, rwrist; int rbicep, rrotate, rshoulder, romoplate; int lthumb, lindex, lmajeure, lringfinger, lpinky, lwrist; int lbicep, lrotate, lshoulder, lomoplate; int neck, rothead, eyeX, eyeY, jaw; int topStom, midStom, lowStom; float rthumbspeed, rindexspeed, rmajeurespeed, rringfingerspeed, rpinkyspeed, rwristspeed; float rbicepspeed, rrotatespeed, rshoulderspeed, romoplatespeed; float lthumbspeed, lindexspeed, lmajeurespeed, lringfingerspeed, lpinkyspeed, lwristspeed; float lbicepspeed, lrotatespeed, lshoulderspeed, lomoplatespeed; float neckspeed, rotheadspeed, eyeXspeed, eyeYspeed, jawspeed; float topStomspeed, midStomspeed, lowStomspeed; int sleep; String speech; String name; } public static class PythonItemHolder { String code; boolean modifyable; boolean function; boolean notfunction; } public static void main(String[] args) throws InterruptedException { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); try { Runtime.start("gui", "GUIService"); Runtime.start("inmoovgesturecreator", "InMoovGestureCreator"); } catch (Exception e) { Logging.logException(e); } } }
package org.commcare.android.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.commcare.android.database.user.models.User; import org.commcare.android.io.DataSubmissionEntity; import org.commcare.android.mime.EncryptedFileBody; import org.commcare.android.net.HttpRequestGenerator; import org.commcare.android.tasks.DataSubmissionListener; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; public class FormUploadUtil { public static final long FULL_SUCCESS = 0; public static final long PARTIAL_SUCCESS = 1; public static final long FAILURE = 2; public static final long TRANSPORT_FAILURE = 4; public static final long PROGRESS_ALL_PROCESSED = 8; public static final long SUBMISSION_BEGIN = 16; public static final long SUBMISSION_START = 32; public static final long SUBMISSION_NOTIFY = 64; public static final long SUBMISSION_DONE = 128; public static final long PROGRESS_LOGGED_OUT = 256; public static final long PROGRESS_SDCARD_REMOVED = 512; private static long MAX_BYTES = (5 * 1048576)-1024; private static final String[] SUPPORTED_FILE_EXTS = {".xml", ".jpg", ".3gpp", ".3gp"}; public static Cipher getDecryptCipher(SecretKeySpec key) { Cipher cipher; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher; //TODO: Something smart here; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static Cipher getDecryptCipher(byte[] key) { Cipher cipher; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES")); return cipher; //TODO: Something smart here; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static long sendInstance(int submissionNumber, File folder, String url, User user) throws FileNotFoundException { return FormUploadUtil.sendInstance(submissionNumber, folder, null, url, null, user); } public static long sendInstance(int submissionNumber, File folder, SecretKeySpec key, String url, AsyncTask listener, User user) throws FileNotFoundException { boolean hasListener = false; DataSubmissionListener myListener = null; if(listener instanceof DataSubmissionListener){ hasListener = true; myListener = (DataSubmissionListener)listener; } File[] files = folder.listFiles(); if(files == null) { //make sure external storage is available to begin with. String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { //If so, just bail as if the user had logged out. throw new SessionUnavailableException("External Storage Removed"); } else { throw new FileNotFoundException("No directory found at: " + folder.getAbsoluteFile()); } } //If we're listening, figure out how much (roughly) we have to send long bytes = 0; for (int j = 0; j < files.length; j++) { //Make sure we'll be sending it boolean supported = false; for(String ext : SUPPORTED_FILE_EXTS) { if(files[j].getName().endsWith(ext)) { supported = true; break; } } if(!supported) { continue;} bytes += files[j].length(); System.out.println("Added file: " + files[j].getName() +". Bytes to send: " + bytes); } if(hasListener){ myListener.startSubmission(submissionNumber, bytes); } HttpRequestGenerator generator; if(user.getUserType().equals(User.TYPE_DEMO)) { generator = new HttpRequestGenerator(); } else { generator = new HttpRequestGenerator(user); } String t = "p+a+s"; if (files == null) { Log.e(t, "no files to upload"); listener.cancel(true); } // mime post MultipartEntity entity = new DataSubmissionEntity(myListener, submissionNumber); for (int j = 0; j < files.length; j++) { File f = files[j]; ContentBody fb; //TODO: Match this with some reasonable library, rather than silly file lines if (f.getName().endsWith(".xml")) { //fb = new InputStreamBody(new CipherInputStream(new FileInputStream(f), getDecryptCipher(aesKey)), "text/xml", f.getName()); fb = new EncryptedFileBody(f, FormUploadUtil.getDecryptCipher(key), "text/xml"); entity.addPart("xml_submission_file", fb); //fb = new FileBody(f, "text/xml"); //Don't know if we can ask for the content length on the input stream, so skip it. // if (fb.getContentLength() <= MAX_BYTES) { // Log.i(t, "added xml file " + f.getName()); // } else { // Log.i(t, "file " + f.getName() + " is too big"); } else if (f.getName().endsWith(".jpg")) { fb = new FileBody(f, "image/jpeg"); if (fb.getContentLength() <= MAX_BYTES) { entity.addPart(f.getName(), fb); Log.i(t, "added image file " + f.getName()); } else { Log.i(t, "file " + f.getName() + " is too big"); } } else if (f.getName().endsWith(".3gpp")) { fb = new FileBody(f, "audio/3gpp"); if (fb.getContentLength() <= MAX_BYTES) { entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else { Log.i(t, "file " + f.getName() + " is too big"); } } else if (f.getName().endsWith(".3gp")) { fb = new FileBody(f, "video/3gpp"); if (fb.getContentLength() <= MAX_BYTES) { entity.addPart(f.getName(), fb); Log.i(t, "added video file " + f.getName()); } else { Log.i(t, "file " + f.getName() + " is too big"); } } else { Log.w(t, "unsupported file type, not adding file: " + f.getName()); } } // prepare response and return uploaded HttpResponse response = null; try { response = generator.postData(url, entity); } catch (ClientProtocolException e) { e.printStackTrace(); return TRANSPORT_FAILURE; } catch (IOException e) { e.printStackTrace(); return TRANSPORT_FAILURE; } catch (IllegalStateException e) { e.printStackTrace(); return TRANSPORT_FAILURE; } String serverLocation = null; Header[] h = response.getHeaders("Location"); if (h != null && h.length > 0) { serverLocation = h[0].getValue(); } else { // something should be done here... Log.e(t, "Location header was absent"); } int responseCode = response.getStatusLine().getStatusCode(); Log.e(t, "Response code:" + responseCode); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { AndroidStreamUtil.writeFromInputToOutput(response.getEntity().getContent(), bos); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(new String(bos.toByteArray())); if(responseCode >= 200 && responseCode < 300) { return FULL_SUCCESS; } else { return FAILURE; } } }
package org.nutz.resource.impl; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Pattern; import org.nutz.lang.util.Disks; import org.nutz.lang.util.FileVisitor; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.resource.NutResource; import org.nutz.resource.ResourceScan; public abstract class AbstractResourceScan implements ResourceScan { private static final Log log = Logs.get(); private static final Map<String, List<String>> jars = new HashMap<String, List<String>>(10); protected List<NutResource> scanInJar(String src, Pattern regex, String jarPath) { List<NutResource> list = new ArrayList<NutResource>(); try { if (log.isDebugEnabled()) log.debugf( "Scan resources in JarFile( %s ) by regex( %s ) base on src ( %s )", jarPath, regex, src); //jar,, if (jars.containsKey(jarPath)) { JarFile jar = null; for (String name : jars.get(jarPath)) if (name.startsWith(src) && (null == regex || regex.matcher(name).find())) { if (jar == null) jar = new JarFile(jarPath); list.add(new JarEntryResource(jar, jar.getJarEntry(name), name.substring(src.length()))); } } else { JarFile jar = new JarFile(jarPath); ArrayList<String> names = new ArrayList<String>(); jars.put(jarPath, names); Enumeration<JarEntry> ens = jar.entries(); while (ens.hasMoreElements()) { JarEntry jen = ens.nextElement(); if (jen.isDirectory()) continue; String name = jen.getName(); if (name.startsWith(src) && (null == regex || regex.matcher(name).find())) list.add(new JarEntryResource(jar, jen, jen.getName().substring(src.length()))); names.add(name); } } if (log.isDebugEnabled()) log.debugf( "Found %s resources in JarFile( %s ) by regex( %s ) base on src ( %s )", list.size(), jarPath, regex, src); } catch (Throwable e) { if (log.isWarnEnabled()) log.warn("Fail to scan path '" + jarPath + "'!", e); } return list; } /* ,Resoucebase, */ protected List<NutResource> scanInDir(final Pattern regex, // final String base, File f, final boolean ignoreHidden) { final List<NutResource> list = new ArrayList<NutResource>(); if (null == f || (ignoreHidden && f.isHidden()) || (!f.exists())) return list; if (!f.isDirectory()) f = f.getParentFile(); final String base = f.getAbsolutePath(); Disks.visitFile(f, new FileVisitor() { public void visit(File file) { list.add(new FileResource(base, file)); } }, new FileFilter() { public boolean accept(File theFile) { if (ignoreHidden && theFile.isHidden()) return false; if (theFile.isDirectory()) { String fnm = theFile.getName().toLowerCase(); // SVN CVS ,Git if (".svn".equals(fnm) || ".cvs".equals(fnm) || ".git".equals(fnm)) return false; return true; } return regex == null || regex.matcher(theFile.getName()).find(); } }); return list; } protected static String checkSrc(String src) { if (src == null) return null; src = src.replace('\\', '/'); if (!src.endsWith("/")) src += "/"; return src; } protected void scanClasspath(String src, Pattern regex, List<NutResource> list) { String classpath = System.getProperties().getProperty("java.class.path"); if (log.isInfoEnabled()) log.info("Try to search in classpath : " + classpath); String[] paths = classpath.split(System.getProperties().getProperty("path.separator")); for (String pathZ : paths) { if (pathZ.endsWith(".jar")) list.addAll(scanInJar(checkSrc(src), regex, pathZ)); else list.addAll(scanInDir(regex, new File(pathZ + "/" + src), true)); } } }
package org.objectweb.asm.util; import java.io.FileInputStream; import java.io.PrintWriter; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassReader; import org.objectweb.asm.CodeVisitor; import org.objectweb.asm.Constants; import org.objectweb.asm.Type; import org.objectweb.asm.util.attrs.ASMifiable; /** * A {@link PrintClassVisitor PrintClassVisitor} that prints the ASM code that * generates the classes it visits. This class visitor can be used to quickly * write ASM code to generate some given bytecode: * <ul> * <li>write the Java source code equivalent to the bytecode you want to * generate;</li> * <li>compile it with <tt>javac</tt>;</li> * <li>make a {@link ASMifierClassVisitor} visit this compiled * class (see the {@link #main main} method);</li> * <li>edit the generated source code, if necessary.</li> * </ul> * The source code printed when visiting the <tt>Hello</tt> class is the * following: * <p> * <blockquote> * <pre> * import org.objectweb.asm.*; * import java.io.FileOutputStream; * * public class Dump implements Constants { * * public static void main (String[] args) throws Exception { * * ClassWriter cw = new ClassWriter(false); * CodeVisitor cv; * * cw.visit(ACC_PUBLIC + ACC_SUPER, "Hello", "java/lang/Object", null, "Hello.java"); * * { * cv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); * cv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); * cv.visitLdcInsn("hello"); * cv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); * cv.visitInsn(RETURN); * cv.visitMaxs(2, 1); * } * { * cv = cw.visitMethod(ACC_PUBLIC, "&lt;init&gt;", "()V", null, null); * cv.visitVarInsn(ALOAD, 0); * cv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "&lt;init&gt;", "()V"); * cv.visitInsn(RETURN); * cv.visitMaxs(1, 1); * } * cw.visitEnd(); * * FileOutputStream os = new FileOutputStream("Dumped.class"); * os.write(cw.toByteArray()); * os.close(); * } * } * </pre> * </blockquote> * where <tt>Hello</tt> is defined by: * <p> * <blockquote> * <pre> * public class Hello { * * public static void main (String[] args) { * System.out.println("hello"); * } * } * </pre> * </blockquote> * * @author Eric Bruneton, Eugene Kuleshov */ public class ASMifierClassVisitor extends PrintClassVisitor { private static final int ACCESS_CLASS = 262144; private static final int ACCESS_FIELD = 524288; /** * Prints the ASM source code to generate the given class to the standard * output. * <p> * Usage: ASMifierClassVisitor [-debug] * &lt;fully qualified class name or class file name&gt; * * @param args the command line arguments. * * @throws Exception if the class cannot be found, or if an IO exception * occurs. */ public static void main (final String[] args) throws Exception { if (args.length < 1 || args.length > 2) { printUsage(); } int i = 0; boolean skipDebug = true; if (args[0].equals("-debug")) { i = 1; skipDebug = false; if (args.length != 2) { printUsage(); } } ClassReader cr; if (args[i].endsWith(".class")) { cr = new ClassReader(new FileInputStream(args[i])); } else { cr = new ClassReader(args[i]); } cr.accept(new ASMifierClassVisitor( new PrintWriter(System.out)), getDefaultAttributes(), skipDebug); } private static void printUsage () { System.err.println("Prints the ASM code to generate the given class."); System.err.println("Usage: ASMifierClassVisitor [-debug] " + "<fully qualified class name or class file name>"); System.exit(-1); } /** * Constructs a new {@link ASMifierClassVisitor} object. * * @param pw the print writer to be used to print the class. */ public ASMifierClassVisitor (final PrintWriter pw) { super(pw); } public void visit ( final int version, final int access, final String name, final String superName, final String[] interfaces, final String sourceFile) { text.add("import org.objectweb.asm.*;\n"); text.add("import org.objectweb.asm.attrs.*;\n"); text.add("import java.util.*;\n"); text.add("import java.io.FileOutputStream;\n\n"); text.add("public class "+name+"Dump implements Constants {\n\n"); text.add("public static void main (String[] args) throws Exception {\n\n"); text.add("ClassWriter cw = new ClassWriter(false);\n"); text.add("CodeVisitor cv;\n\n"); buf.setLength(0); buf.append("cw.visit("); buf.append(version); buf.append(", "); appendAccess(access | ACCESS_CLASS); buf.append(", "); appendConstant(buf, name); buf.append(", "); appendConstant(buf, superName); buf.append(", "); if (interfaces != null && interfaces.length > 0) { buf.append("new String[] {"); for (int i = 0; i < interfaces.length; ++i) { buf.append(i == 0 ? " " : ", "); appendConstant(buf, interfaces[i]); } buf.append(" }"); } else { buf.append("null"); } buf.append(", "); appendConstant(buf, sourceFile); buf.append(");\n\n"); text.add(buf.toString()); } public void visitInnerClass ( final String name, final String outerName, final String innerName, final int access) { buf.setLength(0); buf.append("cw.visitInnerClass("); appendConstant(buf, name); buf.append(", "); appendConstant(buf, outerName); buf.append(", "); appendConstant(buf, innerName); buf.append(", "); appendAccess(access); buf.append(");\n\n"); text.add(buf.toString()); } public void visitField ( final int access, final String name, final String desc, final Object value, final Attribute attrs) { buf.setLength(0); if (attrs != null) { buf.append("// FIELD ATTRIBUTES\n"); Attribute a = attrs; int n = 1; while (a != null) { if (a instanceof ASMifiable) { ((ASMifiable)a).asmify(buf, "fieldAttrs" + n, null); if (n > 1) { buf.append("fieldAttrs" + (n - 1) + " = fieldAttrs" + n + ";\n"); } } else { buf.append("// WARNING! skipped non standard field attribute of type "); buf.append(a.type).append("\n"); } n++; a = a.next; } } buf.append("cw.visitField("); appendAccess(access | ACCESS_FIELD); buf.append(", "); appendConstant(buf, name); buf.append(", "); appendConstant(buf, desc); buf.append(", "); appendConstant(buf, value); if (attrs==null) { buf.append(", null);\n\n"); } else { buf.append(", fieldAttrs1);\n\n"); } text.add(buf.toString()); } public CodeVisitor visitMethod ( final int access, final String name, final String desc, final String[] exceptions, final Attribute attrs) { buf.setLength(0); buf.append("{\n"); if (attrs != null) { buf.append("// METHOD ATTRIBUTES\n"); Attribute a = attrs; int n = 1; while (a != null) { if (a instanceof ASMifiable) { ((ASMifiable)a).asmify(buf, "methodAttrs" + n, null); if (n > 1) { buf.append("methodAttrs" + (n - 1) + ".next = methodAttrs" + n + ";\n"); } } else { buf.append("// WARNING! skipped non standard method attribute of type "); buf.append(a.type).append("\n"); } n++; a = a.next; } } buf.append("cv = cw.visitMethod("); appendAccess(access); buf.append(", "); appendConstant(buf, name); buf.append(", "); appendConstant(buf, desc); buf.append(", "); if (exceptions != null && exceptions.length > 0) { buf.append("new String[] {"); for (int i = 0; i < exceptions.length; ++i) { buf.append(i == 0 ? " " : ", "); appendConstant(buf, exceptions[i]); } buf.append(" }"); } else { buf.append("null"); } if (attrs==null) { buf.append(", null);\n"); } else { buf.append(", methodAttrs1);\n"); } text.add(buf.toString()); PrintCodeVisitor pcv = new ASMifierCodeVisitor(); text.add(pcv.getText()); text.add("}\n"); return pcv; } public void visitAttribute (final Attribute attr) { buf.setLength(0); if (attr instanceof ASMifiable) { buf.append("{\n"); buf.append("// CLASS ATRIBUTE\n"); ((ASMifiable)attr).asmify(buf, "attr", null); buf.append("cw.visitAttribute(attr);\n"); buf.append("}\n"); } else { buf.append("// WARNING! skipped a non standard class attribute of type \""); buf.append(attr.type).append("\"\n"); } text.add(buf.toString()); } public void visitEnd () { text.add("cw.visitEnd();\n\n"); text.add("FileOutputStream os = new FileOutputStream(\"Dumped.class\");\n"); text.add("os.write(cw.toByteArray());\n"); text.add("os.close();\n"); text.add("}\n"); text.add("}\n"); super.visitEnd(); } /** * Appends a string representation of the given access modifiers to {@link * #buf buf}. * * @param access some access modifiers. */ void appendAccess (final int access) { boolean first = true; if ((access & Constants.ACC_PUBLIC) != 0) { buf.append("ACC_PUBLIC"); first = false; } if ((access & Constants.ACC_PRIVATE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PRIVATE"); first = false; } if ((access & Constants.ACC_PROTECTED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PROTECTED"); first = false; } if ((access & Constants.ACC_FINAL) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_FINAL"); first = false; } if ((access & Constants.ACC_STATIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STATIC"); first = false; } if ((access & Constants.ACC_SYNCHRONIZED) != 0) { if (!first) { buf.append(" + "); } if ((access & ACCESS_CLASS) != 0) { buf.append("ACC_SUPER"); } else { buf.append("ACC_SYNCHRONIZED"); } first = false; } if ((access & Constants.ACC_VOLATILE) != 0 && (access & ACCESS_FIELD) != 0 ) { if (!first) { buf.append(" + "); } buf.append("ACC_VOLATILE"); first = false; } if ((access & Constants.ACC_BRIDGE) != 0 && (access & ACCESS_CLASS) == 0 && (access & ACCESS_FIELD) == 0) { if (!first) { buf.append(" + "); } buf.append("ACC_BRIDGE"); first = false; } if ((access & Constants.ACC_VARARGS) != 0 && (access & ACCESS_CLASS) == 0 && (access & ACCESS_FIELD) == 0) { if (!first) { buf.append(" + "); } buf.append("ACC_VARARGS"); first = false; } if ((access & Constants.ACC_TRANSIENT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_TRANSIENT"); first = false; } if ((access & Constants.ACC_NATIVE) != 0 && (access & ACCESS_CLASS) == 0 && (access & ACCESS_FIELD) == 0) { if (!first) { buf.append(" + "); } buf.append("ACC_NATIVE"); first = false; } if ((access & Constants.ACC_ENUM) != 0 && ((access & ACCESS_CLASS) != 0 || (access & ACCESS_FIELD) != 0)) { if (!first) { buf.append(" + "); } buf.append("ACC_ENUM"); first = false; } if ((access & Constants.ACC_ABSTRACT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_ABSTRACT"); first = false; } if ((access & Constants.ACC_INTERFACE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_INTERFACE"); first = false; } if ((access & Constants.ACC_STRICT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STRICT"); first = false; } if ((access & Constants.ACC_SYNTHETIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_SYNTHETIC"); first = false; } if ((access & Constants.ACC_DEPRECATED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_DEPRECATED"); first = false; } if (first) { buf.append("0"); } } /** * Appends a string representation of the given constant to the given buffer. * * @param buf a string buffer. * @param cst an {@link java.lang.Integer Integer}, {@link java.lang.Float * Float}, {@link java.lang.Long Long}, {@link java.lang.Double Double} * or {@link String String} object. May be <tt>null</tt>. */ static void appendConstant (final StringBuffer buf, final Object cst) { if (cst == null) { buf.append("null"); } else if (cst instanceof String) { String s = (String)cst; buf.append("\""); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (c == '\n') { buf.append("\\n"); } else if (c == '\\') { buf.append("\\\\"); } else if (c == '"') { buf.append("\\\""); } else { buf.append(c); } } buf.append("\""); } else if (cst instanceof Type) { buf.append("Type.getType(\""); buf.append(((Type)cst).getDescriptor()); buf.append("\")"); } else if (cst instanceof Integer) { buf.append("new Integer(") .append(cst) .append(")"); } else if (cst instanceof Float) { buf.append("new Float(") .append(cst) .append("F)"); } else if (cst instanceof Long) { buf.append("new Long(") .append(cst) .append("L)"); } else if (cst instanceof Double) { buf.append("new Double(") .append(cst) .append(")"); } } }
package org.opencms.search; import org.opencms.db.CmsPublishedResource; import org.opencms.file.CmsResource; import org.opencms.i18n.CmsMessageContainer; import org.opencms.main.CmsLog; import org.opencms.report.CmsLogReport; import org.opencms.report.I_CmsReport; import java.io.IOException; import org.apache.commons.logging.Log; /** * Implements the management of indexing threads.<p> * * @since 6.0.0 */ public class CmsIndexingThreadManager { /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsIndexingThreadManager.class); /** Number of threads abandoned. */ private int m_abandonedCounter; /** The time the last error was written to the log. */ private long m_lastLogErrorTime; /** The time the last warning was written to the log. */ private long m_lastLogWarnTime; /** The maximum number of modifications before a commit in the search index is triggered. */ private int m_maxModificationsBeforeCommit; /** Number of thread returned. */ private int m_returnedCounter; /** Overall number of threads started. */ private int m_startedCounter; /** Timeout for abandoning threads. */ private long m_timeout; /** * Creates and starts a thread manager for indexing threads.<p> * * @param timeout timeout after a thread is abandoned * @param maxModificationsBeforeCommit the maximum number of modifications before a commit in the search index is triggered */ public CmsIndexingThreadManager(long timeout, int maxModificationsBeforeCommit) { m_timeout = timeout; m_maxModificationsBeforeCommit = maxModificationsBeforeCommit; } /** * Creates and starts a new indexing thread for a resource.<p> * * After an indexing thread was started, the manager suspends itself * and waits for an amount of time specified by the <code>timeout</code> * value. If the timeout value is reached, the indexing thread is * aborted by an interrupt signal.<p> * * @param indexer the VFS indexer to create the index thread for * @param writer the index writer that can update the index * @param res the resource */ public void createIndexingThread(CmsVfsIndexer indexer, I_CmsIndexWriter writer, CmsResource res) { I_CmsReport report = indexer.getReport(); m_startedCounter++; CmsIndexingThread thread = new CmsIndexingThread( indexer.getCms(), res, indexer.getIndex(), m_startedCounter, report); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); try { thread.join(m_timeout); } catch (InterruptedException e) { // ignore } if (thread.isAlive()) { // the thread has not finished - so it must be marked as an abandoned thread m_abandonedCounter++; thread.interrupt(); if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_INDEXING_TIMEOUT_1, res.getRootPath())); } if (report != null) { report.println(); report.print( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_FAILED_0), I_CmsReport.FORMAT_WARNING); report.println( Messages.get().container(Messages.RPT_SEARCH_INDEXING_TIMEOUT_1, res.getRootPath()), I_CmsReport.FORMAT_WARNING); } } else { // the thread finished normally m_returnedCounter++; } I_CmsSearchDocument doc = thread.getResult(); if (doc != null) { // write the document to the index indexer.updateResource(writer, res.getRootPath(), doc); } else { indexer.deleteResource(writer, new CmsPublishedResource(res)); } if ((m_startedCounter % m_maxModificationsBeforeCommit) == 0) { try { writer.commit(); } catch (IOException e) { if (LOG.isWarnEnabled()) { LOG.warn( Messages.get().getBundle().key( Messages.LOG_IO_INDEX_WRITER_COMMIT_2, indexer.getIndex().getName(), indexer.getIndex().getPath()), e); } } } } /** * Returns if the indexing manager still have indexing threads.<p> * * @return true if the indexing manager still have indexing threads */ public boolean isRunning() { if (m_lastLogErrorTime <= 0) { m_lastLogErrorTime = System.currentTimeMillis(); m_lastLogWarnTime = m_lastLogErrorTime; } else { long currentTime = System.currentTimeMillis(); if ((currentTime - m_lastLogWarnTime) > 30000) { // write warning to log after 30 seconds if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key( Messages.LOG_WAITING_ABANDONED_THREADS_2, new Integer(m_abandonedCounter), new Integer((m_startedCounter - m_returnedCounter)))); } m_lastLogWarnTime = currentTime; } if ((currentTime - m_lastLogErrorTime) > 600000) { // write error to log after 10 minutes LOG.error(Messages.get().getBundle().key( Messages.LOG_WAITING_ABANDONED_THREADS_2, new Integer(m_abandonedCounter), new Integer((m_startedCounter - m_returnedCounter)))); m_lastLogErrorTime = currentTime; } } boolean result = (m_returnedCounter + m_abandonedCounter) < m_startedCounter; if (result && LOG.isInfoEnabled()) { // write a note to the log that all threads have finished LOG.info(Messages.get().getBundle().key(Messages.LOG_THREADS_FINISHED_0)); } return result; } /** * Writes statistical information to the report.<p> * * The method reports the total number of threads started * (equals to the number of indexed files), the number of returned * threads (equals to the number of successfully indexed files), * and the number of abandoned threads (hanging threads reaching the timeout). * * @param report the report to write the statistics to */ public void reportStatistics(I_CmsReport report) { if (report != null) { CmsMessageContainer message = Messages.get().container( Messages.RPT_SEARCH_INDEXING_STATS_4, new Object[] { new Integer(m_startedCounter), new Integer(m_returnedCounter), new Integer(m_abandonedCounter), report.formatRuntime()}); report.println(message); if (!(report instanceof CmsLogReport) && LOG.isInfoEnabled()) { // only write to the log if report is not already a log report LOG.info(message.key()); } } } }
package mu.nu.nullpo.game.subsystem.mode; import java.util.Random; import mu.nu.nullpo.game.component.BGMStatus; import mu.nu.nullpo.game.component.Block; import mu.nu.nullpo.game.component.Controller; import mu.nu.nullpo.game.component.Field; import mu.nu.nullpo.game.component.Piece; import mu.nu.nullpo.game.event.EventReceiver; import mu.nu.nullpo.game.play.GameEngine; import mu.nu.nullpo.game.play.GameManager; import mu.nu.nullpo.util.CustomProperties; import mu.nu.nullpo.util.GeneralUtil; import org.apache.log4j.Logger; /** * SPF VS-BATTLE mode (Beta) */ public class SPFMode extends DummyMode { /** Log (Apache log4j) */ static Logger log = Logger.getLogger(SPFMode.class); /** Current version */ private static final int CURRENT_VERSION = 0; /** Enabled piece types */ private static final int[] PIECE_ENABLE = {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}; /** Block colors */ private static final int[] BLOCK_COLORS = { Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_GEM_RED, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GEM_GREEN, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_GEM_BLUE, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_GEM_YELLOW }; private static final double[] ROW_VALUES = { 2.3, 2.2, 2.1, 2.0, 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1, 1.0 }; private static final int DIAMOND_COLOR = Block.BLOCK_COLOR_GEM_RAINBOW; /** Number of players */ private static final int MAX_PLAYERS = 2; /** Names of drop map sets */ private static final String[] DROP_SET_NAMES = {"CLASSIC", "REMIX", "SWORD", "S-MIRROR", "AVALANCHE", "A-MIRROR"}; private static final int[][][][] DROP_PATTERNS = { { {{2,2,2,2}, {5,5,5,5}, {7,7,7,7}, {4,4,4,4}}, {{2,2,4,4}, {2,2,4,4}, {5,5,2,2}, {5,5,2,2}, {7,7,5,5}, {7,7,5,5}}, {{5,5,5,5}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {4,4,4,4}}, {{2,5,7,4}}, {{7,7,4,4}, {4,4,7,7}, {2,2,5,5}, {2,2,5,5}, {4,4,7,7}, {7,7,4,4}}, {{4,7,7,5}, {7,7,5,5}, {7,5,5,2}, {5,5,2,2}, {5,2,2,4}, {2,2,4,4}}, {{2,2,5,5}, {4,4,5,5}, {2,2,5,5}, {4,4,7,7}, {2,2,7,7}, {4,4,7,7}}, {{5,5,5,5}, {2,2,7,7}, {2,2,7,7}, {7,7,2,2}, {7,7,2,2}, {4,4,4,4}}, {{5,7,4,2}, {2,5,7,4}, {4,2,5,7}, {7,4,2,5}}, {{2,5,7,4}, {5,7,4,2}, {7,4,2,5}, {4,2,5,7}}, {{2,2,2,2}} }, { {{2,2,7,2}, {5,5,4,5}, {7,7,5,7}, {4,4,2,4}}, {{2,2,4,4}, {2,2,4,4}, {5,5,2,2}, {5,5,2,2}, {7,7,5,5}, {7,7,5,5}}, {{5,5,4,4}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {4,4,5,5}}, {{2,5,7,4}}, {{7,7,4,4}, {4,4,7,7}, {2,5,5,5}, {2,2,2,5}, {4,4,7,7}, {7,7,4,4}}, {{7,7,7,7}, {5,7,4,2}, {7,4,2,5}, {4,2,5,7}, {2,5,7,4}, {5,5,5,5}}, {{2,2,5,5}, {4,4,5,5}, {2,2,5,5}, {4,4,7,7}, {2,2,7,7}, {4,4,7,7}}, {{5,4,5,4}, {2,2,2,7}, {2,7,7,7}, {7,2,2,2}, {7,7,7,2}, {4,5,4,5}}, {{5,7,4,2}, {2,5,7,4}, {4,2,5,7}, {7,4,2,5}}, {{2,5,7,4}, {5,7,4,2}, {7,4,2,5}, {4,2,5,7}}, {{2,2,2,2}} }, { {{2,5,5,5}, {5,2,2,5}, {5,5,2,2}, {4,4,7,7}, {4,7,7,4}, {7,4,4,4}}, {{2,2,2,5,5,5}, {5,3,7,5,4,5}, {5,5,7,7,4,4}, {4,4,2,4,4,7}, {4,2,4,4,7,4}, {2,4,4,7,4,4}}, {{4,4,5,5,7,2}, {4,4,5,5,7,2}, {5,5,7,7,7,5}, {5,7,7,7,4,5}, {7,7,2,2,5,4}, {7,2,2,2,5,4}}, {{2,2,5,4,2,7}, {2,7,4,5,7,2}, {2,7,4,4,7,7}, {2,7,5,5,2,2}, {2,7,5,4,2,7}, {7,7,4,5,7,2}}, {{2,7,7,7,7}, {2,7,5,7,7}, {2,2,5,5,5}, {2,2,2,5,5}, {2,4,2,4,4}, {4,4,4,4,4}}, {{2,2,5,5}, {2,7,7,5}, {5,7,4,4}, {5,5,2,4}, {4,2,2,7}, {4,4,7,7}}, {{2,2,5,5}, {2,2,5,5}, {5,5,7,7}, {5,5,7,7}, {7,7,4,4}, {7,7,4,4}}, {{2,2,5,4,2,7}, {2,2,4,5,7,2}, {7,7,4,5,7,2}, {7,7,5,4,2,7}, {2,2,5,4,2,7}, {2,2,4,5,7,2}}, {{7,7,4,4,7,7}, {7,7,7,7,5,7}, {2,5,2,2,5,2}, {2,5,2,2,5,2}, {4,4,4,4,5,4}, {4,4,7,7,4,4}}, {{2,5,5,5,5,4}, {5,2,5,5,4,4}, {2,2,2,2,2,2}, {7,7,7,7,7,7}, {4,7,4,4,5,5}, {7,4,4,4,4,5}}, {{2,2,5,2,2,4}, {2,5,5,2,5,5}, {5,5,5,7,7,2}, {7,7,7,5,5,4}, {4,7,7,4,7,7}, {4,4,7,4,4,2}}, {{7,7,5,5,5,5}, {7,2,2,5,5,7}, {7,2,2,4,4,7}, {2,7,7,4,4,2}, {2,7,7,5,5,2}, {7,7,5,5,5,5}}, {{7,7,5,5}, {7,2,5,2}, {5,5,5,2}, {4,4,4,2}, {7,2,4,2}, {7,7,4,4}}, {{2,2,5,5}, {2,7,5,5}, {5,5,7,7}, {5,5,7,7}, {4,7,4,4}, {7,7,4,4}}, {{7,7,5,5,5}, {4,7,7,7,5}, {5,4,4,4,4}, {5,2,2,2,2}, {2,7,7,7,5}, {7,7,5,5,5}}, {{2,2,4}, {2,2,2}, {7,7,7}, {7,7,7}, {5,5,5}, {5,5,4}}, {{7,7,7,7}, {7,2,2,7}, {2,7,5,4}, {4,5,7,2}, {5,4,4,5}, {5,5,5,5}} }, { {{7,4,4,4}, {4,7,7,4}, {4,4,7,7}, {5,5,2,2}, {5,2,2,5}, {2,5,5,5}}, {{2,4,4,7,4,4}, {4,2,4,4,7,4}, {4,4,2,4,4,7}, {5,5,7,7,4,4}, {5,3,7,5,4,5}, {2,2,2,5,5,5}}, {{7,2,2,2,5,4}, {7,7,2,2,5,4}, {5,7,7,7,4,5}, {5,5,7,7,7,5}, {4,4,5,5,7,2}, {4,4,5,5,7,2}}, {{7,7,4,5,7,2}, {2,7,5,4,2,7}, {2,7,5,5,2,2}, {2,7,4,4,7,7}, {2,7,4,5,7,2}, {2,2,5,4,2,7}}, {{4,4,4,4,4}, {2,4,2,4,4}, {2,2,2,5,5}, {2,2,5,5,5}, {2,7,5,7,7}, {2,7,7,7,7}}, {{4,4,7,7}, {4,2,2,7}, {5,5,2,4}, {5,7,4,4}, {2,7,7,5}, {2,2,5,5}}, {{7,7,4,4}, {7,7,4,4}, {5,5,7,7}, {5,5,7,7}, {2,2,5,5}, {2,2,5,5}}, {{2,2,4,5,7,2}, {2,2,5,4,2,7}, {7,7,5,4,2,7}, {7,7,4,5,7,2}, {2,2,4,5,7,2}, {2,2,5,4,2,7}}, {{4,4,7,7,4,4}, {4,4,4,4,5,4}, {2,5,2,2,5,2}, {2,5,2,2,5,2}, {7,7,7,7,5,7}, {7,7,4,4,7,7}}, {{7,4,4,4,4,5}, {4,7,4,4,5,5}, {7,7,7,7,7,7}, {2,2,2,2,2,2}, {5,2,5,5,4,4}, {2,5,5,5,5,4}}, {{4,4,7,4,4,2}, {4,7,7,4,7,7}, {7,7,7,5,5,4}, {5,5,5,7,7,2}, {2,5,5,2,5,5}, {2,2,5,2,2,4}}, {{7,7,5,5,5,5}, {2,7,7,5,5,2}, {2,7,7,4,4,2}, {7,2,2,4,4,7}, {7,2,2,5,5,7}, {7,7,5,5,5,5}}, {{7,7,4,4}, {7,2,4,2}, {4,4,4,2}, {5,5,5,2}, {7,2,5,2}, {7,7,5,5}}, {{7,7,4,4}, {4,7,4,4}, {5,5,7,7}, {5,5,7,7}, {2,7,5,5}, {2,2,5,5}}, {{7,7,5,5,5}, {2,7,7,7,5}, {5,2,2,2,2}, {5,4,4,4,4}, {4,7,7,7,5}, {7,7,5,5,5}}, {{5,5,4}, {5,5,5}, {7,7,7}, {7,7,7}, {2,2,2}, {2,2,4}}, {{5,5,5,5}, {5,4,4,5}, {4,5,7,2}, {2,7,5,4}, {7,2,2,7}, {7,7,7,7}} }, { {{5,4,4,5,5}, {2,5,5,2,2}, {4,2,2,4,4}, {7,4,4,7,7}, {5,7,7,5,5}, {2,5,5,2,2}}, {{2,7,7,7,2}, {5,2,2,2,5}, {5,4,4,4,5}, {4,5,5,5,4}, {4,7,7,7,4}, {7,2,2,2,7}}, {{2,2,5,5,5}, {5,7,7,2,2}, {7,7,2,2,5}, {5,4,4,7,7}, {4,4,7,7,5}, {5,5,5,4,4}}, {{7,2,2,5,5}, {4,4,5,5,2}, {4,7,7,2,2}, {7,7,4,4,5}, {5,4,4,7,7}, {2,2,7,7,4}}, {{7,2,7,2,2}, {7,4,7,7,2}, {5,4,4,7,4}, {5,5,4,5,4}, {2,5,2,5,5}, {2,7,2,2,4}}, {{5,5,4,2,2}, {5,4,4,2,7}, {4,2,2,7,7}, {4,2,7,5,5}, {2,7,7,5,4}, {7,5,5,4,4}}, {{7,7,4,7,7}, {5,5,7,5,5}, {2,2,5,2,2}, {4,4,2,4,4}}, {{4,4,2,2,5}, {2,2,5,5,7}, {5,5,7,7,4}, {7,7,4,4,2}}, {{5,5,5,2,4}, {7,7,7,5,2}, {4,4,4,7,5}, {2,2,2,4,7}}, {{4,4,4,5,7}, {2,2,2,7,4}, {5,5,5,4,2}, {7,7,7,2,5}}, {{4,2,5,5,5}, {7,4,2,2,2}, {5,7,4,4,4}, {2,5,7,7,7}} }, { {{2,5,5,2,2}, {5,7,7,5,5}, {7,4,4,7,7}, {4,2,2,4,4}, {2,5,5,2,2}, {5,4,4,5,5}}, {{7,2,2,2,7}, {4,7,7,7,4}, {4,5,5,5,4}, {5,4,4,4,5}, {5,2,2,2,5}, {2,7,7,7,2}}, {{5,5,5,4,4}, {4,4,7,7,5}, {5,4,4,7,7}, {7,7,2,2,5}, {5,7,7,2,2}, {2,2,5,5,5}}, {{2,2,7,7,4}, {5,4,4,7,7}, {7,7,4,4,5}, {4,7,7,2,2}, {4,4,5,5,2}, {7,2,2,5,5}}, {{2,7,2,2,4}, {2,5,2,5,5}, {5,5,4,5,4}, {5,4,4,7,4}, {7,4,7,7,2}, {7,2,7,2,2}}, {{7,5,5,4,4}, {2,7,7,5,4}, {4,2,7,5,5}, {4,2,2,7,7}, {5,4,4,2,7}, {5,5,4,2,2}}, {{5,5,7,5,5}, {7,7,4,7,7}, {4,4,2,4,4}, {2,2,5,2,2}}, {{2,2,5,5,7}, {4,4,2,2,5}, {7,7,4,4,2}, {5,5,7,7,4}}, {{7,7,7,5,2}, {5,5,5,2,4}, {2,2,2,4,7}, {4,4,4,7,5}}, {{2,2,2,7,4}, {4,4,4,5,7}, {7,7,7,2,5}, {5,5,5,4,2}}, {{7,4,2,2,2}, {4,2,5,5,5}, {2,5,7,7,7}, {5,7,4,4,4}} } }; private static final double[][] DROP_PATTERNS_ATTACK_MULTIPLIERS = { {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.7, 0.7, 1.0}, {1.0, 1.2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.85, 1.0} }; private static final double[][] DROP_PATTERNS_DEFEND_MULTIPLIERS = { {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.2, 1.0, 1.0} }; /** Names of rainbow power settings */ private static final String[] RAINBOW_POWER_NAMES = {"NONE", "50%", "80%", "100%", "50/100%"}; /** Each player's frame color */ private static final int[] PLAYER_COLOR_FRAME = {GameEngine.FRAME_COLOR_RED, GameEngine.FRAME_COLOR_BLUE}; /** GameManager that owns this mode */ private GameManager owner; /** Drawing and event handling EventReceiver */ private EventReceiver receiver; /** Blockcount */ private int[] ojama; /** Blockcount */ private int[] ojamaSent; /** Time to display the most recent increase in score */ private int[] scgettime; /** BGM */ private int bgmno; /** Big */ //private boolean[] big; /** ON/OFF */ private boolean[] enableSE; /** flag */ private boolean[] useMap; /** number */ private int[] mapSet; /** number(-1) */ private int[] mapNumber; /** Last preset number used */ private int[] presetNumber; private int winnerID; /** Property file */ private CustomProperties[] propMap; /** number */ private int[] mapMaxNo; private Field[] fldBackup; /** count */ private Random randMap; /** Version */ private int version; /** Amount of points earned from most recent clear */ private int[] lastscore; /** Score */ private int[] score; /** Settings for starting countdown for ojama blocks */ private int[] ojamaCountdown; /** Hurryupcount(0Hurryup) */ private int[] hurryupSeconds; /** Time to display "ZENKESHI!" */ private int[] zenKeshiDisplay; /** Time to display "TECH BONUS" */ private int[] techBonusDisplay; /** Drop patterns */ private int[][][] dropPattern; /** Drop map set selected */ private int[] dropSet; /** Drop map selected */ private int[] dropMap; /** Drop multipliers */ private double[] attackMultiplier, defendMultiplier; /** Rainbow power settings for each player */ private int[] diamondPower; /** Frame when squares were last checked */ private int[] lastSquareCheck; /** Flag set when counters have been decremented */ private boolean[] countdownDecremented; /* * Mode name */ @Override public String getName() { return "SPF VS-BATTLE (BETA)"; } /* * Number of players */ @Override public int getPlayers() { return MAX_PLAYERS; } /* * Mode initialization */ @Override public void modeInit(GameManager manager) { owner = manager; receiver = owner.receiver; ojama = new int[MAX_PLAYERS]; ojamaSent = new int[MAX_PLAYERS]; scgettime = new int[MAX_PLAYERS]; bgmno = 0; //big = new boolean[MAX_PLAYERS]; enableSE = new boolean[MAX_PLAYERS]; hurryupSeconds = new int[MAX_PLAYERS]; useMap = new boolean[MAX_PLAYERS]; mapSet = new int[MAX_PLAYERS]; mapNumber = new int[MAX_PLAYERS]; presetNumber = new int[MAX_PLAYERS]; propMap = new CustomProperties[MAX_PLAYERS]; mapMaxNo = new int[MAX_PLAYERS]; fldBackup = new Field[MAX_PLAYERS]; randMap = new Random(); lastscore = new int[MAX_PLAYERS]; score = new int[MAX_PLAYERS]; ojamaCountdown = new int[MAX_PLAYERS]; zenKeshiDisplay = new int[MAX_PLAYERS]; techBonusDisplay = new int[MAX_PLAYERS]; dropSet = new int[MAX_PLAYERS]; dropMap = new int[MAX_PLAYERS]; dropPattern = new int[MAX_PLAYERS][][]; attackMultiplier = new double[MAX_PLAYERS]; defendMultiplier = new double[MAX_PLAYERS]; diamondPower = new int[MAX_PLAYERS]; lastSquareCheck = new int[MAX_PLAYERS]; countdownDecremented = new boolean[MAX_PLAYERS]; winnerID = -1; } /** * Read speed presets * @param engine GameEngine * @param prop Property file to read from * @param preset Preset number */ private void loadPreset(GameEngine engine, CustomProperties prop, int preset) { engine.speed.gravity = prop.getProperty("spfvs.gravity." + preset, 4); engine.speed.denominator = prop.getProperty("spfvs.denominator." + preset, 256); engine.speed.are = prop.getProperty("spfvs.are." + preset, 24); engine.speed.areLine = prop.getProperty("spfvs.areLine." + preset, 24); engine.speed.lineDelay = prop.getProperty("spfvs.lineDelay." + preset, 10); engine.speed.lockDelay = prop.getProperty("spfvs.lockDelay." + preset, 30); engine.speed.das = prop.getProperty("spfvs.das." + preset, 14); } /** * Save speed presets * @param engine GameEngine * @param prop Property file to save to * @param preset Preset number */ private void savePreset(GameEngine engine, CustomProperties prop, int preset) { prop.setProperty("spfvs.gravity." + preset, engine.speed.gravity); prop.setProperty("spfvs.denominator." + preset, engine.speed.denominator); prop.setProperty("spfvs.are." + preset, engine.speed.are); prop.setProperty("spfvs.areLine." + preset, engine.speed.areLine); prop.setProperty("spfvs.lineDelay." + preset, engine.speed.lineDelay); prop.setProperty("spfvs.lockDelay." + preset, engine.speed.lockDelay); prop.setProperty("spfvs.das." + preset, engine.speed.das); } /** * * @param engine GameEngine * @param prop Property file to read from */ private void loadOtherSetting(GameEngine engine, CustomProperties prop) { int playerID = engine.playerID; bgmno = prop.getProperty("spfvs.bgmno", 0); //big[playerID] = prop.getProperty("spfvs.big.p" + playerID, false); enableSE[playerID] = prop.getProperty("spfvs.enableSE.p" + playerID, true); hurryupSeconds[playerID] = prop.getProperty("vsbattle.hurryupSeconds.p" + playerID, 0); useMap[playerID] = prop.getProperty("spfvs.useMap.p" + playerID, false); mapSet[playerID] = prop.getProperty("spfvs.mapSet.p" + playerID, 0); mapNumber[playerID] = prop.getProperty("spfvs.mapNumber.p" + playerID, -1); presetNumber[playerID] = prop.getProperty("spfvs.presetNumber.p" + playerID, 0); ojamaCountdown[playerID] = prop.getProperty("spfvs.ojamaHard.p" + playerID, 5); dropSet[playerID] = prop.getProperty("spfvs.dropSet.p" + playerID, 0); dropMap[playerID] = prop.getProperty("spfvs.dropMap.p" + playerID, 0); diamondPower[playerID] = prop.getProperty("spfvs.rainbowPower.p" + playerID, 2); } /** * * @param engine GameEngine * @param prop Property file to save to */ private void saveOtherSetting(GameEngine engine, CustomProperties prop) { int playerID = engine.playerID; prop.setProperty("spfvs.bgmno", bgmno); //prop.setProperty("spfvs.big.p" + playerID, big[playerID]); prop.setProperty("spfvs.enableSE.p" + playerID, enableSE[playerID]); prop.setProperty("vsbattle.hurryupSeconds.p" + playerID, hurryupSeconds[playerID]); prop.setProperty("spfvs.useMap.p" + playerID, useMap[playerID]); prop.setProperty("spfvs.mapSet.p" + playerID, mapSet[playerID]); prop.setProperty("spfvs.mapNumber.p" + playerID, mapNumber[playerID]); prop.setProperty("spfvs.presetNumber.p" + playerID, presetNumber[playerID]); prop.setProperty("spfvs.ojamaHard.p" + playerID, ojamaCountdown[playerID]); prop.setProperty("spfvs.dropSet.p" + playerID, dropSet[playerID]); prop.setProperty("spfvs.dropMap.p" + playerID, dropMap[playerID]); prop.setProperty("spfvs.rainbowPower.p" + playerID, diamondPower[playerID]); } /** * * @param field * @param prop Property file to read from * @param preset ID */ private void loadMap(Field field, CustomProperties prop, int id) { field.reset(); //field.readProperty(prop, id); field.stringToField(prop.getProperty("map." + id, "")); field.setAllAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true); field.setAllAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true); field.setAllAttribute(Block.BLOCK_ATTRIBUTE_SELFPLACED, false); } /** * * @param field * @param prop Property file to save to * @param id ID */ private void saveMap(Field field, CustomProperties prop, int id) { //field.writeProperty(prop, id); prop.setProperty("map." + id, field.fieldToString()); } /** * * @param engine GameEngine * @param playerID number * @param id ID * @param forceReload true */ private void loadMapPreview(GameEngine engine, int playerID, int id, boolean forceReload) { if((propMap[playerID] == null) || (forceReload)) { mapMaxNo[playerID] = 0; propMap[playerID] = receiver.loadProperties("config/map/spf/" + mapSet[playerID] + ".map"); } if((propMap[playerID] == null) && (engine.field != null)) { engine.field.reset(); } else if(propMap[playerID] != null) { mapMaxNo[playerID] = propMap[playerID].getProperty("map.maxMapNumber", 0); engine.createFieldIfNeeded(); loadMap(engine.field, propMap[playerID], id); engine.field.setAllSkin(engine.getSkin()); } } private void loadDropMapPreview(GameEngine engine, int playerID, int[][] pattern) { if((pattern == null) && (engine.field != null)) { engine.field.reset(); } else if(pattern != null) { log.debug("Loading drop map preview"); engine.createFieldIfNeeded(); engine.field.reset(); int patternCol = 0; int maxHeight = engine.field.getHeight()-1; for (int x = 0; x < engine.field.getWidth(); x++) { if (patternCol >= pattern.length) patternCol = 0; for (int patternRow = 0; patternRow < pattern[patternCol].length; patternRow++) { engine.field.setBlockColor(x, maxHeight-patternRow, pattern[patternCol][patternRow]); Block blk = engine.field.getBlock(x, maxHeight-patternRow); blk.setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true); blk.setAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true); } patternCol++; } engine.field.setAllSkin(engine.getSkin()); } } /* * Initialization for each player */ @Override public void playerInit(GameEngine engine, int playerID) { if(playerID == 1) { engine.randSeed = owner.engine[0].randSeed; engine.random = new Random(owner.engine[0].randSeed); } engine.framecolor = PLAYER_COLOR_FRAME[playerID]; engine.clearMode = GameEngine.CLEAR_GEM_COLOR; engine.garbageColorClear = true; engine.lineGravityType = GameEngine.LINE_GRAVITY_CASCADE; for(int i = 0; i < Piece.PIECE_COUNT; i++) engine.nextPieceEnable[i] = (PIECE_ENABLE[i] == 1); engine.blockColors = BLOCK_COLORS; engine.randomBlockColor = true; engine.connectBlocks = false; ojama[playerID] = 0; ojamaSent[playerID] = 0; score[playerID] = 0; scgettime[playerID] = 0; zenKeshiDisplay[playerID] = 0; techBonusDisplay[playerID] = 0; lastSquareCheck[playerID] = -1; countdownDecremented[playerID] = true; if(engine.owner.replayMode == false) { loadOtherSetting(engine, engine.owner.modeConfig); loadPreset(engine, engine.owner.modeConfig, -1 - playerID); version = CURRENT_VERSION; } else { loadOtherSetting(engine, engine.owner.replayProp); loadPreset(engine, engine.owner.replayProp, -1 - playerID); version = owner.replayProp.getProperty("spfvs.version", 0); } } /* * Called at settings screen */ @Override public boolean onSetting(GameEngine engine, int playerID) { // Menu if((engine.owner.replayMode == false) && (engine.statc[4] == 0)) { if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_UP)) { engine.statc[2] if(engine.statc[2] < 0){ engine.statc[2] = 18; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); } else if (engine.statc[2] == 16) engine.field = null; engine.playSE("cursor"); } // Down if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_DOWN)) { engine.statc[2]++; if(engine.statc[2] > 18) { engine.statc[2] = 0; engine.field = null; } else if (engine.statc[2] == 17) loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); engine.playSE("cursor"); } // Configuration changes int change = 0; if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_LEFT)) change = -1; if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_RIGHT)) change = 1; if(change != 0) { engine.playSE("change"); int m = 1; if(engine.ctrl.isPress(Controller.BUTTON_E)) m = 100; if(engine.ctrl.isPress(Controller.BUTTON_F)) m = 1000; switch(engine.statc[2]) { case 0: engine.speed.gravity += change * m; if(engine.speed.gravity < -1) engine.speed.gravity = 99999; if(engine.speed.gravity > 99999) engine.speed.gravity = -1; break; case 1: engine.speed.denominator += change * m; if(engine.speed.denominator < -1) engine.speed.denominator = 99999; if(engine.speed.denominator > 99999) engine.speed.denominator = -1; break; case 2: engine.speed.are += change; if(engine.speed.are < 0) engine.speed.are = 99; if(engine.speed.are > 99) engine.speed.are = 0; break; case 3: engine.speed.areLine += change; if(engine.speed.areLine < 0) engine.speed.areLine = 99; if(engine.speed.areLine > 99) engine.speed.areLine = 0; break; case 4: engine.speed.lineDelay += change; if(engine.speed.lineDelay < 0) engine.speed.lineDelay = 99; if(engine.speed.lineDelay > 99) engine.speed.lineDelay = 0; break; case 5: engine.speed.lockDelay += change; if(engine.speed.lockDelay < 0) engine.speed.lockDelay = 99; if(engine.speed.lockDelay > 99) engine.speed.lockDelay = 0; break; case 6: engine.speed.das += change; if(engine.speed.das < 0) engine.speed.das = 99; if(engine.speed.das > 99) engine.speed.das = 0; break; case 7: case 8: presetNumber[playerID] += change; if(presetNumber[playerID] < 0) presetNumber[playerID] = 99; if(presetNumber[playerID] > 99) presetNumber[playerID] = 0; break; case 9: bgmno += change; if(bgmno < 0) bgmno = BGMStatus.BGM_COUNT - 1; if(bgmno > BGMStatus.BGM_COUNT - 1) bgmno = 0; break; case 10: useMap[playerID] = !useMap[playerID]; if(!useMap[playerID]) { if(engine.field != null) engine.field.reset(); } else { loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } break; case 11: mapSet[playerID] += change; if(mapSet[playerID] < 0) mapSet[playerID] = 99; if(mapSet[playerID] > 99) mapSet[playerID] = 0; if(useMap[playerID]) { mapNumber[playerID] = -1; loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } break; case 12: if(useMap[playerID]) { mapNumber[playerID] += change; if(mapNumber[playerID] < -1) mapNumber[playerID] = mapMaxNo[playerID] - 1; if(mapNumber[playerID] > mapMaxNo[playerID] - 1) mapNumber[playerID] = -1; loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } else { mapNumber[playerID] = -1; } break; case 13: enableSE[playerID] = !enableSE[playerID]; break; case 14: if (m > 10) hurryupSeconds[playerID] += change*m/10; else hurryupSeconds[playerID] += change; if(hurryupSeconds[playerID] < 0) hurryupSeconds[playerID] = 300; if(hurryupSeconds[playerID] > 300) hurryupSeconds[playerID] = 0; break; case 15: ojamaCountdown[playerID] += change; if(ojamaCountdown[playerID] < 1) ojamaCountdown[playerID] = 9; if(ojamaCountdown[playerID] > 9) ojamaCountdown[playerID] = 1; break; case 16: diamondPower[playerID] += change; if(diamondPower[playerID] < 0) diamondPower[playerID] = 3; if(diamondPower[playerID] > 3) diamondPower[playerID] = 0; break; case 17: dropSet[playerID] += change; if(dropSet[playerID] < 0) dropSet[playerID] = DROP_PATTERNS.length-1; if(dropSet[playerID] >= DROP_PATTERNS.length) dropSet[playerID] = 0; if(dropMap[playerID] >= DROP_PATTERNS[dropSet[playerID]].length) dropMap[playerID] = 0; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); break; case 18: dropMap[playerID] += change; if(dropMap[playerID] < 0) dropMap[playerID] = DROP_PATTERNS[dropSet[playerID]].length-1; if(dropMap[playerID] >= DROP_PATTERNS[dropSet[playerID]].length) dropMap[playerID] = 0; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); break; /* case 18: big[playerID] = !big[playerID]; break; */ } } if(engine.ctrl.isPush(Controller.BUTTON_A) && (engine.statc[3] >= 5)) { engine.playSE("decide"); if(engine.statc[2] == 7) { loadPreset(engine, owner.modeConfig, presetNumber[playerID]); } else if(engine.statc[2] == 8) { savePreset(engine, owner.modeConfig, presetNumber[playerID]); receiver.saveModeConfig(owner.modeConfig); } else { saveOtherSetting(engine, owner.modeConfig); savePreset(engine, owner.modeConfig, -1 - playerID); receiver.saveModeConfig(owner.modeConfig); engine.statc[4] = 1; } } // Cancel if(engine.ctrl.isPush(Controller.BUTTON_B)) { engine.quitflag = true; } if(useMap[playerID] && (engine.statc[3] == 0)) { loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } if(useMap[playerID] && (propMap[playerID] != null) && (mapNumber[playerID] < 0)) { if(engine.statc[3] % 30 == 0) { engine.statc[5]++; if(engine.statc[5] >= mapMaxNo[playerID]) engine.statc[5] = 0; loadMapPreview(engine, playerID, engine.statc[5], false); } } engine.statc[3]++; } else if(engine.statc[4] == 0) { engine.statc[3]++; engine.statc[2] = 0; if(engine.statc[3] >= 180) engine.statc[4] = 1; else if(engine.statc[3] > 120) engine.statc[2] = 17; else if (engine.statc[3] == 120) { engine.statc[2] = 17; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); } else if(engine.statc[3] >= 60) engine.statc[2] = 9; } else { if((owner.engine[0].statc[4] == 1) && (owner.engine[1].statc[4] == 1) && (playerID == 1)) { owner.engine[0].stat = GameEngine.STAT_READY; owner.engine[1].stat = GameEngine.STAT_READY; owner.engine[0].resetStatc(); owner.engine[1].resetStatc(); } // Cancel else if(engine.ctrl.isPush(Controller.BUTTON_B)) { engine.statc[4] = 0; } } return true; } @Override public void renderSetting(GameEngine engine, int playerID) { if(engine.statc[4] == 0) { if(engine.statc[2] < 9) { drawMenu(engine, playerID, receiver, 0, EventReceiver.COLOR_ORANGE, 0, "GRAVITY", String.valueOf(engine.speed.gravity), "G-MAX", String.valueOf(engine.speed.denominator), "ARE", String.valueOf(engine.speed.are), "ARE LINE", String.valueOf(engine.speed.areLine), "LINE DELAY", String.valueOf(engine.speed.lineDelay), "LOCK DELAY", String.valueOf(engine.speed.lockDelay), "DAS", String.valueOf(engine.speed.das)); drawMenu(engine, playerID, receiver, 14, EventReceiver.COLOR_GREEN, 7, "LOAD", String.valueOf(presetNumber[playerID]), "SAVE", String.valueOf(presetNumber[playerID])); receiver.drawMenuFont(engine, playerID, 0, 19, "PAGE 1/3", EventReceiver.COLOR_YELLOW); } else if (engine.statc[2] < 17){ drawMenu(engine, playerID, receiver, 0, EventReceiver.COLOR_PINK, 9, "BGM", String.valueOf(bgmno)); drawMenu(engine, playerID, receiver, 2, EventReceiver.COLOR_CYAN, 10, "USE MAP", GeneralUtil.getONorOFF(useMap[playerID]), "MAP SET", String.valueOf(mapSet[playerID]), "MAP NO.", (mapNumber[playerID] < 0) ? "RANDOM" : mapNumber[playerID]+"/"+(mapMaxNo[playerID]-1), "SE", GeneralUtil.getONorOFF(enableSE[playerID]), "HURRYUP", (hurryupSeconds[playerID] == 0) ? "NONE" : hurryupSeconds[playerID]+"SEC", "COUNTDOWN", String.valueOf(ojamaCountdown[playerID])); receiver.drawMenuFont(engine, playerID, 0, 14, "RAINBOW", EventReceiver.COLOR_CYAN); drawMenu(engine, playerID, receiver, 15, EventReceiver.COLOR_CYAN, 16, "GEM POWER", RAINBOW_POWER_NAMES[diamondPower[playerID]]); receiver.drawMenuFont(engine, playerID, 0, 19, "PAGE 2/3", EventReceiver.COLOR_YELLOW); } else { receiver.drawMenuFont(engine, playerID, 0, 0, "ATTACK", EventReceiver.COLOR_CYAN); int multiplier = (int) (100 * getAttackMultiplier(dropSet[playerID], dropMap[playerID])); if (multiplier >= 100) receiver.drawMenuFont(engine, playerID, 2, 1, multiplier + "%", multiplier == 100 ? EventReceiver.COLOR_YELLOW : EventReceiver.COLOR_GREEN); else receiver.drawMenuFont(engine, playerID, 3, 1, multiplier + "%", EventReceiver.COLOR_RED); receiver.drawMenuFont(engine, playerID, 0, 2, "DEFEND", EventReceiver.COLOR_CYAN); multiplier = (int) (100 * getDefendMultiplier(dropSet[playerID], dropMap[playerID])); if (multiplier >= 100) receiver.drawMenuFont(engine, playerID, 2, 3, multiplier + "%", multiplier == 100 ? EventReceiver.COLOR_YELLOW : EventReceiver.COLOR_RED); else receiver.drawMenuFont(engine, playerID, 3, 3, multiplier + "%", EventReceiver.COLOR_GREEN); drawMenu(engine, playerID, receiver, 14, EventReceiver.COLOR_CYAN, 17, "DROP SET", DROP_SET_NAMES[dropSet[playerID]], "DROP MAP", String.format("%2d", dropMap[playerID]+1) + "/" + String.format("%2d", DROP_PATTERNS[dropSet[playerID]].length)); receiver.drawMenuFont(engine, playerID, 0, 19, "PAGE 3/3", EventReceiver.COLOR_YELLOW); } } else { receiver.drawMenuFont(engine, playerID, 3, 10, "WAIT", EventReceiver.COLOR_YELLOW); } } public static double getAttackMultiplier(int set, int map) { try { return DROP_PATTERNS_ATTACK_MULTIPLIERS[set][map]; } catch (ArrayIndexOutOfBoundsException e) { return 1.0; } } public static double getDefendMultiplier(int set, int map) { try { return DROP_PATTERNS_DEFEND_MULTIPLIERS[set][map]; } catch (ArrayIndexOutOfBoundsException e) { return 1.0; } } /* * ReadyInitializationInitialization */ @Override public boolean onReady(GameEngine engine, int playerID) { if(engine.statc[0] == 0) { engine.numColors = BLOCK_COLORS.length; engine.rainbowAnimate = (playerID == 0); engine.blockOutlineType = GameEngine.BLOCK_OUTLINE_CONNECT; dropPattern[playerID] = DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]; attackMultiplier[playerID] = getAttackMultiplier(dropSet[playerID], dropMap[playerID]); defendMultiplier[playerID] = getDefendMultiplier(dropSet[playerID], dropMap[playerID]); if(useMap[playerID]) { if(owner.replayMode) { engine.createFieldIfNeeded(); loadMap(engine.field, owner.replayProp, playerID); engine.field.setAllSkin(engine.getSkin()); } else { if(propMap[playerID] == null) { propMap[playerID] = receiver.loadProperties("config/map/spf/" + mapSet[playerID] + ".map"); } if(propMap[playerID] != null) { engine.createFieldIfNeeded(); if(mapNumber[playerID] < 0) { if((playerID == 1) && (useMap[0]) && (mapNumber[0] < 0)) { engine.field.copy(owner.engine[0].field); } else { int no = (mapMaxNo[playerID] < 1) ? 0 : randMap.nextInt(mapMaxNo[playerID]); loadMap(engine.field, propMap[playerID], no); } } else { loadMap(engine.field, propMap[playerID], mapNumber[playerID]); } engine.field.setAllSkin(engine.getSkin()); fldBackup[playerID] = new Field(engine.field); } } } else if(engine.field != null) { engine.field.reset(); } } else if (engine.statc[0] == 1 && diamondPower[playerID] > 0) for (int x = 24; x < engine.nextPieceArraySize; x += 25) engine.nextPieceArrayObject[x].block[1].color = DIAMOND_COLOR; return false; } @Override public void startGame(GameEngine engine, int playerID) { engine.b2bEnable = false; engine.comboType = GameEngine.COMBO_TYPE_DISABLE; //engine.big = big[playerID]; engine.enableSE = enableSE[playerID]; if(playerID == 1) owner.bgmStatus.bgm = bgmno; //engine.colorClearSize = big[playerID] ? 8 : 2; engine.colorClearSize = 2; engine.ignoreHidden = false; engine.tspinAllowKick = false; engine.tspinEnable = false; engine.useAllSpinBonus = false; } /* * Render score */ @Override public void renderLast(GameEngine engine, int playerID) { if(playerID == 0) { receiver.drawScoreFont(engine, playerID, -1, 0, "SPF VS", EventReceiver.COLOR_GREEN); receiver.drawScoreFont(engine, playerID, -1, 2, "OJAMA", EventReceiver.COLOR_PURPLE); receiver.drawScoreFont(engine, playerID, -1, 3, "1P:", EventReceiver.COLOR_RED); receiver.drawScoreFont(engine, playerID, 3, 3, String.valueOf(ojama[0]), (ojama[0] > 0)); receiver.drawScoreFont(engine, playerID, -1, 4, "2P:", EventReceiver.COLOR_BLUE); receiver.drawScoreFont(engine, playerID, 3, 4, String.valueOf(ojama[1]), (ojama[1] > 0)); receiver.drawScoreFont(engine, playerID, -1, 6, "ATTACK", EventReceiver.COLOR_GREEN); receiver.drawScoreFont(engine, playerID, -1, 7, "1P: " + String.valueOf(ojamaSent[0]), EventReceiver.COLOR_RED); receiver.drawScoreFont(engine, playerID, -1, 8, "2P: " + String.valueOf(ojamaSent[1]), EventReceiver.COLOR_BLUE); receiver.drawScoreFont(engine, playerID, -1, 10, "SCORE", EventReceiver.COLOR_PURPLE); receiver.drawScoreFont(engine, playerID, -1, 11, "1P: " + String.valueOf(score[0]), EventReceiver.COLOR_RED); receiver.drawScoreFont(engine, playerID, -1, 12, "2P: " + String.valueOf(score[1]), EventReceiver.COLOR_BLUE); receiver.drawScoreFont(engine, playerID, -1, 14, "TIME", EventReceiver.COLOR_GREEN); receiver.drawScoreFont(engine, playerID, -1, 15, GeneralUtil.getTime(engine.statistics.time)); } if (!owner.engine[playerID].gameActive) return; if(techBonusDisplay[playerID] > 0) receiver.drawMenuFont(engine, playerID, 0, 20, "TECH BONUS", EventReceiver.COLOR_YELLOW); if(zenKeshiDisplay[playerID] > 0) receiver.drawMenuFont(engine, playerID, 1, 21, "ZENKESHI!", EventReceiver.COLOR_YELLOW); Block b; int blockColor, textColor; if (engine.field != null) for (int x = 0; x < engine.field.getWidth(); x++) for (int y = 0; y < engine.field.getHeight(); y++) { b = engine.field.getBlock(x, y); if (!b.isEmpty() && b.countdown > 0) { blockColor = b.secondaryColor; textColor = EventReceiver.COLOR_WHITE; if (blockColor == Block.BLOCK_COLOR_BLUE) textColor = EventReceiver.COLOR_BLUE; else if (blockColor == Block.BLOCK_COLOR_GREEN) textColor = EventReceiver.COLOR_GREEN; else if (blockColor == Block.BLOCK_COLOR_RED) textColor = EventReceiver.COLOR_RED; else if (blockColor == Block.BLOCK_COLOR_YELLOW) textColor = EventReceiver.COLOR_YELLOW; receiver.drawMenuFont(engine, playerID, x, y, String.valueOf(b.countdown), textColor); } } } @Override public boolean onMove (GameEngine engine, int playerID) { countdownDecremented[playerID] = false; return false; } @Override public void pieceLocked(GameEngine engine, int playerID, int avalanche) { if (engine.field == null) return; checkAll(engine, playerID); } /* * Calculate score */ @Override public void calcScore(GameEngine engine, int playerID, int avalanche) { if (engine.field == null) return; checkAll(engine, playerID); if (engine.field.canCascade()) return; int enemyID = 0; if(playerID == 0) enemyID = 1; int width = engine.field.getWidth(); int height = engine.field.getHeight(); int hiddenHeight = engine.field.getHiddenHeight(); int diamondBreakColor = Block.BLOCK_COLOR_INVALID; if (diamondPower[playerID] > 0) for (int y = (-1*hiddenHeight); y < height && diamondBreakColor == Block.BLOCK_COLOR_INVALID; y++) for (int x = 0; x < width && diamondBreakColor == Block.BLOCK_COLOR_INVALID; x++) if (engine.field.getBlockColor(x, y) == DIAMOND_COLOR) { receiver.blockBreak(engine, playerID, x, y, engine.field.getBlock(x, y)); engine.field.setBlockColor(x, y, Block.BLOCK_COLOR_NONE); if (y+1 >= height) { techBonusDisplay[playerID] = 120; engine.statistics.score += 10000; score[playerID] += 10000; } else diamondBreakColor = engine.field.getBlockColor(x, y+1, true); } double pts = 0; double add, multiplier; Block b; //Clear blocks from diamond if (diamondBreakColor > Block.BLOCK_COLOR_NONE) { engine.field.allClearColor(diamondBreakColor, true, true); for (int y = (-1*hiddenHeight); y < height; y++) { multiplier = getRowValue(y); for (int x = 0; x < width; x++) if (engine.field.getBlockColor(x, y, true) == diamondBreakColor) { pts += multiplier * 7; receiver.blockBreak(engine, playerID, x, y, engine.field.getBlock(x, y)); engine.field.setBlockColor(x, y, Block.BLOCK_COLOR_NONE); } } } if (diamondPower[playerID] == 1) pts *= 0.5; else if (diamondPower[playerID] == 2) pts *= 0.8; //TODO: Add diamond glitch //Clear blocks //engine.field.gemColorCheck(engine.colorClearSize, true, engine.garbageColorClear, engine.ignoreHidden); for (int y = (-1*hiddenHeight); y < height; y++) { multiplier = getRowValue(y); for (int x = 0; x < width; x++) { b = engine.field.getBlock(x, y); if (b == null) continue; if (!b.getAttribute(Block.BLOCK_ATTRIBUTE_ERASE) || b.isEmpty()) continue; add = multiplier * 7; if (b.bonusValue > 1) add *= b.bonusValue; if (b.getAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE)) { add /= 2.0; b.secondaryColor = 0; } receiver.blockBreak(engine, playerID, x, y, b); engine.field.setBlockColor(x, y, Block.BLOCK_COLOR_NONE); pts += add; } } if (engine.chain > 1) pts += (engine.chain-1)*20.0; engine.playSE("combo" + Math.min(engine.chain, 20)); double ojamaNew = (int) (pts*attackMultiplier[playerID]/7.0); if (engine.field.isEmpty()) { engine.playSE("bravo"); zenKeshiDisplay[playerID] = 120; ojamaNew += 12; engine.statistics.score += 1000; score[playerID] += 1000; } lastscore[playerID] = ((int) pts) * 10; scgettime[playerID] = 120; score[playerID] += lastscore[playerID]; if (hurryupSeconds[playerID] > 0 && engine.statistics.time > hurryupSeconds[playerID]) ojamaNew *= 1 << (engine.statistics.time / (hurryupSeconds[playerID] * 60)); if (ojama[playerID] > 0 && ojamaNew > 0.0) { int delta = Math.min(ojama[playerID] << 1, (int) ojamaNew); ojama[playerID] -= delta >> 1; ojamaNew -= delta; } int ojamaSend = (int) (ojamaNew * defendMultiplier[enemyID]); if (ojamaSend > 0) ojama[enemyID] += ojamaSend; } public static double getRowValue(int row) { return ROW_VALUES[Math.min(Math.max(row, 0), ROW_VALUES.length-1)]; } public void checkAll(GameEngine engine, int playerID) { boolean recheck = checkCountdown(engine, playerID); if (recheck) log.debug("Converted garbage blocks to regular blocks. Rechecking squares."); checkSquares(engine, playerID, recheck); } public boolean checkCountdown (GameEngine engine, int playerID) { if (countdownDecremented[playerID]) return false; countdownDecremented[playerID] = true; boolean result = false; for (int y = (engine.field.getHiddenHeight() * -1); y < engine.field.getHeight(); y++) for (int x = 0; x < engine.field.getWidth(); x++) { Block b = engine.field.getBlock(x, y); if (b == null) continue; if (b.countdown > 1) b.countdown else if (b.countdown == 1) { b.countdown = 0; b.setAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE, false); b.color = b.secondaryColor; result = true; } } return result; } public void checkSquares (GameEngine engine, int playerID, boolean forceRecheck) { if (engine.field == null) return; if (engine.statistics.time == lastSquareCheck[playerID] && !forceRecheck) return; lastSquareCheck[playerID] = engine.statistics.time; log.debug("Checking squares."); int width = engine.field.getWidth(); int height = engine.field.getHeight(); int hiddenHeight = engine.field.getHiddenHeight(); int color; Block b; int minX, minY, maxX, maxY; for (int x = 0; x < width; x++) for (int y = (-1*hiddenHeight); y < height; y++) { color = engine.field.getBlockColor(x, y); if (color < Block.BLOCK_COLOR_RED || color > Block.BLOCK_COLOR_PURPLE) continue; minX = x; minY = y; maxX = x; maxY = y; boolean expanded = false; b = engine.field.getBlock(x, y); if (!b.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT) && b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN) && !b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP) && !b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT)) { //Find boundaries of existing gem block maxX++; maxY++; Block test; while (maxX < width) { test = engine.field.getBlock(maxX, y); if (test == null) { maxX break; } if (test.color != color) { maxX break; } if (!test.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) break; maxX++; } while (maxY < height) { test = engine.field.getBlock(x, maxY); if (test == null) { maxY break; } if (test.color != color) { maxY break; } if (!test.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) break; maxY++; } log.debug("Pre-existing square found: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); } else if (b.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && color == engine.field.getBlockColor(x+1, y) && color == engine.field.getBlockColor(x, y+1) && color == engine.field.getBlockColor(x+1, y+1)) { Block bR = engine.field.getBlock(x+1, y); Block bD = engine.field.getBlock(x, y+1); Block bDR = engine.field.getBlock(x+1, y+1); if ( bR.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && bD.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && bDR.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN)) { //Form new gem block maxX = x+1; maxY = y+1; b.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bR.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bD.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bDR.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); expanded = true; } log.debug("New square formed: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); } if (maxX <= minX || maxY <= minY) continue; //No gem block, skip to next block boolean expandHere, done; int testX, testY; Block bTest; log.debug("Testing square for expansion. Coordinates before: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); //Expand up for (testY = minY-1, done = false; testY >= (-1 * hiddenHeight) && !done; testY { log.debug("Testing to expand up. testY = " + testY); if (color != engine.field.getBlockColor(minX, testY) || color != engine.field.getBlockColor(maxX, testY)) break; if (engine.field.getBlock(minX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT) || engine.field.getBlock(maxX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) break; expandHere = true; for (testX = minX; testX <= maxX && !done; testX++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP)) expandHere = false; } if (expandHere) { minY = testY; expanded = true; } } //Expand left for (testX = minX-1, done = false; testX >= 0 && !done; testX { if (color != engine.field.getBlockColor(testX, minY) || color != engine.field.getBlockColor(testX, maxY)) break; if (engine.field.getBlock(testX, minY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP) || engine.field.getBlock(testX, maxY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) break; expandHere = true; for (testY = minY; testY <= maxY && !done; testY++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT)) expandHere = false; } if (expandHere) { minX = testX; expanded = true; } } //Expand right for (testX = maxX+1, done = false; testX < width && !done; testX++) { if (color != engine.field.getBlockColor(testX, minY) || color != engine.field.getBlockColor(testX, maxY)) break; if (engine.field.getBlock(testX, minY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP) || engine.field.getBlock(testX, maxY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) break; expandHere = true; for (testY = minY; testY <= maxY && !done; testY++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) expandHere = false; } if (expandHere) { maxX = testX; expanded = true; } } //Expand down for (testY = maxY+1, done = false; testY < height && !done; testY++) { if (color != engine.field.getBlockColor(minX, testY) || color != engine.field.getBlockColor(maxX, testY)) break; if (engine.field.getBlock(minX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT) || engine.field.getBlock(maxX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) break; expandHere = true; for (testX = minX; testX <= maxX && !done; testX++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) expandHere = false; } if (expandHere) { maxY = testY; expanded = true; } } log.debug("expanded = " + expanded); if (expanded) { log.debug("Expanding square. Coordinates after: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); int size = Math.min(maxX - minX + 1, maxY - minY + 1); for (testX = minX; testX <= maxX; testX++) for (testY = minY; testY <= maxY; testY++) { bTest = engine.field.getBlock(testX, testY); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT, testX != minX); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN, testY != maxY); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP, testY != minY); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT, testX != maxX); bTest.bonusValue = size; } } } } public boolean lineClearEnd(GameEngine engine, int playerID) { if (engine.field == null) return false; int width = engine.field.getWidth(); int height = engine.field.getHeight(); int hiddenHeight = engine.field.getHiddenHeight(); for (int y = (-1*hiddenHeight); y < height; y++) for (int x = 0; x < width; x++) if (engine.field.getBlockColor(x, y) == DIAMOND_COLOR) { calcScore(engine, playerID, 0); return true; } checkAll(engine, playerID); //Drop garbage if needed. if (ojama[playerID] > 0) { int enemyID = 0; if(playerID == 0) enemyID = 1; int dropRows = Math.min((ojama[playerID] + width - 1) / width, engine.field.getHighestBlockY(3)); if (dropRows <= 0) return false; int drop = Math.min(ojama[playerID], width * dropRows); ojama[playerID] -= drop; //engine.field.garbageDrop(engine, drop, big[playerID], ojamaHard[playerID], 3); engine.field.garbageDrop(engine, drop, false, 0, ojamaCountdown[playerID], 3); engine.field.setAllSkin(engine.getSkin()); int patternCol = 0; for (int x = 0; x < engine.field.getWidth(); x++) { if (patternCol >= dropPattern[enemyID].length) patternCol = 0; int patternRow = 0; for (int y = dropRows - hiddenHeight; y >= (-1 * hiddenHeight); y { Block b = engine.field.getBlock(x, y); if (b.getAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE) && b.secondaryColor == 0) { if (patternRow >= dropPattern[enemyID][patternCol].length) patternRow = 0; b.secondaryColor = dropPattern[enemyID][patternCol][patternRow]; patternRow++; } } patternCol++; } return true; } return false; } /* * Called after every frame */ @Override public void onLast(GameEngine engine, int playerID) { scgettime[playerID]++; if (zenKeshiDisplay[playerID] > 0) zenKeshiDisplay[playerID] int width = 1; if (engine.field != null) width = engine.field.getWidth(); int blockHeight = receiver.getBlockGraphicsHeight(engine, playerID); // Meter if(ojama[playerID] * blockHeight / width > engine.meterValue) { engine.meterValue++; } else if(ojama[playerID] * blockHeight / width < engine.meterValue) { engine.meterValue } if(ojama[playerID] > 30) engine.meterColor = GameEngine.METER_COLOR_RED; else if(ojama[playerID] > 10) engine.meterColor = GameEngine.METER_COLOR_YELLOW; else engine.meterColor = GameEngine.METER_COLOR_GREEN; if((playerID == 1) && (owner.engine[0].gameActive)) { if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) { winnerID = -1; owner.engine[0].gameActive = false; owner.engine[1].gameActive = false; owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING; } else if((owner.engine[0].stat != GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) { winnerID = 0; owner.engine[0].gameActive = false; owner.engine[1].gameActive = false; owner.engine[0].stat = GameEngine.STAT_EXCELLENT; owner.engine[0].resetStatc(); owner.engine[0].statc[1] = 1; owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING; } else if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat != GameEngine.STAT_GAMEOVER)) { winnerID = 1; owner.engine[0].gameActive = false; owner.engine[1].gameActive = false; owner.engine[1].stat = GameEngine.STAT_EXCELLENT; owner.engine[1].resetStatc(); owner.engine[1].statc[1] = 1; owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING; } } } /* * Render results screen */ @Override public void renderResult(GameEngine engine, int playerID) { receiver.drawMenuFont(engine, playerID, 0, 1, "RESULT", EventReceiver.COLOR_ORANGE); if(winnerID == -1) { receiver.drawMenuFont(engine, playerID, 6, 2, "DRAW", EventReceiver.COLOR_GREEN); } else if(winnerID == playerID) { receiver.drawMenuFont(engine, playerID, 6, 2, "WIN!", EventReceiver.COLOR_YELLOW); } else { receiver.drawMenuFont(engine, playerID, 6, 2, "LOSE", EventReceiver.COLOR_WHITE); } receiver.drawMenuFont(engine, playerID, 0, 3, "ATTACK", EventReceiver.COLOR_ORANGE); String strScore = String.format("%10d", ojamaSent[playerID]); receiver.drawMenuFont(engine, playerID, 0, 4, strScore); receiver.drawMenuFont(engine, playerID, 0, 5, "LINE", EventReceiver.COLOR_ORANGE); String strLines = String.format("%10d", engine.statistics.lines); receiver.drawMenuFont(engine, playerID, 0, 6, strLines); receiver.drawMenuFont(engine, playerID, 0, 7, "PIECE", EventReceiver.COLOR_ORANGE); String strPiece = String.format("%10d", engine.statistics.totalPieceLocked); receiver.drawMenuFont(engine, playerID, 0, 8, strPiece); receiver.drawMenuFont(engine, playerID, 0, 9, "ATTACK/MIN", EventReceiver.COLOR_ORANGE); float apm = (float)(ojamaSent[playerID] * 3600) / (float)(engine.statistics.time); String strAPM = String.format("%10g", apm); receiver.drawMenuFont(engine, playerID, 0, 10, strAPM); receiver.drawMenuFont(engine, playerID, 0, 11, "LINE/MIN", EventReceiver.COLOR_ORANGE); String strLPM = String.format("%10g", engine.statistics.lpm); receiver.drawMenuFont(engine, playerID, 0, 12, strLPM); receiver.drawMenuFont(engine, playerID, 0, 13, "PIECE/SEC", EventReceiver.COLOR_ORANGE); String strPPS = String.format("%10g", engine.statistics.pps); receiver.drawMenuFont(engine, playerID, 0, 14, strPPS); receiver.drawMenuFont(engine, playerID, 0, 15, "TIME", EventReceiver.COLOR_ORANGE); String strTime = String.format("%10s", GeneralUtil.getTime(owner.engine[0].statistics.time)); receiver.drawMenuFont(engine, playerID, 0, 16, strTime); } /* * Called when saving replay */ @Override public void saveReplay(GameEngine engine, int playerID, CustomProperties prop) { saveOtherSetting(engine, owner.replayProp); savePreset(engine, owner.replayProp, -1 - playerID); if(useMap[playerID] && (fldBackup[playerID] != null)) { saveMap(fldBackup[playerID], owner.replayProp, playerID); } owner.replayProp.setProperty("spfvs.version", version); } }
package net.argius.stew.ui.window; import static java.awt.event.InputEvent.SHIFT_DOWN_MASK; import static java.awt.event.KeyEvent.*; import static java.awt.event.MouseEvent.MOUSE_DRAGGED; import static java.awt.event.MouseEvent.MOUSE_PRESSED; import static javax.swing.KeyStroke.getKeyStroke; import static net.argius.stew.ui.window.AnyActionKey.*; import static net.argius.stew.ui.window.ResultSetTable.ActionKey.*; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.io.*; import java.sql.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import javax.swing.text.*; import net.argius.stew.*; import net.argius.stew.io.*; import net.argius.stew.text.*; /** * Table for Result Set. */ final class ResultSetTable extends JTable implements AnyActionListener, TextSearch { enum ActionKey { copyWithEscape, clearSelectedCellValue, setCurrentTimeValue, copyColumnName, findColumnName, addEmptyRow, insertFromClipboard, duplicateRows, linkRowsToDatabase, deleteRows, sort, jumpToColumn, doNothing, } static final String TAB = "\t"; private static final Logger log = Logger.getLogger(ResultSetTable.class); private static final TableCellRenderer nullRenderer = new NullValueRenderer(); private final AnyActionListener anyActionListener; private final ColumnHeaderCellRenderer columnHeaderRenderer; private final RowHeader rowHeader; private final Point mousePositionForColumnHeader = new Point(); private int lastSortedIndex; private boolean lastSortedIsReverse; private String autoAdjustMode; // It is used by the process that has no key-event. private volatile KeyEvent lastKeyEvent; /** * Constructor. */ ResultSetTable(AnyActionListener anyActionListener) { this.anyActionListener = anyActionListener; JTableHeader columnHeader = getTableHeader(); TableCellRenderer columnHeaderDefaultRenderer = columnHeader.getDefaultRenderer(); final RowHeader rowHeader = new RowHeader(this); this.columnHeaderRenderer = new ColumnHeaderCellRenderer(columnHeaderDefaultRenderer); this.rowHeader = rowHeader; setColumnSelectionAllowed(true); setAutoResizeMode(AUTO_RESIZE_OFF); columnHeader.setDefaultRenderer(columnHeaderRenderer); columnHeader.setReorderingAllowed(false); // [Events] // column header MouseInputListener colHeaderMouseListener = new ColumnHeaderMouseInputListener(); columnHeader.addMouseListener(colHeaderMouseListener); columnHeader.addMouseMotionListener(colHeaderMouseListener); // row header MouseInputListener rowHeaderMouseListener = new RowHeaderMouseInputListener(rowHeader); rowHeader.addMouseListener(rowHeaderMouseListener); rowHeader.addMouseMotionListener(rowHeaderMouseListener); // cursor for (int i = 0; i < 2; i++) { final boolean withSelect = (i == 1); bindJumpAction("home", VK_HOME, withSelect); bindJumpAction("end", VK_END, withSelect); bindJumpAction("top", VK_UP, withSelect); bindJumpAction("bottom", VK_DOWN, withSelect); bindJumpAction("leftmost", VK_LEFT, withSelect); bindJumpAction("rightmost", VK_RIGHT, withSelect); } // key binds final int shortcutKey = Utilities.getMenuShortcutKeyMask(); AnyAction aa = new AnyAction(this); aa.bindSelf(copyWithEscape, getKeyStroke(VK_C, shortcutKey | InputEvent.SHIFT_DOWN_MASK)); aa.bindSelf(paste, getKeyStroke(VK_V, shortcutKey)); aa.bindSelf(clearSelectedCellValue, getKeyStroke(VK_DELETE, 0)); aa.bindKeyStroke(true, adjustColumnWidth, getKeyStroke(VK_SLASH, shortcutKey)); aa.bindKeyStroke(false, doNothing, getKeyStroke(VK_ESCAPE, 0)); } private final class RowHeaderMouseInputListener extends MouseInputAdapter { @SuppressWarnings("hiding") private final RowHeader rowHeader; private int dragStartRow; RowHeaderMouseInputListener(RowHeader rowHeader) { this.rowHeader = rowHeader; } @Override public void mousePressed(MouseEvent e) { changeSelection(e); } @Override public void mouseDragged(MouseEvent e) { changeSelection(e); } private void changeSelection(MouseEvent e) { Point p = new Point(e.getX(), e.getY()); if (SwingUtilities.isLeftMouseButton(e)) { int id = e.getID(); boolean isMousePressed = (id == MOUSE_PRESSED); boolean isMouseDragged = (id == MOUSE_DRAGGED); if (isMousePressed || isMouseDragged) { if (p.y >= rowHeader.getBounds().height) { return; } if (!e.isControlDown() && !e.isShiftDown()) { clearSelection(); } int rowIndex = rowAtPoint(p); if (rowIndex < 0 || getRowCount() < rowIndex) { return; } final int index0; final int index1; if (isMousePressed) { if (e.isShiftDown()) { index0 = dragStartRow; index1 = rowIndex; } else { dragStartRow = rowIndex; index0 = rowIndex; index1 = rowIndex; } } else if (isMouseDragged) { index0 = dragStartRow; index1 = rowIndex; } else { return; } addRowSelectionInterval(index0, index1); addColumnSelectionInterval(getColumnCount() - 1, 0); requestFocus(); // justify a position between table and its row header JViewport tableView = (JViewport)getParent(); Point viewPosition = tableView.getViewPosition(); viewPosition.y = ((JViewport)rowHeader.getParent()).getViewPosition().y; tableView.setViewPosition(viewPosition); } } } } private final class ColumnHeaderMouseInputListener extends MouseInputAdapter { private int dragStartColumn; ColumnHeaderMouseInputListener() { } // empty @SuppressWarnings("synthetic-access") @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { changeSelection(e); } mousePositionForColumnHeader.setLocation(e.getPoint()); } @Override public void mouseDragged(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { changeSelection(e); } } private void changeSelection(MouseEvent e) { final Point p = e.getPoint(); int id = e.getID(); boolean isMousePressed = (id == MOUSE_PRESSED); boolean isMouseDragged = (id == MOUSE_DRAGGED); if (isMousePressed || isMouseDragged) { if (!e.isControlDown() && !e.isShiftDown()) { clearSelection(); } int columnIndex = columnAtPoint(p); if (columnIndex < 0 || getColumnCount() <= columnIndex) { return; } final int index0; final int index1; if (isMousePressed) { if (e.isShiftDown()) { index0 = dragStartColumn; index1 = columnIndex; } else { dragStartColumn = columnIndex; index0 = columnIndex; index1 = columnIndex; } } else if (isMouseDragged) { index0 = dragStartColumn; index1 = columnIndex; } else { return; } selectColumn(index0, index1); requestFocus(); } } } @Override protected void processKeyEvent(KeyEvent e) { super.processKeyEvent(e); lastKeyEvent = e; } @Override public void anyActionPerformed(AnyActionEvent ev) { try { processAnyActionEvent(ev); } catch (Exception ex) { WindowOutputProcessor.showErrorDialog(this, ex); } } public void processAnyActionEvent(AnyActionEvent ev) throws Exception { if (ev.isAnyOf(copy, selectAll)) { final String cmd = ev.getActionCommand(); getActionMap().get(cmd).actionPerformed(new ActionEvent(this, 0, cmd)); } else if (ev.isAnyOf(copyWithEscape)) { List<String> rows = new ArrayList<String>(); for (int rowIndex : getSelectedRows()) { List<Object> row = new ArrayList<Object>(); for (int columnIndex : getSelectedColumns()) { final Object o = getValueAt(rowIndex, columnIndex); row.add(CsvFormatter.AUTO.format(o == null ? "" : String.valueOf(o))); } rows.add(TextUtilities.join(TAB, row)); } ClipboardHelper.setStrings(rows); } else if (ev.isAnyOf(paste)) { try { InputStream is = new ByteArrayInputStream(ClipboardHelper.getString().getBytes()); Importer importer = new SmartImporter(is, TAB); try { int[] selectedColumns = getSelectedColumns(); for (int rowIndex : getSelectedRows()) { Object[] values = importer.nextRow(); final int limit = Math.min(selectedColumns.length, values.length); for (int x = 0; x < limit; x++) { setValueAt(values[x], rowIndex, selectedColumns[x]); } } } finally { importer.close(); } repaint(); } finally { editingCanceled(new ChangeEvent(ev.getSource())); } } else if (ev.isAnyOf(clearSelectedCellValue)) { try { setValueAtSelectedCells(null); repaint(); } finally { editingCanceled(new ChangeEvent(ev.getSource())); } } else if (ev.isAnyOf(setCurrentTimeValue)) { try { setValueAtSelectedCells(new Timestamp(System.currentTimeMillis())); repaint(); } finally { editingCanceled(new ChangeEvent(ev.getSource())); } } else if (ev.isAnyOf(copyColumnName)) { List<String> a = new ArrayList<String>(); ResultSetTableModel m = getResultSetTableModel(); if (ev.getModifiers() == 0) { for (int i = 0, n = m.getColumnCount(); i < n; i++) { a.add(m.getColumnName(i)); } } else { for (final int i : getSelectedColumns()) { a.add(m.getColumnName(i)); } } ClipboardHelper.setString(TextUtilities.join(TAB, a)); } else if (ev.isAnyOf(findColumnName)) { anyActionListener.anyActionPerformed(ev); } else if (ev.isAnyOf(addEmptyRow)) { ResultSetTableModel m = getResultSetTableModel(); int[] selectedRows = getSelectedRows(); if (selectedRows.length > 0) { final int nextRow = selectedRows[selectedRows.length - 1] + 1; for (int i = 0; i < selectedRows.length; i++) { m.insertUnlinkedRow(nextRow, new Object[m.getColumnCount()]); } } else { m.addUnlinkedRow(new Object[m.getColumnCount()]); } } else if (ev.isAnyOf(insertFromClipboard)) { try { Importer importer = new SmartImporter(ClipboardHelper.getReaderForText(), TAB); try { ResultSetTableModel m = getResultSetTableModel(); while (true) { Object[] row = importer.nextRow(); if (row.length == 0) { break; } m.addUnlinkedRow(row); m.linkRow(m.getRowCount() - 1); } repaintRowHeader("model"); } finally { importer.close(); } } finally { editingCanceled(new ChangeEvent(ev.getSource())); } } else if (ev.isAnyOf(duplicateRows)) { ResultSetTableModel m = getResultSetTableModel(); List<?> rows = m.getDataVector(); int[] selectedRows = getSelectedRows(); int index = selectedRows[selectedRows.length - 1]; for (int rowIndex : selectedRows) { m.insertUnlinkedRow(++index, (Vector<?>)((Vector<?>)rows.get(rowIndex)).clone()); } repaint(); repaintRowHeader("model"); } else if (ev.isAnyOf(linkRowsToDatabase)) { ResultSetTableModel m = getResultSetTableModel(); try { for (int rowIndex : getSelectedRows()) { m.linkRow(rowIndex); } } finally { repaintRowHeader("unlinkedRowStatus"); } } else if (ev.isAnyOf(deleteRows)) { try { ResultSetTableModel m = getResultSetTableModel(); while (true) { final int selectedRow = getSelectedRow(); if (selectedRow < 0) { break; } if (m.isLinkedRow(selectedRow)) { final boolean removed = m.removeLinkedRow(selectedRow); assert removed; } else { m.removeRow(selectedRow); } } } finally { repaintRowHeader("model"); } } else if (ev.isAnyOf(adjustColumnWidth)) { adjustColumnWidth(); } else if (ev.isAnyOf(widenColumnWidth)) { changeTableColumnWidth(1.5f); } else if (ev.isAnyOf(narrowColumnWidth)) { changeTableColumnWidth(1 / 1.5f); } else if (ev.isAnyOf(sort)) { doSort(getTableHeader().columnAtPoint(mousePositionForColumnHeader)); } else if (ev.isAnyOf(jumpToColumn)) { Object[] args = ev.getArgs(); if (args != null && args.length > 0) { jumpToColumn(String.valueOf(args[0])); } } else if (ev.isAnyOf(showColumnNumber)) { setShowColumnNumber(!columnHeaderRenderer.fixesColumnNumber); updateUI(); } else { log.warn("not expected: Event=%s", ev); } } @Override public void editingStopped(ChangeEvent e) { try { super.editingStopped(e); } catch (Exception ex) { WindowOutputProcessor.showErrorDialog(getParent(), ex); } } @Override public boolean editCellAt(int row, int column, EventObject e) { boolean succeeded = super.editCellAt(row, column, e); if (succeeded) { if (editorComp instanceof JTextField) { // make it selected when starting edit-mode if (lastKeyEvent != null && lastKeyEvent.getKeyCode() != VK_F2) { JTextField editor = (JTextField)editorComp; initializeEditorComponent(editor); editor.requestFocus(); editor.selectAll(); } } } return succeeded; } @Override public TableCellEditor getCellEditor() { TableCellEditor editor = super.getCellEditor(); if (editor instanceof DefaultCellEditor) { DefaultCellEditor d = (DefaultCellEditor)editor; initializeEditorComponent(d.getComponent()); } return editor; } private void initializeEditorComponent(Component c) { final Color bgColor = Color.ORANGE; if (c != null && c.getBackground() != bgColor) { // determines initialized state by bgcolor if (!c.isEnabled()) { c.setEnabled(true); } c.setFont(getFont()); c.setBackground(bgColor); if (c instanceof JTextComponent) { final JTextComponent text = (JTextComponent)c; AnyAction aa = new AnyAction(text); aa.setUndoAction(); c.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { editingCanceled(new ChangeEvent(e.getSource())); } }); } } } @Override public TableCellRenderer getCellRenderer(int row, int column) { final Object v = getValueAt(row, column); if (v == null) { return nullRenderer; } return super.getCellRenderer(row, column); } @Override public void updateUI() { super.updateUI(); adjustRowHeight(this); } static void adjustRowHeight(JTable table) { Component c = new JLabel("0"); final int height = c.getPreferredSize().height; if (height > 0) { table.setRowHeight(height); } } @Override protected void configureEnclosingScrollPane() { super.configureEnclosingScrollPane(); Container p = getParent(); if (p instanceof JViewport) { Container gp = p.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane)gp; JViewport viewport = scrollPane.getViewport(); if (viewport == null || viewport.getView() != this) { return; } scrollPane.setRowHeaderView(rowHeader); } } } @Override public void setModel(TableModel dataModel) { dataModel.addTableModelListener(rowHeader); super.setModel(dataModel); } /** * Selects colomns. * @param index0 index of start * @param index1 index of end */ void selectColumn(int index0, int index1) { if (getRowCount() > 0) { addColumnSelectionInterval(index0, index1); addRowSelectionInterval(getRowCount() - 1, 0); } } /** * Jumps to specified column. * @param index * @return whether the column exists or not */ boolean jumpToColumn(int index) { final int columnCount = getColumnCount(); if (0 <= index && index < columnCount) { if (getSelectedRowCount() == 0) { changeSelection(-1, index, false, false); } else { int[] selectedRows = getSelectedRows(); changeSelection(getSelectedRow(), index, false, false); for (final int selectedRow : selectedRows) { changeSelection(selectedRow, index, false, true); } } return true; } return false; } /** * Jumps to specified column. * @param name * @return whether the column exists or not */ boolean jumpToColumn(String name) { TableColumnModel columnModel = getColumnModel(); for (int i = 0, n = columnModel.getColumnCount(); i < n; i++) { if (name.equals(String.valueOf(columnModel.getColumn(i).getHeaderValue()))) { jumpToColumn(i); return true; } } return false; } RowHeader getRowHeader() { return rowHeader; } ResultSetTableModel getResultSetTableModel() { return (ResultSetTableModel)getModel(); } boolean isShowColumnNumber() { return columnHeaderRenderer.fixesColumnNumber; } void setShowColumnNumber(boolean showColumnNumber) { final boolean oldValue = this.columnHeaderRenderer.fixesColumnNumber; this.columnHeaderRenderer.fixesColumnNumber = showColumnNumber; firePropertyChange("showNumber", oldValue, showColumnNumber); } void repaintRowHeader(String propName) { if (rowHeader != null) { rowHeader.propertyChange(new PropertyChangeEvent(this, propName, null, null)); } } String getAutoAdjustMode() { return autoAdjustMode; } void setAutoAdjustMode(String autoAdjustMode) { final String oldValue = this.autoAdjustMode; this.autoAdjustMode = autoAdjustMode; firePropertyChange("autoAdjustMode", oldValue, autoAdjustMode); } private void bindJumpAction(String suffix, int key, boolean withSelect) { final String actionKey = String.format("%s-to-%s", (withSelect) ? "select" : "jump", suffix); final CellCursor c = new CellCursor(this, withSelect); final int modifiers = Utilities.getMenuShortcutKeyMask() | (withSelect ? SHIFT_DOWN_MASK : 0); KeyStroke[] keyStrokes = {getKeyStroke(key, modifiers)}; c.putValue(Action.ACTION_COMMAND_KEY, actionKey); InputMap im = this.getInputMap(); for (KeyStroke ks : keyStrokes) { im.put(ks, actionKey); } this.getActionMap().put(actionKey, c); } private static final class CellCursor extends AbstractAction { private final JTable table; private final boolean extend; CellCursor(JTable table, boolean extend) { this.table = table; this.extend = extend; } int getColumnPosition() { int[] a = table.getSelectedColumns(); if (a == null || a.length == 0) { return -1; } ListSelectionModel csm = table.getColumnModel().getSelectionModel(); return (a[0] == csm.getAnchorSelectionIndex()) ? a[a.length - 1] : a[0]; } int getRowPosition() { int[] a = table.getSelectedRows(); if (a == null || a.length == 0) { return -1; } ListSelectionModel rsm = table.getSelectionModel(); return (a[0] == rsm.getAnchorSelectionIndex()) ? a[a.length - 1] : a[0]; } @Override public void actionPerformed(ActionEvent e) { final String cmd = e.getActionCommand(); final int ri; final int ci; if (cmd == null) { assert false : "command is null"; return; } else if (cmd.endsWith("-to-home")) { ri = 0; ci = 0; } else if (cmd.endsWith("-to-end")) { ri = table.getRowCount() - 1; ci = table.getColumnCount() - 1; } else if (cmd.endsWith("-to-top")) { ri = 0; ci = getColumnPosition(); } else if (cmd.endsWith("-to-bottom")) { ri = table.getRowCount() - 1; ci = getColumnPosition(); } else if (cmd.endsWith("-to-leftmost")) { ri = getRowPosition(); ci = 0; } else if (cmd.endsWith("-to-rightmost")) { ri = getRowPosition(); ci = table.getColumnCount() - 1; } else { assert false : "unknown command: " + cmd; return; } table.changeSelection(ri, ci, false, extend); } } private static final class NullValueRenderer extends DefaultTableCellRenderer { NullValueRenderer() { } // empty @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, "NULL", isSelected, hasFocus, row, column); c.setForeground(new Color(63, 63, 192, 192)); Font font = c.getFont(); c.setFont(font.deriveFont(font.getSize() * 0.8f)); return c; } } private static final class ColumnHeaderCellRenderer implements TableCellRenderer { TableCellRenderer renderer; boolean fixesColumnNumber; ColumnHeaderCellRenderer(TableCellRenderer renderer) { this.renderer = renderer; this.fixesColumnNumber = false; } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Object o = fixesColumnNumber ? String.format("%d %s", column + 1, value) : value; return renderer.getTableCellRendererComponent(table, o, isSelected, hasFocus, row, column); } } private static final class RowHeader extends JTable implements PropertyChangeListener { private static final int DEFAULT_WIDTH = 40; private DefaultTableModel model; private TableCellRenderer renderer; RowHeader(JTable table) { this.model = new DefaultTableModel(0, 1) { @Override public boolean isCellEditable(int row, int column) { return false; } }; final ResultSetTable t = (ResultSetTable)table; this.renderer = new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { assert t.getModel() instanceof ResultSetTableModel; final boolean rowLinked = t.getResultSetTableModel().isLinkedRow(row); JLabel label = new JLabel(String.format("%s ", rowLinked ? row + 1 : "+")); label.setHorizontalAlignment(RIGHT); label.setFont(table.getFont()); label.setOpaque(true); return label; } }; setModel(model); setWidth(table); setFocusable(false); table.addPropertyChangeListener(this); } @Override public void propertyChange(PropertyChangeEvent e) { JTable table = (JTable)e.getSource(); if (table == null) { return; } String propertyName = e.getPropertyName(); if (propertyName.equals("enabled")) { boolean isEnabled = table.isEnabled(); setVisible(isEnabled); if (isEnabled) { setWidth(table); resetViewPosition(table); } } else if (propertyName.equals("font")) { setFont(table.getFont()); } else if (propertyName.equals("rowHeight")) { setRowHeight(table.getRowHeight()); } else if (propertyName.equals("model")) { model.setRowCount(table.getRowCount()); } else if (propertyName.equals("unlinkedRowStatus")) { repaint(); } else if (propertyName.equals("ancestor")) { // empty } else { // empty } validate(); } @Override public void tableChanged(TableModelEvent e) { Object src = e.getSource(); if (model != null && src != null) { model.setRowCount(((TableModel)src).getRowCount()); } super.tableChanged(e); } @Override public void updateUI() { super.updateUI(); adjustRowHeight(this); } void setWidth(JTable table) { // XXX unstable final int rowCount = table.getRowCount(); model.setRowCount(rowCount); JLabel label = new JLabel(String.valueOf(rowCount * 1000L)); Dimension d = getSize(); d.width = Math.max(label.getPreferredSize().width, DEFAULT_WIDTH); setPreferredScrollableViewportSize(d); } private void resetViewPosition(JTable table) { // forces to reset its view position to table's view position Container p1 = table.getParent(); Container p2 = getParent(); if (p1 instanceof JViewport && p2 instanceof JViewport) { JViewport v1 = (JViewport)p1; JViewport v2 = (JViewport)p2; v2.setViewPosition(v1.getViewPosition()); } } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public TableCellRenderer getCellRenderer(int row, int column) { return renderer; } } // text search @Override public boolean search(Matcher matcher) { final int rowCount = getRowCount(); if (rowCount <= 0) { return false; } final int columnCount = getColumnCount(); final boolean backward = matcher.isBackward(); final int amount = backward ? -1 : 1; final int rowStart = backward ? rowCount - 1 : 0; final int rowEnd = backward ? 0 : rowCount - 1; final int columnStart = backward ? columnCount - 1 : 0; final int columnEnd = backward ? 0 : columnCount - 1; int row = rowStart; int column = columnStart; if (getSelectedColumnCount() > 0) { column = getSelectedColumn(); row = getSelectedRow() + amount; if (backward) { if (row < 0) { --column; if (column < 0) { return false; } row = rowStart; } } else { if (row >= rowCount) { ++column; if (column >= columnCount) { return false; } row = rowStart; } } } final TableModel m = getModel(); for (; backward ? column >= columnEnd : column <= columnEnd; column += amount) { for (; backward ? row >= rowEnd : row <= rowEnd; row += amount) { if (matcher.find(String.valueOf(m.getValueAt(row, column)))) { changeSelection(row, column, false, false); return true; } } row = rowStart; } return false; } @Override public void reset() { // empty } static final class TableHeaderTextSearch implements TextSearch { private ResultSetTable rstable; private JTableHeader tableHeader; TableHeaderTextSearch(ResultSetTable rstable, JTableHeader tableHeader) { this.rstable = rstable; this.tableHeader = tableHeader; } @Override public boolean search(Matcher matcher) { TableColumnModel m = tableHeader.getColumnModel(); int columnCount = m.getColumnCount(); if (columnCount < 1) { return false; } final boolean backward = matcher.isBackward(); final int amount = backward ? -1 : 1; final int columnStart = backward ? columnCount - 1 : 0; final int columnEnd = backward ? 0 : columnCount - 1; int column = columnStart; if (rstable.getSelectedColumnCount() > 0) { column = rstable.getSelectedColumn() + amount; } for (; backward ? column >= columnEnd : column <= columnEnd; column += amount) { if (matcher.find(String.valueOf(m.getColumn(column).getHeaderValue()))) { rstable.jumpToColumn(column); return true; } } return false; } @Override public void reset() { // empty } } // event-handlers private void setValueAtSelectedCells(Object value) { int[] selectedColumns = getSelectedColumns(); for (int rowIndex : getSelectedRows()) { for (int colIndex : selectedColumns) { setValueAt(value, rowIndex, colIndex); } } } private void adjustColumnWidth() { final int rowCount = getRowCount(); final boolean byHeader; final boolean byValue; switch (AnyActionKey.of(autoAdjustMode)) { case autoAdjustModeNone: byHeader = false; byValue = false; break; case autoAdjustModeHeader: byHeader = true; byValue = false; break; case autoAdjustModeValue: byHeader = false; byValue = true; break; case autoAdjustModeHeaderAndValue: byHeader = true; byValue = true; break; default: log.warn("autoAdjustMode=%s", autoAdjustMode); return; } if (!byHeader && rowCount == 0) { return; } final float max = getParent().getWidth() * 0.8f; TableColumnModel columnModel = getColumnModel(); JTableHeader header = getTableHeader(); for (int columnIndex = 0, n = getColumnCount(); columnIndex < n; columnIndex++) { float size = 0f; if (byHeader) { TableColumn column = columnModel.getColumn(columnIndex); TableCellRenderer renderer = column.getHeaderRenderer(); if (renderer == null) { renderer = header.getDefaultRenderer(); } if (renderer != null) { Component c = renderer.getTableCellRendererComponent(this, column.getHeaderValue(), false, false, 0, columnIndex); size = c.getPreferredSize().width * 1.5f; } } if (byValue) { for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { TableCellRenderer renderer = getCellRenderer(rowIndex, columnIndex); if (renderer == null) { continue; } Object value = getValueAt(rowIndex, columnIndex); Component c = renderer.getTableCellRendererComponent(this, value, false, false, rowIndex, columnIndex); size = Math.max(size, c.getPreferredSize().width); if (size >= max) { break; } } } int width = Math.round(size > max ? max : size) + 1; columnModel.getColumn(columnIndex).setPreferredWidth(width); } } void doSort(int columnIndex) { if (getColumnCount() == 0) { return; } final boolean reverse; if (lastSortedIndex == columnIndex) { reverse = (lastSortedIsReverse == false); } else { lastSortedIndex = columnIndex; reverse = false; } lastSortedIsReverse = reverse; getResultSetTableModel().sort(columnIndex, reverse); repaint(); repaintRowHeader("unlinkedRowStatus"); } void changeTableColumnWidth(double rate) { for (TableColumn column : Collections.list(getColumnModel().getColumns())) { column.setPreferredWidth((int)(column.getWidth() * rate)); } } }
//Title: TASSELMainFrame //Company: NCSU package net.maizegenetics.tassel; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.plugindef.Datum; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.gui.PrintTextArea; import javax.swing.*; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Event; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.*; import java.awt.image.ImageProducer; import java.io.*; import java.net.URL; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import net.maizegenetics.baseplugins.ExportPlugin; import net.maizegenetics.gui.PrintHeapAction; import net.maizegenetics.plugindef.PluginEvent; import net.maizegenetics.plugindef.ThreadedPluginListener; import net.maizegenetics.progress.ProgressPanel; import net.maizegenetics.util.Utils; import net.maizegenetics.wizard.Wizard; import net.maizegenetics.wizard.WizardPanelDescriptor; import net.maizegenetics.wizard.panels.TestPanel1Descriptor; import net.maizegenetics.wizard.panels.TestPanel2Descriptor; import net.maizegenetics.wizard.panels.TestPanel3Descriptor; import net.maizegenetics.wizard.panels.TestPanel4Descriptor; import org.apache.log4j.Logger; /** * TASSELMainFrame * */ public class TASSELMainFrame extends JFrame { private static final Logger myLogger = Logger.getLogger(TASSELMainFrame.class); public static final String version = "4.0.26"; public static final String versionDate = "July 26, 2012"; DataTreePanel theDataTreePanel; DataControlPanel theDataControlPanel; AnalysisControlPanel theAnalysisControlPanel; ResultControlPanel theResultControlPanel; private String tasselDataFile = "TasselDataFile"; //a variable to control when the progress bar was last updated private long lastProgressPaint = 0; private String dataTreeLoadFailed = "Unable to open the saved data tree. The file format of this version is " + "incompatible with other versions."; static final String GENOTYPE_DATA_NEEDED = "Please select genotypic data from the data tree."; static final String RESULTS_DATA_NEEDED = "Please select results data from the data tree."; JFileChooser filerSave = new JFileChooser(); JFileChooser filerOpen = new JFileChooser(); JPanel mainPanel = new JPanel(); JPanel dataTreePanelPanel = new JPanel(); JPanel reportPanel = new JPanel(); JPanel optionsPanel = new JPanel(); JPanel optionsPanelPanel = new JPanel(); JPanel modeSelectorsPanel = new JPanel(); JPanel buttonPanel = new JPanel(); JSplitPane dataTreeReportMainPanelsSplitPanel = new JSplitPane(); JSplitPane dataTreeReportPanelsSplitPanel = new JSplitPane(); JScrollPane reportPanelScrollPane = new JScrollPane(); JTextArea reportPanelTextArea = new JTextArea(); JScrollPane mainPanelScrollPane = new JScrollPane(); JPanel mainDisplayPanel = new JPanel(); //mainPanelTextArea corresponds to what is called Main Panel in the user documentation ThreadedJTextArea mainPanelTextArea = new ThreadedJTextArea(); JTextField statusBar = new JTextField(); JButton resultButton = new JButton(); JButton dataButton = new JButton(); JButton deleteButton = new JButton(); JButton printButton = new JButton(); JButton analysisButton = new JButton(); JPopupMenu mainPopupMenu = new JPopupMenu(); JMenuBar jMenuBar = new JMenuBar(); JMenu fileMenu = new JMenu(); JMenu toolsMenu = new JMenu(); JMenuItem saveMainMenuItem = new JMenuItem(); JCheckBoxMenuItem matchCheckBoxMenuItem = new JCheckBoxMenuItem(); JMenuItem openCompleteDataTreeMenuItem = new JMenuItem(); JMenuItem openDataMenuItem = new JMenuItem(); JMenuItem saveAsDataTreeMenuItem = new JMenuItem(); JMenuItem saveCompleteDataTreeMenuItem = new JMenuItem(); JMenuItem saveDataTreeAsMenuItem = new JMenuItem(); JMenuItem exitMenuItem = new JMenuItem(); JMenu helpMenu = new JMenu(); JMenuItem helpMenuItem = new JMenuItem(); JMenuItem preferencesMenuItem = new JMenuItem(); JMenuItem aboutMenuItem = new JMenuItem(); PreferencesDialog thePreferencesDialog; String UserComments = ""; private final ProgressPanel myProgressPanel = ProgressPanel.getInstance(); JButton wizardButton = new JButton(); ExportPlugin myExportPlugin = null; public TASSELMainFrame(boolean debug) { try { loadSettings(); addMenuBar(); theDataTreePanel = new DataTreePanel(this, true, debug); theDataTreePanel.setToolTipText("Data Tree Panel"); theDataControlPanel = new DataControlPanel(this, theDataTreePanel); theAnalysisControlPanel = new AnalysisControlPanel(this, theDataTreePanel); theResultControlPanel = new ResultControlPanel(this, theDataTreePanel); theResultControlPanel.setToolTipText("Report Panel"); initializeMyFrame(); setIcon(); initDataMode(); this.setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage) " + this.version); } catch (Exception e) { e.printStackTrace(); } } private void setIcon() { URL url = this.getClass().getResource("Logo_small.png"); if (url == null) { return; } Image img = null; try { img = createImage((ImageProducer) url.getContent()); } catch (Exception e) { } if (img != null) { setIconImage(img); } } private void initWizard() { Wizard wizard = new Wizard(theDataTreePanel); wizard.getDialog().setTitle("TASSEL Wizard (In development)"); WizardPanelDescriptor descriptor1 = new TestPanel1Descriptor(); wizard.registerWizardPanel(TestPanel1Descriptor.IDENTIFIER, descriptor1); WizardPanelDescriptor descriptor2 = new TestPanel2Descriptor(); wizard.registerWizardPanel(TestPanel2Descriptor.IDENTIFIER, descriptor2); WizardPanelDescriptor descriptor3 = new TestPanel3Descriptor(); wizard.registerWizardPanel(TestPanel3Descriptor.IDENTIFIER, descriptor3); WizardPanelDescriptor descriptor4 = new TestPanel4Descriptor(); wizard.registerWizardPanel(TestPanel4Descriptor.IDENTIFIER, descriptor4); wizard.setCurrentPanel(TestPanel1Descriptor.IDENTIFIER); wizard.getDialog().setLocationRelativeTo(this); int ret = wizard.showModalDialog(); // System.out.println("Dialog return code is (0=Finish,1=Cancel,2=Error): " + ret); // System.out.println("Second panel selection is: " + // (((TestPanel2)descriptor2.getPanelComponent()).getRadioButtonSelected())); // System.exit(0); } private JButton getHeapButton() { JButton heapButton = new JButton(PrintHeapAction.getInstance(this)); heapButton.setText("Show Memory"); heapButton.setToolTipText("Show Memory Usage"); return heapButton; } private void initDataMode() { buttonPanel.removeAll(); buttonPanel.add(theDataControlPanel, BorderLayout.NORTH); dataTreePanelPanel.removeAll(); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); this.validate(); repaint(); } private void initAnalysisMode() { buttonPanel.removeAll(); buttonPanel.add(theAnalysisControlPanel, null); dataTreePanelPanel.removeAll(); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); this.validate(); repaint(); } private void initResultMode() { buttonPanel.removeAll(); buttonPanel.add(theResultControlPanel, null); dataTreePanelPanel.removeAll(); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); this.validate(); repaint(); } //Component initialization private void initializeMyFrame() throws Exception { this.getContentPane().setLayout(new BorderLayout()); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // it is time for TASSEL to claim more (almost all) of the screen real estate for itself // this size was selected so as to encourage the user to resize to full screen, thereby // insuring that all parts of the frame are visible. this.setSize(new Dimension(screenSize.width * 19 / 20, screenSize.height * 19 / 20)); this.setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage)"); this.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(WindowEvent e) { this_windowClosing(e); } }); filerSave.setDialogType(JFileChooser.SAVE_DIALOG); mainPanel.setLayout(new BorderLayout()); dataTreeReportPanelsSplitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT); optionsPanelPanel.setLayout(new BorderLayout()); dataTreePanelPanel.setLayout(new BorderLayout()); dataTreePanelPanel.setToolTipText("Data Tree Panel"); reportPanel.setLayout(new BorderLayout()); reportPanelTextArea.setEditable(false); reportPanelTextArea.setToolTipText("Report Panel"); mainPanelTextArea.setDoubleBuffered(true); mainPanelTextArea.setEditable(false); mainPanelTextArea.setFont(new java.awt.Font("Monospaced", 0, 12)); mainPanelTextArea.setToolTipText("Main Panel"); mainPanelTextArea.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(MouseEvent e) { mainTextArea_mouseClicked(e); } }); statusBar.setBackground(Color.lightGray); statusBar.setBorder(null); statusBar.setText("Program Status"); modeSelectorsPanel.setLayout(new GridBagLayout()); modeSelectorsPanel.setMinimumSize(new Dimension(380, 32)); modeSelectorsPanel.setPreferredSize(new Dimension(700, 32)); URL imageURL = TASSELMainFrame.class.getResource("images/help1.gif"); ImageIcon helpIcon = null; if (imageURL != null) { helpIcon = new ImageIcon(imageURL); } JButton helpButton = new JButton(); helpButton.setIcon(helpIcon); helpButton.setMargin(new Insets(0, 0, 0, 0)); helpButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpButton_actionPerformed(e); } }); helpButton.setBackground(Color.white); helpButton.setMinimumSize(new Dimension(20, 20)); helpButton.setToolTipText("Help me!!"); resultButton.setText("Results"); resultButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { resultButton_actionPerformed(e); } }); resultButton.setMargin(new Insets(2, 2, 2, 2)); imageURL = TASSELMainFrame.class.getResource("images/Results.gif"); ImageIcon resultsIcon = null; if (imageURL != null) { resultsIcon = new ImageIcon(imageURL); } if (resultsIcon != null) { resultButton.setIcon(resultsIcon); } resultButton.setPreferredSize(new Dimension(90, 25)); resultButton.setMinimumSize(new Dimension(87, 25)); resultButton.setMaximumSize(new Dimension(90, 25)); resultButton.setBackground(Color.white); wizardButton.setText("Wizard"); wizardButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { wizardButton_actionPerformed(e); } }); wizardButton.setMargin(new Insets(2, 2, 2, 2)); wizardButton.setPreferredSize(new Dimension(90, 25)); wizardButton.setMinimumSize(new Dimension(87, 25)); wizardButton.setMaximumSize(new Dimension(90, 25)); wizardButton.setBackground(Color.white); dataButton.setBackground(Color.white); dataButton.setMaximumSize(new Dimension(90, 25)); dataButton.setMinimumSize(new Dimension(87, 25)); dataButton.setPreferredSize(new Dimension(90, 25)); imageURL = TASSELMainFrame.class.getResource("images/DataSeq.gif"); ImageIcon dataSeqIcon = null; if (imageURL != null) { dataSeqIcon = new ImageIcon(imageURL); } if (dataSeqIcon != null) { dataButton.setIcon(dataSeqIcon); } dataButton.setMargin(new Insets(2, 2, 2, 2)); dataButton.setText("Data"); dataButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { dataButton_actionPerformed(e); } }); printButton.setBackground(Color.white); printButton.setToolTipText("Print selected datum"); imageURL = TASSELMainFrame.class.getResource("images/print1.gif"); ImageIcon printIcon = null; if (imageURL != null) { printIcon = new ImageIcon(imageURL); } if (printIcon != null) { printButton.setIcon(printIcon); } printButton.setMargin(new Insets(0, 0, 0, 0)); printButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { printButton_actionPerformed(e); } }); analysisButton.setText("Analysis"); analysisButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { analysisButton_actionPerformed(e); } }); analysisButton.setMargin(new Insets(2, 2, 2, 2)); imageURL = TASSELMainFrame.class.getResource("images/Analysis.gif"); ImageIcon analysisIcon = null; if (imageURL != null) { analysisIcon = new ImageIcon(imageURL); } if (analysisIcon != null) { analysisButton.setIcon(analysisIcon); } analysisButton.setPreferredSize(new Dimension(90, 25)); analysisButton.setMinimumSize(new Dimension(87, 25)); analysisButton.setMaximumSize(new Dimension(90, 25)); analysisButton.setBackground(Color.white); // delete button added moved from data panel by yogesh. deleteButton.setOpaque(true); deleteButton.setForeground(Color.RED); deleteButton.setText("Delete"); deleteButton.setFont(new java.awt.Font("Dialog", 1, 12)); deleteButton.setToolTipText("Delete Dataset"); deleteButton.setMargin(new Insets(2, 2, 2, 2)); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { theDataTreePanel.deleteSelectedNodes(); } }); optionsPanel.setLayout(new BorderLayout(0, 0)); buttonPanel.setLayout(new BorderLayout(0, 0)); optionsPanel.setToolTipText("Options Panel"); mainPopupMenu.setInvoker(this); saveMainMenuItem.setText("Save"); matchCheckBoxMenuItem.setText("Match"); matchCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { matchCheckBoxMenuItem_actionPerformed(e); } }); fileMenu.setText("File"); toolsMenu.setText("Tools"); saveCompleteDataTreeMenuItem.setText("Save Data Tree"); saveCompleteDataTreeMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveCompleteDataTreeMenuItem_actionPerformed(e); } }); saveDataTreeAsMenuItem.setText("Save Data Tree As ..."); saveDataTreeAsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { saveDataTreeMenuItem_actionPerformed(e); } }); openCompleteDataTreeMenuItem.setText("Open Data Tree"); openCompleteDataTreeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openCompleteDataTreeMenuItem_actionPerformed(e); } }); openDataMenuItem.setText("Open Data Tree..."); openDataMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openDataMenuItem_actionPerformed(e); } }); saveAsDataTreeMenuItem.setText("Save Selected As..."); saveAsDataTreeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { ExportPlugin plugin = getExportPlugin(); PluginEvent event = new PluginEvent(theDataTreePanel.getSelectedTasselDataSet()); ProgressPanel progressPanel = getProgressPanel(); ThreadedPluginListener thread = new ThreadedPluginListener(plugin, event); thread.start(); progressPanel.addPlugin(plugin); } }); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { exitMenuItem_actionPerformed(e); } }); helpMenu.setText("Help"); helpMenuItem.setText("Help Manual"); helpMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpButton_actionPerformed(e); } }); preferencesMenuItem.setText("Set Preferences"); preferencesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { preferencesMenuItem_actionPerformed(e); } }); aboutMenuItem.setText("About"); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpAbout_actionPerformed(e); } }); this.getContentPane().add(dataTreeReportMainPanelsSplitPanel, BorderLayout.CENTER); dataTreeReportMainPanelsSplitPanel.add(optionsPanelPanel, JSplitPane.TOP); optionsPanelPanel.add(dataTreeReportPanelsSplitPanel, BorderLayout.CENTER); dataTreeReportPanelsSplitPanel.add(dataTreePanelPanel, JSplitPane.TOP); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); JSplitPane reportProgress = new JSplitPane(JSplitPane.VERTICAL_SPLIT); reportProgress.add(reportPanel, JSplitPane.TOP); reportPanel.add(reportPanelScrollPane, BorderLayout.CENTER); reportPanelScrollPane.getViewport().add(reportPanelTextArea, null); reportProgress.add(new JScrollPane(myProgressPanel), JSplitPane.BOTTOM); dataTreeReportPanelsSplitPanel.add(reportProgress, JSplitPane.BOTTOM); dataTreeReportMainPanelsSplitPanel.add(mainPanel, JSplitPane.BOTTOM); /** * Provides a save filer that remembers the last location something was saved to */ public File getSaveFile() { File saveFile = null; int returnVal = filerSave.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { saveFile = filerSave.getSelectedFile(); TasselPrefs.putSaveDir(filerSave.getCurrentDirectory().getPath()); } return saveFile; } /** * Provides a open filer that remember the last location something was opened from */ public File getOpenFile() { File openFile = null; int returnVal = filerOpen.showOpenDialog(this); System.out.println("returnVal = " + returnVal); System.out.println("JFileChooser.OPEN_DIALOG " + JFileChooser.OPEN_DIALOG); if (returnVal == JFileChooser.OPEN_DIALOG || returnVal == JFileChooser.APPROVE_OPTION) { openFile = filerOpen.getSelectedFile(); System.out.println("openFile = " + openFile); TasselPrefs.putOpenDir(filerOpen.getCurrentDirectory().getPath()); } return openFile; } void this_windowClosing(WindowEvent e) { exitMenuItem_actionPerformed(null); } public void addDataSet(DataSet theDataSet, String defaultNode) { theDataTreePanel.addDataSet(theDataSet, defaultNode); } private void saveDataTree(String file) { Map dataToSerialize = new LinkedHashMap(); Map dataFromTree = theDataTreePanel.getDataList(); StringBuilder builder = new StringBuilder(); Iterator itr = dataFromTree.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) dataFromTree.get(currentDatum); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(currentDatum); oos.close(); if (out.toByteArray().length > 0) { dataToSerialize.put(currentDatum, currentNode); } } catch (Exception e) { myLogger.warn("saveDataTree: object: " + currentDatum.getName() + " type: " + currentDatum.getData().getClass().getName() + " does not serialize."); myLogger.warn("saveDataTree: message: " + e.getMessage()); if (builder.length() == 0) { builder.append("Due to error, these data sets could not\n"); builder.append("included in the saved file..."); } builder.append("Data set: "); builder.append(currentDatum.getName()); builder.append(" type: "); builder.append(currentDatum.getData().getClass().getName()); builder.append("\n"); } } try { File theFile = new File(Utils.addSuffixIfNeeded(file, ".zip")); FileOutputStream fos = new FileOutputStream(theFile); java.util.zip.ZipOutputStream zos = new ZipOutputStream(fos); Map data = theDataTreePanel.getDataList(); ZipEntry thisEntry = new ZipEntry("DATA"); zos.putNextEntry(thisEntry); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(dataToSerialize); oos.flush(); zos.closeEntry(); fos.close(); sendMessage("Data saved to " + theFile.getAbsolutePath()); } catch (Exception ee) { sendErrorMessage("Data could not be saved: " + ee); ee.printStackTrace(); } if (builder.length() != 0) { JOptionPane.showMessageDialog(this, builder.toString(), "These data sets not saved...", JOptionPane.INFORMATION_MESSAGE); } } private boolean readDataTree(String file) { boolean loadedDataTreePanel = false; try { FileInputStream fis = null; ObjectInputStream ois = null; if (file.endsWith("zip")) { fis = new FileInputStream(file); java.util.zip.ZipInputStream zis = new java.util.zip.ZipInputStream(fis); zis.getNextEntry(); ois = new ObjectInputStream(zis); } else { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); } try { Map data = (Map) ois.readObject(); Iterator itr = data.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) data.get(currentDatum); theDataTreePanel.addDatum(currentNode, currentDatum); } loadedDataTreePanel = true; } catch (InvalidClassException ice) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); } finally { fis.close(); } if (loadedDataTreePanel) { sendMessage("Data loaded."); } } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(this, "File not found: " + file, "File not found", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } catch (Exception ee) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed + ee, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } return loadedDataTreePanel; } private void wizardButton_actionPerformed(ActionEvent e) { initWizard(); } private void dataButton_actionPerformed(ActionEvent e) { initDataMode(); } private void analysisButton_actionPerformed(ActionEvent e) { initAnalysisMode(); } private void resultButton_actionPerformed(ActionEvent e) { initResultMode(); } private void printButton_actionPerformed(ActionEvent e) { DataSet ds = theDataTreePanel.getSelectedTasselDataSet(); try { for (int i = 0; i < ds.getSize(); i++) { PrintTextArea pta = new PrintTextArea(this); pta.printThis(ds.getData(i).getData().toString()); } } catch (Exception ee) { System.err.println("printButton_actionPerformed:" + ee); } this.statusBar.setText("Datasets were sent to the printer"); } private void helpButton_actionPerformed(ActionEvent e) { HelpDialog theHelpDialog = new HelpDialog(this); theHelpDialog.setLocationRelativeTo(this); theHelpDialog.setVisible(true); } private void mainTextArea_mouseClicked(MouseEvent e) { // For this example event, we are checking for right-mouse click. if (e.getModifiers() == Event.META_MASK) { mainPanelTextArea.add(mainPopupMenu); // JPopupMenu must be added to the component whose event is chosen. // Make the jPopupMenu visible relative to the current mouse position in the container. mainPopupMenu.show(mainPanelTextArea, e.getX(), e.getY()); } } private void matchCheckBoxMenuItem_actionPerformed(ActionEvent e) { //theSettings.matchChar = matchCheckBoxMenuItem.isSelected(); } private void openCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { String dataFileName = this.tasselDataFile + ".zip"; File dataFile = new File(dataFileName); if (dataFile.exists()) { readDataTree(dataFileName); } else if (new File("QPGADataFile").exists()) { // this exists to maintain backward compatibility with previous versions (pre-v0.99) readDataTree("QPGADataFile"); } else { JOptionPane.showMessageDialog(this, "File: " + dataFile.getAbsolutePath() + " does not exist.\n" + "Try using File/Open Data Tree..."); } } private void openDataMenuItem_actionPerformed(ActionEvent e) { File f = getOpenFile(); if (f != null) { readDataTree(f.getAbsolutePath()); } } private void saveDataTreeMenuItem_actionPerformed(ActionEvent e) { File f = getSaveFile(); if (f != null) { saveDataTree(f.getAbsolutePath()); } } private void saveCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { saveDataTree(this.tasselDataFile + ".zip"); } private void exitMenuItem_actionPerformed(ActionEvent e) { System.exit(0); } private void preferencesMenuItem_actionPerformed(ActionEvent e) { if (thePreferencesDialog == null) { thePreferencesDialog = new PreferencesDialog(); thePreferencesDialog.pack(); } thePreferencesDialog.setLocationRelativeTo(this); thePreferencesDialog.setVisible(true); } public void updateMainDisplayPanel(JPanel panel) { mainDisplayPanel.removeAll(); mainDisplayPanel.add(panel, BorderLayout.CENTER); mainDisplayPanel.repaint(); mainDisplayPanel.validate(); } public void addMenu(JMenu menu) { jMenuBar.add(menu); } public DataTreePanel getDataTreePanel() { return theDataTreePanel; } public ProgressPanel getProgressPanel() { return myProgressPanel; } }
import org.xdi.util.LDAPConstants; /** * Constants loads the LDAP schema attribute names like uid, iname * * @author Yuriy Movchan * @version 0.1, 10/14/2010 */ public class OxConstants extends LDAPConstants { public static final String schemaDN = "cn=schema"; public static final String INUM = "inum"; public static final String INAME = "iname"; public static final String DISPLAY_NAME = "displayName"; public static final String DESCRIPTION = "description"; public static final String ORIGIN = "gluuAttributeOrigin"; public static final String MAIL = "mail"; public static final String CACHE_ORGANIZATION_KEY = "organization"; public static final String CACHE_METRICS_KEY = "metrics"; public static final String CACHE_APPLICATION_NAME = "ApplicationCache"; public static final String CACHE_ATTRIBUTE_NAME = "AttributeCache"; public static final String CACHE_LOOKUP_NAME = "LookupCache"; public static final String CACHE_METRICS_NAME = "metricsCache"; public static final String CACHE_ATTRIBUTE_KEY_LIST = "attributeList"; public static final String CACHE_ACTIVE_ATTRIBUTE_KEY_LIST = "activeAttributeList"; public static final String CACHE_ACTIVE_ATTRIBUTE_NAME = "ActiveAttributeCache"; public static final String SCRIPT_TYPE_INTERNAL_RESERVED_NAME = "internal"; }
package com.microsoft.azure.management; import com.microsoft.azure.management.cdn.CdnEndpoint; import com.microsoft.azure.management.cdn.CdnProfile; import com.microsoft.azure.management.cdn.CdnProfiles; import com.microsoft.azure.management.cdn.GeoFilter; import com.microsoft.azure.management.cdn.GeoFilterActions; import com.microsoft.azure.management.cdn.QueryStringCachingBehavior; import com.microsoft.azure.management.cdn.SkuName; import com.microsoft.azure.management.resources.fluentcore.arm.CountryISOCode; import com.microsoft.azure.management.resources.fluentcore.arm.Region; import org.junit.Assert; import java.util.Map; /** * Test of CDN management. */ public class TestCdn extends TestTemplate<CdnProfile, CdnProfiles> { @Override public CdnProfile createResource(CdnProfiles profiles) throws Exception { final Region region = Region.US_EAST; final String groupName = "rg" + this.testId; final String cdnProfileName = "cdnProfile" + this.testId; final String cdnEndpointName = "cdnEndpoint" + this.testId; final String cdnOriginHostName = "mylinuxapp.azurewebsites.net"; CdnProfile cdnProfile = profiles.define(cdnProfileName) .withRegion(region) .withNewResourceGroup(groupName) .withStandardAkamaiSku() .defineNewEndpoint(cdnEndpointName) .withOrigin(cdnOriginHostName) .withGeoFilter("/path/videos", GeoFilterActions.BLOCK, CountryISOCode.ARGENTINA) .withGeoFilter("/path/images", GeoFilterActions.BLOCK, CountryISOCode.BELGIUM) .withContentTypeToCompress("text/plain") .withCompressionEnabled(true) .withQueryStringCachingBehavior(QueryStringCachingBehavior.BYPASS_CACHING) .withHttpsAllowed(true) .withHttpsPort(444) .withHttpAllowed(false) .withHttpPort(85) .attach() .create(); Assert.assertTrue(cdnProfile.sku().name().equals(SkuName.STANDARD_AKAMAI)); Assert.assertNotNull(cdnProfile.endpoints()); Assert.assertEquals(1, cdnProfile.endpoints().size()); CdnEndpoint endpoint = cdnProfile.endpoints().get(cdnEndpointName); Assert.assertNotNull(endpoint); Assert.assertEquals(cdnOriginHostName, endpoint.originHostName()); Assert.assertEquals(444, endpoint.httpsPort()); Assert.assertEquals(85, endpoint.httpPort()); Assert.assertFalse(endpoint.isHttpAllowed()); Assert.assertTrue(endpoint.isHttpsAllowed()); Assert.assertTrue(endpoint.isCompressionEnabled()); Assert.assertEquals(QueryStringCachingBehavior.BYPASS_CACHING, endpoint.queryStringCachingBehavior()); Assert.assertNotNull(endpoint.geoFilters()); Assert.assertEquals(QueryStringCachingBehavior.BYPASS_CACHING, endpoint.queryStringCachingBehavior()); return cdnProfile; } @Override public CdnProfile updateResource(CdnProfile profile) throws Exception { String firstEndpointName = profile.endpoints().keySet().iterator().next(); // Remove an endpoint, update two endpoints and add new one profile.update() .withTag("provider", "Akamai") .withNewEndpoint("www.bing.com") .defineNewEndpoint("somenewnamefortheendpoint") .withOrigin("www.contoso.com") .withGeoFilter("/path/music", GeoFilterActions.BLOCK, CountryISOCode.UNITED_STATES_OUTLYING_ISLANDS) .attach() .updateEndpoint(firstEndpointName) .withHttpAllowed(true) .withHttpPort(1111) .withoutGeoFilters() .parent() .apply(); Assert.assertEquals(3, profile.endpoints().size()); CdnEndpoint updatedEndpoint = profile.endpoints().get(firstEndpointName); Assert.assertTrue(updatedEndpoint.isHttpsAllowed()); Assert.assertEquals(1111, updatedEndpoint.httpPort()); Assert.assertEquals(0, updatedEndpoint.geoFilters().size()); return profile; } @Override public void print(CdnProfile profile) { StringBuilder info = new StringBuilder(); info.append("CDN Profile: ").append(profile.id()) .append("\n\tName: ").append(profile.name()) .append("\n\tResource group: ").append(profile.resourceGroupName()) .append("\n\tRegion: ").append(profile.regionName()) .append("\n\tSku: ").append(profile.sku().name()) .append("\n\tTags: ").append(profile.tags()); Map<String, CdnEndpoint> cdnEndpoints = profile.endpoints(); if (!cdnEndpoints.isEmpty()) { info.append("\n\tCDN endpoints:"); int idx = 1; for (CdnEndpoint endpoint : cdnEndpoints.values()) { info.append("\n\t\tCDN endpoint: #").append(idx++) .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tName: ").append(endpoint.name()) .append("\n\t\t\tState: ").append(endpoint.resourceState()) .append("\n\t\t\tHost name: ").append(endpoint.hostName()) .append("\n\t\t\tOrigin host name: ").append(endpoint.originHostName()) .append("\n\t\t\tOrigin host header: ").append(endpoint.originHostHeader()) .append("\n\t\t\tOrigin path: ").append(endpoint.originPath()) .append("\n\t\t\tOptimization type: ").append(endpoint.optimizationType()) .append("\n\t\t\tQuery string caching behavior: ").append(endpoint.queryStringCachingBehavior()) .append("\n\t\t\tHttp allowed: ").append(endpoint.isHttpAllowed()) .append("\t\tHttp port: ").append(endpoint.httpPort()) .append("\n\t\t\tHttps allowed: ").append(endpoint.isHttpsAllowed()) .append("\t\tHttps port: ").append(endpoint.httpsPort()) .append("\n\t\t\tCompression enabled: ").append(endpoint.isCompressionEnabled()); info.append("\n\t\t\tContent types to compress: "); for (String contentTypeToCompress : endpoint.contentTypesToCompress()) { info.append("\n\t\t\t\t").append(contentTypeToCompress); } info.append("\n\t\t\tGeo filters: "); for (GeoFilter geoFilter : endpoint.geoFilters()) { info.append("\n\t\t\t\tAction: ").append(geoFilter.action()); info.append("\n\t\t\t\tRelativePath: ").append(geoFilter.relativePath()); info.append("\n\t\t\t\tCountry codes: "); for (String countryCode : geoFilter.countryCodes()) { info.append("\n\t\t\t\t\t").append(countryCode); } } info.append("\n\t\t\tCustom domains: "); for (String customDomain : endpoint.customDomains()) { info.append("\n\t\t\t\t").append(customDomain); } } } System.out.println(info.toString()); } }
package org.hyperic.sigar.win32.test; import java.util.List; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.test.SigarTestCase; import org.hyperic.sigar.win32.Service; import org.hyperic.sigar.win32.ServiceConfig; import org.hyperic.sigar.win32.Win32Exception; public class TestService extends SigarTestCase { private static final String EVENTLOG_NAME = "Eventlog"; private static final String TEST_NAME = "MyTestService"; private static final String PREFIX = "sigar.test.service."; private static final boolean TEST_CREATE = "true".equals(System.getProperty(PREFIX + "create")); private static final boolean TEST_DELETE = "true".equals(System.getProperty(PREFIX + "delete")); public TestService(String name) { super(name); } public void testServiceOpen() throws Exception { Service service = new Service(EVENTLOG_NAME); service.getConfig(); service.close(); String dummyName = "DOESNOTEXIST"; try { new Service(dummyName); assertTrue(false); } catch (Win32Exception e) { traceln(dummyName + ": " + e.getMessage()); assertTrue(true); } } public void testServiceNames() throws Exception { List services = Service.getServiceNames(); assertGtZeroTrace("getServiceNames", services.size()); final String[] ptql = { "Service.Name.ct=Ev", "Service.Path.ew=.exe", }; for (int i=0; i<ptql.length; i++) { services = Service.getServiceNames(getSigar(), ptql[i]); assertGtZeroTrace(ptql[i], services.size()); } final String[] invalid = { "State.Name.ct=Ev", "Service.Invalid.ew=.exe", "-" }; for (int i=0; i<invalid.length; i++) { try { services = Service.getServiceNames(getSigar(), invalid[i]); fail("'" + invalid[i] + "' did not throw Exception"); } catch (Exception e) { //expected } } } public void testServiceConfig() throws Exception { List configs = Service.getServiceConfigs(getSigar(), "svchost.exe"); assertGtZeroTrace("getServiceConfigs", configs.size()); } public void testServicePtql() throws Exception { Sigar sigar = new Sigar(); try { long pid = sigar.getServicePid(EVENTLOG_NAME); String ptql = "Service.Pid.eq=" + pid; List names = Service.getServiceNames(sigar, ptql); traceln(ptql + "==" + names); assertTrue(names.contains(EVENTLOG_NAME)); } finally { sigar.close(); } } public void testServiceCreateDelete() throws Exception { if (!TEST_CREATE) { return; } ServiceConfig config = new ServiceConfig(TEST_NAME); config.setStartType(ServiceConfig.START_MANUAL); config.setDisplayName("My Test Service"); config.setDescription("A Description of " + config.getDisplayName()); config.setPath("C:\\Program Files\\My Test 1.0\\mytest.exe"); Service.create(config); } public void testDeleteService() throws Exception { if (!TEST_DELETE) { return; } Service service = new Service(TEST_NAME); service.delete(); } }
package dk.aau.kah.bits.database; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import da.aau.kah.bits.exceptions.InvalidDatabaseConfig; public class DatabaseConfig { File TDBFile; private String scaleFactor; private String ontologyModelName; private String ontologyStorageModel; private String dimensionModelName; private String dimensionStorageModel; private String factModelName; private String factStorageModel; public String getScaleFactor() { return scaleFactor; } public String getScaleFactorString() { return "sf-"+getScaleFactor(); } public String getOntologyModelName() { return ontologyModelName; } public String getOntologyStorageModel() { return ontologyStorageModel; } public String getDimensionModelName() { return dimensionModelName; } public String getDimensionStorageModel() { return dimensionStorageModel; } public String getFactModelName() { return factModelName; } public String getFactStorageModel() { return factStorageModel; } public void setScaleFactor(String d) { this.scaleFactor = d; } public void setOntologyModelName(String ontologyModelName) { this.ontologyModelName = ontologyModelName; } public void setOntologyStorageModel(String ontologyStorageModel) { this.ontologyStorageModel = ontologyStorageModel; } public void setDimensionModelName(String dimensionModelName) { this.dimensionModelName = dimensionModelName; } public void setDimensionStorageModel(String dimensionStorageModel) { this.dimensionStorageModel = dimensionStorageModel; } public void setFactModelName(String factModelName) { this.factModelName = factModelName; } public void setFactStorageModel(String factStorageModel) { this.factStorageModel = factStorageModel; } public boolean validate() throws InvalidDatabaseConfig { // TODO if (false) { throw new InvalidDatabaseConfig("Some message TODO"); } return true; } public String getTDBPath() { String ontoModelNumber = "0"; String dimModelNumber; String factModelNumber; factModelNumber = (ontologyModelName == factModelName ? "0" : "1" ); // reasoning about what number the dimension model corresponds to in the TDB naming system if (ontologyModelName == dimensionModelName) { dimModelNumber = ontoModelNumber; } else if (dimensionModelName == factModelName ) { dimModelNumber = ontoModelNumber; } else { dimModelNumber = "2"; } return "src/main/resources/tdb/"+"onto"+ontoModelNumber+ontologyStorageModel+"-"+"fact"+ factModelNumber+factStorageModel+"-"+"dim"+dimModelNumber+dimensionStorageModel+"/"; } public File getTDBPathFile() { if (TDBFile == null) { return new File(getTDBPath()); } return TDBFile; } @Override public String toString () { String filepath = getTDBPath(); return filepath.substring(23); } }
package net.time4j.calendar.astro; import net.time4j.CalendarUnit; import net.time4j.ClockUnit; import net.time4j.Moment; import net.time4j.PlainDate; import net.time4j.PlainTime; import net.time4j.PlainTimestamp; import net.time4j.base.ResourceLoader; import net.time4j.engine.CalendarDate; import net.time4j.engine.ChronoCondition; import net.time4j.engine.ChronoFunction; import net.time4j.engine.EpochDays; import net.time4j.scale.TimeScale; import net.time4j.tz.OffsetSign; import net.time4j.tz.TZID; import net.time4j.tz.ZonalOffset; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; public final class SolarTime implements Serializable { private static final double EQUATORIAL_RADIUS = 6378137.0; private static final double POLAR_RADIUS = 6356752.3; private static final double STD_ZENITH = 90.0 + (50.0 / 60.0); private static final Calculator DEFAULT_CALCULATOR; private static final Map<String, Calculator> CALCULATORS; static { Calculator loaded = null; Map<String, Calculator> calculators = new HashMap<>(); for (Calculator calculator : ResourceLoader.getInstance().services(Calculator.class)) { loaded = calculator; calculators.put(calculator.name(), calculator); } calculators.put(Calculator.SIMPLE, StdCalculator.SIMPLE); calculators.put(Calculator.NOAA, StdCalculator.NOAA); CALCULATORS = Collections.unmodifiableMap(calculators); DEFAULT_CALCULATOR = ((loaded == null) ? StdCalculator.NOAA : loaded); } private static final long serialVersionUID = -4816619838743247977L; /** * @serial the geographical latitude in degrees * @since 3.34/4.29 */ private final double latitude; /** * @serial the geographical longitude in degrees * @since 3.34/4.29 */ private final double longitude; /** * @serial the geographical altitude in meters * @since 3.34/4.29 */ private final int altitude; /** * @serial name of the calculator for this instance * @since 3.34/4.29 */ private final String calculator; private SolarTime( double latitude, double longitude, int altitude, String calculator ) { super(); this.latitude = latitude; this.longitude = longitude; this.altitude = altitude; this.calculator = calculator; } /** * <p>Obtains the solar time for given geographical location at sea level. </p> * * <p>The default calculator is usually {@link Calculator#NOAA} unless another calculator was * set up via the service loader mechnism. </p> * * @param latitude geographical latitude in degrees ({@code -90.0 <= x <= +90.0}) * @param longitude geographical longitude in degrees ({@code -180.0 <= x < 180.0}) * @return instance of local solar time * @since 3.34/4.29 */ /*[deutsch] * <p>Liefert die Sonnenzeit zur angegebenen geographischen Position auf Meeresh&ouml;he. </p> * * <p>Die Standardberechnungsmethode ist gew&ouml;hnlich {@link Calculator#NOAA}, es sei denn, * eine andere Methode wurde &uuml;ber den {@code ServiceLoader}-Mechanismus geladen. </p> * * @param latitude geographical latitude in degrees ({@code -90.0 <= x <= +90.0}) * @param longitude geographical longitude in degrees ({@code -180.0 <= x < 180.0}) * @return instance of local solar time * @since 3.34/4.29 */ public static SolarTime ofLocation( double latitude, double longitude ) { return ofLocation(latitude, longitude, 0, DEFAULT_CALCULATOR.name()); } /** * <p>Obtains the solar time for given geographical location. </p> * * @param latitude geographical latitude in degrees ({@code -90.0 <= x <= +90.0}) * @param longitude geographical longitude in degrees ({@code -180.0 <= x < 180.0}) * @param altitude geographical altitude relative to sea level in meters ({@code -1,000 <= x < 10,0000}) * @param calculator name of solar time calculator * @return instance of local solar time * @see Calculator#NOAA * @see Calculator#SIMPLE * @since 3.34/4.29 */ /*[deutsch] * <p>Liefert die Sonnenzeit zur angegebenen geographischen Position. </p> * * @param latitude geographical latitude in degrees ({@code -90.0 <= x <= +90.0}) * @param longitude geographical longitude in degrees ({@code -180.0 <= x < 180.0}) * @param altitude geographical altitude relative to sea level in meters ({@code -1,000 <= x < 10,0000}) * @param calculator name of solar time calculator * @return instance of local solar time * @see Calculator#NOAA * @see Calculator#SIMPLE * @since 3.34/4.29 */ public static SolarTime ofLocation( double latitude, double longitude, int altitude, String calculator ) { check(latitude, longitude, altitude, calculator); return new SolarTime(latitude, longitude, altitude, calculator); } /** * <p>Obtains the geographical latitude of this instance. </p> * * @return latitude in degrees * @since 3.34/4.29 */ /*[deutsch] * <p>Liefert den geographischen Breitengrad dieser Instanz. </p> * * @return latitude in degrees * @since 3.34/4.29 */ public double getLatitude() { return this.latitude; } /** * <p>Obtains the geographical longitude of this instance. </p> * * @return longitude in degrees * @since 3.34/4.29 */ /*[deutsch] * <p>Liefert den geographischen L&auml;ngengrad dieser Instanz. </p> * * @return longitude in degrees * @since 3.34/4.29 */ public double getLongitude() { return this.longitude; } /** * <p>Obtains the geographical altitude of this instance relative to sea level. </p> * * @return altitude in meters * @since 3.34/4.29 */ /*[deutsch] * <p>Liefert die geographische H&ouml;he dieser Instanz relativ zum Meeresspiegel. </p> * * @return altitude in meters * @since 3.34/4.29 */ public int getAltitude() { return this.altitude; } /** * <p>Obtains the name of the underlying calculator. </p> * * @return String * @since 3.34/4.29 */ /*[deutsch] * <p>Liefert den Namen der zugrundeliegenden Berechnungsmethode. </p> * * @return String * @since 3.34/4.29 */ public Calculator getCalculator() { return CALCULATORS.get(this.calculator); } /** * <p>Calculates the moment of sunrise at the location of this instance. </p> * * <p>Example: </p> * * <pre> * SolarTime hamburg = SolarTime.ofLocation(53.55, 10.0); * Optional&lt;Moment&gt; result = PlainDate.nowInSystemTime().get(hamburg.sunrise()); * System.out.println(result.get().toZonalTimestamp(() -&gt; &quot;Europe/Berlin&quot;)); * </pre> * * <p>Note: The precision is generally constrained to minutes. </p> * * @return sunrise function applicable on any calendar date * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet den Moment des Sonnenaufgangs an der Position dieser Instanz. </p> * * <p>Beispiel: </p> * * <pre> * SolarTime hamburg = SolarTime.ofLocation(53.55, 10.0); * Optional&lt;Moment&gt; result = PlainDate.nowInSystemTime().get(hamburg.sunrise()); * System.out.println(result.get().toZonalTimestamp(() -&gt; &quot;Europe/Berlin&quot;)); * </pre> * * <p>Hinweis: Die Genauigkeit liegt generell im Minutenbereich. </p> * * @return sunrise function applicable on any calendar date * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, Optional<Moment>> sunrise() { return date -> this.getCalculator().sunrise(date, this.latitude, this.longitude, this.zenithAngle()); } /** * <p>Calculates the time of given twilight at sunrise and the location of this instance. </p> * * <p>Note: The precision is generally constrained to minutes. </p> * * @param twilight relevant definition of twilight * @return twilight function at sunrise applicable on any calendar date * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet die Zeit der angegebenen D&auml;mmerung zum Sonnenaufgang an der Position dieser Instanz. </p> * * <p>Hinweis: Die Genauigkeit liegt generell im Minutenbereich. </p> * * @param twilight relevant definition of twilight * @return twilight function at sunrise applicable on any calendar date * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, Optional<Moment>> sunrise(Twilight twilight) { double effAngle = 90.0 + this.sunAngleOfAltitude() + twilight.getAngle(); return date -> this.getCalculator().sunrise(date, this.latitude, this.longitude, effAngle); } /** * <p>Calculates the local time of sunrise at the location of this instance in given timezone. </p> * * <p>Note: The precision is generally constrained to minutes. It is possible in some rare edge cases * that the calculated clock time is related to the previous day. </p> * * @param tzid the identifier of the timezone the local time of the result refers to * @return sunrise function applicable on any calendar date * @see #sunrise() * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet die lokale Uhrzeit des Sonnenaufgangs an der Position dieser Instanz * in der angegebenen Zeitzone. </p> * * <p>Hinweis: Die Genauigkeit liegt generell im Minutenbereich. Es ist in seltenen F&auml;llen * m&ouml;glich, da&szlig; die ermittelte Uhrzeit zum vorherigen Tag geh&ouml;rt. </p> * * @param tzid the identifier of the timezone the local time of the result refers to * @return sunrise function applicable on any calendar date * @see #sunrise() * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, Optional<PlainTime>> sunrise(TZID tzid) { return date -> { Optional<Moment> m = this.getCalculator().sunrise(date, latitude, longitude, this.zenithAngle()); if (m.isPresent()) { return Optional.of(m.get().toZonalTimestamp(tzid).getWallTime()); } else { return Optional.empty(); } }; } /** * <p>Calculates the moment of sunset at the location of this instance. </p> * * <p>Example: </p> * * <pre> * SolarTime hamburg = SolarTime.ofLocation(53.55, 10.0); * Optional&lt;Moment&gt; result = PlainDate.nowInSystemTime().get(hamburg.sunset()); * System.out.println(result.get().toZonalTimestamp(() -&gt; &quot;Europe/Berlin&quot;)); * </pre> * * <p>Note: The precision is generally constrained to minutes. </p> * * @return sunset function applicable on any calendar date * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet den Moment des Sonnenuntergangs an der Position dieser Instanz. </p> * * <p>Beispiel: </p> * * <pre> * SolarTime hamburg = SolarTime.ofLocation(53.55, 10.0); * Optional&lt;Moment&gt; result = PlainDate.nowInSystemTime().get(hamburg.sunset()); * System.out.println(result.get().toZonalTimestamp(() -&gt; &quot;Europe/Berlin&quot;)); * </pre> * * <p>Hinweis: Die Genauigkeit liegt generell im Minutenbereich. </p> * * @return sunset function applicable on any calendar date * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, Optional<Moment>> sunset() { return date -> this.getCalculator().sunset(date, this.latitude, this.longitude, this.zenithAngle()); } /** * <p>Calculates the time of given twilight at sunset and the location of this instance. </p> * * <p>Note: The precision is generally constrained to minutes. </p> * * @param twilight relevant definition of twilight * @return twilight function at sunset applicable on any calendar date * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet die Zeit der angegebenen D&auml;mmerung zum Sonnenuntergang an der Position dieser Instanz. </p> * * <p>Hinweis: Die Genauigkeit liegt generell im Minutenbereich. </p> * * @param twilight relevant definition of twilight * @return twilight function at sunset applicable on any calendar date * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, Optional<Moment>> sunset(Twilight twilight) { double effAngle = 90.0 + this.sunAngleOfAltitude() + twilight.getAngle(); return date -> this.getCalculator().sunset(date, this.latitude, this.longitude, effAngle); } /** * <p>Calculates the local time of sunset at the location of this instance in given timezone. </p> * * <p>Note: The precision is generally constrained to minutes. It is possible in some rare edge cases * that the calculated clock time is related to the next day. </p> * * @param tzid the identifier of the timezone the local time of the result refers to * @return sunset function applicable on any calendar date * @see #sunset() * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet die lokale Uhrzeit des Sonnenuntergangs an der Position dieser Instanz * in der angegebenen Zeitzone. </p> * * <p>Hinweis: Die Genauigkeit liegt generell im Minutenbereich. Es ist in seltenen F&auml;llen * m&ouml;glich, da&szlig; die ermittelte Uhrzeit zum n&auml;chsten Tag geh&ouml;rt. </p> * * @param tzid the identifier of the timezone the local time of the result refers to * @return sunset function applicable on any calendar date * @see #sunset() * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, Optional<PlainTime>> sunset(TZID tzid) { return date -> { Optional<Moment> m = this.getCalculator().sunset(date, latitude, longitude, this.zenithAngle()); if (m.isPresent()) { return Optional.of(m.get().toZonalTimestamp(tzid).getWallTime()); } else { return Optional.empty(); } }; } /** * <p>Queries a given calendar date for its associated sunshine data. </p> * * @param tzid the identifier of the timezone any local times of the result refer to * @return function for obtaining sunshine data * @since 3.34/4.29 */ /*[deutsch] * <p>Fragt zu einem gegebenen Kalenderdatum die damit verbundenen Sonnenscheindaten ab. </p> * * @param tzid the identifier of the timezone any local times of the result refer to * @return function for obtaining sunshine data * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, Sunshine> sunshine(TZID tzid) { return date -> { PlainDate d = toGregorian(date); Calculator c = this.getCalculator(); double zenith = this.zenithAngle(); Optional<Moment> start = c.sunrise(date, this.latitude, this.longitude, zenith); Optional<Moment> end = c.sunset(date, this.latitude, this.longitude, zenith); boolean absent = false; if (!start.isPresent() && !end.isPresent()) { double elevation = this.getHighestElevationOfSun(d); if (Double.compare(elevation, 90 - zenith) < 0) { absent = true; } } return new Sunshine(d, start, end, tzid, absent); }; } /** * <p>Determines if the sun is invisible all day on a given calendar date. </p> * * @return ChronoCondition * @since 3.34/4.29 */ /*[deutsch] * <p>Ermittelt, ob an einem gegebenen Kalenderdatum Polarnacht herrscht. </p> * * @return ChronoCondition * @since 3.34/4.29 */ public ChronoCondition<CalendarDate> polarNight() { return date -> { if (Double.compare(Math.abs(this.latitude), 66.0) < 0) { return false; } PlainDate d = toGregorian(date); Calculator c = this.getCalculator(); double zenith = this.zenithAngle(); Optional<Moment> start = c.sunrise(date, this.latitude, this.longitude, zenith); Optional<Moment> end = c.sunset(date, this.latitude, this.longitude, zenith); if (start.isPresent() || end.isPresent()) { return false; } double elevation = this.getHighestElevationOfSun(d); return (Double.compare(elevation, 90 - zenith) < 0); }; } /** * <p>Determines if the sun is visible all day on a given calendar date. </p> * * @return ChronoCondition * @since 3.34/4.29 */ /*[deutsch] * <p>Ermittelt, ob an einem gegebenen Kalenderdatum Mitternachtssonne herrscht. </p> * * @return ChronoCondition * @since 3.34/4.29 */ public ChronoCondition<CalendarDate> midnightSun() { return date -> { if (Double.compare(Math.abs(this.latitude), 66.0) < 0) { return false; } PlainDate d = toGregorian(date); Calculator c = this.getCalculator(); double zenith = this.zenithAngle(); Optional<Moment> start = c.sunrise(date, this.latitude, this.longitude, zenith); Optional<Moment> end = c.sunset(date, this.latitude, this.longitude, zenith); if (start.isPresent() || end.isPresent()) { return false; } double elevation = this.getHighestElevationOfSun(d); return (Double.compare(elevation, 90 - zenith) > 0); }; } /** * <p>Calculates the moment of noon at the location of this instance (solar transit). </p> * * <p>Note: The transit time does not tell if the sun is above or below the horizon. </p> * * @return noon function applicable on any calendar date * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet den Moment der h&ouml;chsten Position der Sonne an der Position dieser Instanz. </p> * * <p>Hinweis: Die Transit-Zeit besagt nicht, ob die Sonne &uuml;ber oder unter dem Horizont ist. </p> * * @return noon function applicable on any calendar date * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, Moment> transitAtNoon() { return date -> transitAtNoon(date, this.longitude, this.calculator); } /** * <p>Calculates the local time of noon at the location of this instance in given timezone. </p> * * <p>Note: The transit time does not tell if the sun is above or below the horizon. </p> * * @param tzid the identifier of the timezone the local time of the result refers to * @return noon function applicable on any calendar date * @see #transitAtNoon() * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet die lokale Uhrzeit des Mittags an der Position dieser Instanz * in der angegebenen Zeitzone. </p> * * <p>Hinweis: Die Transit-Zeit besagt nicht, ob die Sonne &uuml;ber oder unter dem Horizont ist. </p> * * @param tzid the identifier of the timezone the local time of the result refers to * @return noon function applicable on any calendar date * @see #transitAtNoon() * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, PlainTime> transitAtNoon(TZID tzid) { return date -> { Moment m = transitAtNoon(date, this.longitude, this.calculator); return m.toZonalTimestamp(tzid).getWallTime(); }; } /** * <p>Calculates the moment of midnight at the location of this instance (lowest position of sun). </p> * * <p>Note: The transit time does not tell if the sun is above or below the horizon. </p> * * @return midnight function applicable on any calendar date * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet den Moment der niedrigsten Position der Sonne an der Position dieser Instanz. </p> * * <p>Hinweis: Die Transit-Zeit besagt nicht, ob die Sonne &uuml;ber oder unter dem Horizont ist. </p> * * @return midnight function applicable on any calendar date * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, Moment> transitAtMidnight() { return date -> transitAtMidnight(date, this.longitude, this.calculator); } /** * <p>Calculates the local time of midnight at the location of this instance in given timezone. </p> * * <p>Note: The transit time does not tell if the sun is above or below the horizon. </p> * * @param tzid the identifier of the timezone the local time of the result refers to * @return midnight function applicable on any calendar date * @see #transitAtMidnight() * @since 3.34/4.29 */ /*[deutsch] * <p>Berechnet die lokale Uhrzeit von Mitternacht an der Position dieser Instanz * in der angegebenen Zeitzone. </p> * * <p>Hinweis: Die Transit-Zeit besagt nicht, ob die Sonne &uuml;ber oder unter dem Horizont ist. </p> * * @param tzid the identifier of the timezone the local time of the result refers to * @return midnight function applicable on any calendar date * @see #transitAtMidnight() * @since 3.34/4.29 */ public ChronoFunction<CalendarDate, PlainTime> transitAtMidnight(TZID tzid) { return date -> { Moment m = transitAtMidnight(date, this.longitude, this.calculator); return m.toZonalTimestamp(tzid).getWallTime(); }; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof SolarTime){ SolarTime that = (SolarTime) obj; return ( this.calculator.equals(that.calculator) && (Double.compare(this.latitude, that.latitude) == 0) && (Double.compare(this.longitude, that.longitude) == 0) && (this.altitude == that.altitude)); } else { return false; } } @Override public int hashCode() { return ( this.calculator.hashCode() + 7 * Double.hashCode(this.latitude) + 31 * Double.hashCode(this.longitude) + 37 * this.altitude ); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SolarTime[latitude="); sb.append(this.latitude); sb.append(",longitude="); sb.append(this.longitude); if (this.altitude != 0) { sb.append(",altitude="); sb.append(this.altitude); } if (!this.calculator.equals(DEFAULT_CALCULATOR.name())) { sb.append(",calculator="); sb.append(this.calculator); } sb.append(']'); return sb.toString(); } /** * <p>Determines the apparent solar time of any moment at given local time zone offset. </p> * * <p>Based on the astronomical equation of time. The default calculator is usually * {@link Calculator#NOAA} unless another calculator was set up via the service loader mechnism. </p> * * @param offset the time zone offset which might depend on the geographical longitude * @return function for getting the apparent solar time * @see ZonalOffset#atLongitude(OffsetSign, int, int, double) * @see #equationOfTime(Moment) */ /*[deutsch] * <p>Ermittelt die wahre Ortszeit zur angegebenen lokalen Zeitzonendifferenz. </p> * * <p>Basiert auf der astronomischen Zeitgleichung. Die Standardberechnungsmethode ist * gew&ouml;hnlich {@link Calculator#NOAA}, es sei denn, eine andere Methode wurde * &uuml;ber den {@code ServiceLoader}-Mechanismus geladen. </p> * * @param offset the time zone offset which might depend on the geographical longitude * @return function for getting the apparent solar time * @see ZonalOffset#atLongitude(OffsetSign, int, int, double) * @see #equationOfTime(Moment) */ public static ChronoFunction<Moment, PlainTimestamp> apparentAt(ZonalOffset offset) { return context -> { PlainTimestamp meanSolarTime = onAverage(context, offset); double eot = equationOfTime(context); long secs = (long) Math.floor(eot); int nanos = (int) ((eot - secs) * 1_000_000_000); return meanSolarTime.plus(secs, ClockUnit.SECONDS).plus(nanos, ClockUnit.NANOS); }; } /** * <p>Determines the apparent solar time of any moment at given local time zone offset. </p> * * <p>Based on the astronomical equation of time. </p> * * @param offset the time zone offset which might depend on the geographical longitude * @param calculator name of solar time calculator * @return function for getting the apparent solar time * @see ZonalOffset#atLongitude(OffsetSign, int, int, double) * @see #equationOfTime(Moment, String) * @see Calculator#NOAA * @see Calculator#SIMPLE * @since 3.34/4.29 */ /*[deutsch] * <p>Ermittelt die wahre Ortszeit zur angegebenen lokalen Zeitzonendifferenz. </p> * * <p>Basiert auf der astronomischen Zeitgleichung. </p> * * @param offset the time zone offset which might depend on the geographical longitude * @param calculator name of solar time calculator * @return function for getting the apparent solar time * @see ZonalOffset#atLongitude(OffsetSign, int, int, double) * @see #equationOfTime(Moment, String) * @see Calculator#NOAA * @see Calculator#SIMPLE * @since 3.34/4.29 */ public static ChronoFunction<Moment, PlainTimestamp> apparentAt( ZonalOffset offset, String calculator ) { return context -> { PlainTimestamp meanSolarTime = onAverage(context, offset); double eot = equationOfTime(context, calculator); long secs = (long) Math.floor(eot); int nanos = (int) ((eot - secs) * 1_000_000_000); return meanSolarTime.plus(secs, ClockUnit.SECONDS).plus(nanos, ClockUnit.NANOS); }; } /** * <p>Determines the mean solar time of any moment at given local time zone offset. </p> * * @param offset the time zone offset which might depend on the geographical longitude * @return function for getting the mean solar time * @see ZonalOffset#atLongitude(OffsetSign, int, int, double) */ /*[deutsch] * <p>Ermittelt die mittlere Ortszeit zur angegebenen lokalen Zeitzonendifferenz. </p> * * @param offset the time zone offset which might depend on the geographical longitude * @return function for getting the mean solar time * @see ZonalOffset#atLongitude(OffsetSign, int, int, double) */ public static ChronoFunction<Moment, PlainTimestamp> onAverage(ZonalOffset offset) { return context -> onAverage(context, offset); } public static double equationOfTime(Moment moment) { double jde = JulianDay.getValue(moment, TimeScale.TT); return DEFAULT_CALCULATOR.equationOfTime(jde); } public static double equationOfTime( Moment moment, String calculator ) { if (calculator == null) { throw new NullPointerException("Missing calculator parameter."); } else if (CALCULATORS.containsKey(calculator)) { double jde = JulianDay.getValue(moment, TimeScale.TT); return CALCULATORS.get(calculator).equationOfTime(jde); } else { throw new IllegalArgumentException("Unknown calculator: " + calculator); } } // used in test classes double getHighestElevationOfSun(PlainDate date) { Moment noon = date.get(this.transitAtNoon()); double jde = JulianDay.getValue(noon, TimeScale.TT); double decInRad = Math.toRadians(this.getCalculator().declination(jde)); double latInRad = Math.toRadians(this.latitude); double sinElevation = // Extra term left out => Math.cos(Math.toRadians(trueNoon)) := 1.0 (per definition) Math.sin(latInRad) * Math.sin(decInRad) + Math.cos(latInRad) * Math.cos(decInRad); // Meeus (13.6) return Math.toDegrees(Math.asin(sinElevation)); } private static PlainTimestamp onAverage(Moment context, ZonalOffset offset) { Moment ut = Moment.of( context.getElapsedTime(TimeScale.UT) + 2 * 365 * 86400, context.getNanosecond(TimeScale.UT), TimeScale.POSIX); return ut.toZonalTimestamp(offset); } private static Moment transitAtNoon( CalendarDate date, double longitude, String calculator ) { Moment utc = fromLocalEvent(date, 12, longitude, calculator); return utc.with(Moment.PRECISION, calculator.equals(Calculator.SIMPLE) ? TimeUnit.MINUTES : TimeUnit.SECONDS); } private static Moment transitAtMidnight( CalendarDate date, double longitude, String calculator ) { Moment utc = fromLocalEvent(date, 0, longitude, calculator); return utc.with(Moment.PRECISION, calculator.equals(Calculator.SIMPLE) ? TimeUnit.MINUTES : TimeUnit.SECONDS); } private static Moment fromLocalEvent( CalendarDate date, int hourOfEvent, double longitude, String calculator ) { // numerical approximation of equation-of-time in two steps Calculator c = CALCULATORS.get(calculator); double elapsed = date.getDaysSinceEpochUTC() * 86400 + hourOfEvent * 3600 - longitude * 240; long secs = (long) Math.floor(elapsed); int nanos = (int) ((elapsed - secs) * 1_000_000_000); Moment m1 = Moment.of(secs, nanos, TimeScale.UT); double eot = c.equationOfTime(JulianDay.getValue(m1, TimeScale.TT)); // first step secs = (long) Math.floor(eot); nanos = (int) ((eot - secs) * 1_000_000_000); Moment m2 = m1.minus(secs, TimeUnit.SECONDS).minus(nanos, TimeUnit.NANOSECONDS); eot = c.equationOfTime(JulianDay.getValue(m2, TimeScale.TT)); // second step secs = (long) Math.floor(eot); nanos = (int) ((eot - secs) * 1_000_000_000); return m1.minus(secs, TimeUnit.SECONDS).minus(nanos, TimeUnit.NANOSECONDS); } private static PlainDate toGregorian(CalendarDate date) { if (date instanceof PlainDate) { return (PlainDate) date; } else { return PlainDate.of(date.getDaysSinceEpochUTC(), EpochDays.UTC); } } private double earthRadius() { // curvature radius of earth rotation ellipsoid in the prime vertical (east-west), see also: // https://en.wikipedia.org/wiki/Earth_radius#Radii_of_curvature double lat = Math.toRadians(this.latitude); double r1 = EQUATORIAL_RADIUS * Math.cos(lat); double r2 = POLAR_RADIUS * Math.sin(lat); return EQUATORIAL_RADIUS * EQUATORIAL_RADIUS / Math.sqrt(r1 * r1 + r2 * r2); } private double sunAngleOfAltitude() { if (this.altitude == 0) { return 0.0; } double r = this.earthRadius(); return Math.toDegrees(Math.acos(r / (r + this.altitude))); } private double zenithAngle() { return STD_ZENITH + this.sunAngleOfAltitude(); } private static void check( double latitude, double longitude, double elevation, String calculator ) { if ((Double.compare(latitude, 90.0) > 0) || (Double.compare(latitude, -90.0) < 0)) { throw new IllegalArgumentException("Degrees out of range -90.0 <= latitude <= +90.0: " + latitude); } else if ((Double.compare(longitude, 180.0) >= 0) || (Double.compare(longitude, -180.0) < 0)) { throw new IllegalArgumentException("Degrees out of range -180.0 <= longitude < +180.0: " + longitude); } else if ((elevation < -1000) || (elevation > 9999)) { throw new IllegalArgumentException("Meters out of range -1000 <= elevation < +10,000: " + elevation); } else if (calculator == null) { throw new NullPointerException("Missing calculator."); } else if (!CALCULATORS.containsKey(calculator)) { throw new IllegalArgumentException("Unknown calculator: " + calculator); } } private void readObject(ObjectInputStream in) throws IOException { check(this.latitude, this.longitude, this.altitude, this.calculator); } /** * <p>An SPI-interface representing a facade for the calculation engine regarding sunrise or sunset. </p> * * @see java.util.ServiceLoader * @since 3.34/4.29 * @doctags.spec All implementations must have a public no-arg constructor. */ /*[deutsch] * <p>Ein SPI-Interface, das eine Fassade f&uuml;r die Berechnung von Sonnenaufgang oder Sonnenuntergang * darstellt. </p> * * @see java.util.ServiceLoader * @since 3.34/4.29 * @doctags.spec All implementations must have a public no-arg constructor. */ public interface Calculator { String NOAA = "NOAA"; String SIMPLE = "SIMPLE"; /** * <p>Obtains the name of the calculation method. </p> * * @return String */ /*[deutsch] * <p>Liefert den Namen der Berechnungsmethode. </p> * * @return String */ String name(); Optional<Moment> sunrise( CalendarDate date, double latitude, double longitude, double zenith ); Optional<Moment> sunset( CalendarDate date, double latitude, double longitude, double zenith ); /** * <p>Calculates the difference between true and mean solar time. </p> * * @param jde julian day in ephemeris time * @return value in seconds */ /*[deutsch] * <p>Berechnet die Differenz zwischen wahrer und mittlerer Ortszeit. </p> * * @param jde julian day in ephemeris time * @return value in seconds */ double equationOfTime(double jde); /** * <p>Determines the declination of sun. </p> * * @param jde julian day in ephemeris time * @return declination of sun in degrees */ /*[deutsch] * <p>Bestimmt die Deklination der Sonne. </p> * * @param jde julian day in ephemeris time * @return declination of sun in degrees */ double declination(double jde); } /** * <p>Collects various data around sunrise and sunset. </p> * * @author Meno Hochschild * @since 3.34/4.29 */ /*[deutsch] * <p>Sammelt verschiedene Daten um Sonnenauf- oder Sonnenuntergang herum. </p> * * @author Meno Hochschild * @since 3.34/4.29 */ public static class Sunshine { private final Moment startUTC; private final Moment endUTC; private final PlainTimestamp startLocal; private final PlainTimestamp endLocal; private Sunshine( PlainDate date, Optional<Moment> start, Optional<Moment> end, TZID tzid, boolean absent ) { super(); if (absent) { // polar night this.startUTC = null; this.endUTC = null; this.startLocal = null; this.endLocal = null; } else if (start.isPresent()) { this.startUTC = start.get(); this.startLocal = this.startUTC.toZonalTimestamp(tzid); if (end.isPresent()) { // standard use-case this.endUTC = end.get(); this.endLocal = this.endUTC.toZonalTimestamp(tzid); } else { PlainDate next = date.plus(1, CalendarUnit.DAYS); this.endUTC = next.atFirstMoment(tzid); this.endLocal = next.atStartOfDay(tzid); } } else if (end.isPresent()) { this.startUTC = date.atFirstMoment(tzid); this.startLocal = date.atStartOfDay(tzid); this.endUTC = end.get(); this.endLocal = this.endUTC.toZonalTimestamp(tzid); } else { // midnight sun this.startUTC = date.atFirstMoment(tzid); this.startLocal = date.atStartOfDay(tzid); PlainDate next = date.plus(1, CalendarUnit.DAYS); this.endUTC = next.atFirstMoment(tzid); this.endLocal = next.atStartOfDay(tzid); } } public Moment startUTC() { return checkAndGet(this.startUTC); } public Moment endUTC() { return checkAndGet(this.endUTC); } public PlainTimestamp startLocal() { return checkAndGet(this.startLocal); } public PlainTimestamp endLocal() { return checkAndGet(this.endLocal); } /** * <p>Is there any sunshine at given moment? </p> * * @param moment the instant to be queried * @return boolean */ /*[deutsch] * <p>Scheint zum angegebenen Moment die Sonne? </p> * * @param moment the instant to be queried * @return boolean */ public boolean isPresent(Moment moment) { if (this.isAbsent()) { return false; } return (!this.startUTC.isAfter(moment) && moment.isBefore(this.endUTC)); } /** * <p>Is there any sunshine at given local timestamp? </p> * * @param tsp the local timestamp to be queried * @return boolean */ /*[deutsch] * <p>Scheint zur angegebenen lokalen Zeit die Sonne? </p> * * @param tsp the local timestamp to be queried * @return boolean */ public boolean isPresent(PlainTimestamp tsp) { if (this.isAbsent()) { return false; } return (!this.startLocal.isAfter(tsp) && tsp.isBefore(this.endLocal)); } /** * <p>Checks if any sunshine is unavailable (polar night). </p> * * @return {@code true} if this instance corresponds to a polar night else {@code false} */ /*[deutsch] * <p>Pr&uuml;ft, ob gar kein Sonnenschein vorhanden ist (Polarnacht). </p> * * @return {@code true} if this instance corresponds to a polar night else {@code false} */ public boolean isAbsent() { return (this.startUTC == null); // sufficient, see constructor } /** * <p>Obtains the length of sunshine in seconds. </p> * * @return physical length of sunshine in seconds (without leap seconds) * @see TimeUnit#SECONDS */ /*[deutsch] * <p>Liefert die Sonnenscheindauer in Sekunden. </p> * * @return physical length of sunshine in seconds (without leap seconds) * @see TimeUnit#SECONDS */ public int length() { if (this.isAbsent()) { return 0; } return (int) this.startUTC.until(this.endUTC, TimeUnit.SECONDS); // safe cast } /** * <p>For debugging purposes. </p> * * @return String */ /*[deutsch] * <p>F&uuml;r Debugging-Zwecke. </p> * * @return String */ @Override public String toString() { if (this.isAbsent()) { return "Polar night"; } StringBuilder sb = new StringBuilder(128); sb.append("Sunshine["); sb.append("utc="); sb.append(this.startUTC); sb.append('/'); sb.append(this.endUTC); sb.append(",local="); sb.append(this.startLocal); sb.append('/'); sb.append(this.endLocal); sb.append(",length="); sb.append(this.length()); sb.append(']'); return sb.toString(); } private static <T> T checkAndGet(T value) { if (value == null) { throw new IllegalStateException("Sunshine is absent (polar night)."); } else { return value; } } } private static enum StdCalculator implements Calculator { SIMPLE { @Override public Optional<Moment> sunrise(CalendarDate date, double latitude, double longitude, double zenith) { return event(date, latitude, longitude, zenith, true); } @Override public Optional<Moment> sunset(CalendarDate date, double latitude, double longitude, double zenith) { return event(date, latitude, longitude, zenith, false); } @Override public double equationOfTime(double jde) { // => page B8, formula 1 (precision about 0.8 minutes) double t = time0(jde); return ( -7.66 * Math.sin(Math.toRadians(0.9856 * t - 3.8)) - 9.78 * Math.sin(Math.toRadians(1.9712 * t + 17.96)) ) * 60; } @Override public double declination(double jde) { double t0 = time0(jde); double L = trueLongitudeOfSunInDegrees(t0); double sinDec = 0.39782 * Math.sin(Math.toRadians(L)); return Math.toDegrees(Math.asin(sinDec)); } private double time0(double jde) { PlainTimestamp tsp = JulianDay.ofEphemerisTime(jde).toMoment().toZonalTimestamp(ZonalOffset.UTC); return tsp.getCalendarDate().getDayOfYear() + tsp.getWallTime().get(PlainTime.SECOND_OF_DAY) / 86400.0; } private double trueLongitudeOfSunInDegrees(double t0) { double M = // mean anomaly of sun in degrees (0.9856 * t0) - 3.289; double L = M + (1.916 * Math.sin(Math.toRadians(M))) + (0.020 * Math.sin(2 * Math.toRadians(M))) + 282.634; return adjustRange(L); } private Optional<Moment> event( CalendarDate date, double latitude, double longitude, double zenith, boolean sunrise ) { // => page B5/B6/B7 PlainDate d = toGregorian(date); int doy = d.getDayOfYear(); double lngHour = longitude / 15; double t0 = doy + (((sunrise ? 6 : 18) - lngHour) / 24); double L = trueLongitudeOfSunInDegrees(t0); double RA = // right ascension of sun in degrees Math.toDegrees(Math.atan(0.91764 * Math.tan(Math.toRadians(L)))); RA = adjustRange(RA); double Lquadrant = Math.floor(L / 90) * 90; double RAquadrant = Math.floor(RA / 90) * 90; RA = (RA + (Lquadrant - RAquadrant)) / 15; // RA in same quadrant as L double sinDec = 0.39782 * Math.sin(Math.toRadians(L)); double cosDec = Math.cos(Math.asin(sinDec)); double latInRad = Math.toRadians(latitude); double cosH = // local hour angle of sun (Math.cos(Math.toRadians(zenith)) - (sinDec * Math.sin(latInRad))) / (cosDec * Math.cos(latInRad)); if ((Double.compare(cosH, 1.0) > 0) || (Double.compare(cosH, -1.0) < 0)) { // the sun never rises or sets on this location (on the specified date) return Optional.empty(); } double H = Math.toDegrees(Math.acos(cosH)); if (sunrise) { H = 360 - H; } H = H / 15; double lmt = H + RA - (0.06571 * t0) - 6.622; if (Double.compare(0.0, lmt) > 0) { lmt += 24; } else if (Double.compare(24.0, lmt) <= 0) { lmt -= 24; } double ut = lmt - lngHour; int tod = (int) Math.floor(ut * 3600); long secs = d.get(EpochDays.UTC) * 86400 + tod; // we truncate/neglect the fractional seconds here and round to full minutes Moment utc = Moment.of(Math.round(secs / 60.0) * 60, TimeScale.UT); return Optional.of(utc.with(Moment.PRECISION, TimeUnit.MINUTES)); } private double adjustRange(double value) { // range [0.0, 360.0) while (Double.compare(0.0, value) > 0) { value += 360; } while (Double.compare(value, 360.0) >= 0) { value -= 360; } return value; } }, NOAA() { @Override public Optional<Moment> sunrise(CalendarDate date, double latitude, double longitude, double zenith) { return this.event(true, date, latitude, longitude, zenith); } @Override public Optional<Moment> sunset(CalendarDate date, double latitude, double longitude, double zenith) { return this.event(false, date, latitude, longitude, zenith); } // Meeus p.185 (lower accuracy model), returns units of second @Override public double equationOfTime(double jde) { double jct = (jde - 2451545.0) / 36525; // julian centuries (J2000) double tanEpsilonHalf = Math.tan(Math.toRadians(obliquity(jct) / 2)); double y = tanEpsilonHalf * tanEpsilonHalf; double l2Rad = Math.toRadians(2 * meanLongitude(jct)); double e = excentricity(jct); double mRad = Math.toRadians(meanAnomaly(jct)); double sinM = Math.sin(mRad); double eot = y * Math.sin(l2Rad) - 2 * e * sinM + 4 * e * y * sinM * Math.cos(l2Rad) - y * y * Math.sin(2 * l2Rad) / 2 - 5 * e * e * Math.sin(2 * mRad) / 4; return Math.toDegrees(eot) * 240; } @Override public double declination(double jde) { double jct = (jde - 2451545.0) / 36525; return Math.toDegrees(declinationRad(jct)); } private Optional<Moment> event( boolean rise, CalendarDate date, double latitude, double longitude, double zenith ) { Moment m = fromLocalEvent(date, 12, longitude, this.name()); // noon double jde = JulianDay.getValue(m, TimeScale.TT); double H = localHourAngle(rise, jde, latitude, zenith); if (Double.isNaN(H)) { return Optional.empty(); } else { H = localHourAngle(rise, jde + H / 86400, latitude, zenith); // corrected for local time of day if (Double.isNaN(H)) { return Optional.empty(); } else { long secs = (long) Math.floor(H); int nanos = (int) ((H - secs) * 1_000_000_000); Moment utc = m.plus(secs, TimeUnit.SECONDS).plus(nanos, TimeUnit.NANOSECONDS); return Optional.of(utc.with(Moment.PRECISION, TimeUnit.SECONDS)); } } } private double localHourAngle(boolean rise, double jde, double latitude, double zenith) { double jct = (jde - 2451545.0) / 36525; // julian centuries (J2000) double H = localHourAngle(jct, latitude, zenith); if (Double.isNaN(H)) { return Double.NaN; } else { if (rise) { H = -H; } return H; } } // Meeus (22.2), in degrees private double obliquity(double jct) { double obliquity = 23.0 + 26.0 / 60 + (21.448 + (-46.815 + (-0.00059 + 0.001813 * jct) * jct) * jct) / 3600; double corr = 0.00256 * Math.cos(Math.toRadians(125.04 - 1934.136 * jct)); // Meeus (25.8) return obliquity + corr; } // Meeus (25.2), in degrees private double meanLongitude(double jct) { return (280.46646 + (36000.76983 + 0.0003032 * jct) * jct) % 360; } // Meeus (25.3), in degrees private double meanAnomaly(double jct) { return 357.52911 + (35999.05029 - 0.0001537 * jct) * jct; } // Meeus (25.4), unit-less private double excentricity(double jct) { return 0.016708634 - (0.000042037 + 0.0000001267 * jct) * jct; } // W2-term in NOAA-Excel-sheet private double localHourAngle( double jct, double latitude, double zenith ) { double latInRad = Math.toRadians(latitude); double decInRad = declinationRad(jct); double cosH = (Math.cos(Math.toRadians(zenith)) - (Math.sin(decInRad) * Math.sin(latInRad))) / (Math.cos(decInRad) * Math.cos(latInRad)); if ((Double.compare(cosH, 1.0) > 0) || (Double.compare(cosH, -1.0) < 0)) { // the sun never rises or sets on this location (on the specified date) return Double.NaN; } return Math.toDegrees(Math.acos(cosH)) * 240; // in decimal seconds } // T2-term in NOAA-Excel-sheet (in radians) private double declinationRad(double jct) { return Math.asin( Math.sin(Math.toRadians(obliquity(jct))) * Math.sin(Math.toRadians(apparentLongitude(jct)))); } // P2-term in NOAA-Excel-sheet private double apparentLongitude(double jct) { return meanLongitude(jct) + equationOfCenter(jct) - 0.00569 - 0.00478 * Math.sin(Math.toRadians(125.04 - 1934.136 * jct)); } // L2-term in NOAA-Excel-sheet private double equationOfCenter(double jct) { double j2 = Math.toRadians(meanAnomaly(jct)); return ( Math.sin(j2) * (1.914602 - (0.004817 + 0.000014 * jct) * jct) + Math.sin(2 * j2) * (0.019993 - 0.000101 * jct) + Math.sin(3 * j2) * 0.000289 ); } } } }
package io.spine.type; import com.google.common.testing.NullPointerTester; import com.google.protobuf.Descriptors; import com.google.protobuf.StringValue; import io.spine.code.java.PackageName; import io.spine.code.java.SimpleClassName; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class ClassNameShould { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void reject_empty_value() { thrown.expect(IllegalArgumentException.class); ClassName.of(""); } @Test public void pass_null_tolerance_check() { Descriptors.Descriptor descriptor = StringValue.getDescriptor(); new NullPointerTester() .setDefault(SimpleClassName.class, SimpleClassName.ofMessage(descriptor)) .setDefault(PackageName.class, PackageName.resolve(descriptor.getFile() .toProto())) .testAllPublicStaticMethods(ClassName.class); } }
package medium; import utils.CommonUtils; /**300. Longest Increasing Subsequence QuestionEditorial Solution My Submissions Total Accepted: 38678 Total Submissions: 108774 Difficulty: Medium Given an unsorted array of integers, find the length of longest increasing subsequence. For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length. Your algorithm should run in O(n2) complexity. Follow up: Could you improve it to O(n log n) time complexity? Credits: Special thanks to @pbrother for adding this problem and creating all test cases.*/ public class LengthIncreasingSubsequence { public static void main(String...strings){ LengthIncreasingSubsequence test = new LengthIncreasingSubsequence(); int[] nums = new int[]{10, 9, 2, 5, 3, 7, 101, 18}; // int[] nums = new int[]{10,9,2,5,3,4}; // int[] nums = new int[]{1,3,6,7,9,4,10,5,6}; // int[] nums = new int[]{18,55,66,2,3,54}; System.out.println(test.lengthOfLIS(nums)); } /**This is the closest I got, passed all normal cases, made it to 22/23 test cases, but got TLE, as I expected, * since this algorithm runs in O(n^3) time. * My idea: compute a 2D tabular: n*n. * * Then miracle happens, I was about to turn to Discuss, before that, I clicked the Show Tags button, it says: * Binary Search, this hints me to take a second look at my code, then I added this line: * if(nums.length-i < max) return max; * then it got AC'ed! * This is the power of pruning! So Cool! * * Also, another key was that let j start from i, not 0, we don't need to initialize the bottom left part to 1, just * leave them as zero, that's fine, since we don't need to touch that part at all! * This also saves time! Cool! * */ public int lengthOfLIS(int[] nums) { if (nums == null || nums.length == 0) return 0; int[][] dp = new int[nums.length][nums.length]; int max = 0; for (int i = 0; i < nums.length; i++) { if(nums.length-i < max) return max; for (int j = i; j < nums.length; j++) { if (nums[j] > nums[i]) { for (int k = j - 1; k >= i; k if (nums[k] < nums[j]) { dp[i][j] = Math.max(dp[i][k] + 1, dp[i][j]); } } } else dp[i][j] = 1; max = Math.max(max, dp[i][j]); } } CommonUtils.printMatrix(dp); return max; } }
package ru.job4j.collections; import java.util.*; public class ConvertList { /** * toList. * @param array * @return list */ public List<Integer> toList(int[][] array) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < array.length; i++) { for (int j =0; j <array[0].length; j++) { list.add(array[i][j]); } } return list; } /** * toArray. * @param list * @param rows * @return arrayInt */ public int[][] toArray(List<Integer> list, int rows) { ArrayList<Integer> arrayList = (ArrayList) list; arrayList.trimToSize(); int size = arrayList.size() <= rows ? 1 : arrayList.size() % rows == 0 ? arrayList.size() / rows : arrayList.size() / rows + 1; int[][] arrayInt = new int[rows][size]; System.out.println(size); Iterator<Integer> iterator = arrayList.iterator(); for (int i = 0; i < rows; i++) { for (int j = 0; j < size; j++) { if (iterator.hasNext()) { arrayInt[i][j] = iterator.next(); } } System.out.println(); } return arrayInt; } /** * convert. * @param list * @return */ public List<Integer> convert (List<int[]> list) { LinkedList<int[]> tempList = (LinkedList) list; List<Integer> allLists = new LinkedList<>(); for (int i = 0; i < tempList.size(); i++ ) { for (int j = 0; j < tempList.get(i).length; j++) { allLists.add(Integer.valueOf(list.get(i)[j])); } } return allLists; } }
package ru.job4j.convertlist; import java.util.List; import java.util.ArrayList; import java.util.Iterator; public class ConvertList { public List<Integer> toList(int[][]array) { List<Integer> list = new ArrayList<Integer>(); for (int[] row:array) { for (int element:row) { list.add(element); } } return list; } public int[][] toArray(List<Integer> list, int rows) { int columns = list.size() / rows; Iterator<Integer> iterator = list.iterator(); if ((list.size() % rows) != 0) { columns++; } int[][] array = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if ((i * columns + j) < list.size()) { array[i][j] = iterator.next(); } else { array[i][j] = 0; } } } return array; } }
package org.chromium.chrome; /** * Contains all of the command line switches that are specific to the chrome/ * portion of Chromium on Android. */ public abstract class ChromeSwitches { // Switches used from Java. Please continue switch style used Chrome where // options-have-hypens and are_not_split_with_underscores. /** Testing: pretend that the switch value is the name of a child account. */ public static final String CHILD_ACCOUNT = "child-account"; /** Mimic a low end device */ public static final String ENABLE_ACCESSIBILITY_TAB_SWITCHER = "enable-accessibility-tab-switcher"; /** Whether fullscreen support is disabled (auto hiding controls, etc...). */ public static final String DISABLE_FULLSCREEN = "disable-fullscreen"; /** Show the undo bar for high end UI devices. */ public static final String ENABLE_HIGH_END_UI_UNDO = "enable-high-end-ui-undo"; /** Enable toolbar swipe to change tabs in document mode */ public static final String ENABLE_TOOLBAR_SWIPE_IN_DOCUMENT_MODE = "enable-toolbar-swipe-in-document-mode"; /** Whether instant is disabled. */ public static final String DISABLE_INSTANT = "disable-instant"; /** Enables StrictMode violation detection. By default this logs violations to logcat. */ public static final String STRICT_MODE = "strict-mode"; /** Don't restore persistent state from saved files on startup. */ public static final String NO_RESTORE_STATE = "no-restore-state"; /** Disable the First Run Experience. */ public static final String DISABLE_FIRST_RUN_EXPERIENCE = "disable-fre"; /** Force the crash dump to be uploaded regardless of preferences. */ public static final String FORCE_CRASH_DUMP_UPLOAD = "force-dump-upload"; /** Enable debug logs for the video casting feature. */ public static final String ENABLE_CAST_DEBUG_LOGS = "enable-cast-debug"; /** Prevent automatic reconnection to current Cast video when Chrome restarts. */ public static final String DISABLE_CAST_RECONNECTION = "disable-cast-reconnection"; /** Whether or not to enable the experimental tablet tab stack. */ public static final String ENABLE_TABLET_TAB_STACK = "enable-tablet-tab-stack"; /** Disables support for playing videos remotely via Android MediaRouter API. */ public static final String DISABLE_CAST = "disable-cast"; /** Never forward URL requests to external intents. */ public static final String DISABLE_EXTERNAL_INTENT_REQUESTS = "disable-external-intent-requests"; /** Disable document mode. */ public static final String DISABLE_DOCUMENT_MODE = "disable-document-mode"; /** Disable Contextual Search. */ public static final String DISABLE_CONTEXTUAL_SEARCH = "disable-contextual-search"; /** Enable Contextual Search. */ public static final String ENABLE_CONTEXTUAL_SEARCH = "enable-contextual-search"; /** Disable Contextual Search first-run flow, for testing. Not exposed to user. */ public static final String DISABLE_CONTEXTUAL_SEARCH_PROMO_FOR_TESTING = "disable-contextual-search-promo-for-testing"; /** Enable Contextual Search for instrumentation testing. Not exposed to user. */ public static final String ENABLE_CONTEXTUAL_SEARCH_FOR_TESTING = "enable-contextual-search-for-testing"; /** * Enable embedded mode so that embedded activity can be launched. */ public static final String ENABLE_EMBEDDED_MODE = "enable-embedded-mode"; // How many thumbnails should we allow in the cache (per tab stack)? public static final String THUMBNAILS = "thumbnails"; // How many "approximated" thumbnails should we allow in the cache // (per tab stack)? These take very low memory but have poor quality. public static final String APPROXIMATION_THUMBNAILS = "approximation-thumbnails"; // Native Switches /** * Sets the max number of render processes to use. * Native switch - content_switches::kRendererProcessLimit. */ public static final String RENDER_PROCESS_LIMIT = "renderer-process-limit"; /** * Enable enhanced bookmarks feature. * Native switch - switches::kEnhancedBookmarksExperiment */ public static final String ENABLE_ENHANCED_BOOKMARKS = "enhanced-bookmarks-experiment"; /** Enable the DOM Distiller. */ public static final String ENABLE_DOM_DISTILLER = "enable-dom-distiller"; /** Enable experimental web-platform features, such as Push Messaging. */ public static final String EXPERIMENTAL_WEB_PLAFTORM_FEATURES = "enable-experimental-web-platform-features"; /** Enable Reader Mode button animation. */ public static final String ENABLE_READER_MODE_BUTTON_ANIMATION = "enable-dom-distiller-button-animation"; /** Enable the native app banners. */ public static final String ENABLE_APP_INSTALL_ALERTS = "enable-app-install-alerts"; /** * Use sandbox Wallet environment for requestAutocomplete. * Native switch - autofill::switches::kWalletServiceUseSandbox. */ public static final String USE_SANDBOX_WALLET_ENVIRONMENT = "wallet-service-use-sandbox"; /** * Change Google base URL. * Native switch - switches::kGoogleBaseURL. */ public static final String GOOGLE_BASE_URL = "google-base-url"; /** * Use fake device for Media Stream to replace actual camera and microphone. * Native switch - switches::kUseFakeDeviceForMediaStream. */ public static final String USE_FAKE_DEVICE_FOR_MEDIA_STREAM = "use-fake-device-for-media-stream"; // Prevent instantiation. private ChromeSwitches() {} }
package pp2016.team13.server.engine; import java.io.IOException; import pp2016.team13.server.map.Labyrinth; import pp2016.team13.shared.*; public class Levelverwaltung { //Level ID public static int levelID; //speichert alle Spieler, inkl. ihrer Eigenschaften; Zugriff ber spielerID static Spieler []spielerListe; //speichert alle Gegner, inkl. ihrer Eigenschaften; Zugriff ber gegnerID static Monster[]gegnerListe; //speichert alle Traenke; Zugriff ueber TrankID static Heiltrank [] trankListe; //Speichert alle Zellen des Levels //Level Inhalt : 0=Wand, 1 = Boden, 2 = Charakter, 3 = Monster, 4 = Trank, 5=Schluessel, 6 = Tuer public static int [][] levelInhalt; //Die Anzahl der Level wird festgelegt public static int anzahlLevel; //Die Groesse der Level wird festgelegt public static int groesse; //Initialisierung des Speicherortes fr alle Level public static int [][][] levelSpeicherort; //Initialisierung der Level als Array public Level [] levelSendePaket; //Koordinaten des Schluessels static int SchluesselX; static int SchluesselY; //Koordinaten der Tuer static int tuerX; static int tuerY; //Konstruktor Levelverwaltung ; Spielwelt public Levelverwaltung(int levelID, int charakterLebenspunkte, int charakterSchaden, int charakterTraenke, int monsterLebenspunkte, int monsterSchaden, int groesse, int anzLevel) throws IOException{ levelSendePaket = new Level[anzLevel]; this.levelID = levelID; anzahlLevel = anzLevel; this.groesse = groesse; levelSpeicherort = new int [anzahlLevel][groesse][groesse]; levelInhalt = new int [groesse][groesse]; //Level anlegen int levelZaehler = 0; //Vom Levelgenerator ankommendes zweidimensionales Integer Array while (levelZaehler < anzahlLevel){ Labyrinth map = new Labyrinth(); levelInhalt = map.map; levelSendePaket [levelZaehler] =new Level(levelZaehler, map.map); for (int i = 0; i<groesse; i++){ for (int j = 0; j<groesse ; j++){ levelSpeicherort[levelZaehler][j][i] = levelInhalt[j][i]; } } levelZaehler++; } for (int i = 0; i<groesse ; i++){ for (int j = 0; j<groesse ; j++){ levelInhalt[j][i] = levelSpeicherort[levelID][j][i]; } System.out.println();; } //Initialisierung der IDs int spielerID = 0; int monsterID = 0; int trankID = 0; //Definierung der Arrays spielerListe = new Spieler[anzahlLevel]; gegnerListe = new Monster [anzahlLevel]; trankListe = new Heiltrank [anzahlLevel]; //Das Level durchsuchen, um for (int i = 0; i<levelInhalt.length ; i++){ for (int j = 0; j<levelInhalt.length ; j++){ if(levelInhalt[j][i]==2){ //Charakter zu finden und die ID zuzuordnen Spieler spieler = new Spieler (spielerID); spieler.setPos(i, j); spielerListe[spielerID] = spieler; spielerID++; levelInhalt[j][i]=1; levelSpeicherort[this.levelID][j][i] = 1; }else if(levelInhalt[j][i] == 3){ //Monster zu finden und ihnen eine ID zuzuordnen ; festlegen, ob Monster Trank trgt boolean trankVorhanden; double zufallszahl = Math.random(); if(zufallszahl<=0.5){ trankVorhanden = true; }else{ trankVorhanden = false; } Monster gegner = new Monster (monsterID, monsterLebenspunkte, monsterSchaden, trankVorhanden, j, i); gegnerListe [monsterID] = gegner; monsterID++; }else if(levelInhalt[j][i] == 4){ //Trnke zu finden und ihnen ihre ID zuzuordnen Heiltrank trank = new Heiltrank (trankID , j , i); trankListe [trankID] = trank; trankID ++; }else if(levelInhalt[j][i] == 5){ //Schluessel zu finden und die Koordinaten zu speichern Schluessel key = new Schluessel(j, i); SchluesselX = j; SchluesselY = i; }else if(levelInhalt[j][i] == 6){ //Tuer zu finden und ihre Koordinaten zu speichern tuerX = j; tuerY = i; } } } } //Getter Methoden die Spieler Liste public static Spieler [] getSpielerListe(){ return spielerListe; } //Getter Methode fr die Gegner Liste public static Monster [] getGegnerListe(){ return gegnerListe; } public static Heiltrank [] getTrankListe(){ return trankListe; } //setter-Methode, um bestimmte Felder im Level zu verndern public static void setLevelInhalt(int levelID, int x, int y, int inhalt, Levelverwaltung spiel){ levelInhalt[x][y] = inhalt; //Wenn es um den Charakter geht ; der inhalt = 2 ist, dann if(inhalt == 2){ boolean gefunden = false; int spielerID = 0; while(!gefunden){ //sucht er nach der SpielerID ; dem Spieler if (spielerListe[spielerID].getXPos() == x && spielerListe[spielerID].getYPos() == y){ //wenn er gefunden wird, dann wird seine neue Position in die Spielerliste bertragen gefunden = true; spiel.spielerListe[spielerID].setXPos(x); spiel.spielerListe[spielerID].setYPos(y); }else{ //wenn der Spieler nicht gefunden wird, so wird der nchste Spieler ausprobiert. //Dies geht solange, bis die ganze Spielerliste durchgegangen wurde if (spielerID < spielerListe.length-1) { spielerID++; }else{ Nachricht Fehlermeldung = new Nachricht (7, "Spieler nicht auffindbar"); gefunden = true; } } } }else if (inhalt == 3){ //Erklaerung fr die Monstersuche ist identisch zur Erklaerung in der Spielersuche boolean gefunden = false; int gegnerID = 0; while(!gefunden){ if (spiel.levelInhalt[x][y] != 0 && gegnerListe[gegnerID].getPosX() == x && gegnerListe[gegnerID].getPosY() == y){ gefunden = true; spiel.levelInhalt[gegnerListe[gegnerID].getPosX()][gegnerListe[gegnerID].getPosY()] = 1; spiel.gegnerListe[gegnerID].setPosX(x); spiel.gegnerListe[gegnerID].setPosY(y); }else{ if (gegnerID < gegnerListe.length-1) { gegnerID++; }else{ Nachricht Fehlermeldung = new Nachricht (7, "Monster nicht auffindbar"); gefunden = true; } } } }else if (inhalt == 4){ //Tranksuche identisch zur Monster- und Spielersuche boolean gefunden = false; int trankID = 0; while(!gefunden){ if (trankListe[trankID].getPosX() == x && trankListe[trankID].getPosY() == y){ gefunden = true; trankListe[trankID].setPosX(x); trankListe[trankID].setPosY(y); trankListe[trankID].aufgehoben = false; }else{ if (trankID < trankListe.length-1) { trankID++; }else{ Nachricht Fehlermeldung = new Nachricht (7, "Trank nicht auffindbar"); gefunden = true; } } } } } //ueberprueft, ob der Spieler mit der SpielerID einen Trank benutzen kann //wird ueberprueft, indem die Anzahl der Traenke ueberprueft wird public static boolean trankBenutzbar(int spielerID){ boolean funktioniert; if (spielerListe[spielerID].getAnzahlHeiltraenke()>0){ funktioniert = true; }else { funktioniert = false; } return funktioniert; } //void Methode, um einen Trank zu benutzen. Hierbei werden die Lebenspunkte des Spielers wieder aufgefllt public static void benutzeTrank(int spielerID){ if (trankBenutzbar(spielerID)){ spielerListe[spielerID].setAnzahlHeiltraenke(spielerListe[spielerID].getAnzahlHeiltraenke()-1); spielerListe[spielerID].setLebenspunkte(10); } } //Einordnung der Nachrichten. Je nachdem welche Art von Nachricht ankommt, so wird sie zum jeweiligen Nachrichten Behandler weiter geleitet. //Dieser gibt dann einen Boolean zurck. Je nachdem wird eine bestimmte Aussage ausgegeben public static void verarbeiteNachricht(Nachricht Nachricht, Levelverwaltung spiel){ if (Nachricht.typ == 1){ if (spiel.behandleSpielerbewegung(Nachricht, spiel)){ System.out.println("Spieler darf bewegt werden. Neue Position: " + spiel.spielerListe[Nachricht.getID()].getXPos() + " " + spiel.spielerListe[Nachricht.getID()].getYPos()); }else{ Nachricht Fehlermeldung = new Nachricht (7, "Spieler zu weit vom Feld entfernt, oder Wand im Weg. Bewegung nicht mglich"); System.out.println("Spieler darf nicht bewegt werden"); } }else if (Nachricht.typ == 2){ System.out.println(spiel.spielerListe[Nachricht.getID()].getAnzahlHeiltraenke()); if(spiel.behandleTrankaufnahme(Nachricht, spiel)){ System.out.println("Spieler beim Trank"); System.out.println(spiel.spielerListe[Nachricht.getID()].getAnzahlHeiltraenke()); }else{ System.out.println("Spieler nicht beim Trank"); System.out.println(spiel.spielerListe[Nachricht.getID()].getAnzahlHeiltraenke()); } }else if (Nachricht.typ == 3){ if(spiel.behandleLevelGeschafft(Nachricht.getID(), spiel)){ System.out.println("Nchstes Level"); }else{ System.out.println("Level konnte nicht beendet werden"); Nachricht Fehlermeldung = new Nachricht (7, "level nicht beendet"); } }else if (Nachricht.typ == 4){ if(spiel.behandleschluesselaufgehoben(Nachricht.getID(), spiel)){ System.out.println("Schlssel aufgehoben"); }else{ System.out.println("Schlssel nicht aufgehoben"); Nachricht Fehlermeldung = new Nachricht (7, "Schlssel nicht bei Spieler"); } }else if (Nachricht.typ == 5){ Chat.nachrichtEmpfanden(Nachricht.getNachricht()); }else if (Nachricht.typ == 7){ if(spiel.behandleLevelUebersprungen(spiel)){ System.out.println("Level bersprungen"); }else{ System.out.println("Level konnte nicht bersprungen werden"); } } } //Behandelt die Nachrichten, die eine Spielerbewegung beinhalten. //Zunchst wird ueberprueft, ob der Spieler an diese Position gehen darf. //danach wird seine Position gendert public static boolean behandleSpielerbewegung(Nachricht Spielerbewegung, Levelverwaltung spiel){ boolean moeglich; if (spiel.levelInhalt[Spielerbewegung.getxKoo()][Spielerbewegung.getyKoo()] != 0 &&spiel.levelInhalt[Spielerbewegung.getxKoo()][Spielerbewegung.getyKoo()] != 3 && ((Spielerbewegung.getxKoo() == spiel.spielerListe[Spielerbewegung.getID()].getXPos() && (Spielerbewegung.getyKoo() == spiel.spielerListe[Spielerbewegung.getID()].getYPos() +1 || Spielerbewegung.getyKoo() == spiel.spielerListe[Spielerbewegung.getID()].getYPos() -1)) || (Spielerbewegung.getyKoo() == spiel.spielerListe[Spielerbewegung.getID()].getYPos() && (Spielerbewegung.getxKoo() == spiel.spielerListe[Spielerbewegung.getID()].getXPos() +1 || Spielerbewegung.getxKoo() == spiel.spielerListe[Spielerbewegung.getID()].getXPos() -1)))){ spiel.setLevelInhalt(0, Spielerbewegung.getxKoo(), Spielerbewegung.getyKoo(), 2, spiel); moeglich = true; }else { moeglich = false; } return moeglich; } //Nachrichten Behandler fr die Aufnhame eines Trankes //zunchst wird ueberprueft, ob der Trank aufgenommen werden darf //danach wird er zum Inventar hinzugefuegt public static boolean behandleTrankaufnahme(Nachricht trankAufnahme, Levelverwaltung spiel) { boolean moeglich; if (!(spiel.trankListe[trankAufnahme.getTrankID()].aufgehoben) && spiel.trankListe[trankAufnahme.getTrankID()].getPosX() == spiel.spielerListe[trankAufnahme.getID()].getXPos() && spiel.trankListe[trankAufnahme.getTrankID()].getPosY() == spiel.spielerListe[trankAufnahme.getID()].getYPos()){ spiel.trankListe[0].aufgehoben = true; spiel.spielerListe[trankAufnahme.getID()].setAnzahlHeiltraenke(spiel.spielerListe[trankAufnahme.getID()].getAnzahlHeiltraenke()+1); moeglich = true; }else{ System.out.println(spiel.trankListe[trankAufnahme.getTrankID()].getPosX() + " "+ spiel.trankListe[trankAufnahme.getTrankID()].getPosY()); System.out.println(spiel.spielerListe[trankAufnahme.getID()].getXPos() + " " + spiel.spielerListe[trankAufnahme.getID()].getYPos()); moeglich = false; } return moeglich; } //Nachrichten Behandler fuer das beendete Level //zunaechst Ueberpruefung, ob der Schluessel aufgehoben wurde und ob der Spieler bei der Tuer ist //danach wird true zurueck gegeben und das naechste Level kann gestartet werden. public static boolean behandleLevelGeschafft(int spielerID, Levelverwaltung spiel) { boolean moeglich; if(spiel.spielerListe[spielerID].hatSchluessel() && spiel.spielerListe[spielerID].getXPos() == tuerX && spiel.spielerListe[spielerID].getYPos() == tuerY){ //Level wechseln -- wenn Levelgenerator da ist. Mglichkeit besteht, siehe Test moeglich= true; levelID++; for (int i = 0; i<groesse ; i++){ for (int j = 0; j<groesse ; j++){ levelInhalt[j][i] = levelSpeicherort[levelID][j][i]; } } }else{ moeglich= false; } return moeglich; } //Nachrichtenbehandler fuer einen aufgehobenen Schluessel //zunaechst wird ueberprueft, ob er aufgehoben werden kann //anschlieend wird der schluesselstatus auf wahr gesetzt public static boolean behandleschluesselaufgehoben(int id, Levelverwaltung spiel) { boolean moeglich; if(spiel.spielerListe[id].getXPos() == SchluesselX && spiel.spielerListe[id].getYPos() == SchluesselY){ spiel.spielerListe[id].nimmSchluessel(); moeglich = true; }else{ moeglich = false; } return moeglich; } //Nachrichtenbehandler fuer das Uebersprungene Level //Der Spieler wird dafuer auf die Tuer gesetzt und ihm wird der Schluessel uebergeben public static boolean behandleLevelUebersprungen (Levelverwaltung spiel){ spiel.levelInhalt[spiel.spielerListe[0].getXPos()][spiel.spielerListe[0].getYPos()]=1; spiel.levelInhalt[tuerX][tuerY] = 2; spiel.spielerListe[0].setXPos(tuerX); spiel.spielerListe[0].setYPos(tuerY); spiel.spielerListe[0].nimmSchluessel(); behandleLevelGeschafft(0, spiel); return true; } }
package ru.cfuv.ieu.phonebook.model; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PhonebookNumber { public enum Format { USCANADA("1", "+%1 (%2%3%4) %5%6%7-%8%9%A%B"), RUSSIAKZ("7", "+%1 (%2%3%4) %5%6%7-%8%9-%A%B"), UKRAINE("380", "+%1%2%3 (%4%5) %6%7%8-%9%A-%B%C"), BRITAIN("44", "+%1%2 %3%4%5%6 %7%8%9%A%B%C"), GERMANY("49", "+%1%2 %3%4%5%6 %7%8%9%A%B%C"), SINGAPORE("65", "+%1%2 %3%4%5%6 %7%8%9%A"), CHINA("86", "+%1%2 %3%4%5 %6%7%8%9 %A%B%C%D"); Format(String country, String format) { this.country = country; this.format = format; } String country; String format; } private final int id; private String number; public PhonebookNumber(String sNumber) { this(-1, sNumber); } public PhonebookNumber(int id, String sNumber) { this.id = id; this.number = sNumber; } @Override public String toString() { for (Format format : Format.values()) { for (int i = 3; i > 0; i if (number.substring(0, i).equals(format.country)) { String fstring = format.format; String sNumber; sNumber = fstring.replaceAll("%0", number); Pattern pat1 = Pattern.compile("%([1-9A-Fa-f])"); Matcher m = pat1.matcher(fstring); while (m.find()) { char c = m.group(1).charAt(0); String digit = String.valueOf(number.charAt( Character.digit(c, 16)-1)); sNumber = sNumber.replaceFirst("%" + c, digit); } return sNumber; } } } return "+" + number; } public int getId() { return id; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } }
package org.builditbreakit.seada.data; import java.io.Serializable; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Visitor implements Serializable { private static final long serialVersionUID = -2865757182731074012L; private final String name; private final VisitorType visitorType; private final List<ArrivalRecord> history; public Visitor(String name, VisitorType visitorType) { this.name = name; this.visitorType = visitorType; this.history = new LinkedList<>(); } public Location getCurrentLocation() { if(history.isEmpty()) { return Location.OFF_PREMISES; } return history.get(history.size() - 1).getLocation(); } public String getName() { return name; } public VisitorType getVisitorType() { return visitorType; } public List<ArrivalRecord> getHistory() { return Collections.unmodifiableList(history); } void moveTo(long timestamp, Location newLocation) { ValidationUtil.assertValidUINT32(timestamp, "Timestamp"); ValidationUtil.assertNotNull(newLocation, "Location"); assertValidStateTransition(newLocation); history.add(new ArrivalRecord(timestamp, newLocation)); } @Override public int hashCode() { /* Eclipse Generated */ final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { /* Eclipse Generated */ if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Visitor other = (Visitor) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } private void assertValidStateTransition(Location newLocation) { Location currentLocation = getCurrentLocation(); if ((currentLocation.isInRoom() || currentLocation.isOffPremises()) && !newLocation.isInGallery()) { throw new IllegalStateException(getStateTransitionErrorMsg( currentLocation, newLocation)); } if (currentLocation.isInGallery() && newLocation.isInGallery()) { throw new IllegalStateException(getStateTransitionErrorMsg( currentLocation, newLocation)); } } private static String getStateTransitionErrorMsg(Location currentLocation, Location newLocation) { StringBuilder builder = new StringBuilder(80); builder.append("Cannot transition from state ").append(currentLocation) .append(" to state ").append(newLocation); return builder.toString(); } }
package kawa.standard; import kawa.lang.*; import gnu.mapping.*; /** * Implement the Scheme standard function "call-with-current-continuation". * This is a restricted version, that only works for escape-like applications. * @author Per Bothner */ public class callcc extends Procedure1 { /** Call a precedure with the current continuation. */ public static Object apply (Procedure proc) throws Throwable { kawa.lang.Continuation cont = new kawa.lang.Continuation (); try { return proc.apply1 (cont); } catch (CalledContinuation ex) { if (ex.continuation != cont) throw ex; return ex.value; } finally { cont.invoked = true; } } public Object apply1 (Object arg1) throws Throwable { Procedure proc; try { proc = (Procedure) arg1; } catch (ClassCastException ex) { throw new GenericError ("argument to call/cc is not procedure"); } return apply (proc); } /* public void apply (CallContext stack) { kawa.lang.Continuation cont = new Continuation (); cont.frame = stack.proc; cont.pc = stack.pc; stack.value = cont; } */ } /* class Continuation extends MethodProc { Procedure frame; int pc; public void apply (CallContext stack) { Object result = Values.make(stack.args); stack.pc = pc; stack.proc = frame; stack.result = result; } } */
package com.dianping.cat; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import com.dianping.cat.message.spi.core.HtmlMessageCodecTest; import com.dianping.cat.message.spi.core.MessagePathBuilderTest; import com.dianping.cat.message.spi.core.TcpSocketReceiverTest; import com.dianping.cat.message.spi.core.WaterfallMessageCodecTest; import com.dianping.cat.storage.dump.LocalMessageBucketManagerTest; import com.dianping.cat.storage.dump.LocalMessageBucketTest; import com.dianping.cat.storage.report.LocalReportBucketTest; import com.dianping.cat.task.TaskManagerTest; @RunWith(Suite.class) @SuiteClasses({ HtmlMessageCodecTest.class, WaterfallMessageCodecTest.class, /* .storage.dump */ LocalMessageBucketTest.class, LocalMessageBucketManagerTest.class, /* .storage.report */ LocalReportBucketTest.class, /* .task */ TaskManagerTest.class, TcpSocketReceiverTest.class, MessagePathBuilderTest.class }) public class AllTests { }
package org.croudtrip.activities; import android.app.Fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import com.google.android.gms.location.LocationRequest; import org.croudtrip.Constants; import org.croudtrip.R; import org.croudtrip.account.AccountManager; import org.croudtrip.api.account.User; import org.croudtrip.fragments.GcmTestFragment; import org.croudtrip.fragments.JoinTripFragment; import org.croudtrip.fragments.JoinTripRequestsFragment; import org.croudtrip.fragments.JoinTripResultsFragment; import org.croudtrip.fragments.NavigationFragment; import org.croudtrip.fragments.OfferTripFragment; import org.croudtrip.fragments.PickUpPassengerFragment; import org.croudtrip.fragments.ProfileFragment; import org.croudtrip.fragments.SettingsFragment; import org.croudtrip.gcm.GcmManager; import org.croudtrip.location.LocationUpdater; import org.croudtrip.utils.DefaultTransformer; import java.io.InputStream; import java.net.URL; import javax.inject.Inject; import javax.net.ssl.HttpsURLConnection; import it.neokree.materialnavigationdrawer.MaterialNavigationDrawer; import it.neokree.materialnavigationdrawer.elements.MaterialAccount; import it.neokree.materialnavigationdrawer.elements.MaterialSection; import pl.charmas.android.reactivelocation.ReactiveLocationProvider; import rx.Observable; import rx.Subscription; import rx.functions.Action1; import rx.functions.Func0; import rx.subscriptions.CompositeSubscription; import timber.log.Timber; /** * We will probably use fragments, so this activity works as a container for all these fragments and will probably do * some initialization and stuff */ public class MainActivity extends AbstractRoboDrawerActivity { public final static String ACTION_SHOW_JOIN_TRIP_REQUESTS = "SHOW_JOIN_TRIP_REQUESTS"; public final static String ACTION_SHOW_REQUEST_ACCEPTED = "SHOW_REQUEST_ACCEPTED"; public final static String ACTION_SHOW_REQUEST_DECLINED = "SHOW_REQUEST_DECLINED"; public static final String ACTION_SHOW_FOUND_MATCHES = "SHOW_FOUND_MATCHES"; @Inject private GcmManager gcmManager; @Inject private LocationUpdater locationUpdater; private CompositeSubscription subscriptions = new CompositeSubscription(); private Subscription locationUpdateSubscription; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LocalBroadcastManager.getInstance(this).registerReceiver(driverAcceptedReceiver,new IntentFilter(Constants.EVENT_DRIVER_ACCEPTED)); } @Override public void init(Bundle savedInstanceState) { this.disableLearningPattern(); this.allowArrowAnimation(); this.setBackPattern(MaterialNavigationDrawer.BACKPATTERN_BACK_TO_FIRST); this.setDrawerHeaderImage(R.drawable.background_drawer); SharedPreferences prefs = getSharedPreferences(Constants.SHARED_PREF_FILE_PREFERENCES, Context.MODE_PRIVATE); User user = AccountManager.getLoggedInUser(getApplicationContext()); String firstName = (user == null || user.getFirstName() == null) ? "" : user.getFirstName(); String lastName = (user == null || user.getLastName() == null) ? "" : user.getLastName(); String email = (user == null || user.getEmail() == null) ? "" : user.getEmail(); final String avatarUrl = (user == null || user.getAvatarUrl() == null) ? null : user.getAvatarUrl(); final MaterialAccount account = new MaterialAccount(this.getResources(),firstName+ " " + lastName,email,R.drawable.profile, R.drawable.background_drawer); this.addAccount(account); // subscribe to location updates LocationRequest request = LocationRequest.create() //standard GMS LocationRequest .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setNumUpdates(5) .setInterval(100); ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(this); Subscription locationUpdateSubscription = locationProvider.getUpdatedLocation(request) .subscribe(new Action1<Location>() { @Override public void call(Location location) { locationUpdater.setLastLocation( location ); } }); subscriptions.add(locationUpdateSubscription); // create sections //if (prefs.getBoolean(Constants.SHARED_PREF_KEY_SEARCHING, false)) { Intent intent = getIntent(); String action = intent.getAction(); action = action == null ? "" : action; // join trip/my joined trip if ( false || action.equalsIgnoreCase(ACTION_SHOW_REQUEST_DECLINED) || action.equalsIgnoreCase(ACTION_SHOW_FOUND_MATCHES) ) { //TODO: this solution works only if we get some kind of notification from the server if there are (no) results. There //TODO: we have to set "loading" in the sp to false this.addSection(newSection(getString(R.string.menu_my_trip), R.drawable.hitchhiker, new JoinTripResultsFragment())); } if (prefs.getBoolean(Constants.SHARED_PREF_KEY_SEARCHING, false) || prefs.getBoolean(Constants.SHARED_PREF_KEY_ACCEPTED, false)) { this.addSection(newSection(getString(R.string.menu_my_trip), R.drawable.hitchhiker, new JoinTripResultsFragment())); } else { this.addSection(newSection(getString(R.string.menu_join_trip), R.drawable.hitchhiker, new JoinTripFragment())); } // offer trip/ my offered trip if( action.equalsIgnoreCase(ACTION_SHOW_JOIN_TRIP_REQUESTS) ) { this.addSection(newSection("My Trip Requests", R.drawable.distance, new JoinTripRequestsFragment())); } else { this.addSection(newSection(getString(R.string.menu_offer_trip), R.drawable.ic_directions_car_white, new OfferTripFragment())); } // profile if(AccountManager.isUserLoggedIn(this)) { // only logged-in users can view their profile this.addSection(newSection(getString(R.string.menu_profile), R.drawable.profile_icon, new ProfileFragment())); } // TODO: remove navigation tab from drawer this.addSection(newSection(getString(R.string.navigation), R.drawable.distance, new NavigationFragment()) ); // TODO: remove from navigation drawer and call after push notification with REAL data PickUpPassengerFragment fragment = new PickUpPassengerFragment(); Bundle args = new Bundle(); args.putString(PickUpPassengerFragment.KEY_PASSENGER_NAME, "Otto"); args.putDouble(PickUpPassengerFragment.KEY_PASSENGER_LATITUDE, 1234.5); args.putDouble(PickUpPassengerFragment.KEY_PASSENGER_LONGITUDE, 678.9); args.putInt(PickUpPassengerFragment.KEY_PASSENGER_PRICE, 200); fragment.setArguments(args); this.addSection(newSection("Pick up passenger", R.drawable.distance, fragment)); //TODO: remove from drawer this.addSection(newSection("Join Trip - Requests", R.drawable.distance, new JoinTripRequestsFragment())); // create bottom section this.addBottomSection(newSection(getString(R.string.menu_settings), R.drawable.ic_settings, new SettingsFragment())); // test gcm section TODO remove this at some point after the next demo addSection(newSection("GCM Demo", (Bitmap) null, new GcmTestFragment())); //this.addSection(newSection("Vehicle", R.drawable.ic_directions_car_white, new VehicleInfoFragment())); if (!GPSavailable()) { checkForGPS(); } // set the section that should be loaded at the start of the application if( action.equalsIgnoreCase(ACTION_SHOW_REQUEST_DECLINED) || action.equals(ACTION_SHOW_FOUND_MATCHES) ) { this.setDefaultSectionLoaded(0); MaterialSection section = this.getSectionByTitle(getString(R.string.menu_my_trip)); Bundle extras = getIntent().getExtras(); Bundle bundle = new Bundle(); bundle.putAll(extras); Fragment requestFrag = (Fragment) section.getTargetFragment(); requestFrag.setArguments(bundle); } else if( action.equalsIgnoreCase(ACTION_SHOW_JOIN_TRIP_REQUESTS) ) { this.setDefaultSectionLoaded(1); } // do registration for GCM, if we are not registered if( !gcmManager.isRegistered() ) { Subscription subscription = gcmManager.register() .compose(new DefaultTransformer<Void>()) .retry(3) .subscribe( new Action1<Void>() { @Override public void call(Void aVoid) { Timber.d("Registered at GCM."); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.e("Could not register at GCM services: " + throwable.getMessage() ); } }); subscriptions.add(subscription); } // download avatar if (avatarUrl == null) return; Observable .defer(new Func0<Observable<Bitmap>>() { @Override public Observable<Bitmap> call() { try { URL url = new URL(avatarUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); return Observable.just(BitmapFactory.decodeStream(input)); } catch (Exception e) { return Observable.error(e); } } }) .compose(new DefaultTransformer<Bitmap>()) .subscribe(new Action1<Bitmap>() { @Override public void call(Bitmap avatar) { Timber.d("avatar is null " + (avatar == null)); Timber.d("" + avatar.getWidth()); account.setPhoto(avatar); notifyAccountDataChanged(); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.e(throwable, "failed to download avatar"); } }); } @Override public void onPause() { super.onPause(); subscriptions.unsubscribe(); subscriptions.clear(); } @Override public void onStop() { super.onStop(); } @Override protected void onDestroy() { LocalBroadcastManager.getInstance(this).unregisterReceiver(driverAcceptedReceiver); super.onDestroy(); } private BroadcastReceiver driverAcceptedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { getSectionList().get(0).setTarget(new JoinTripResultsFragment()); getSectionList().get(0).setTitle(getString(R.string.menu_my_trip)); setFragment(new JoinTripResultsFragment(), getString(R.string.menu_my_trip)); } }; private boolean GPSavailable() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); } private void checkForGPS() { final SharedPreferences prefs = getSharedPreferences(Constants.SHARED_PREF_FILE_PREFERENCES, Context.MODE_PRIVATE); final SharedPreferences.Editor editor = prefs.edit(); AlertDialog.Builder adb = new AlertDialog.Builder(this); LayoutInflater adbInflater = LayoutInflater.from(this); View dialogLayout = adbInflater.inflate(R.layout.dialog_enable_gps, null); final CheckBox dontShowAgain = (CheckBox) dialogLayout.findViewById(R.id.skip); adb.setView(dialogLayout); adb.setTitle(getResources().getString(R.string.enable_gps_title)); adb.setMessage(getResources().getString(R.string.enable_gps_description)); adb.setPositiveButton(getResources().getString(R.string.enable_gps_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (dontShowAgain.isChecked()) { editor.putBoolean(Constants.SHARED_PREF_KEY_SKIP_ENABLE_GPS, true); editor.apply(); } startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); return; } }); adb.setNegativeButton(getResources().getString(R.string.enable_gps_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { return; } }); boolean skip = prefs.getBoolean(Constants.SHARED_PREF_KEY_SKIP_ENABLE_GPS, false); //if (!skip) { adb.show(); } }
package com.archimatetool.zest; import java.beans.PropertyChangeEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.help.HelpSystem; import org.eclipse.help.IContext; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IActionBars; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.zest.layouts.LayoutStyles; import org.eclipse.zest.layouts.algorithms.SpringLayoutAlgorithm; import com.archimatetool.editor.model.IEditorModelManager; import com.archimatetool.editor.ui.ArchiLabelProvider; import com.archimatetool.editor.ui.IArchiImages; import com.archimatetool.editor.ui.services.ViewManager; import com.archimatetool.editor.utils.StringUtils; import com.archimatetool.editor.views.AbstractModelView; import com.archimatetool.editor.views.tree.ITreeModelView; import com.archimatetool.editor.views.tree.actions.IViewerAction; import com.archimatetool.editor.views.tree.actions.PropertiesAction; import com.archimatetool.model.IArchimateConcept; import com.archimatetool.model.IArchimateModel; import com.archimatetool.model.IArchimateModelObject; import com.archimatetool.model.IArchimatePackage; import com.archimatetool.model.IBounds; import com.archimatetool.model.util.ArchimateModelUtils; import com.archimatetool.model.viewpoints.IViewpoint; import com.archimatetool.model.viewpoints.ViewpointManager; /** * Zest View * * @author Phillip Beauvoir * @author Jean-Baptiste Sarrodie */ public class ZestView extends AbstractModelView implements IZestView, ISelectionListener { private ZestGraphViewer fGraphViewer; private CLabel fLabel; private IAction fActionLayout; private IViewerAction fActionProperties; private IAction fActionPinContent; private IAction fActionCopyImageToClipboard; private IAction fActionExportImageToFile; private IAction fActionSelectInModelTree; // Depth Actions private IAction[] fDepthActions; private List<IAction> fViewpointActions; private List<IAction> fElementActions; private List<IAction> fStrategyElementActions; private List<IAction> fBusinessElementActions; private List<IAction> fApplicationElementActions; private List<IAction> fTechnologyElementActions; private List<IAction> fPhysicalElementActions; private List<IAction> fImplementationMigrationElementActions; private List<IAction> fMotivationElementActions; private List<IAction> fOtherElementActions; private List<IAction> fRelationshipActions; private IAction[] fDirectionActions; private DrillDownManager fDrillDownManager; @Override protected void doCreatePartControl(Composite parent) { GridLayout layout = new GridLayout(); layout.marginHeight = 0; layout.marginWidth = 0; layout.verticalSpacing = 0; parent.setLayout(layout); fLabel = new CLabel(parent, SWT.NONE); fLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fGraphViewer = new ZestGraphViewer(parent, SWT.NONE); fGraphViewer.getGraphControl().setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true)); // spring is the default - we do need to set this here! fGraphViewer.setLayoutAlgorithm(new SpringLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING), true); //fGraphViewer.setLayoutAlgorithm(new TreeLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING), true); //fGraphViewer.setLayoutAlgorithm(new RadialLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING), true); //fGraphViewer.setLayoutAlgorithm(new HorizontalTreeLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING), true); // Graph selection listener fGraphViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { // Update actions updateActions(); // Need to do this in order for Tabbed Properties View to update on Selection getSite().getSelectionProvider().setSelection(event.getSelection()); } }); // Double-click fGraphViewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { fDrillDownManager.goInto(); } }); fDrillDownManager = new DrillDownManager(this); makeActions(); hookContextMenu(); registerGlobalActions(); makeLocalToolBar(); // This will update previous Undo/Redo text if View was closed before updateActions(); // Register selections getSite().setSelectionProvider(getViewer()); // Listen to global selections to update the viewer getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this); // Help PlatformUI.getWorkbench().getHelpSystem().setHelp(fGraphViewer.getControl(), HELP_ID); // Initialise with whatever is selected in the workbench ISelection selection = getSite().getWorkbenchWindow().getSelectionService().getSelection(); selectionChanged(null, selection); } @Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { if(part == this) { return; } if(fActionPinContent.isChecked()) { return; } if(selection instanceof IStructuredSelection && !selection.isEmpty()) { Object object = ((IStructuredSelection)selection).getFirstElement(); setElement(object); } } @Override protected void selectAll() { fGraphViewer.getGraphControl().selectAll(); } private void setElement(Object object) { IArchimateConcept concept = null; if(object instanceof IArchimateConcept) { concept = (IArchimateConcept)object; } else if(object instanceof IAdaptable) { concept = ((IAdaptable)object).getAdapter(IArchimateConcept.class); } fDrillDownManager.setNewInput(concept); updateActions(); updateLabel(); } void refresh() { updateActions(); updateLabel(); getViewer().refresh(); } /** * Update local label */ void updateLabel() { String text = ArchiLabelProvider.INSTANCE.getLabel(fDrillDownManager.getCurrentConcept()); text = StringUtils.escapeAmpersandsInText(text); String viewPointName = getContentProvider().getViewpointFilter().getName(); String elementName = getElementFilterName(getContentProvider().getElementFilter()); String relationshipName = getRelationshipFilterName(getContentProvider().getRelationshipFilter()); fLabel.setText(text + " (" + Messages.ZestView_5 + ": " + viewPointName + ", " + /* Messages.ZestView_9 + ": " */ "Element Filter: " + elementName + ", " + Messages.ZestView_6 + ": " + relationshipName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ fLabel.setImage(ArchiLabelProvider.INSTANCE.getImage(fDrillDownManager.getCurrentConcept())); } /** * Update the Local Actions depending on the selection, and undo/redo actions */ void updateActions() { IStructuredSelection selection = (IStructuredSelection)getViewer().getSelection(); fActionProperties.update(); fActionSelectInModelTree.setEnabled(!selection.isEmpty()); boolean hasData = fGraphViewer.getInput() != null; fActionExportImageToFile.setEnabled(hasData); fActionCopyImageToClipboard.setEnabled(hasData); fActionLayout.setEnabled(hasData); updateUndoActions(); } /** * Populate the ToolBar */ private void makeLocalToolBar() { IActionBars bars = getViewSite().getActionBars(); IToolBarManager manager = bars.getToolBarManager(); fDrillDownManager.addNavigationActions(manager); manager.add(new Separator()); manager.add(fActionPinContent); manager.add(new Separator()); manager.add(fActionLayout); final IMenuManager menuManager = bars.getMenuManager(); IMenuManager depthMenuManager = new MenuManager(Messages.ZestView_3); menuManager.add(depthMenuManager); // Depth Actions fDepthActions = new Action[6]; for(int i = 0; i < fDepthActions.length; i++) { fDepthActions[i] = createDepthAction(i, i + 1); depthMenuManager.add(fDepthActions[i]); } // Set depth from prefs int depth = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DEPTH); getContentProvider().setDepth(depth); fDepthActions[depth].setChecked(true); // Set filter based on Viewpoint IMenuManager viewpointMenuManager = new MenuManager(Messages.ZestView_5); menuManager.add(viewpointMenuManager); // Get viewpoint from prefs String viewpointID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_VIEWPOINT); getContentProvider().setViewpointFilter(ViewpointManager.INSTANCE.getViewpoint(viewpointID)); // Viewpoint actions fViewpointActions = new ArrayList<IAction>(); for(IViewpoint vp : ViewpointManager.INSTANCE.getAllViewpoints()) { IAction action = createViewpointMenuAction(vp); fViewpointActions.add(action); viewpointMenuManager.add(action); // Set checked if(vp.getID().equals(viewpointID)) { action.setChecked(true); } } // Set filter based on Elements IMenuManager elementMenuManager = new MenuManager( "Element Filter" /* Messages.ZestView_9*/ ), strategyElementMenuManager = new MenuManager( "Strategy Elements" /* Messages.ZestView_10*/ ), businessElementMenuManager = new MenuManager( "Business Elements" /* Messages.ZestView_11*/ ), applicationElementMenuManager = new MenuManager( "Application Elements" /* Messages.ZestView_12*/ ), technologyElementMenuManager = new MenuManager( "Technology Elements" /* Messages.ZestView_13*/ ), physicalElementMenuManager = new MenuManager( "Physical Elements" /* Messages.ZestView_14*/ ), motivationElementMenuManager = new MenuManager( "Technology Elements" /* Messages.ZestView_15*/ ), implementationMigrationElementMenuManager = new MenuManager( "Implementation & Migration Elements" /* Messages.ZestView_16*/ ), otherElementMenuManager = new MenuManager( "Other Elements" /* Messages.ZestView_17*/ ); menuManager.add(elementMenuManager); elementMenuManager.add(strategyElementMenuManager); elementMenuManager.add(businessElementMenuManager); elementMenuManager.add(applicationElementMenuManager); elementMenuManager.add(technologyElementMenuManager); elementMenuManager.add(physicalElementMenuManager); elementMenuManager.add(motivationElementMenuManager); elementMenuManager.add(implementationMigrationElementMenuManager); elementMenuManager.add(otherElementMenuManager); // Get elements from prefs String elementsID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_ELEMENT); EClass elementClass = (EClass)IArchimatePackage.eINSTANCE.getEClassifier(elementsID); getContentProvider().setElementFilter(elementClass); // Element actions, first the "None" concept fElementActions = new ArrayList <IAction>(); IAction elementAction = createElementMenuAction(null); if(elementClass == null) elementAction.setChecked(true); fElementActions.add(elementAction); elementMenuManager.add(elementAction); // Then get all Elements and sort them // Strategy Element fStrategyElementActions = new ArrayList<IAction>(); ArrayList<EClass> elementsStrategyClassList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getStrategyClasses())); elementsStrategyClassList.sort((o1, o2)-> o1.getName().compareTo(o2.getName())); for (EClass elem : elementsStrategyClassList) { elementAction = createElementMenuAction(elem); fStrategyElementActions.add(elementAction); strategyElementMenuManager.add(elementAction); // Set Checked if(elementClass != null && elem.getName().equals(elementClass.getName())) elementAction.setChecked(true); } // Business fBusinessElementActions = new ArrayList<IAction>(); ArrayList<EClass> elementsBusinessClassList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getBusinessClasses())); elementsBusinessClassList.sort((o1, o2)-> o1.getName().compareTo(o2.getName())); for (EClass elem : elementsBusinessClassList) { elementAction = createElementMenuAction(elem); fBusinessElementActions.add(elementAction); businessElementMenuManager.add(elementAction); // Set Checked if(elementClass != null && elem.getName().equals(elementClass.getName())) elementAction.setChecked(true); } // Application fApplicationElementActions = new ArrayList<IAction>(); ArrayList<EClass> elementsApplicationClassList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getApplicationClasses())); elementsApplicationClassList.sort((o1, o2)-> o1.getName().compareTo(o2.getName())); for (EClass elem : elementsApplicationClassList) { elementAction = createElementMenuAction(elem); fApplicationElementActions.add(elementAction); applicationElementMenuManager.add(elementAction); // Set Checked if(elementClass != null && elem.getName().equals(elementClass.getName())) elementAction.setChecked(true); } // Technology fTechnologyElementActions = new ArrayList<IAction>(); ArrayList<EClass> elementsTechnologyClassList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getTechnologyClasses())); elementsTechnologyClassList.sort((o1, o2)-> o1.getName().compareTo(o2.getName())); for (EClass elem : elementsTechnologyClassList) { elementAction = createElementMenuAction(elem); fTechnologyElementActions.add(elementAction); technologyElementMenuManager.add(elementAction); // Set Checked if(elementClass != null && elem.getName().equals(elementClass.getName())) elementAction.setChecked(true); } // Physical fPhysicalElementActions = new ArrayList<IAction>(); ArrayList<EClass> elementsPhysicalClassList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getPhysicalClasses())); elementsPhysicalClassList.sort((o1, o2)-> o1.getName().compareTo(o2.getName())); for (EClass elem : elementsPhysicalClassList) { elementAction = createElementMenuAction(elem); fPhysicalElementActions.add(elementAction); physicalElementMenuManager.add(elementAction); // Set Checked if(elementClass != null && elem.getName().equals(elementClass.getName())) elementAction.setChecked(true); } // Motivation fMotivationElementActions = new ArrayList<IAction>(); ArrayList<EClass> elementsMotivationClassList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getMotivationClasses())); elementsMotivationClassList.sort((o1, o2)-> o1.getName().compareTo(o2.getName())); for (EClass elem : elementsMotivationClassList) { elementAction = createElementMenuAction(elem); fMotivationElementActions.add(elementAction); motivationElementMenuManager.add(elementAction); // Set Checked if(elementClass != null && elem.getName().equals(elementClass.getName())) elementAction.setChecked(true); } // Implementation & Migration fImplementationMigrationElementActions = new ArrayList<IAction>(); ArrayList<EClass> elementsImplementationMigrationClassList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getImplementationMigrationClasses())); elementsImplementationMigrationClassList.sort((o1, o2)-> o1.getName().compareTo(o2.getName())); for (EClass elem : elementsImplementationMigrationClassList) { elementAction = createElementMenuAction(elem); fImplementationMigrationElementActions.add(elementAction); implementationMigrationElementMenuManager.add(elementAction); // Set Checked if(elementClass != null && elem.getName().equals(elementClass.getName())) elementAction.setChecked(true); } // Other fOtherElementActions = new ArrayList<IAction>(); ArrayList<EClass> elementsOtherClassList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getOtherClasses())); elementsOtherClassList.sort((o1, o2)-> o1.getName().compareTo(o2.getName())); for (EClass elem : elementsOtherClassList) { elementAction = createElementMenuAction(elem); fOtherElementActions.add(elementAction); otherElementMenuManager.add(elementAction); // Set Checked if(elementClass != null && elem.getName().equals(elementClass.getName())) elementAction.setChecked(true); } // Set filter based on Relationship IMenuManager relationshipMenuManager = new MenuManager(Messages.ZestView_6); menuManager.add(relationshipMenuManager); // Get relationship from prefs String relationshipID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_RELATIONSHIP); EClass eClass = (EClass)IArchimatePackage.eINSTANCE.getEClassifier(relationshipID); getContentProvider().setRelationshipFilter(eClass); // Relationship actions, first the "None" relationship fRelationshipActions = new ArrayList<IAction>(); IAction action = createRelationshipMenuAction(null); if(eClass == null) { action.setChecked(true); } fRelationshipActions.add(action); relationshipMenuManager.add(action); // Then get all relationships and sort them ArrayList<EClass> actionList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getRelationsClasses())); actionList.sort((o1, o2) -> o1.getName().compareTo(o2.getName())); for(EClass rel : actionList) { action = createRelationshipMenuAction(rel); fRelationshipActions.add(action); relationshipMenuManager.add(action); // Set checked if(eClass != null && rel.getName().equals(eClass.getName())) { action.setChecked(true); } } // Orientation IMenuManager orientationMenuManager = new MenuManager(Messages.ZestView_32); menuManager.add(orientationMenuManager); // Direction fDirectionActions = new Action[3]; fDirectionActions[0] = createOrientationMenuAction(0, Messages.ZestView_33, ZestViewerContentProvider.DIR_BOTH); orientationMenuManager.add(fDirectionActions[0]); fDirectionActions[1] = createOrientationMenuAction(1, Messages.ZestView_34, ZestViewerContentProvider.DIR_IN); orientationMenuManager.add(fDirectionActions[1]); fDirectionActions[2] = createOrientationMenuAction(2, Messages.ZestView_35, ZestViewerContentProvider.DIR_OUT); orientationMenuManager.add(fDirectionActions[2]); // Set direction from prefs int direction = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DIRECTION); getContentProvider().setDirection(direction); fDirectionActions[direction].setChecked(true); menuManager.add(new Separator()); menuManager.add(fActionSelectInModelTree); menuManager.add(fActionCopyImageToClipboard); menuManager.add(fActionExportImageToFile); } private IAction createDepthAction(final int actionId, final int depth) { IAction act = new Action(Messages.ZestView_3 + " " + depth, IAction.AS_RADIO_BUTTON) { //$NON-NLS-1$ @Override public void run() { IStructuredSelection selection = (IStructuredSelection)fGraphViewer.getSelection(); // set depth int depth = Integer.valueOf(getId()); getContentProvider().setDepth(depth); // store in prefs ArchiZestPlugin.INSTANCE.getPreferenceStore().setValue(IPreferenceConstants.VISUALISER_DEPTH, depth); // update viewer fGraphViewer.setInput(fGraphViewer.getInput()); fGraphViewer.setSelection(selection); fGraphViewer.doApplyLayout(); } }; act.setId(Integer.toString(actionId)); return act; } private IAction createElementMenuAction (final EClass elementClass) { String id = elementClass == null ? "none" : elementClass.getName(); //$NON-NLS-1$ IAction act = new Action(getElementFilterName(elementClass), IAction.AS_RADIO_BUTTON) { @Override public void run() { // Set element filter getContentProvider().setElementFilter(elementClass); // Store in prefs ArchiZestPlugin.INSTANCE.getPreferenceStore().setValue(IPreferenceConstants.VISUALISER_ELEMENT, id); // update viewer fGraphViewer.setInput(fGraphViewer.getInput()); IStructuredSelection selection = (IStructuredSelection)fGraphViewer.getSelection(); fGraphViewer.setSelection(selection); fGraphViewer.doApplyLayout(); updateLabel(); } }; act.setId(id); return act; } private IAction createViewpointMenuAction(final IViewpoint vp) { IAction act = new Action(vp.getName(), IAction.AS_RADIO_BUTTON) { @Override public void run() { // Set viewpoint filter getContentProvider().setViewpointFilter(vp); // Store in prefs ArchiZestPlugin.INSTANCE.getPreferenceStore().setValue(IPreferenceConstants.VISUALISER_VIEWPOINT, vp.getID()); // update viewer fGraphViewer.setInput(fGraphViewer.getInput()); IStructuredSelection selection = (IStructuredSelection)fGraphViewer.getSelection(); fGraphViewer.setSelection(selection); fGraphViewer.doApplyLayout(); updateLabel(); } }; act.setId(vp.getID()); return act; } private IAction createRelationshipMenuAction(final EClass relationClass) { String id = relationClass == null ? "none" : relationClass.getName(); //$NON-NLS-1$ IAction act = new Action(getRelationshipFilterName(relationClass), IAction.AS_RADIO_BUTTON) { @Override public void run() { // Set relationship filter getContentProvider().setRelationshipFilter(relationClass); // Store in prefs ArchiZestPlugin.INSTANCE.getPreferenceStore().setValue(IPreferenceConstants.VISUALISER_RELATIONSHIP, id); // update viewer fGraphViewer.setInput(fGraphViewer.getInput()); IStructuredSelection selection = (IStructuredSelection)fGraphViewer.getSelection(); fGraphViewer.setSelection(selection); fGraphViewer.doApplyLayout(); updateLabel(); } }; act.setId(id); return act; } private IAction createOrientationMenuAction(final int actionId, String label, final int orientation) { IAction act = new Action(label, IAction.AS_RADIO_BUTTON) { @Override public void run() { IStructuredSelection selection = (IStructuredSelection)fGraphViewer.getSelection(); // Set orientation getContentProvider().setDirection(orientation); // Store in prefs ArchiZestPlugin.INSTANCE.getPreferenceStore().setValue(IPreferenceConstants.VISUALISER_DIRECTION, actionId); // update viewer fGraphViewer.setInput(fGraphViewer.getInput()); fGraphViewer.setSelection(selection); fGraphViewer.doApplyLayout(); } }; act.setId(Integer.toString(actionId)); return act; } private String getRelationshipFilterName(EClass relationClass) { return relationClass == null ? Messages.ZestView_7: ArchiLabelProvider.INSTANCE.getDefaultName(relationClass); } private String getElementFilterName(EClass elementClass) { return elementClass == null ? Messages.ZestView_7 : ArchiLabelProvider.INSTANCE.getDefaultName(elementClass); } @Override public void setFocus() { if(fGraphViewer != null) { fGraphViewer.getControl().setFocus(); } } @Override public ZestGraphViewer getViewer() { return fGraphViewer; } /** * Make local actions */ private void makeActions() { fActionProperties = new PropertiesAction(getViewer()); fActionLayout = new Action(Messages.ZestView_0) { @Override public void run() { fGraphViewer.doApplyLayout(); } @Override public String getToolTipText() { return getText(); } @Override public ImageDescriptor getImageDescriptor() { return AbstractUIPlugin.imageDescriptorFromPlugin(ArchiZestPlugin.PLUGIN_ID, "img/layout.gif"); //$NON-NLS-1$ } }; fActionPinContent = new Action(Messages.ZestView_4, IAction.AS_CHECK_BOX) { { setToolTipText(Messages.ZestView_1); setImageDescriptor(IArchiImages.ImageFactory.getImageDescriptor(IArchiImages.ICON_PIN)); } }; fActionCopyImageToClipboard = new CopyZestViewAsImageToClipboardAction(fGraphViewer); fActionExportImageToFile = new ExportAsImageAction(fGraphViewer); fActionSelectInModelTree = new Action(Messages.ZestView_8) { @Override public void run() { IStructuredSelection selection = (IStructuredSelection)getViewer().getSelection(); ITreeModelView view = (ITreeModelView)ViewManager.showViewPart(ITreeModelView.ID, true); if(view != null && !selection.isEmpty()) { view.getViewer().setSelection(new StructuredSelection(selection.toArray()), true); } } @Override public String getToolTipText() { return getText(); } }; } /** * Register Global Action Handlers */ private void registerGlobalActions() { IActionBars actionBars = getViewSite().getActionBars(); // Register our interest in the global menu actions actionBars.setGlobalActionHandler(ActionFactory.PROPERTIES.getId(), fActionProperties); } /** * Hook into a right-click menu */ private void hookContextMenu() { MenuManager menuMgr = new MenuManager("#ZestViewPopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillContextMenu(manager); } }); Menu menu = menuMgr.createContextMenu(getViewer().getControl()); getViewer().getControl().setMenu(menu); getSite().registerContextMenu(menuMgr, getViewer()); } /** * Fill context menu when user right-clicks * @param manager */ private void fillContextMenu(IMenuManager manager) { Object selected = ((IStructuredSelection)getViewer().getSelection()).getFirstElement(); boolean isEmpty = selected == null; fDrillDownManager.addNavigationActions(manager); manager.add(new Separator()); manager.add(fActionLayout); manager.add(new Separator()); // Depth IMenuManager depthMenuManager = new MenuManager(Messages.ZestView_3); manager.add(depthMenuManager); for(IAction action : fDepthActions) { depthMenuManager.add(action); } // Viewpoint filter IMenuManager vpMenuManager = new MenuManager(Messages.ZestView_5); manager.add(vpMenuManager); for(IAction action : fViewpointActions) { vpMenuManager.add(action); } // Element filter IMenuManager elementMenuManager = new MenuManager( "Element Filter" /* Messages.ZestView_9*/ ), strategyElementMenuManager = new MenuManager( "Strategy Elements" /* Messages.ZestView_10*/ ), businessElementMenuManager = new MenuManager( "Business Elements" /* Messages.ZestView_11*/ ), applicationElementMenuManager = new MenuManager( "Application Elements" /* Messages.ZestView_12*/ ), technologyElementMenuManager = new MenuManager( "Technology Elements" /* Messages.ZestView_13*/ ), physicalElementMenuManager = new MenuManager( "Physical Elements" /* Messages.ZestView_14*/ ), motivationElementMenuManager = new MenuManager( "Motivation Elements" /* Messages.ZestView_15*/ ), implementationMigrationElementMenuManager = new MenuManager( "Implementation & Migration Elements" /* Messages.ZestView_16*/ ), otherElementMenuManager = new MenuManager( "Other Elements" /* Messages.ZestView_17*/ ); manager.add(elementMenuManager); elementMenuManager.add(strategyElementMenuManager); elementMenuManager.add(businessElementMenuManager); elementMenuManager.add(applicationElementMenuManager); elementMenuManager.add(technologyElementMenuManager); elementMenuManager.add(physicalElementMenuManager); elementMenuManager.add(motivationElementMenuManager); elementMenuManager.add(implementationMigrationElementMenuManager); elementMenuManager.add(otherElementMenuManager); for(IAction action : fElementActions) { elementMenuManager.add(action); } for(IAction action : fStrategyElementActions) { strategyElementMenuManager.add(action); } for(IAction action : fBusinessElementActions) { businessElementMenuManager.add(action); } for(IAction action : fApplicationElementActions) { applicationElementMenuManager.add(action); } for(IAction action : fTechnologyElementActions) { technologyElementMenuManager.add(action); } for(IAction action : fPhysicalElementActions) { physicalElementMenuManager.add(action); } for(IAction action : fMotivationElementActions) { motivationElementMenuManager.add(action); } for(IAction action : fImplementationMigrationElementActions) { implementationMigrationElementMenuManager.add(action); } for(IAction action : fOtherElementActions) { otherElementMenuManager.add(action); } // Relationship filter IMenuManager relationshipMenuManager = new MenuManager(Messages.ZestView_6); manager.add(relationshipMenuManager); for(IAction action : fRelationshipActions) { relationshipMenuManager.add(action); } // Direction IMenuManager directionMenuManager = new MenuManager(Messages.ZestView_32); manager.add(directionMenuManager); for(IAction action : fDirectionActions) { directionMenuManager.add(action); } manager.add(new Separator()); manager.add(fActionCopyImageToClipboard); manager.add(fActionExportImageToFile); if(!isEmpty) { manager.add(fActionSelectInModelTree); manager.add(new Separator()); manager.add(fActionProperties); } // Other plug-ins can contribute their actions here manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } @Override protected IArchimateModel getActiveArchimateModel() { IArchimateConcept concept = fDrillDownManager.getCurrentConcept(); return concept != null ? concept.getArchimateModel() : null; } /** * @return Casted Content Provider */ protected ZestViewerContentProvider getContentProvider() { return (ZestViewerContentProvider)fGraphViewer.getContentProvider(); } @Override public void dispose() { super.dispose(); // Explicit dispose seems to be needed if the GraphViewer is displaying scrollbars // In fact, Graph.dispose() seems never to be called // fGraphViewer.getControl().dispose(); // Unregister selection listener getSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this); } // Listen to Editor Model Changes @Override public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); Object newValue = evt.getNewValue(); // Model Closed if(propertyName == IEditorModelManager.PROPERTY_MODEL_REMOVED) { Object input = getViewer().getInput(); if(input instanceof IArchimateModelObject && ((IArchimateModelObject)input).getArchimateModel() == newValue) { fDrillDownManager.reset(); } } // Command Stack - update Actions else if(propertyName == IEditorModelManager.COMMAND_STACK_CHANGED) { updateActions(); } else { super.propertyChange(evt); } } // React to ECore Model Changes @Override protected void eCoreChanged(Notification msg) { switch(msg.getEventType()) { case Notification.ADD: case Notification.ADD_MANY: case Notification.REMOVE: case Notification.REMOVE_MANY: case Notification.MOVE: refresh(); break; case Notification.SET: // Current component name change if(msg.getNotifier() == fDrillDownManager.getCurrentConcept()) { updateLabel(); } if(!(msg.getNewValue() instanceof IBounds)) { // Don't update on bounds change. This can cause a conflict with Undo/Redo animation super.eCoreChanged(msg); } break; default: break; } } @Override protected void doRefreshFromNotifications(List<Notification> notifications) { refresh(); super.doRefreshFromNotifications(notifications); } // Contextual Help support @Override public int getContextChangeMask() { return NONE; } @Override public IContext getContext(Object target) { return HelpSystem.getContext(HELP_ID); } @Override public String getSearchExpression(Object target) { return Messages.ZestView_2; } }
package is.ru.honn.ruber.test; import is.ru.honn.ruber.domain.History; import is.ru.honn.ruber.domain.Trip; import is.ru.honn.ruber.domain.User; import is.ru.honn.ruber.service.*; import junit.framework.TestCase; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.SpringBeanJobFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"/res/app-test-stub.xml"}) @DirtiesContext(classMode= DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class TestRuberService extends TestCase { Logger log = Logger.getLogger(TestRuberService.class.getName()); @Autowired private RuberService service; //A user to test signup logic @Autowired private User testUser1; //A user to test signup logic @Autowired private User testUser2; //This user should never be signed up @Autowired private User testUser3; @Before public void setUp() throws Exception { } /** * Tests the methods signup(), getUsers() and getUser() in a given RuberService implementation */ @DirtiesContext @Test public void testUser() { log.info("testUser"); //Try to get users from an empty list List<User> tempList = new ArrayList<User>(); try{ tempList = service.getUsers(0); } catch (ServiceException e){ } assertTrue(tempList.isEmpty()); //Test adding users to the service addTestUsers(); //Try to get users from a non-empty list try{ tempList = service.getUsers(0); } catch (ServiceException e){ } assertFalse(tempList.isEmpty()); } private void addTestUsers(){ boolean exceptionThrown = false; //Try to get a user from an empty database try{ service.getUser(testUser1.getUsername()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; //Try to sign up a user try{ service.signup(testUser1.getUsername(), testUser1.getFirstName(), testUser1.getLastName(), testUser1.getEmail(), testUser1.getPassword(), testUser1.getPicture(), testUser1.getPromoCode()); } catch(UsernameExistsException e){ exceptionThrown = true; } assertFalse(exceptionThrown); exceptionThrown = false; //Try to sign up an already existing user try { service.signup(testUser1.getUsername(), testUser1.getFirstName(), testUser1.getLastName(), testUser1.getEmail(), testUser1.getPassword(), testUser1.getPicture(), testUser1.getPromoCode()); } catch(UsernameExistsException e){ exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; //Try to sign up a new user try { service.signup(testUser2.getUsername(), testUser2.getFirstName(), testUser2.getLastName(), testUser2.getEmail(), testUser2.getPassword(), testUser2.getPicture(), testUser2.getPromoCode()); } catch(UsernameExistsException e){ exceptionThrown = true; } assertFalse(exceptionThrown); exceptionThrown = false; //Try to get a non-existing user from a non-empty user service try{ service.getUser(testUser3.getUsername()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; //Try to get an existing user try{ service.getUser(testUser1.getUsername()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertFalse(exceptionThrown); } /** * Tests the methods addTrips() and getHistory() in a given RuberService implementation */ @DirtiesContext @Test public void testActivity() { log.info("testActivity"); boolean exceptionThrown = false; History tempHistory = null; //Try to get the history of a user when there are no users ready try{ tempHistory = service.getHistory(testUser1.getUsername()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertTrue(exceptionThrown); assertNull(tempHistory); tempHistory = null; exceptionThrown = false; //Try to add a trip when there are no users ready try{ service.addTrips(testUser1.getUsername(), new Trip()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; //Add a user service.signup( testUser1.getUsername(), testUser1.getFirstName(), testUser1.getLastName(), testUser1.getEmail(), testUser1.getPassword(), testUser1.getPicture(), testUser1.getPromoCode()); //Try to get the history of a user that has no trips try{ tempHistory = service.getHistory(testUser1.getUsername()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertFalse(exceptionThrown); assertNotNull(tempHistory); assertTrue(tempHistory.getHistory().isEmpty()); tempHistory = null; exceptionThrown = false; //Try to add a trip for an existing user try{ service.addTrips(testUser1.getUsername(), new Trip()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertFalse(exceptionThrown); exceptionThrown = false; //Try to get the history of a user that has 1 trip try{ tempHistory = service.getHistory(testUser1.getUsername()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertFalse(exceptionThrown); assertNotNull(tempHistory); assertFalse(tempHistory.getHistory().isEmpty()); assertEquals(1, tempHistory.getHistory().size()); tempHistory = null; exceptionThrown = false; //Try to add a trip for a non-existing user try{ service.addTrips(testUser3.getUsername(), new Trip()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; //Try to add a second trip for an existing user try{ service.addTrips(testUser1.getUsername(), new Trip()); } catch(UserNotFoundException e){ exceptionThrown = true; } assertFalse(exceptionThrown); } }
package better.jsonrpc.core; import java.io.IOException; import java.util.Vector; import java.util.concurrent.atomic.AtomicInteger; import better.jsonrpc.client.JsonRpcClient; import better.jsonrpc.server.JsonRpcServer; import better.jsonrpc.util.ProxyUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.log4j.Logger; /** * JSON-RPC connections * * These objects represent a single, possibly virtual, * connection between JSON-RPC speakers. * * Depending on the transport type, a connection can * be used as an RPC server and/or client. Notifications * may or may not be supported in either direction. * */ public abstract class JsonRpcConnection { /** Global logger, may be used by subclasses */ protected static final Logger LOG = Logger.getLogger(JsonRpcConnection.class); /** Global counter for connection IDs */ private static final AtomicInteger sConnectionIdCounter = new AtomicInteger(); /** Automatically assign connections an ID for debugging and other purposes */ protected final int mConnectionId = sConnectionIdCounter.incrementAndGet(); /** * Object mapper to be used for this connection * * Both client and server should always use this mapper for this connection. */ ObjectMapper mMapper; /** * Server instance attached to this client * * This object is responsible for handling requests and notifications. * * It will also send responses where appropriate. */ JsonRpcServer mServer; /** * Client instance attached to this client * * This object is responsible for handling responses. * * It will send requests and notifications where appropriate. */ JsonRpcClient mClient; /** * Handler instance for this client * * RPC calls will be dispatched to this through the server. */ Object mServerHandler; /** Connection listeners */ Vector<Listener> mListeners = new Vector<Listener>(); /** * Main constructor */ public JsonRpcConnection(ObjectMapper mapper) { mMapper = mapper; } /** * Get the numeric local connection ID * @return */ public int getConnectionId() { return mConnectionId; } /** @return the object mapper for this connection */ public ObjectMapper getMapper() { return mMapper; } /** @return true if this connection has a client bound to it */ public boolean isClient() { return mClient != null; } /** @return the client if there is one (throws otherwise!) */ public JsonRpcClient getClient() { if(mClient == null) { throw new RuntimeException("Connection not configured for client mode"); } return mClient; } /** Bind the given client to this connection */ public void bindClient(JsonRpcClient client) { if(mClient != null) { throw new RuntimeException("Connection already has a client"); } if(LOG.isDebugEnabled()) { LOG.debug("[" + mConnectionId + "] binding client"); } mClient = client; mClient.bindConnection(this); } /** Create and return a client proxy */ public <T> T makeProxy(Class<T> clazz) { return ProxyUtil.createClientProxy(clazz.getClassLoader(), clazz, this); } /** @return true if this connection has a server bound to it */ public boolean isServer() { return mServer != null; } /** @return the server if there is one (throws otherwise!) */ public JsonRpcServer getServer() { if(mServer == null) { throw new RuntimeException("Connection not configured for server mode"); } return mServer; } /** Bind the given server to this connection */ public void bindServer(JsonRpcServer server, Object handler) { if(mServer != null) { throw new RuntimeException("Connection already has a server"); } if(LOG.isDebugEnabled()) { LOG.debug("[" + mConnectionId + "] binding server"); } mServer = server; mServerHandler = handler; } /** Returns true if the connection is currently connected */ abstract public boolean isConnected(); /** Sends a request through the connection */ abstract public void sendRequest(ObjectNode request) throws Exception; /** Sends a response through the connection */ abstract public void sendResponse(ObjectNode response) throws Exception; /** Sends a notification through the connection */ abstract public void sendNotification(ObjectNode notification) throws Exception; /** Dispatch connection open event (for subclasses to call) */ protected void onOpen() { for(Listener l: mListeners) { l.onOpen(this); } } /** Dispatch connection close event (for subclasses to call) */ protected void onClose() { for(Listener l: mListeners) { l.onClose(this); } } /** Dispatch an incoming request (for subclasses to call) */ public void handleRequest(ObjectNode request) { if(mServer != null) { try { mServer.handleRequest(mServerHandler, request, this); } catch (Throwable throwable) { LOG.error("Exception handling request", throwable); } } } /** Dispatch an incoming response (for subclasses to call) */ public void handleResponse(ObjectNode response) { if(mClient != null) { try { mClient.handleResponse(response, this); } catch (Throwable throwable) { LOG.error("Exception handling response", throwable); } } } /** Dispatch an incoming notification (for subclasses to call) */ public void handleNotification(ObjectNode notification) { if(mServer != null) { try { mServer.handleRequest(mServerHandler, notification, this); } catch (Throwable throwable) { LOG.error("Exception handling notification", throwable); } } } /** Interface of connection state listeners */ public interface Listener { public void onOpen(JsonRpcConnection connection); public void onClose(JsonRpcConnection connection); } /** * Add a connection state listener * @param l */ public void addListener(Listener l) { mListeners.add(l); } /** * Remove the given connection state listener * @param l */ public void removeListener(Listener l) { mListeners.remove(l); } }
package net.jonp.armi.base; /** Library of conversion functions. */ public class Conversion { private Conversion() { // Prevent instantiation } /** * Convert a section of a byte array into a long (big-endian). * * @param bytes The byte array to read. * @param off The offset of the first byte to read. * @return The value converted from bytes. */ public static long bytesToLong(final byte[] bytes, final int off) { return ((bytes[off + 0] & 0xffL) << 56 | (bytes[off + 1] & 0xffL) << 48 | (bytes[off + 2] & 0xffL) << 40 | (bytes[off + 3] & 0xffL) << 32 | (bytes[off + 4] & 0xffL) << 24 | (bytes[off + 5] & 0xffL) << 16 | (bytes[off + 6] & 0xffL) << 8 | (bytes[off + 7] & 0xffL) << 0); } /** * Insert a long into an array of bytes, in big-endian byte order. * * @param bytes [OUT] The array of bytes to write into. * @param off The offset within the array to write the first byte. * @param value The value to convert to bytes. */ public static void longToBytes(final byte[] bytes, final int off, final long value) { bytes[off + 0] = (byte)((value >> 56) & 0xff); bytes[off + 1] = (byte)((value >> 48) & 0xff); bytes[off + 2] = (byte)((value >> 40) & 0xff); bytes[off + 3] = (byte)((value >> 32) & 0xff); bytes[off + 4] = (byte)((value >> 24) & 0xff); bytes[off + 5] = (byte)((value >> 16) & 0xff); bytes[off + 6] = (byte)((value >> 8) & 0xff); bytes[off + 7] = (byte)((value >> 0) & 0xff); } /** * Convert a section of a byte array into a long (little-endian). * * @param bytes The byte array to read. * @param off The offset of the first byte to read. * @return The value converted from bytes. */ public static long bytesToLongLE(final byte[] bytes, final int off) { return ((bytes[off + 0] & 0xffL) << 0 | (bytes[off + 1] & 0xffL) << 8 | (bytes[off + 2] & 0xffL) << 16 | (bytes[off + 3] & 0xffL) << 24 | (bytes[off + 4] & 0xffL) << 32 | (bytes[off + 5] & 0xffL) << 40 | (bytes[off + 6] & 0xffL) << 48 | (bytes[off + 7] & 0xffL) << 56); } /** * Insert a long into an array of bytes, in little-endian byte order. * * @param bytes [OUT] The array of bytes to write into. * @param off The offset within the array to write the first byte. * @param value The value to convert to bytes. */ public static void longToBytesLE(final byte[] bytes, final int off, final long value) { bytes[off + 0] = (byte)((value >> 0) & 0xff); bytes[off + 1] = (byte)((value >> 8) & 0xff); bytes[off + 2] = (byte)((value >> 16) & 0xff); bytes[off + 3] = (byte)((value >> 24) & 0xff); bytes[off + 4] = (byte)((value >> 32) & 0xff); bytes[off + 5] = (byte)((value >> 40) & 0xff); bytes[off + 6] = (byte)((value >> 48) & 0xff); bytes[off + 7] = (byte)((value >> 56) & 0xff); } /** * Convert a section of a byte array into an int (big-endian). * * @param bytes The byte array to read. * @param off The offset of the first byte to read. * @return The value converted from bytes. */ public static int bytesToInt(final byte[] bytes, final int off) { return ((bytes[off + 0] & 0xff) << 24 | (bytes[off + 1] & 0xff) << 16 | (bytes[off + 2] & 0xff) << 8 | (bytes[off + 3] & 0xff) << 0); } /** * Insert an int into an array of bytes, in big-endian byte order. * * @param bytes [OUT] The array of bytes to write into. * @param off The offset within the array to write the first byte. * @param value The value to convert to bytes. */ public static void intToBytes(final byte[] bytes, final int off, final int value) { bytes[off + 0] = (byte)((value >> 24) & 0xff); bytes[off + 1] = (byte)((value >> 16) & 0xff); bytes[off + 2] = (byte)((value >> 8) & 0xff); bytes[off + 3] = (byte)((value >> 0) & 0xff); } /** * Convert a section of a byte array into an int (little-endian). * * @param bytes The byte array to read. * @param off The offset of the first byte to read. * @return The value converted from bytes. */ public static int bytesToIntLE(final byte[] bytes, final int off) { return ((bytes[off + 0] & 0xff) << 0 | (bytes[off + 1] & 0xff) << 8 | (bytes[off + 2] & 0xff) << 16 | (bytes[off + 3] & 0xff) << 24); } /** * Insert an int into an array of bytes, in little-endian byte order. * * @param bytes [OUT] The array of bytes to write into. * @param off The offset within the array to write the first byte. * @param value The value to convert to bytes. */ public static void intToBytesLE(final byte[] bytes, final int off, final int value) { bytes[off + 0] = (byte)((value >> 0) & 0xff); bytes[off + 1] = (byte)((value >> 8) & 0xff); bytes[off + 2] = (byte)((value >> 16) & 0xff); bytes[off + 3] = (byte)((value >> 24) & 0xff); } /** * Convert a section of a byte array into a short (big-endian). * * @param bytes The byte array to read. * @param off The offset of the first byte to read. * @return The value converted from bytes. */ public static short bytesToShort(final byte[] bytes, final int off) { return (short)((bytes[off + 0] & 0xff) << 8 | (bytes[off + 1] & 0xff) << 0); } /** * Insert a short into an array of bytes, in big-endian byte order. * * @param bytes [OUT] The array of bytes to write into. * @param off The offset within the array to write the first byte. * @param value The value to convert to bytes. */ public static void shortToBytes(final byte[] bytes, final int off, final short value) { bytes[off + 0] = (byte)((value >> 8) & 0xff); bytes[off + 1] = (byte)((value >> 0) & 0xff); } /** * Convert a section of a byte array into a short (little-endian). * * @param bytes The byte array to read. * @param off The offset of the first byte to read. * @return The value converted from bytes. */ public static short bytesToShortLE(final byte[] bytes, final int off) { return (short)((bytes[off + 0] & 0xff) << 0 | (bytes[off + 1] & 0xff) << 8); } /** * Insert a short into an array of bytes, in little-endian byte order. * * @param bytes [OUT] The array of bytes to write into. * @param off The offset within the array to write the first byte. * @param value The value to convert to bytes. */ public static void shortToBytesLE(final byte[] bytes, final int off, final short value) { bytes[off + 0] = (byte)((value >> 0) & 0xff); bytes[off + 1] = (byte)((value >> 8) & 0xff); } /** * Concatenate the elements of an array into a string. * * @param array The array whose elements to concatenate. * @param join The string to put between the elements of the array. * @return The result. */ public static String arrayToString(final Object[] array, final String join) { return arrayToString(array, 0, array.length, join); } /** * Concatenate the elements of an array slice into a string. * * @param array The array. * @param off The index of the first element in the array to include. * @param len The number of elements to include. * @param join The string to put between the included elements of the array. * @return The result. */ public static String arrayToString(final Object[] array, final int off, final int len, final String join) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; i++) { final Object o = array[off + i]; if (builder.length() > 0) { builder.append(join); } if (o == null) { builder.append("(null)"); } else { builder.append(o); } } return builder.toString(); } /** * Describe an object, which may be <code>null</code> or an array. * * @param object The object. * @return A description of the object. */ public static String describe(final Object object) { if (object instanceof Object[]) { return describeArray((Object[])object); } else { return String.format("%s", object); } } /** * Describe an array, recursing through sub-arrays as necessary. * * @param array The array to describe. * @return An intuitive <code>toString()</code> kind of result on the array. */ public static String describeArray(final Object[] array) { final StringBuilder buf = new StringBuilder(); buf.append("["); boolean first = true; for (final Object element : array) { if (first) { first = false; } else { buf.append(", "); } buf.append(describe(element)); } buf.append("]"); return buf.toString(); } /** * Update the given string so its initial character is capitalized. * * @param s The string to update. * @return The updated string, unless it was <code>null</code> or empty, in * which case the original string is returned. */ public static String capFirst(final String s) { if (null == s || s.isEmpty()) { return s; } else { return (s.substring(0, 1).toUpperCase() + s.substring(1)); } } }
package com.akiban.sql.parser; import com.akiban.sql.StandardException; import org.junit.Test; public class RowCtorTest { // no parexception means "pass" @Test public void regularCase() throws StandardException { // smoke test // make sure it didn't break things that are working doTest("SELECT 3 IN (4,5,6)"); } @Test public void testWithBoolOp1() throws StandardException { doTest("select ((1 and 2) and 3) IN (2, 4, 5)"); } // TODO: not passing because of the [5 or 6] // why? // @Test // public void testWithBoolOp2() throws StandardException // doTest("select ((1 or 2) and 3) IN (2, 4, 5 or 6)"); @Test public void testWithTables() throws StandardException { doTest(" select (c1, c2) in ((1, 3), (c3, c4)) from t"); } @Test public void matchingColumn() throws StandardException { doTest("SELECT (2, 3, 4) IN ((5, 6, 7), (8, (9, 10, 11)))"); } @Test public void mistmatchColumnTest() throws StandardException { // This should still pass // It's not the parser's job to check the number of columns // should be handle in InExpression // Could add a field called 'depth' to RowConstructorNode // so some checking could be done here // (ie., the left list MUST be one level deeper than the right one) doTest("SELECT (2, 3, 4) IN (4, 5, 6)"); } @Test public void nestedRows() throws StandardException { doTest("SELECT ((2, 3), (4, 5)) in ((4, 5), (5, 7))"); } @Test public void nonNestedRowsWithParens() throws StandardException { doTest("SELECT 1 in ((4, ((5))))"); } static void doTest(String st) throws StandardException { SQLParser parser = new SQLParser(); StatementNode node = parser.parseStatement(st); } }
package us.illyohs.civilmagicks.common.block.nodes; import us.illyohs.civilmagicks.common.lib.LibInfo; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; public class ManaRing extends BlockContainer { public ManaRing() { super(Material.rock); this.setBlockName(LibInfo.MOD_ID+":manaring"); } @Override public TileEntity createNewTileEntity(World world, int meta) { // TODO Auto-generated method stub return null; } }
package com.apm4all.tracy; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Test; public class TracyTestFuture { private static final int NTHREDS = 10; static final String TASK_ID = "TID-ab1234-x"; static final String PARENT_OPT_ID = "AAAA"; static final String L1_LABEL_NAME = "L1 Operation"; static final String L11_LABEL_NAME = "L11 Operation"; private ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); //TODO: Create TracyableFuture interface providing getData() and getTracyThreadContext() private Future<String> futureIt(final int i) { Callable<String> worker = null; System.out.println("Executing future"); //TODO: Create ctx = Tracy.createFutureTheadContext(); worker = new Callable<String>() { public String call() throws Exception { System.out.println("Executing future (call) " + i); String out = Thread.currentThread().getName() + " " + Integer.toString(i); return out; } }; return executor.submit(worker); } @Test public void testFutureTrace() { //FIXME: Future test blocking final int NUM_FUTURES = 2; ArrayList<Future<String>> futuresList = new ArrayList<Future<String>>(); int i; try { for (i=0; i<NUM_FUTURES ; i++) { System.out.println("Calling future " +i); futuresList.add(futureIt(i)); } // Thread.sleep(1000); for (Future<String> future : futuresList) { System.out.println("Polling future"); String out = future.get(); System.out.println("Got future " + out); //TODO: Create Tracy.mergeFutureThreadContext(ctx); } } catch (Exception e) { throw new RuntimeException(e); } } }
// BaseZeissReader.java package loci.formats.in; import java.io.IOException; import java.util.Arrays; import java.util.EnumSet; import java.util.Set; import java.util.HashSet; import java.util.Hashtable; import java.util.HashMap; import java.util.Map; import java.util.Vector; import java.util.ArrayList; import java.lang.Math; import loci.common.DateTools; import loci.formats.CoreMetadata; import loci.formats.FormatTools; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.MetadataTools; import loci.formats.meta.DummyMetadata; import loci.formats.meta.MetadataStore; import ome.xml.model.primitives.PositiveFloat; import ome.xml.model.primitives.PositiveInteger; import ome.xml.model.primitives.Timestamp; /** * BaseZeissReader contains common functionality required by * readers for Zeiss AxioVision formats. * * @author Melissa Linkert melissa at glencoesoftware.com */ public abstract class BaseZeissReader extends FormatReader { // -- Fields -- /** Number of bytes per pixel. */ protected int bpp; protected String[] imageFiles; protected int[] offsets; protected int[][] coordinates; protected Hashtable<Integer, String> timestamps, exposureTime; protected int cIndex = -1; protected boolean isJPEG, isZlib; protected int realWidth, realHeight; protected Vector<String> tagsToParse; protected int nextEmWave = 0, nextExWave = 0, nextChName = 0; protected Hashtable<Integer, Double> stageX = new Hashtable<Integer, Double>(); protected Hashtable<Integer, Double> stageY = new Hashtable<Integer, Double>(); protected int timepoint = 0; protected int[] channelColors; protected int lastPlane = 0; protected Hashtable<Integer, Integer> tiles = new Hashtable<Integer, Integer>(); protected Hashtable<Integer, Double> detectorGain = new Hashtable<Integer, Double>(); protected Hashtable<Integer, Double> detectorOffset = new Hashtable<Integer, Double>(); protected Hashtable<Integer, PositiveInteger> emWavelength = new Hashtable<Integer, PositiveInteger>(); protected Hashtable<Integer, PositiveInteger> exWavelength = new Hashtable<Integer, PositiveInteger>(); protected Hashtable<Integer, String> channelName = new Hashtable<Integer, String>(); protected Double physicalSizeX, physicalSizeY, physicalSizeZ; protected int rowCount, colCount, rawCount; protected String imageDescription; protected Set<Integer> channelIndices = new HashSet<Integer>(); protected Set<Integer> zIndices = new HashSet<Integer>(); protected Set<Integer> timepointIndices = new HashSet<Integer>(); protected Set<Integer> tileIndices = new HashSet<Integer>(); protected Vector<String> roiIDs = new Vector<String>(); // Layer annotations (contain Shapes, i.e. ROIs). public ArrayList<Layer> layers = new ArrayList<BaseZeissReader.Layer>(); // -- Constructor -- /** Constructs a new ZeissZVI reader. */ public BaseZeissReader(String name, String suffix) { super(name, suffix); } /** Constructs a new ZeissZVI reader. */ public BaseZeissReader(String name, String[] suffixes) { super(name, suffixes); } // -- IFormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFileMain(String id) throws FormatException, IOException { MetadataStore store = makeFilterMetadata(); initVars(id); fillMetadataPass1(store); fillMetadataPass2(store); fillMetadataPass3(store); fillMetadataPass4(store); fillMetadataPass5(store); fillMetadataPass6(store); MetadataTools.populatePixels(store, this, true); fillMetadataPass7(store); storeROIs(store); } protected void initVars(String id) throws FormatException, IOException { timestamps = new Hashtable<Integer, String>(); exposureTime = new Hashtable<Integer, String>(); tagsToParse = new Vector<String>(); } protected void countImages() { if (getImageCount() == 0) core[0].imageCount = 1; offsets = new int[getImageCount()]; coordinates = new int[getImageCount()][3]; imageFiles = new String[getImageCount()]; } /** * Read and store basic dimensions in model * @param store * @throws FormatException * @throws IOException */ protected void fillMetadataPass1(MetadataStore store) throws FormatException, IOException { } /** * Read and store basic dimensions in model * @param store * @throws FormatException * @throws IOException */ protected void fillMetadataPass2(MetadataStore store) throws FormatException, IOException { LOGGER.info("Populating metadata"); stageX.clear(); stageY.clear(); core[0].sizeZ = zIndices.size(); core[0].sizeT = timepointIndices.size(); core[0].sizeC = channelIndices.size(); core[0].littleEndian = true; core[0].interleaved = true; core[0].falseColor = true; core[0].metadataComplete = true; core[0].imageCount = getSizeZ() * getSizeT() * getSizeC(); if (getImageCount() == 0 || getImageCount() == 1) { core[0].imageCount = 1; core[0].sizeZ = 1; core[0].sizeC = 1; core[0].sizeT = 1; } core[0].rgb = (bpp % 3) == 0; if (isRGB()) core[0].sizeC *= 3; } /** * Read and store basic dimensions in model * @param store * @throws FormatException * @throws IOException */ protected void fillMetadataPass3(MetadataStore store) throws FormatException, IOException { } /** * Read and store basic dimensions in model * @param store * @throws FormatException * @throws IOException */ protected void fillMetadataPass4(MetadataStore store) throws FormatException, IOException { int totalTiles = offsets.length / getImageCount(); if (totalTiles <= 1) { totalTiles = 1; } if (totalTiles > 1) { CoreMetadata originalCore = core[0]; core = new CoreMetadata[totalTiles]; core[0] = originalCore; } core[0].dimensionOrder = "XY"; if (isRGB()) core[0].dimensionOrder += "C"; for (int i=0; i<coordinates.length-1; i++) { int[] zct1 = coordinates[i]; int[] zct2 = coordinates[i + 1]; int deltaZ = zct2[0] - zct1[0]; int deltaC = zct2[1] - zct1[1]; int deltaT = zct2[2] - zct1[2]; if (deltaZ > 0 && getDimensionOrder().indexOf("Z") == -1) { core[0].dimensionOrder += "Z"; } if (deltaC > 0 && getDimensionOrder().indexOf("C") == -1) { core[0].dimensionOrder += "C"; } if (deltaT > 0 && getDimensionOrder().indexOf("T") == -1) { core[0].dimensionOrder += "T"; } } core[0].dimensionOrder = MetadataTools.makeSaneDimensionOrder(getDimensionOrder()); } /** * Read and store basic dimensions in model * @param store * @throws FormatException * @throws IOException */ protected void fillMetadataPass5(MetadataStore store) throws FormatException, IOException { } /** * Read and store basic dimensions in model * @param store * @throws FormatException * @throws IOException */ protected void fillMetadataPass6(MetadataStore store) throws FormatException, IOException { if (getSizeX() == 0) { core[0].sizeX = 1; } if (getSizeY() == 0) { core[0].sizeY = 1; } if (bpp == 1 || bpp == 3) core[0].pixelType = FormatTools.UINT8; else if (bpp == 2 || bpp == 6) core[0].pixelType = FormatTools.UINT16; if (isJPEG) core[0].pixelType = FormatTools.UINT8; core[0].indexed = !isRGB() && channelColors != null; for (int i=1; i<core.length; i++) { core[i] = new CoreMetadata(this, 0); } } /** * Store basic dimensions in model * @param store * @throws FormatException * @throws IOException */ protected void fillMetadataPass7(MetadataStore store) throws FormatException, IOException { for (int i=0; i<getSeriesCount(); i++) { long firstStamp = 0; if (timestamps.size() > 0) { String timestamp = timestamps.get(new Integer(0)); firstStamp = parseTimestamp(timestamp); String date = DateTools.convertDate((long) (firstStamp / 1600), DateTools.ZVI); if (date != null) { store.setImageAcquisitionDate(new Timestamp(date), i); } } } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { // link Instrument and Image String instrumentID = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrumentID, 0); String objectiveID = MetadataTools.createLSID("Objective", 0, 0); store.setObjectiveID(objectiveID, 0, 0); store.setObjectiveCorrection(getCorrection("Other"), 0, 0); store.setObjectiveImmersion(getImmersion("Other"), 0, 0); Integer[] channelKeys = channelName.keySet().toArray(new Integer[0]); Arrays.sort(channelKeys); // link DetectorSettings to an actual Detector for (int i=0; i<getEffectiveSizeC(); i++) { String detectorID = MetadataTools.createLSID("Detector", 0, i); store.setDetectorID(detectorID, 0, i); store.setDetectorType(getDetectorType("Other"), 0, i); for (int s=0; s<getSeriesCount(); s++) { int c = i; if (i < channelKeys.length) { c = channelKeys[i]; } store.setDetectorSettingsID(detectorID, s, i); store.setDetectorSettingsGain(detectorGain.get(c), s, i); store.setDetectorSettingsOffset(detectorOffset.get(c), s, i); store.setChannelName(channelName.get(c), s, i); store.setChannelEmissionWavelength(emWavelength.get(c), s, i); store.setChannelExcitationWavelength(exWavelength.get(c), s, i); } } for (int i=0; i<getSeriesCount(); i++) { store.setImageInstrumentRef(instrumentID, i); store.setObjectiveSettingsID(objectiveID, i); if (imageDescription != null) { store.setImageDescription(imageDescription, i); } if (getSeriesCount() > 1) { store.setImageName("Tile #" + (i + 1), i); } if (physicalSizeX != null && physicalSizeX > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(physicalSizeX), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeX; got {}", physicalSizeX); } if (physicalSizeY != null && physicalSizeY > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(physicalSizeY), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeY; got {}", physicalSizeY); } if (physicalSizeZ != null && physicalSizeZ > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(physicalSizeZ), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeZ; got {}", physicalSizeZ); } long firstStamp = parseTimestamp(timestamps.get(new Integer(0))); for (int plane=0; plane<getImageCount(); plane++) { int[] zct = getZCTCoords(plane); int expIndex = zct[1]; if (channelKeys.length > 0) { expIndex += channelKeys[0]; } String exposure = exposureTime.get(expIndex); if (exposure == null && exposureTime.size() == 1) { exposure = exposureTime.get(exposureTime.keys().nextElement()); } Double exp = new Double(0.0); try { exp = new Double(exposure); } catch (NumberFormatException e) { } catch (NullPointerException e) { } store.setPlaneExposureTime(exp, i, plane); int posIndex = i * getImageCount() + plane; if (posIndex < timestamps.size()) { String timestamp = timestamps.get(new Integer(posIndex)); long stamp = parseTimestamp(timestamp); stamp -= firstStamp; store.setPlaneDeltaT(new Double(stamp / 1600000), i, plane); } if (stageX.get(posIndex) != null) { store.setPlanePositionX(stageX.get(posIndex), i, plane); } if (stageY.get(posIndex) != null) { store.setPlanePositionY(stageY.get(posIndex), i, plane); } } } for (int i=0; i<getSeriesCount(); i++) { for (int roi=0; roi<roiIDs.size(); roi++) { store.setImageROIRef(roiIDs.get(roi), i, roi); } } } } /* @see loci.formats.IFormatReader#getOptimalTileHeight() */ public int getOptimalTileHeight() { FormatTools.assertId(currentId, true, 1); return getSizeY(); } /** * Store basic dimensions in model * @param store * @throws FormatException * @throws IOException */ protected void storeROIs(MetadataStore store) throws FormatException, IOException { int roiIndex = 0; int shapeIndex = 0; String shapeID; StringBuffer points; for (Layer layer : layers) { for (Shape shape : layer.shapes) { shapeIndex = 0; if (shape.type == FeatureType.UNKNOWN || shape.type == FeatureType.LUT) continue; // Not representable at this point. String roiID = MetadataTools.createLSID("ROI", roiIndex); roiIDs.add(roiID); store.setROIID(roiID, roiIndex); if (shape.name != null) store.setROIName(shape.name, roiIndex); if (shape.text != null && shape.text.length() == 0) shape.text = null; switch (shape.type) { case POINT: case POINTS: case MEAS_POINT: case MEAS_POINTS: for (int i = 0; i < (shape.points.length / 2); i++) { shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setPointID(shapeID, roiIndex, shapeIndex); store.setPointX(shape.points[(i*2)], roiIndex, shapeIndex); store.setPointY(shape.points[(i*2)+1], roiIndex, shapeIndex); if (shape.text != null && i == 0 && (shape.type == FeatureType.MEAS_POINT || shape.type == FeatureType.MEAS_POINTS)) store.setPointText(shape.text, roiIndex, shapeIndex); shapeIndex++; } break; case LINE: case MEAS_LINE: case MEAS_PROFILE: // Uses a line as the profile path, but we can't handle that yet. shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setLineID(shapeID, roiIndex, shapeIndex); store.setLineX1(shape.points[0], roiIndex, shapeIndex); store.setLineY1(shape.points[1], roiIndex, shapeIndex); store.setLineX2(shape.points[2], roiIndex, shapeIndex); store.setLineY2(shape.points[3], roiIndex, shapeIndex); if (shape.text != null && shape.type == FeatureType.MEAS_LINE) store.setLineText(shape.text, roiIndex, shapeIndex); shapeIndex++; break; case CALIPER: case MEAS_CALIPER: case MULTIPLE_CALIPER: case MEAS_MULTIPLE_CALIPER: case DISTANCE: case MEAS_DISTANCE: case MULTIPLE_DISTANCE: case MEAS_MULTIPLE_DISTANCE: // Note that the last line is the baseline. // First point of each line before the last line is on the baseline, // second point is the actual editable point chosen by the user. int caliperPoints = shape.points.length / 2; if (shape.type == FeatureType.CALIPER || shape.type == FeatureType.MEAS_CALIPER) caliperPoints -= 2; // Contains third line which we don't need for caliper types. // This isn't true for distance types, but it's only for display, so don't store for the time being. // This is a discrepancy between distance (which stores it) and multiple distance (which does not) in // the Zeiss shape types. Conversely, caliper stores it when it's not used for this type. // Here, we store a set of lines, starting at the baseline, finally followed by the baseline, for // all these types. for (int i = 0; i < caliperPoints; i++) { shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setLineID(shapeID, roiIndex, shapeIndex); store.setLineX1(shape.points[(i*2)+0], roiIndex, shapeIndex); store.setLineY1(shape.points[(i*2)+1], roiIndex, shapeIndex); store.setLineX2(shape.points[(i*2)+2], roiIndex, shapeIndex); store.setLineY2(shape.points[(i*2)+3], roiIndex, shapeIndex); if (shape.text != null && i == caliperPoints - 2 && // Store label on baseline shape.type == FeatureType.MEAS_CALIPER || shape.type == FeatureType.MEAS_MULTIPLE_CALIPER || shape.type == FeatureType.MEAS_DISTANCE || shape.type == FeatureType.MEAS_MULTIPLE_DISTANCE) store.setLineText(shape.text, roiIndex, shapeIndex); shapeIndex++; } break; case ANGLE3: case MEAS_ANGLE3: case ANGLE4: case MEAS_ANGLE4: // First point of each line is the common origin (if any) for (int i = 0; i < 4; i+=2) { shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setLineID(shapeID, roiIndex, shapeIndex); store.setLineX1(shape.points[(i*2)+0], roiIndex, shapeIndex); store.setLineY1(shape.points[(i*2)+1], roiIndex, shapeIndex); store.setLineX2(shape.points[(i*2)+2], roiIndex, shapeIndex); store.setLineY2(shape.points[(i*2)+3], roiIndex, shapeIndex); if (shape.text != null && i == 0 && (shape.type == FeatureType.MEAS_ANGLE3 || shape.type == FeatureType.MEAS_ANGLE3)) store.setLineText(shape.text, roiIndex, shapeIndex); shapeIndex++; } break; case CIRCLE: case MEAS_CIRCLE: // Compute radius from line length. double xdiff = Math.abs(shape.points[0] - shape.points[2]); double ydiff = Math.abs(shape.points[1] - shape.points[3]); double radius = Math.sqrt(Math.pow(xdiff, 2.0) + Math.pow(ydiff, 2.0)); shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setEllipseID(shapeID, roiIndex, shapeIndex); store.setEllipseX(shape.points[0], roiIndex, shapeIndex); store.setEllipseY(shape.points[1], roiIndex, shapeIndex); store.setEllipseRadiusX(radius, roiIndex, shapeIndex); store.setEllipseRadiusY(radius, roiIndex, shapeIndex); if (shape.text != null && shape.type == FeatureType.MEAS_ELLIPSE) store.setEllipseText(shape.text, roiIndex, shapeIndex); shapeIndex++; shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setLineID(shapeID, roiIndex, shapeIndex); store.setLineX1(shape.points[0], roiIndex, shapeIndex); store.setLineY1(shape.points[1], roiIndex, shapeIndex); store.setLineX2(shape.points[2], roiIndex, shapeIndex); store.setLineY2(shape.points[3], roiIndex, shapeIndex); shapeIndex++; break; case SCALE_BAR: // TODO: Set line ends. Also set scale text. shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setLineID(shapeID, roiIndex, shapeIndex); store.setLineX1(shape.points[0], roiIndex, shapeIndex); store.setLineY1(shape.points[1], roiIndex, shapeIndex); store.setLineX2(shape.points[2], roiIndex, shapeIndex); store.setLineY2(shape.points[3], roiIndex, shapeIndex); store.setLineText(shape.text, roiIndex, shapeIndex); shapeIndex++; shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setLabelID(shapeID, roiIndex, shapeIndex); store.setLabelX(shape.points[0], roiIndex, shapeIndex); store.setLabelY(shape.points[1], roiIndex, shapeIndex); if (shape.text != null) store.setLabelText(shape.text, roiIndex, shapeIndex); shapeIndex++; // Adding a rectangle is a hack to make the length get displayed in ImageJ. This should be removed. shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setRectangleID(shapeID, roiIndex, shapeIndex); store.setRectangleX(shape.points[0], roiIndex, shapeIndex); store.setRectangleY(shape.points[1], roiIndex, shapeIndex); store.setRectangleWidth(shape.points[2] - shape.points[0], roiIndex, shapeIndex); store.setRectangleHeight(shape.points[3] - shape.points[1], roiIndex, shapeIndex); if (shape.text != null) store.setRectangleText(shape.text, roiIndex, shapeIndex); shapeIndex++; break; case POLYLINE_OPEN: case MEAS_POLYLINE_OPEN: case POLYLINE_CLOSED: case MEAS_POLYLINE_CLOSED: case SPLINE_OPEN: case MEAS_SPLINE_OPEN: case SPLINE_CLOSED: case MEAS_SPLINE_CLOSED: // Currently splines not representable in model, so use polyline. points = new StringBuffer(); for (int p=0; p < shape.points.length; p+=2) { points.append(shape.points[p+0]); points.append(","); points.append(shape.points[p+1]); if (p < (shape.points.length - 2)) points.append(" "); } shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); boolean closed = (shape.type == FeatureType.POLYLINE_CLOSED || shape.type == FeatureType.SPLINE_CLOSED || shape.type == FeatureType.MEAS_POLYLINE_CLOSED || shape.type == FeatureType.MEAS_SPLINE_CLOSED); if (closed) { store.setPolygonID(shapeID, roiIndex, shapeIndex); store.setPolygonPoints(points.toString(), roiIndex, shapeIndex); if (shape.text != null && shape.type == FeatureType.MEAS_POLYLINE_OPEN || shape.type == FeatureType.MEAS_POLYLINE_CLOSED || shape.type == FeatureType.MEAS_SPLINE_OPEN || shape.type == FeatureType.MEAS_SPLINE_CLOSED) store.setPolygonText(shape.text, roiIndex, shapeIndex); } else { store.setPolylineID(shapeID, roiIndex, shapeIndex); store.setPolylinePoints(points.toString(), roiIndex, shapeIndex); if (shape.text != null && shape.type == FeatureType.MEAS_POLYLINE_OPEN || shape.type == FeatureType.MEAS_POLYLINE_CLOSED || shape.type == FeatureType.MEAS_SPLINE_OPEN || shape.type == FeatureType.MEAS_SPLINE_CLOSED) store.setPolylineText(shape.text, roiIndex, shapeIndex); } shapeIndex++; break; case ALIGNED_RECTANGLE: case MEAS_ALIGNED_RECTANGLE: case TEXT: // TODO: Determine top-left corner for text display? // We create a separate text and rectangle objects; this might need changing in the future. shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setLabelID(shapeID, roiIndex, shapeIndex); store.setLabelX(shape.points[0], roiIndex, shapeIndex); store.setLabelY(shape.points[1], roiIndex, shapeIndex); if (shape.text != null) store.setLabelText(shape.text, roiIndex, shapeIndex); shapeIndex++; shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setRectangleID(shapeID, roiIndex, shapeIndex); store.setRectangleX(shape.points[0], roiIndex, shapeIndex); store.setRectangleY(shape.points[1], roiIndex, shapeIndex); store.setRectangleWidth(shape.points[4] - shape.points[0], roiIndex, shapeIndex); store.setRectangleHeight(shape.points[5] - shape.points[1], roiIndex, shapeIndex); if (shape.text != null) store.setRectangleText(shape.text, roiIndex, shapeIndex); shapeIndex++; break; case RECTANGLE: case MEAS_RECTANGLE: points = new StringBuffer(); for (int p=0; p < 8; p+=2) { points.append(shape.points[p+0]); points.append(","); points.append(shape.points[p+1]); if (p < 3) points.append(" "); } shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setPolygonID(shapeID, roiIndex, shapeIndex); store.setPolygonPoints(points.toString(), roiIndex, shapeIndex); if (shape.text != null && shape.type == FeatureType.MEAS_POLYLINE_OPEN || shape.type == FeatureType.MEAS_POLYLINE_CLOSED || shape.type == FeatureType.MEAS_SPLINE_OPEN || shape.type == FeatureType.MEAS_SPLINE_CLOSED) store.setPolygonText(shape.text, roiIndex, shapeIndex); shapeIndex++; break; case ELLIPSE: case MEAS_ELLIPSE: shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setEllipseID(shapeID, roiIndex, shapeIndex); store.setEllipseX((shape.points[0] + shape.points[4])/2, roiIndex, shapeIndex); store.setEllipseY((shape.points[1] + shape.points[5])/2, roiIndex, shapeIndex); store.setEllipseRadiusX((shape.points[4] - shape.points[0])/2.0, roiIndex, shapeIndex); store.setEllipseRadiusY((shape.points[5] - shape.points[1])/2.0, roiIndex, shapeIndex); if (shape.text != null) // Done for both types since annotations are permitted labels store.setEllipseText(shape.text, roiIndex, shapeIndex); shapeIndex++; break; case LENGTH: case MEAS_LENGTH: // Three lines. First is the length, second and third are guide lines ending at the first line. for (int i = 0; i < 6; i+=2) { shapeID = MetadataTools.createLSID("Shape", roiIndex, shapeIndex); store.setLineID(shapeID, roiIndex, shapeIndex); store.setLineX1(shape.points[(i*2)+0], roiIndex, shapeIndex); store.setLineY1(shape.points[(i*2)+1], roiIndex, shapeIndex); store.setLineX2(shape.points[(i*2)+2], roiIndex, shapeIndex); store.setLineY2(shape.points[(i*2)+3], roiIndex, shapeIndex); if (shape.text != null && i == 0 && shape.type == FeatureType.MEAS_LENGTH) store.setLineText(shape.text, roiIndex, shapeIndex); shapeIndex++; } break; // case LUT: // The lookup table shape is a rectangle gradient. We could generate this // as a series of 256 coloured rectangles with some labels. // break; } roiIndex++; } } } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { int pixelType = getPixelType(); if ((pixelType != FormatTools.INT8 && pixelType != FormatTools.UINT8) || !isIndexed()) { return null; } byte[][] lut = new byte[3][256]; int channel = getZCTCoords(lastPlane)[1]; if (channel >= channelColors.length) return null; int color = channelColors[channel]; float red = (color & 0xff) / 255f; float green = ((color & 0xff00) >> 8) / 255f; float blue = ((color & 0xff0000) >> 16) / 255f; for (int i=0; i<lut[0].length; i++) { lut[0][i] = (byte) (red * i); lut[1][i] = (byte) (green * i); lut[2][i] = (byte) (blue * i); } return lut; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { int pixelType = getPixelType(); if ((pixelType != FormatTools.INT16 && pixelType != FormatTools.UINT16) || !isIndexed()) { return null; } short[][] lut = new short[3][65536]; int channel = getZCTCoords(lastPlane)[1]; if (channel >= channelColors.length) return null; int color = channelColors[channel]; float red = (color & 0xff) / 255f; float green = ((color & 0xff00) >> 8) / 255f; float blue = ((color & 0xff0000) >> 16) / 255f; for (int i=0; i<lut[0].length; i++) { lut[0][i] = (short) (red * i); lut[1][i] = (short) (green * i); lut[2][i] = (short) (blue * i); } return lut; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { timestamps = exposureTime = null; offsets = null; coordinates = null; imageFiles = null; cIndex = -1; bpp = 0; isJPEG = isZlib = false; tagsToParse = null; nextEmWave = nextExWave = nextChName = 0; realWidth = realHeight = 0; stageX.clear(); stageY.clear(); channelColors = null; lastPlane = 0; tiles.clear(); detectorGain.clear(); detectorOffset.clear(); emWavelength.clear(); exWavelength.clear(); channelName.clear(); physicalSizeX = physicalSizeY = physicalSizeZ = null; rowCount = colCount = rawCount = 0; imageDescription = null; channelIndices.clear(); zIndices.clear(); timepointIndices.clear(); tileIndices.clear(); timepoint = 0; roiIDs.clear(); layers.clear(); } } // -- Internal FormatReader API methods -- void parseMainTags(int image, MetadataStore store, ArrayList<Tag> tags) throws FormatException, IOException { int effectiveSizeC = 0; try { effectiveSizeC = getEffectiveSizeC(); } catch (ArithmeticException e) { } for (Tag t : tags) { String key = t.getKey(); String value = t.getValue(); try { if (key.equals("Image Channel Index")) { cIndex = Integer.parseInt(value); int v = 0; while (getGlobalMeta(key + " " + v) != null) v++; if (!getGlobalMetadata().containsValue(cIndex)) { addGlobalMeta(key + " " + v, cIndex); } continue; } else if (key.equals("ImageWidth")) { int v = Integer.parseInt(value); if (getSizeX() == 0 || v < getSizeX()) { core[0].sizeX = v; } if (realWidth == 0 && v > realWidth) realWidth = v; } else if (key.equals("ImageHeight")) { int v = Integer.parseInt(value); if (getSizeY() == 0 || v < getSizeY()) core[0].sizeY = v; if (realHeight == 0 || v > realHeight) realHeight = v; } if (cIndex != -1) key += " " + cIndex; addGlobalMeta(key, value); if (key.startsWith("ImageTile") && !(store instanceof DummyMetadata)) { if (!tiles.containsKey(new Integer(value))) { tiles.put(new Integer(value), new Integer(1)); } else { int v = tiles.get(new Integer(value)).intValue() + 1; tiles.put(new Integer(value), new Integer(v)); } } if (key.startsWith("MultiChannel Color")) { if (cIndex >= 0 && cIndex < effectiveSizeC) { if (channelColors == null || effectiveSizeC > channelColors.length) { channelColors = new int[effectiveSizeC]; } if (channelColors[cIndex] == 0) { channelColors[cIndex] = Integer.parseInt(value); } } else if (cIndex == effectiveSizeC && channelColors != null && channelColors[0] == 0) { System.arraycopy( channelColors, 1, channelColors, 0, channelColors.length - 1); channelColors[cIndex - 1] = Integer.parseInt(value); } } else if (key.startsWith("Scale Factor for X") && physicalSizeX == null) { physicalSizeX = Double.parseDouble(value); } else if (key.startsWith("Scale Factor for Y") && physicalSizeY == null) { physicalSizeY = Double.parseDouble(value); } else if (key.startsWith("Scale Factor for Z") && physicalSizeZ == null) { physicalSizeZ = Double.parseDouble(value); } else if (key.startsWith("Number Rows") && rowCount == 0) { rowCount = parseInt(value); } else if (key.startsWith("Number Columns") && colCount == 0) { colCount = parseInt(value); } else if (key.startsWith("NumberOfRawImages") && rawCount == 0) { rawCount = parseInt(value); } else if (key.startsWith("Emission Wavelength")) { if (cIndex != -1) { Integer wave = new Integer(value); if (wave.intValue() > 0) { emWavelength.put(cIndex, new PositiveInteger(wave)); } else { LOGGER.warn( "Expected positive value for EmissionWavelength; got {}", wave); } } } else if (key.startsWith("Excitation Wavelength")) { if (cIndex != -1) { Integer wave = new Integer((int) Double.parseDouble(value)); if (wave.intValue() > 0) { exWavelength.put(cIndex, new PositiveInteger(wave)); } else { LOGGER.warn( "Expected positive value for ExcitationWavelength; got {}", wave); } } } else if (key.startsWith("Channel Name")) { if (cIndex != -1) { channelName.put(cIndex, value); } } else if (key.startsWith("Exposure Time [ms]")) { if (exposureTime.get(new Integer(cIndex)) == null) { double exp = Double.parseDouble(value) / 1000; exposureTime.put(new Integer(cIndex), String.valueOf(exp)); } } else if (key.startsWith("User Name")) { String[] username = value.split(" "); if (username.length >= 2) { String id = MetadataTools.createLSID("Experimenter", 0); store.setExperimenterID(id, 0); store.setExperimenterFirstName(username[0], 0); store.setExperimenterLastName(username[username.length - 1], 0); } } else if (key.equals("User company")) { String id = MetadataTools.createLSID("Experimenter", 0); store.setExperimenterID(id, 0); store.setExperimenterInstitution(value, 0); } else if (key.startsWith("Objective Magnification")) { int magnification = (int) Double.parseDouble(value); if (magnification > 0) { store.setObjectiveNominalMagnification( new PositiveInteger(magnification), 0, 0); } else { LOGGER.warn( "Expected positive value for NominalMagnification; got {}", magnification); } } else if (key.startsWith("Objective ID")) { store.setObjectiveID("Objective:" + value, 0, 0); store.setObjectiveCorrection(getCorrection("Other"), 0, 0); store.setObjectiveImmersion(getImmersion("Other"), 0, 0); } else if (key.startsWith("Objective N.A.")) { store.setObjectiveLensNA(new Double(value), 0, 0); } else if (key.startsWith("Objective Name")) { String[] tokens = value.split(" "); for (int q=0; q<tokens.length; q++) { int slash = tokens[q].indexOf("/"); if (slash != -1 && slash - q > 0) { int mag = (int) Double.parseDouble(tokens[q].substring(0, slash - q)); String na = tokens[q].substring(slash + 1); if (mag > 0) { store.setObjectiveNominalMagnification( new PositiveInteger(mag), 0, 0); } else { LOGGER.warn( "Expected positive value for NominalMagnification; got {}", mag); } store.setObjectiveLensNA(new Double(na), 0, 0); store.setObjectiveCorrection(getCorrection(tokens[q - 1]), 0, 0); break; } } } else if (key.startsWith("Objective Working Distance")) { store.setObjectiveWorkingDistance(new Double(value), 0, 0); } else if (key.startsWith("Objective Immersion Type")) { String immersion = "Other"; switch (Integer.parseInt(value)) { // case 1: no immersion case 2: immersion = "Oil"; break; case 3: immersion = "Water"; break; } store.setObjectiveImmersion(getImmersion(immersion), 0, 0); } else if (key.startsWith("Stage Position X")) { stageX.put(image, new Double(value)); addGlobalMeta("X position for position #" + stageX.size(), value); } else if (key.startsWith("Stage Position Y")) { stageY.put(image, new Double(value)); addGlobalMeta("Y position for position #" + stageY.size(), value); } else if (key.startsWith("Orca Analog Gain")) { detectorGain.put(cIndex, new Double(value)); } else if (key.startsWith("Orca Analog Offset")) { detectorOffset.put(cIndex, new Double(value)); } else if (key.startsWith("Comments")) { imageDescription = value; } else if (key.startsWith("Acquisition Date")) { if (timepoint > 0) { timestamps.put(new Integer(timepoint - 1), value); addGlobalMeta("Timestamp " + timepoint, value); } timepoint++; } } catch (NumberFormatException e) { } } } /** * Parse an Integer from a String. * @param number the number to parse * @return an Integer. 0 if number was null. */ protected static int parseInt(String number) { return parseInt(number, 0); } /** * Parse an Integer from a String. * @param number the number to parse * @param defaultnum the number to return if number is null or empty * @return an Integer. 0 if number was null. */ protected static int parseInt(String number, int defaultnum) { if (number != null && number.trim().length() > 0) { return Integer.parseInt(number); } return defaultnum; } /** * Parse timestamp from string. Note this may be ZVI-specific * due to the use of locale-specific date formats in the TIFF XML. * @param s * @return */ private long parseTimestamp(String s) { long stamp = 0; try { stamp = Long.parseLong(s); } catch (NumberFormatException exc) { if (s != null) { stamp = DateTools.getTime(s, "M/d/y h:mm:ss aa"); if (stamp < 0) { stamp = DateTools.getTime(s, "d/M/y H:mm:ss"); } stamp += DateTools.ZVI_EPOCH; stamp *= 1600; } } return stamp; } public enum Context { MAIN, SCALING, PLANE } /** * Content of a single tag from a Tags block. */ public class Tag { // index number of the tag in the XML. Not useful except for parsing validation. private int index; // key number of the tag (I element). Needs mapping to a descriptive name. private int keyid; // value of the tag (V element). private String value; // category (presumed) of the tag (A element). private int category; // Context in which this tag is found. private Context context; /** * Constructor. * All variables are initialised to be invalid to permit later validation of correct parsing. * @param index the index number of the tag. */ public Tag(int index, Context context) { this.index = index; keyid = -1; value = null; category = -1; this.context = context; } /** * Constructor. The key id will be automatically set. * @param keyid the key number of the tag. * @param value the value of the tag. */ public Tag(int keyid, String value, Context context) { this.index = 0; this.keyid = keyid; this.value = value; this.category = 0; this.context = context; } public void setKey(int keyid) { this.keyid = keyid; } public String getKey() { return getKey(keyid); } public void setValue(String value) { this.value = value; } public String getValue() { return value; } public void setIndex(int index) { this.index = index; } public int getIndex() { return index; } public void setCategory(int category) { this.category = category; } public int getCategory() { return category; } /** * Check if the tag is valid (key, value and category have been set). * @return true if valid, otherwise false. */ public boolean valid () { return keyid != -1 && value != null && category != -1; } public String toString() { String s = new String(); s += " " + keyid + "(" + getKey() + ") = " + getValue(); switch (context) { case MAIN: s += " [main]"; break; case SCALING: s += " [scaling]"; break; case PLANE: s += " [plane]"; break; default: s+= " [unknown]"; break; } s+= "\n"; return s; } /** Return the string corresponding to the given ID. */ protected String getKey(int tagID) { switch (tagID) { case -1: return "INVALID"; case 222: return "Compression"; case 257: return "DateMappingTable"; case 258: return "BlackValue"; // "Black Value" case 259: return "WhiteValue"; // "White Value" case 260: return "ImageDataMappingAutoRange"; case 261: return "Thumbnail"; // "Image Thumbnail" case 262: return "GammaValue"; // "Gamma Value" case 264: return "ImageOverExposure"; case 265: return "ImageRelativeTime1"; case 266: return "ImageRelativeTime2"; case 267: return "ImageRelativeTime3"; case 268: return "ImageRelativeTime4"; case 300: return "ImageRelativeTime"; case 301: return "ImageBaseTime1"; // Also "ImageBaseTimeFirst" case 302: return "ImageBaseTime2"; case 303: return "ImageBaseTime3"; case 305: return "ImageBaseTime4"; case 333: return "RelFocusPosition1"; case 334: return "RelFocusPosition2"; case 513: return "ObjectType"; case 515: return "ImageWidth"; // "Image Width (Pixel)" case 516: return "ImageHeight"; // "Image Height (Pixel)" case 517: return "Number Raw Count"; // "ImageCountRaw" case 518: return "PixelType"; // "Pixel Type" case 519: return "NumberOfRawImages"; // "Number Raw Images" case 520: return "ImageSize"; // "Image Size" case 521: return "CompressionFactorForSave"; case 522: return "DocumentSaveFlags"; case 523: return "Acquisition pause annotation"; case 530: return "Document Subtype"; case 531: return "Acquisition Bit Depth"; case 532: return "Image Memory Usage (RAM)"; case 534: return "Z-Stack single representative"; case 769: return "Scale Factor for X"; case 770: return "Scale Unit for X"; case 771: return "Scale Width"; case 772: return "Scale Factor for Y"; case 773: return "Scale Unit for Y"; case 774: return "Scale Height"; case 775: return "Scale Factor for Z"; case 776: return "Scale Unit for Z"; case 777: return "Scale Depth"; case 778: return "Scaling Parent"; case 1001: return "Date"; case 1002: return "Code"; case 1003: return "Source"; case 1004: return "Message"; case 1025: return "Acquisition Date"; // Also "Camera Acquisition Time" in latest AxioVision, which more closely matches its per-plane meaning. and "CameraImageAcquisitionTime" in the spec case 1026: return "8-bit Acquisition"; case 1027: return "Camera Bit Depth"; case 1029: return "MonoReferenceLow"; case 1030: return "MonoReferenceHigh"; case 1031: return "RedReferenceLow"; case 1032: return "RedReferenceHigh"; case 1033: return "GreenReferenceLow"; case 1034: return "GreenReferenceHigh"; case 1035: return "BlueReferenceLow"; case 1036: return "BlueReferenceHigh"; case 1041: return "FrameGrabber Name"; // "Framegrabber Name" in spec. case 1042: return "Camera"; case 1044: return "CameraTriggerSignalType"; case 1045: return "CameraTriggerEnable"; case 1046: return "GrabberTimeout"; case 1047: return "tag_ID_1047"; // Undocumented in spec. case 1281: return "MultiChannelEnabled"; case 1282: return "MultiChannel Color"; // False colour for the channel; "Multichannel Colour" in spec. case 1283: return "MultiChannel Weight"; // False colour weighting; "Multichannel Weight" in spec. case 1284: return "Channel Name"; case 1536: return "DocumentInformationGroup"; case 1537: if (context == Context.SCALING) return "Scale Unit for Z"; // Only within a Scalings block. else return "Title"; case 1538: return "Author"; case 1539: return "Keywords"; case 1540: return "Comments"; case 1541: return "SampleID"; case 1542: return "Subject"; case 1543: return "RevisionNumber"; case 1544: return "Save Folder"; case 1545: return "FileLink"; case 1546: return "Document Type"; case 1547: return "Storage Media"; case 1548: return "File ID"; case 1549: return "Reference"; case 1550: return "File Date"; case 1551: return "File Size"; case 1553: return "Filename"; case 1792: return "ProjectGroup"; case 1793: return "Acquisition Date"; case 1794: return "Last modified by"; case 1795: return "User Company"; case 1796: return "User Company Logo"; case 1797: return "Image"; case 1800: return "User ID"; case 1801: return "User Name"; case 1802: return "User City"; case 1803: return "User Address"; case 1804: return "User Country"; case 1805: return "User Phone"; case 1806: return "User Fax"; case 2049: return "Objective Name"; case 2050: return "Optovar"; case 2051: return "Reflector"; case 2052: return "Condenser Contrast"; case 2053: return "Transmitted Light Filter 1"; case 2054: return "Transmitted Light Filter 2"; case 2055: return "Reflected Light Shutter"; case 2056: return "Condenser Front Lens"; case 2057: return "Excitation Filter Name"; // "Excitation Filer Name" in the spec, but must be a typo. case 2060: return "Transmitted Light Fieldstop Aperture"; case 2061: return "Reflected Light Aperture"; case 2062: return "Condenser N.A."; case 2063: return "Light Path"; case 2064: return "HalogenLampOn"; case 2065: return "Halogen Lamp Mode"; case 2066: return "Halogen Lamp Voltage"; case 2068: return "Fluorescence Lamp Level"; case 2069: return "Fluorescence Lamp Intensity"; case 2070: return "LightManagerEnabled"; // "Light Manager is Enabled" in spec. case 2071: return "tag_ID_2071"; // Undocumented in spec. case 2072: return "Focus Position"; case 2073: return "Stage Position X"; case 2074: return "Stage Position Y"; case 2075: return "Microscope Name"; case 2076: return "Objective Magnification"; case 2077: return "Objective N.A."; case 2078: return "MicroscopeIllumination"; // "Microscope Illumination" in spec. case 2079: return "External Shutter 1"; case 2080: return "External Shutter 2"; case 2081: return "External Shutter 3"; case 2082: return "External Filter Wheel 1 Name"; case 2083: return "External Filter Wheel 2 Name"; case 2084: return "Parfocal Correction"; case 2086: return "External Shutter 4"; case 2087: return "External Shutter 5"; case 2088: return "External Shutter 6"; case 2089: return "External Filter Wheel 3 Name"; case 2090: return "External Filter Wheel 4 Name"; case 2103: return "Objective Turret Position"; case 2104: return "Objective Contrast Method"; case 2105: return "Objective Immersion Type"; case 2107: return "Reflector Position"; case 2109: return "Transmitted Light Filter 1 Position"; case 2110: return "Transmitted Light Filter 2 Position"; case 2112: return "Excitation Filter Position"; case 2113: return "Lamp Mirror Position"; case 2114: return "External Filter Wheel 1 Position"; case 2115: return "External Filter Wheel 2 Position"; case 2116: return "External Filter Wheel 3 Position"; case 2117: return "External Filter Wheel 4 Position"; case 2118: return "Lightmanager Mode"; case 2119: return "Halogen Lamp Calibration"; case 2120: return "CondenserNAGoSpeed"; case 2121: return "TransmittedLightFieldstopGoSpeed"; case 2122: return "OptovarGoSpeed"; case 2123: return "Focus calibrated"; case 2124: return "FocusBasicPosition"; case 2125: return "FocusPower"; case 2126: return "FocusBacklash"; case 2127: return "FocusMeasurementOrigin"; case 2128: return "FocusMeasurementDistance"; case 2129: return "FocusSpeed"; case 2130: return "FocusGoSpeed"; case 2131: return "FocusDistance"; // "Focus Distance" in spec case 2132: return "FocusInitPosition"; case 2133: return "Stage calibrated"; case 2134: return "StagePower"; case 2135: return "StageXBacklash"; case 2136: return "StageYBacklash"; case 2137: return "StageSpeedX"; // "Stage Speed X" case 2138: return "StageSpeedY"; // "Stage Speed Y" case 2139: return "StageSpeed"; // "Stage Speed" case 2140: return "StageGoSpeedX"; // "Stage Go Speed X" case 2141: return "StageGoSpeedY"; // "Stage Go Speed Y" case 2142: return "StageStepDistanceX"; // "Stage Step Distance X" case 2143: return "StageStepDistanceY"; // "Stage Step Distance Y" case 2144: return "StageInitialisationPositionX"; // "Stage Initialisation Position X" case 2145: return "StageInitialisationPositionY"; // "Stage Initialisation Position Y" case 2146: return "MicroscopeMagnification"; case 2147: return "ReflectorMagnification"; // "Reflector Magnification" case 2148: return "LampMirrorPosition"; // "Lamp Mirror Position" case 2149: return "FocusDepth"; case 2150: return "MicroscopeType"; // "Microscope Type" case 2151: return "Objective Working Distance"; case 2152: return "ReflectedLightApertureGoSpeed"; case 2153: return "External Shutter"; case 2154: return "ObjectiveImmersionStop"; // "Objective Immersion Stop" case 2155: return "Focus Start Speed"; case 2156: return "Focus Acceleration"; case 2157: return "ReflectedLightFieldstop"; // "Reflected Light Fieldstop" case 2158: return "ReflectedLightFieldstopGoSpeed"; case 2159: return "ReflectedLightFilter 1"; // "Reflected Light Filter 1" case 2160: return "ReflectedLightFilter 2"; // "Reflected Light Filter 2" case 2161: return "ReflectedLightFilter1Position"; // "Reflected Light Filter 1 Position" case 2162: return "ReflectedLightFilter2Position"; // "Reflected Light Filter 2 Position" case 2163: return "TransmittedLightAttenuator"; // "Transmitted Light Attenuator" case 2164: return "ReflectedLightAttenuator"; // "Reflected Light Attenuator" case 2165: return "Transmitted Light Shutter"; case 2166: return "TransmittedLightAttenuatorGoSpeed"; case 2167: return "ReflectedLightAttenuatorGoSpeed"; case 2176: return "TransmittedLightVirtualFilterPosition"; case 2177: return "TransmittedLightVirtualFilter"; // "Transmitted Light Virtual Filter" case 2178: return "ReflectedLightVirtualFilterPosition"; case 2179: return "ReflectedLightVirtualFilter"; // "Reflected Light Virtual Filter" case 2180: return "ReflectedLightHalogenLampMode"; // "Reflected Light Halogen Lamp Mode" case 2181: return "ReflectedLightHalogenLampVoltage"; // "Reflected Light Halogen Lamp Voltage" case 2182: return "ReflectedLightHalogenLampColorTemperature"; // "Reflected Light Halogen Lamp Colour Temperature" in spec case 2183: return "ContrastManagerMode"; // "Contrastmanager Mode" case 2184: return "Dazzle Protection Active"; case 2195: return "Zoom"; case 2196: return "ZoomGoSpeed"; case 2197: return "LightZoom"; // "Light Zoom" case 2198: return "LightZoomGoSpeed"; case 2199: return "LightZoomCoupled"; // "Lightzoom Coupled", probably "LightZoom Coupled" case 2200: return "TransmittedLightHalogenLampMode"; // "Transmitted Light Halogen Lamp Mode" case 2201: return "TransmittedLightHalogenLampVoltage"; // "Transmitted Light Halogen Lamp Voltage" case 2202: return "TransmittedLightHalogenLampColorTemperature"; // "Transmitted Light Halogen Colour Temperature" in spec case 2203: return "Reflected Coldlight Mode"; case 2204: return "Reflected Coldlight Intensity"; case 2205: return "Reflected Coldlight Color Temperature"; // "Reflected Coldlight Colour Temperature" in spec case 2206: return "Transmitted Coldlight Mode"; case 2207: return "Transmitted Coldlight Intensity"; case 2208: return "Transmitted Coldlight Color Temperature"; // "Transmitted Coldlight Colour Temperature" in spec case 2209: return "Infinityspace Portchanger Position"; case 2210: return "Beamsplitter Infinity Space"; case 2211: return "TwoTv VisCamChanger Position"; case 2212: return "Beamsplitter Ocular"; case 2213: return "TwoTv CamerasChanger Position"; case 2214: return "Beamsplitter Cameras"; case 2215: return "Ocular Shutter"; case 2216: return "TwoTv CamerasChangerCube"; case 2217: return "LightWaveLength"; case 2218: return "Ocular Magnification"; case 2219: return "Camera Adapter Magnification"; case 2220: return "Microscope Port"; case 2221: return "Ocular Total Magnification"; case 2222: return "Field of View"; case 2223: return "Ocular"; case 2224: return "CameraAdapter"; case 2225: return "StageJoystickEnabled"; case 2226: return "ContrastManager Contrast Method"; // "ContrastManagerContrastMethod" in spec case 2229: return "CamerasChanger Beamsplitter Type"; // "CamerasChanger BeamSplitter Type" case 2235: return "Rearport Slider Position"; case 2236: return "Rearport Source"; case 2237: return "Beamsplitter Type Infinity Space"; case 2238: return "Fluorescence Attenuator"; case 2239: return "Fluorescence Attenuator Position"; case 2247: return "tag_ID_2247"; case 2252: return "tag_ID_2252"; case 2253: return "tag_ID_2253"; case 2254: return "tag_ID_2254"; case 2255: return "tag_ID_2255"; case 2256: return "tag_ID_2256"; case 2257: return "tag_ID_2257"; case 2258: return "tag_ID_2258"; case 2259: return "tag_ID_2259"; case 2260: return "tag_ID_2260"; case 2261: return "Objective ID"; case 2262: return "Reflector ID"; case 2307: return "Camera Framestart Left"; // Camera Frame Left case 2308: return "Camera Framestart Top"; // Camera Frame Top case 2309: return "Camera Frame Width"; case 2310: return "Camera Frame Height"; case 2311: return "Camera Binning"; case 2312: return "CameraFrameFull"; case 2313: return "CameraFramePixelDistance"; case 2318: return "DataFormatUseScaling"; case 2319: return "CameraFrameImageOrientation"; case 2320: return "VideoMonochromeSignalType"; case 2321: return "VideoColorSignalType"; case 2322: return "MeteorChannelInput"; case 2323: return "MeteorChannelSync"; case 2324: return "WhiteBalanceEnabled"; case 2325: return "CameraWhiteBalanceRed"; case 2326: return "CameraWhiteBalanceGreen"; case 2327: return "CameraWhiteBalanceBlue"; case 2331: return "CameraFrameScalingFactor"; case 2562: return "Meteor Camera Type"; case 2564: return "Exposure Time [ms]"; case 2568: return "CameraExposureTimeAutoCalculate"; case 2569: return "Meteor Gain Value"; case 2571: return "Meteor Gain Automatic"; case 2572: return "MeteorAdjustHue"; case 2573: return "MeteorAdjustSaturation"; case 2574: return "MeteorAdjustRedLow"; case 2575: return "MeteorAdjustGreenLow"; case 2576: return "Meteor Blue Low"; case 2577: return "MeteorAdjustRedHigh"; case 2578: return "MeteorAdjustGreenHigh"; case 2579: return "MeteorBlue High"; case 2582: return "CameraExposureTimeCalculationControl"; case 2585: return "AxioCamFadingCorrectionEnable"; case 2587: return "CameraLiveImage"; case 2588: return "CameraLiveEnabled"; case 2589: return "LiveImageSyncObjectName"; case 2590: return "CameraLiveSpeed"; case 2591: return "CameraImage"; case 2592: return "CameraImageWidth"; case 2593: return "CameraImageHeight"; case 2594: return "CameraImagePixelType"; case 2595: return "CameraImageShMemoryName"; case 2596: return "CameraLiveImageWidth"; case 2597: return "CameraLiveImageHeight"; case 2598: return "CameraLiveImagePixelType"; case 2599: return "CameraLiveImageShMemoryName"; case 2600: return "CameraLiveMaximumSpeed"; case 2601: return "CameraLiveBinning"; case 2602: return "CameraLiveGainValue"; case 2603: return "CameraLiveExposureTimeValue"; case 2604: return "CameraLiveScalingFactor"; case 2817: return "Image Index U"; case 2818: return "Image Index V"; case 2819: return "Image Index Z"; case 2820: return "Image Channel Index"; // "Image Index C" case 2821: return "Image Index T"; case 2822: return "ImageTile Index"; // "Image Index T" case 2823: return "Image acquisition Index"; case 2824: return "ImageCount Tiles"; case 2825: return "ImageCount A"; case 2827: return "Image Index S"; // "Image Index S" case 2828: return "Image Index Raw"; case 2832: return "Image Count Z"; case 2833: return "Image Count C"; case 2834: return "Image Count T"; case 2838: return "Number Rows"; // "Image Count U" case 2839: return "Number Columns"; // "Image Count V" case 2840: return "Image Count S"; case 2841: return "Original Stage Position X"; case 2842: return "Original Stage Position Y"; case 3088: return "LayerDrawFlags"; case 3334: return "RemainingTime"; // "Remaining Time" case 3585: return "User Field 1"; case 3586: return "User Field 2"; case 3587: return "User Field 3"; case 3588: return "User Field 4"; case 3589: return "User Field 5"; case 3590: return "User Field 6"; case 3591: return "User Field 7"; case 3592: return "User Field 8"; case 3593: return "User Field 9"; case 3594: return "User Field 10"; case 3840: return "ID"; case 3841: return "Name"; case 3842: return "Value"; case 5501: return "PvCamClockingMode"; case 8193: return "Autofocus Status Report"; case 8194: return "Autofocus Position"; case 8195: return "Autofocus Position Offset"; case 8196: return "Autofocus Empty Field Threshold"; case 8197: return "Autofocus Calibration Name"; case 8198: return "Autofocus Current Calibration Item"; case 20478: return "tag_ID_20478"; case 65537: return "CameraFrameFullWidth"; case 65538: return "CameraFrameFullHeight"; case 65541: return "AxioCam Shutter Signal"; case 65542: return "AxioCam Delay Time"; case 65543: return "AxioCam Shutter Control"; case 65544: return "AxioCam BlackRefIsCalculated"; case 65545: return "AxioCam Black Reference"; case 65547: return "Camera Shading Correction"; case 65550: return "AxioCam Enhance Color"; case 65551: return "AxioCam NIR Mode"; case 65552: return "CameraShutterCloseDelay"; case 65553: return "CameraWhiteBalanceAutoCalculate"; case 65556: return "AxioCam NIR Mode Available"; case 65557: return "AxioCam Fading Correction Available"; case 65559: return "AxioCam Enhance Color Available"; case 65565: return "MeteorVideoNorm"; case 65566: return "MeteorAdjustWhiteReference"; case 65567: return "MeteorBlackReference"; case 65568: return "MeteorChannelInputCountMono"; case 65570: return "MeteorChannelInputCountRGB"; case 65571: return "MeteorEnableVCR"; case 65572: return "Meteor Brightness"; case 65573: return "Meteor Contrast"; case 65575: return "AxioCam Selector"; // "AxioCamSelector" case 65576: return "AxioCam Type"; case 65577: return "AxioCam Info"; // "AxioCamInfo" case 65580: return "AxioCam Resolution"; case 65581: return "AxioCam Color Model"; // "AxioCam Colour Model" case 65582: return "AxioCam MicroScanning"; case 65585: return "Amplification Index"; case 65586: return "Device Command"; // "DeviceCommand" case 65587: return "BeamLocation"; case 65588: return "ComponentType"; case 65589: return "ControllerType"; case 65590: return "CameraWhiteBalanceCalculationRedPaint"; case 65591: return "CameraWhiteBalanceCalculationBluePaint"; case 65592: return "CameraWhiteBalanceSetRed"; case 65593: return "CameraWhiteBalanceSetGreen"; case 65594: return "CameraWhiteBalanceSetBlue"; case 65595: return "CameraWhiteBalanceSetTargetRed"; case 65596: return "CameraWhiteBalanceSetTargetGreen"; case 65597: return "CameraWhiteBalanceSetTargetBlue"; case 65598: return "ApotomeCamCalibrationMode"; case 65599: return "ApoTome Grid Position"; case 65600: return "ApotomeCamScannerPosition"; case 65601: return "ApoTome Full Phase Shift"; case 65602: return "ApoTome Grid Name"; case 65603: return "ApoTome Staining"; case 65604: return "ApoTome Processing Mode"; case 65605: return "ApotomeCamLiveCombineMode"; case 65606: return "ApoTome Filter Name"; case 65607: return "Apotome Filter Strength"; case 65608: return "ApotomeCamFilterHarmonics"; case 65609: return "ApoTome Grating Period"; case 65610: return "ApoTome Auto Shutter Used"; case 65611: return "Apotome Cam Status"; // "ApoTomeCamStatus" case 65612: return "ApotomeCamNormalize"; case 65613: return "ApotomeCamSettingsManager"; case 65614: return "DeepviewCamSupervisorMode"; case 65615: return "DeepView Processing"; case 65616: return "DeepviewCamFilterName"; case 65617: return "DeepviewCamStatus"; case 65618: return "DeepviewCamSettingsManager"; case 65619: return "DeviceScalingName"; case 65620: return "CameraShadingIsCalculated"; case 65621: return "CameraShadingCalculationName"; case 65622: return "CameraShadingAutoCalculate"; case 65623: return "CameraTriggerAvailable"; case 65626: return "CameraShutterAvailable"; case 65627: return "AxioCam ShutterMicroScanningEnable"; // "AxioCamShutterMicroScanningEnable" case 65628: return "ApotomeCamLiveFocus"; case 65629: return "DeviceInitStatus"; case 65630: return "DeviceErrorStatus"; case 65631: return "ApotomeCamSliderInGridPosition"; case 65632: return "Orca NIR Mode Used"; case 65633: return "Orca Analog Gain"; case 65634: return "Orca Analog Offset"; case 65635: return "Orca Binning"; case 65636: return "Orca Bit Depth"; case 65637: return "ApoTome Averaging Count"; case 65638: return "DeepView DoF"; case 65639: return "DeepView EDoF"; case 65643: return "DeepView Slider Name"; case 65651: return "tag_ID_65651"; case 65652: return "tag_ID_65652"; case 65655: return "DeepView Slider Name"; // Also "Camera NIR Mode Enabled" case 65657: return "tag_ID_65657"; case 65658: return "tag_ID_65658"; case 65661: return "tag_ID_65661"; case 65662: return "tag_ID_65662"; // Camera driver? case 5439491: return "Acquisition Software"; case 16777488: return "Excitation Wavelength"; case 16777489: return "Emission Wavelength"; case 101515267: return "File Name"; case 101253123: case 101777411: return "Image Name"; default: return "tag_ID_" + tagID; } } } /* * AvioVision ROI/Annotation properties */ /** * Feature types. Two major catagories, "annotations" and "measurements". * * NOTE: Some of the point types are relative to a defined coordinate system (not yet seen). */ enum FeatureType { UNKNOWN(-1, 0), POINT(0, 1), // Single point (1 point for xy location) POINTS(1, 0), // Set of points (n points) LINE(2, 2), // Single line (2 points) CALIPER(3, 6), // Distance at right angles to baseline; two intersecting perpendicular lines; Same as DISTANCE, but omit drawing the last line. DISTANCE(4, 6), // Distance between two parallel lines; three lines drawn at right angles; Pair1: distance being measured, p2 and p3 are the caliper ends. Note that p2/3 are for display only; they need recomputing if edited. MULTIPLE_CALIPER(5, -4), // Multiple distances at right angles to baseline; The last pair is the baseline. All preceding pairs are distances to the baseline. First point is on the baseline. If the baseline is moved, the baseline points need recomputing. MULTIPLE_DISTANCE(5, -4), // Multiple distances between two parallel lines; Same as for 5. But, an extra line the same length as the baseline is drawn at the other end of each line; this extra line is not stored. ANGLE3(7, 4), // In degrees (4 points--2 lines with common origin); angle determined from intersection ANGLE4(8, 4), // In degrees (4 points--2 lines with no common origin); angle determined from (virtual) intersection CIRCLE(9, 2), // Circle (2 points defining radius); Point 1 is centre, point 2 is edge. Draw circle from this. (radius line + circle) SCALE_BAR(10, 2), // Scale bar (2 points); Start and end of scale bar line. POLYLINE_OPEN(12, -2), // Open polyline (>= 2 points) ALIGNED_RECTANGLE(13, 5), // Simple rectangle (5 points); can contain tag name/value or text string; points are a special case of open polyline RECTANGLE(14, 5), // Rectangle in any orientation (5 points); special case of open polyline; second point is rotation origin in UI, handles controlling size and rotation ELLIPSE(15, 5), // Ellipse drawn inside rectangle (as for aligned rectangle); can't be rotated. POLYLINE_CLOSED(16, -2), // Outline/polygon of straight lines. TEXT(17, 5), // Text box (5 points for closed bounding box like a rectangle); in UI hiding text also hides the rectangle outline. LENGTH(18, 6), // Distance (6 points--3 lines, first line is the real distance, second two are guides) SPLINE_OPEN(19, -3), // Open spline curve (probably natural spline) (>= 3 points); curve passes through all points SPLINE_CLOSED(20, -3), // Closed spline curve (probably natural spline) (>= 3 points); curve passes through all points LUT(21, 5), // Rectangle defining area for LUT gradient with adjacent text labels; gradient drawn inside rectangle, with labels down the right edge // Type 25 segfaults AxioVision :( But icon looks like some sort of polyline/outline shape. // Type 26 same icon as 25 but nothing shows; may be >10 points. // Type 27 looks like a numbered points list, but nothing shown. // Like type 1, but not selectable or editable. MEAS_PROFILE(28, 2), // Line for line profile; line thickness controls averaging (measurement); the profile itself is not stored, and needs computing. // Type 29 is a text box (rectangle with text), but icon is a set square + clock--maybe timeseries measurement? // Points: 5 // Type 30 same as 29, but rectangle + clock. // Points: 5 // Type 31 same as 29, but icon is a circle divided into coloured r/g/b thirds - channel related? // Points: 5 MEAS_POINT(32, 1), // Same as POINT, with label (measurement) MEAS_POINTS(33, 0), //Same as POINTS, with label (measurement) MEAS_LINE(34, 2), // Same as LINE, with label (measurement) MEAS_CALIPER(35, 6), // Same as CALIPER, with label along baseline [not distance?] (measurement) MEAS_DISTANCE(36, 6), // Same as DISTANCE, with label along baseline [not distance?] (measurement) MEAS_MULTIPLE_CALIPER(37, -4), // Same as MULTIPLE_CALIPER, with label along baseline [not distance?] (measurement) MEAS_MULTIPLE_DISTANCE(38, -4), // Same as MULTIPLE_DISTANCE, with label along baseline [not distance?] (measurement) MEAS_ANGLE3(39, 4), // Same as ANGLE3, with label (measurement) MEAS_ANGLE4(40, 4), // Same as ANGLE4, with label (measurement) MEAS_CIRCLE(41, 2), // Same as CIRCLE, with label along radius line from centre (measurement) MEAS_POLYLINE_OPEN(42, -2), // Same as POLYLINE_OPEN, with label to bottom right of top/right-most point (measurement) MEAS_ALIGNED_RECTANGLE(43, 5), // Same as ALIGNED_RECTANGLE, with label inside (measurement) MEAS_RECTANGLE(44, 5), // Same as RECTANGLE, with label to bottom right of top/right-most point (measurement) MEAS_ELLIPSE(45, 5), // Same as ELLIPSE, with label in top of bounding box as for rectangle (measurement) MEAS_POLYLINE_CLOSED(46, -2), // Same as POLYLINE_CLOSED, with label to bottom right of top/right-most point (measurement) MEAS_LENGTH(48, 6), // Same as LENGTH, with label (measurement) MEAS_SPLINE_OPEN(49, -3), // Same as SPLINE_OPEN, with label to bottom right of top/right-most point (measurement) MEAS_SPLINE_CLOSED(50, -3); // Same as SPLINE_CLOSED, with label to bottom right of top/right-most point (measurement) // Types 51,52,53 are a rectangle + text. Text not editable; text not updated (not a measurement?). // Icons suggest time and/or 3D, either Z or 3D shapes. // Types 54, 55. Like 6. // Types 56, 58, 59, 60. No bboxes, no displayed ROI, icon is closed polyline. // Type 57. Like 8. // Types 11, 22, 23, 24, 47, 61, 62, 63, 236. Text, not editable or movable. // This appears to be the default (invalid?) shape. Or more likely, shapes which we haven't created valid metadata for, which are extensions to AxioVision. private static final Map<Integer,FeatureType> lookup = new HashMap<Integer,FeatureType>(); static { for (FeatureType d : EnumSet.allOf(FeatureType.class)) lookup.put(d.getValue(), d); // Alternative mappings: lookup.put(284, MEAS_PROFILE); // Is only the low byte 24? What are the higher bytes? } private int value; private int points; // Number of points. 0=unlimited, negative is >= n private FeatureType (int value, int points) { this.value = value; this.points = points; } public int getValue() { return value; } public int getPoints() { return points; } boolean checkPoints(int points) { boolean status = false; if (this.points == 0) status = true; else if (this.points > 0 && points == this.points) status = true; else if (this.points < 0 && points >= (-this.points)) status = true; return status; } public static FeatureType get(int value) { FeatureType ret = lookup.get(value); if (ret == null) ret = UNKNOWN; return ret; } } /** * Line drawing styles. */ enum DrawStyle { NO_LINE(0), // Transparent SOLID(1), DOT(3), DASH(2), DASH_DOT(4), DASH_DOT_DOT(5); private static final Map<Integer,DrawStyle> lookup = new HashMap<Integer,DrawStyle>(); static { for (DrawStyle d : EnumSet.allOf(DrawStyle.class)) lookup.put(d.getValue(), d); } private int value; private DrawStyle (int value) { this.value = value; } public int getValue() { return value; } public static DrawStyle get(int value) { DrawStyle ret = lookup.get(value); if (ret == null) ret = SOLID; return ret; } } /** * Fill styles. */ enum FillStyle { NONE (1), // No fill SOLID(0), HORIZONTAL_LINE(2), VERTICAL_LINE(3), DOWNWARDS_DIAGONAL(4), UPWARDS_DIAGONAL(5), CROSS(6), // DIAGONAL_CROSS(7); // private static final Map<Integer,FillStyle> lookup = new HashMap<Integer,FillStyle>(); static { for (FillStyle f : EnumSet.allOf(FillStyle.class)) lookup.put(f.getValue(), f); } private int value; private FillStyle (int value) { this.value = value; } public int getValue() { return value; } public static FillStyle get(int value) { FillStyle ret = lookup.get(value); if (ret == null) ret = SOLID; return ret; } } /** * Line ending styles. */ enum LineEndStyle { NONE (1), // No ends ARROWS(5), // Arrowheads (unfilled) END_TICKS(2), // Scale bar end marks (lines) FILLED_ARROWS(3); // Arrowheads (filled) private static final Map<Integer,LineEndStyle> lookup = new HashMap<Integer,LineEndStyle>(); static { for (LineEndStyle f : EnumSet.allOf(LineEndStyle.class)) lookup.put(f.getValue(), f); } private int value; private LineEndStyle (int value) { this.value = value; } public int getValue() { return value; } public static LineEndStyle get(int value) { LineEndStyle ret = lookup.get(value); if (ret == null) ret = ARROWS; return ret; } } /** * Point styles. */ enum PointStyle { NONE (0), // Blank PLUS(2), CROSS(7), SQUARE(1), DIAMOND(3), ASTERISK(4), // 8-spoke asterisk ARROW(5), // > Right, open arrowhead BAR(6), // | Vertical bar FILLED_ARROW(8), // Right, filled arrowhead CROSSHAIR(9); // It does not appear to be possible to rotate arrowheads. The point is at the tip of the arrowhead, not centred as for the others. private static final Map<Integer,PointStyle> lookup = new HashMap<Integer,PointStyle>(); static { for (PointStyle f : EnumSet.allOf(PointStyle.class)) lookup.put(f.getValue(), f); } private int value; private PointStyle (int value) { this.value = value; } public int getValue() { return value; } public static PointStyle get(int value) { PointStyle ret = lookup.get(value); if (ret == null) ret = CROSS; return ret; } } /* * Line ending positions. */ enum LineEndPositions { NONE (0), // No ends LEFT(1), // Left end RIGHT(2), // Right end BOTH(3); // Both left and right ends private static final Map<Integer,LineEndPositions> lookup = new HashMap<Integer,LineEndPositions>(); static { for (LineEndPositions f : EnumSet.allOf(LineEndPositions.class)) lookup.put(f.getValue(), f); } private int value; private LineEndPositions (int value) { this.value = value; } public int getValue() { return value; } public static LineEndPositions get(int value) { LineEndPositions ret = lookup.get(value); if (ret == null) ret = NONE; return ret; } } /* * Text alignment. Justification can be set to left/centre/right. None means that no text is displayed, * and so is a display toggle rather than an alignment settings. This turns off display of the bounding * rectangle for the text type. */ enum TextAlignment { LEFT(0), CENTER(1), RIGHT(2), NONE(3); private static final Map<Integer,TextAlignment> lookup = new HashMap<Integer,TextAlignment>(); static { for (TextAlignment f : EnumSet.allOf(TextAlignment.class)) lookup.put(f.getValue(), f); } private int value; private TextAlignment (int value) { this.value = value; } public int getValue() { return value; } public static TextAlignment get(int value) { TextAlignment ret = lookup.get(value); if (ret == null) ret = LEFT; return ret; } } /* * Character sets. Mapping from <windows.h> values to Java charset names. Not all mappings are supported. * Pages not representable in unicode will get a null Charset. */ enum Charset { ANSI(0,"windows-1252"), MAC_CHARSET(77,"MacRoman"), SHIFTJIS_CHARSET(128,"x-MS932_0213"), HANGUL_CHARSET(129,"x-windows-949"), GB2313_CHARSET(134,"x-mswin-936"), CHINESEBIG5_CHARSET(136,"x-windows-950"), GREEK_CHARSET(161,"windows-1253"), TURKISH_CHARSET(162,"windows-1254"), VIETNAMESE_CHARSET(163,"CP-1258"), HEBREW_CHARSET(177,"windows-1255"), ARABIC_CHARSET(178,"windows-1256"), BALTIC_CHARSET(186,"windows-1257"), RUSSIAN_CHARSET(204,"windows-1251"), THAI_CHARSET(222,"x-windows-874"), EASTEUROPE_CHARSET(238,"windows-1250"); private static final Map<Integer,Charset> lookup = new HashMap<Integer,Charset>(); static { for (Charset f : EnumSet.allOf(Charset.class)) lookup.put(f.getValue(), f); } private int value; String name; private Charset (int value, String name) { this.value = value; this.name = name; } public int getValue() { return value; } public String getName() { return name; } public static Charset get(int value) { Charset ret = lookup.get(value); if (ret == null) ret = ANSI; return ret; } } /* * Colours (in AxioVision UI; not represented in output except as RGB values): * black 0/0/0 * white 255/255/255 * dark grey 64/64/64 * bright grey 224/224/224 * grey 128/128/128 * silver 192/192/192 * maroon 128/0/0 * red 255/0/0 * olive 128/128/0 * yellow 255/255/0 * green 0/128/0 * lime 0/255/0 * teal 0/128/128 * aqua 0/255/255 * navy 0/0/128 * blue 0/0/255 * purple 128/0/128 * fuschia 255/0/255 * */ /** * Shape class representing the metadata within an AxioVision Shape ROI */ class Shape { int id = 0; // Shape number <Key> FeatureType type = FeatureType.UNKNOWN; int unknown1, unknown2, unknown3; // Pos 4-15 // Bounding box (pixels from top left) int x1 = 0, y1 = 0, x2 = 0, y2 = 0, width = 0, height = 0; int unknown4, unknown5, unknown6, unknown7; // Pos 32-47. 38-40 is probably a colour. // From <ShapeAttributes>, typically an array of comma-separated uint8 numbers. First number is the total number of elements. // Drawing settings: byte fb = (byte) (0xFF&0xFF); int fillColour = parseColor(fb, fb,fb); // 48-50 int textColour = parseColor(fb, fb,fb); // 52-54 int drawColour = parseColor(fb, fb,fb); // 56-58 int lineWidth = 1; // Limited to 0,1,2,3,4,5,6,7,8,10,15,20,25,30 (AxioVision interface) DrawStyle drawStyle = DrawStyle.NO_LINE; // Line drawing style FillStyle fillStyle = FillStyle.NONE; // Fill style int unknown8; // 72-75 int unknown10, unknown11, unknown12; // Pos 96-111 int unknown13, unknown14, unknown15, unknown16; // Pos 112-127 int unknown17, unknown18, unknown19; // Pos 128-135, 140-143 LineEndStyle lineEndStyle = LineEndStyle.NONE; // Line ending style PointStyle pointStyle = PointStyle.CROSS; // Line ending style int lineEndSize = 10; // Line ending shape size (pixels). Also used for point sizes. LineEndPositions lineEndPositions = LineEndPositions.NONE; // Line ending positions // Font settings: String fontName; int fontSize = 10; int fontWeight = 300; boolean bold = false; boolean italic = false; boolean underline = false; boolean strikeout = false; Charset charset = Charset.ANSI; TextAlignment textAlignment= TextAlignment.LEFT; //int zpos; // Z position of annotation (relative to others?) // Label settings: String name; // Annotation name (UI only). String text; // Text displayed as part of the annotation (e.g. measurement value or label). Tag tagID; // Set if displaying a tag name. Note Text will automatically include the tag name. boolean displayTag; // Misc: int handleSize; // UI setting? // Points int pointCount = 0; double points[]; public String toString() { String s = new String(); s += " SHAPE: " + id; s += " Type=" + type; s += " Unknown1=" + Long.toHexString(unknown1&0xFFFFFFFFL) + " Unknown2=" + Long.toHexString(unknown2&0xFFFFFFFFL) + " Unknown3=" + Long.toHexString(unknown3&0xFFFFFFFFL) + "\n"; s += " Bbox=" + x1 + "," + y1 + " " + x2 + "," + y2 + "\n"; s += " Unknown4=" + Long.toHexString(unknown4&0xFFFFFFFFL) + " Unknown5=" + Long.toHexString(unknown5&0xFFFFFFFFL) + " Unknown6=" + Long.toHexString(unknown6&0xFFFFFFFFL) + " Unknown7=" + Long.toHexString(unknown7&0xFFFFFFFFL) + "\n"; s += " Unknown8=" + Long.toHexString(unknown8&0xFFFFFFFFL) + "\n"; s += " Unknown10=" + Long.toHexString(unknown10&0xFFFFFFFFL) + " Unknown11=" + Long.toHexString(unknown11&0xFFFFFFFFL) + " Unknown12=" + Long.toHexString(unknown12&0xFFFFFFFFL) + "\n"; s += " Unknown13=" + Long.toHexString(unknown13&0xFFFFFFFFL) + " Unknown14=" + Long.toHexString(unknown14&0xFFFFFFFFL) + " Unknown15=" + Long.toHexString(unknown15&0xFFFFFFFFL) + " Unknown16=" + Long.toHexString(unknown16&0xFFFFFFFFL) + "\n"; s += " Unknown17=" + Long.toHexString(unknown17&0xFFFFFFFFL) + " Unknown18=" + Long.toHexString(unknown18&0xFFFFFFFFL) + " Unknown19=" + Long.toHexString(unknown19&0xFFFFFFFFL) + "\n"; s += " fillColour=" + Long.toHexString(fillColour&0xFFFFFFFFL) + " textColour=" + Long.toHexString((textColour&0xFFFFFFFFL)) + " drawColour=" + Long.toHexString((drawColour&0xFFFFFFFFL)) + "\n"; s += " drawStyle=" + drawStyle + " fillStyle=" + fillStyle + " lineEndStyle=" + lineEndStyle + " lineEndSize=" + lineEndSize + " lineEndPositions=" + lineEndPositions + "\n"; s += "displayTag=" + displayTag + "\n"; s += " fontName=" + fontName + " size="+fontSize + " weight="+fontWeight + " bold="+bold + " italic=" + italic + " underline="+underline + " strikeout="+strikeout + " alignment=" + textAlignment + " charset=" + charset + "\n"; s += " name: " + name + "\n"; s += " text: " + text + "\n"; //s += " Zpos: " + zpos; s += " tagID:" + tagID.getKey() + "\n"; s += " handleSize:" + handleSize + "\n"; s += " pointCount:" + pointCount + "\n "; for (double point : points) s+=point + ", "; s+= "\n"; return s; } } class Layer { int key; // Layer number String flags; // Unknown. public ArrayList<Shape> shapes = new ArrayList<Shape>(); // List of shape objects, displayed deepest first, topmost last. public String toString() { String s = new String(); s += "LAYER: " + key + "\n"; for (Shape shape : shapes) { s += shape; } return s; } } // TODO: Replace me with a proper Color class when available. protected static int parseColor(byte r, byte g, byte b) { return ((r&0xFF) << 24) | ((g&0xFF) << 16) | ((b&0xFF) << 8); } }
package com.crawljax.browser; import org.openqa.selenium.By; import com.crawljax.core.CrawljaxException; import com.crawljax.core.state.Eventable; import com.crawljax.core.state.Identification; import com.crawljax.forms.FormInput; /** * Real Empty class for place holding {@link EmbeddedBrowser} in UnitTests. There is absolutely NO * contents in this class other than the required methods which performs NOTHING! (Returning false * in boolean case, null otherwise) * * @author Stefan Lenselink <S.R.Lenselink@student.tudelft.nl> * @version $Id$ */ public class DummyBrowser implements EmbeddedBrowser { @Override public void close() { } @Override public void closeOtherWindows() { } @Override public Object executeJavaScript(String script) throws CrawljaxException { return null; } @Override public boolean fireEvent(Eventable event) throws CrawljaxException { return false; } @Override public String getCurrentUrl() { return null; } @Override public String getDom() throws CrawljaxException { return null; } @Override public String getDomWithoutIframeContent() throws CrawljaxException { return null; } @Override public void goBack() { } @Override public void goToUrl(String url) throws CrawljaxException { } @Override public boolean input(Eventable eventable, String text) throws CrawljaxException { return false; } @Override public boolean isVisible(By locater) { return false; } @Override public EmbeddedBrowser clone() { return new DummyBrowser(); } @Override public FormInput getInputWithRandomValue(FormInput inputForm) { return null; } @Override public String getFrameDom(String iframeIdentification) { return null; } @Override public boolean elementExists(Identification identification) { return false; } }
package retrobox.utils; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; import android.app.Activity; import android.os.AsyncTask; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import retrobox.content.LoginInfo; import retrobox.content.SaveStateInfo; import retrobox.fileselector.FilesPanel; import xtvapps.core.AndroidFonts; import xtvapps.core.Callback; import xtvapps.core.SimpleCallback; import xtvapps.core.Utils; import xtvapps.core.content.KeyValue; import xtvapps.vfile.VirtualFile; public class RetroBoxDialog { protected static final String LOGTAG = RetroBoxDialog.class.getSimpleName(); private static final int DIALOG_OPENING_THRESHOLD = 800; private static Callback<String> cbListDialogDismiss = null; private static SimpleCallback cbGamepadDialog = null; private static String preselected = null; private static long openTimeStart = 0; public static void showAlert(final Activity activity, String message) { showAlertAsk(activity, null, message, null, null, null, null); } public static void showAlert(final Activity activity, String message, final SimpleCallback callback) { showAlertAsk(activity, null, message, null, null, callback, null); } public static void showAlert(final Activity activity, String title, String message) { showAlertAsk(activity, title, message, null, null, null, null); } public static void showAlert(final Activity activity, String title, String message, final SimpleCallback callback) { showAlertAsk(activity, title, message, null, null, callback, null); } public static void showAlertAsk(final Activity activity, String message, String optYes, String optNo, final SimpleCallback callback) { showAlertAsk(activity, null, message, optYes, optNo, callback, null); } public static void showAlertAsk(final Activity activity, String message, String optYes, String optNo, final SimpleCallback callbackYes, final SimpleCallback callbackNo) { showAlertAsk(activity, null, message, optYes, optNo, callbackYes, callbackNo); } public static void showException(final Activity activity, Exception e, SimpleCallback callback) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Throwable cause = e.getCause(); if (cause!=null) { cause.printStackTrace(pw); } else { e.printStackTrace(pw); } final TextView text = (TextView)activity.findViewById(R.id.txtDialogAction); text.setTextSize(12); String msg = e.toString() + "\n" + e.getMessage() + "\n" + sw.toString(); showAlert(activity, "Error", msg, callback); } public static void showAlertAsk(final Activity activity, String title, String message, String optYes, String optNo, final SimpleCallback callback, final SimpleCallback callbackNo) { activity.findViewById(R.id.modal_dialog_actions).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_actions, new SimpleCallback(){ @Override public void onResult() { if (callback!=null) { callback.onError(); callback.onFinally(); } } }); } }); TextView txtMessage = (TextView)activity.findViewById(R.id.txtDialogAction); txtMessage.setText(message); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogActionTitle); if (Utils.isEmptyString(title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(title); txtTitle.setVisibility(View.VISIBLE); } final Button btnYes = (Button)activity.findViewById(R.id.btnDialogActionPositive); final Button btnNo = (Button)activity.findViewById(R.id.btnDialogActionNegative); if (Utils.isEmptyString(optYes)) optYes = "OK"; btnYes.setText(optYes); btnYes.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_actions, callback); } }); final boolean hasNoButton = !Utils.isEmptyString(optNo); if (hasNoButton) { btnNo.setVisibility(View.VISIBLE); btnNo.setText(optNo); btnNo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_actions, new SimpleCallback() { @Override public void onResult() { if (callbackNo!=null) callbackNo.onResult(); if (callback!=null) callback.onError(); if (callbackNo!=null) callbackNo.onFinally(); if (callback!=null) callback.onFinally(); } }); } }); } else { btnNo.setVisibility(View.GONE); } openDialog(activity, R.id.modal_dialog_actions, new SimpleCallback(){ @Override public void onResult() { Button activeButton = hasNoButton?btnNo:btnYes; activeButton.setFocusable(true); activeButton.setFocusableInTouchMode(true); activeButton.requestFocus(); } }); } public static void showAlertCustom(final Activity activity, int viewResourceId, Callback<View> customViewCallback, final Callback<View> customViewFocusCallback, String optYes, String optNo, final SimpleCallback callback, final SimpleCallback callbackNo) { activity.findViewById(R.id.modal_dialog_custom).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_custom, new SimpleCallback(){ @Override public void onResult() { if (callback!=null) { callback.onError(); callback.onFinally(); } } }); } }); ViewGroup container = (ViewGroup)activity.findViewById(R.id.modal_dialog_custom_container); container.removeAllViews(); LayoutInflater layoutInflater = activity.getLayoutInflater(); View customView = layoutInflater.inflate(viewResourceId, container); if (customViewCallback!=null) customViewCallback.onResult(customView); final Button btnYes = (Button)activity.findViewById(R.id.btnDialogCustomPositive); final Button btnNo = (Button)activity.findViewById(R.id.btnDialogCustomNegative); final boolean hasNoButton = !Utils.isEmptyString(optNo); final boolean hasButtons = optYes != null || optNo != null; View actions = activity.findViewById(R.id.modal_dialog_custom_buttons); if (!hasButtons) { actions.setVisibility(View.GONE); } else { actions.setVisibility(View.VISIBLE); if (Utils.isEmptyString(optYes)) optYes = "OK"; btnYes.setText(optYes); btnYes.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_custom, new SimpleCallback() { @Override public void onResult() { if (callback!=null) { callback.onResult(); callback.onFinally(); } } }); } }); if (hasNoButton) { btnNo.setVisibility(View.VISIBLE); btnNo.setText(optNo); btnNo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_custom, new SimpleCallback() { @Override public void onResult() { if (callbackNo!=null) callbackNo.onResult(); if (callback!=null) callback.onError(); if (callbackNo!=null) callbackNo.onFinally(); if (callback!=null) callback.onFinally(); } }); } }); } else { btnNo.setVisibility(View.GONE); } } openDialog(activity, R.id.modal_dialog_custom, new SimpleCallback(){ @Override public void onResult() { if (customViewFocusCallback!=null) { customViewFocusCallback.onResult(activity.findViewById(R.id.modal_dialog_custom)); } else { if (hasButtons) { Button activeButton = hasNoButton?btnNo:btnYes; activeButton.setFocusable(true); activeButton.setFocusableInTouchMode(true); activeButton.requestFocus(); } } } }); } public static void showLogin(final Activity activity, String title, String user, String password, String optLogin, String optCancel, final Callback<LoginInfo> callback) { activity.findViewById(R.id.modal_dialog_login).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_login, new SimpleCallback(){ @Override public void onResult() { if (callback!=null) { callback.onError(); callback.onFinally(); } } }); } }); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogLogin); if (Utils.isEmptyString(title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(title); txtTitle.setVisibility(View.VISIBLE); } final SimpleCallback wrapCallback = new SimpleCallback() { @Override public void onResult() { EditText txtUser = (EditText)activity.findViewById(R.id.txtDialogLoginUser); EditText txtPass = (EditText)activity.findViewById(R.id.txtDialogLoginPassword); LoginInfo loginInfo = new LoginInfo(); loginInfo.user = txtUser.getText().toString(); loginInfo.password = txtPass.getText().toString(); callback.onResult(loginInfo); callback.onFinally(); } @Override public void onError() { callback.onError(); } @Override public void onFinally() { callback.onFinally(); } }; final Button btnYes = (Button)activity.findViewById(R.id.btnDialogLoginPositive); final Button btnNo = (Button)activity.findViewById(R.id.btnDialogLoginNegative); if (!Utils.isEmptyString(optLogin)) { btnYes.setText(optLogin); } if (!Utils.isEmptyString(optCancel)) { btnNo.setText(optCancel); } btnYes.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_login, wrapCallback); } }); btnNo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_login, new SimpleCallback() { @Override public void onResult() { if (callback!=null) callback.onError(); if (callback!=null) callback.onFinally(); } }); } }); openDialog(activity, R.id.modal_dialog_login, new SimpleCallback(){ @Override public void onResult() { activity.findViewById(R.id.txtDialogLoginUser).requestFocus(); } }); } private static void dismissGamepadDialog(Activity activity, SimpleCallback callback) { closeDialog(activity, R.id.modal_dialog_gamepad, callback); } // ingame gamepad dialog has fixed labels, and alwas calls callback on close public static void showGamepadDialogIngame(final Activity activity, GamepadInfoDialog dialog, final SimpleCallback callback) { dialog.updateGamepadVisible(activity); activity.findViewById(R.id.modal_dialog_gamepad).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismissGamepadDialog(activity, callback); } }); openDialog(activity, R.id.modal_dialog_gamepad, null); } // this is called by retrobox client: // * it can be cancelled // * if it has a callback, call it and then hide the dialog (called when starting a game) public static void showGamepadDialog(final Activity activity, GamepadInfoDialog dialog, String[] labels, String textTop, String textBottom, SimpleCallback callback) { cbGamepadDialog = callback; activity.findViewById(R.id.modal_dialog_gamepad).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (cbGamepadDialog!=null) { cbGamepadDialog.onResult(); cbGamepadDialog = null; activity.runOnUiThread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } setDialogVisible(activity, R.id.modal_dialog_gamepad, false); } }); } else { dismissGamepadDialog(activity, null); } } }); dialog.setLabels(labels); dialog.updateGamepadVisible(activity); dialog.setInfo(textTop, textBottom); openDialog(activity, R.id.modal_dialog_gamepad, null); } public static void showListDialog(final Activity activity, String title, List<ListOption> options, Callback<KeyValue> callback) { showListDialog(activity, title, new ListOptionAdapter(options), callback, null); } public static void showListDialog(final Activity activity, String title, List<ListOption> options, Callback<KeyValue> callback, Callback<String> callbackDismiss) { showListDialog(activity, title, new ListOptionAdapter(options), callback, callbackDismiss); } public static void showListDialog(final Activity activity, String title, final BaseAdapter adapter, Callback<KeyValue> callback) { showListDialog(activity, title, adapter, callback, null); } public static void showListDialog(final Activity activity, String title, final BaseAdapter adapter, final Callback<KeyValue> callback, Callback<String> callbackDismiss) { activity.findViewById(R.id.modal_dialog_list).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_list, new SimpleCallback(){ @Override public void onResult() { callback.onError(); callback.onFinally(); } }); } }); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogListTitle); if (Utils.isEmptyString(title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(title); txtTitle.setVisibility(View.VISIBLE); } TextView txtInfo = (TextView)activity.findViewById(R.id.txtDialogListInfo); txtInfo.setVisibility(View.GONE); preselected = null; cbListDialogDismiss = callbackDismiss; final ListView lv = (ListView)activity.findViewById(R.id.lstDialogList); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> vadapter, View v, int position, long id) { final KeyValue result = (KeyValue)adapter.getItem(position); preselected = result.getKey(); closeDialog(activity, R.id.modal_dialog_list, new SimpleCallback() { @Override public void onResult() { if (callback!=null) { callback.onResult(result); callback.onFinally(); } } }); } }); openDialog(activity, R.id.modal_dialog_list, new SimpleCallback() { @Override public void onResult() { lv.setSelection(0); lv.setFocusable(true); lv.setFocusableInTouchMode(true); lv.requestFocus(); } }); } public static void dismissListDialog(Activity activity) { closeDialog(activity, R.id.modal_dialog_list, new SimpleCallback() { @Override public void onResult() { if (cbListDialogDismiss!=null) cbListDialogDismiss.onResult(preselected); cbListDialogDismiss = null; } }); } public static boolean cancelDialog(Activity activity) { View dialog = getVisibleDialog(activity); if (dialog == null) return false; dialog.performClick(); return true; } private static boolean isVisible(View v) { return v!=null && v.getVisibility() == View.VISIBLE; } private static boolean isVisible(Activity activity, int dialogResourceId) { View dialog = activity.findViewById(dialogResourceId); return dialog !=null && dialog.getVisibility() == View.VISIBLE; } private static View getVisibleDialog(Activity activity) { View sideBar = activity.findViewById(R.id.modal_sidebar); View dialogActions = activity.findViewById(R.id.modal_dialog_actions); View dialogList = activity.findViewById(R.id.modal_dialog_list); View dialogChooser = activity.findViewById(R.id.modal_dialog_chooser); View gamepadDialog = activity.findViewById(R.id.modal_dialog_gamepad); View saveStateDialog = activity.findViewById(R.id.modal_dialog_savestates); View loginDialog = activity.findViewById(R.id.modal_dialog_login); View customDialog = activity.findViewById(R.id.modal_dialog_custom); View dialog = isVisible(gamepadDialog)? gamepadDialog : isVisible(dialogActions)? dialogActions : isVisible(dialogList) ? dialogList : isVisible(dialogChooser) ? dialogChooser : isVisible(saveStateDialog) ? saveStateDialog : isVisible(loginDialog) ? loginDialog : isVisible(customDialog) ? customDialog : isVisible(sideBar) ? sideBar : null; return dialog; } public static boolean isDialogVisible(Activity activity) { return getVisibleDialog(activity) != null; } public static boolean onKeyDown(Activity activity, int keyCode, final KeyEvent event) { // TODO use gamepad mappings //Log.v("RetroBoxDialog", "DOWN keyCode: " + keyCode); return false; } public static boolean onKeyUp(Activity activity, int keyCode, final KeyEvent event) { // TODO use gamepad mappings //Log.v("RetroBoxDialog", "UP keyCode: " + keyCode + " elapsed " + (System.currentTimeMillis() - openTimeStart)); if (keyCode == KeyEvent.KEYCODE_BACK && isDialogVisible(activity)) { if ((System.currentTimeMillis() - openTimeStart) < DIALOG_OPENING_THRESHOLD) { // ignore if this is a key up from a tap on the BACK/SELECT key return true; } cbGamepadDialog = null; cancelDialog(activity); return true; } if (isVisible(activity, R.id.modal_dialog_gamepad)) { cancelDialog(activity); return true; } return false; } private static void openDialog(Activity activity, int dialogResourceId, final SimpleCallback callback) { Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new DecelerateInterpolator()); fadeIn.setDuration(400); final View view = activity.findViewById(dialogResourceId); fadeIn.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { if (callback!=null) callback.onResult(); } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) { view.setVisibility(View.VISIBLE); } }); openTimeStart = System.currentTimeMillis(); view.startAnimation(fadeIn); } private static void closeDialog(Activity activity, int dialogResourceId, final SimpleCallback callback) { Animation fadeOut = new AlphaAnimation(1, 0); fadeOut.setInterpolator(new DecelerateInterpolator()); fadeOut.setDuration(300); final View view = activity.findViewById(dialogResourceId); fadeOut.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.GONE); if (callback!=null) { callback.onResult(); callback.onFinally(); } } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) {} }); view.startAnimation(fadeOut); } public static void showSaveStatesDialog(final Activity activity, String title, final SaveStateSelectorAdapter adapter, final Callback<Integer> callback) { OnClickListener closingClickListener = new OnClickListener() { @Override public void onClick(View v) { closeDialog(activity, R.id.modal_dialog_savestates, new SimpleCallback(){ @Override public void onResult() { adapter.releaseImages(); callback.onError(); callback.onFinally(); } }); } }; activity.findViewById(R.id.modal_dialog_savestates).setOnClickListener(closingClickListener); activity.findViewById(R.id.btnSaveStateCancel).setOnClickListener(closingClickListener); AndroidFonts.setViewFont(activity.findViewById(R.id.txtDialogSaveStatesTitle), RetroBoxUtils.FONT_DEFAULT_B); AndroidFonts.setViewFont(activity.findViewById(R.id.txtDialogSaveStatesInfo), RetroBoxUtils.FONT_DEFAULT_M); AndroidFonts.setViewFont(activity.findViewById(R.id.txtDialogSaveStatesSlot), RetroBoxUtils.FONT_DEFAULT_M); AndroidFonts.setViewFont(activity.findViewById(R.id.btnSaveStateCancel), RetroBoxUtils.FONT_DEFAULT_M); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogSaveStatesTitle); if (Utils.isEmptyString(title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(title); txtTitle.setVisibility(View.VISIBLE); } final TextView txtSlot = (TextView)activity.findViewById(R.id.txtDialogSaveStatesSlot); final TextView txtInfo = (TextView)activity.findViewById(R.id.txtDialogSaveStatesInfo); final Callback<Integer> onSelectCallback = new Callback<Integer>(){ @Override public void onResult(Integer index) { System.out.println("show info " + index); if (index >= 0 && index < adapter.getCount()) { SaveStateInfo info = (SaveStateInfo)adapter.getItem(index); txtSlot.setText(info.getSlotInfo()); txtInfo.setText(info.getInfo()); } else { txtInfo.setText(""); } }}; final GridView grid = (GridView)activity.findViewById(R.id.savestates_grid); grid.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View view, int index, long arg3) { System.out.println("on item selected " + index); onSelectCallback.onResult(index); } @Override public void onNothingSelected(AdapterView<?> arg0) { System.out.println("on nothing selected "); onSelectCallback.onResult(-1); } }); grid.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { System.out.println("on onFocusChange " + hasFocus); if (!hasFocus) { onSelectCallback.onResult(-1); } else { int selected = grid.getSelectedItemPosition(); onSelectCallback.onResult(selected); } } }); grid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) { System.out.println("on click listener"); callback.onResult(index); } }); grid.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int index, long arg3) { System.out.println("on long click listener"); onSelectCallback.onResult(index); return true; } }); AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { adapter.loadImages(); return null; } @Override protected void onPostExecute(Void result) { final GridView grid = (GridView)activity.findViewById(R.id.savestates_grid); grid.setAdapter(adapter); grid.setSelection(getSelectedSaveState(adapter)); openDialog(activity, R.id.modal_dialog_savestates, new SimpleCallback() { @Override public void onResult() { grid.requestFocus(); } }); } }; task.execute(); } private static int getSelectedSaveState(SaveStateSelectorAdapter adapter) { for(int i=0; i<adapter.getCount(); i++) { SaveStateInfo info = (SaveStateInfo)adapter.getItem(i); if (info.isSelected()) { return i; } } return 0; } public static void showSidebar(final Activity activity, final BaseAdapter mainAdapter, final BaseAdapter secondaryAdapter, final Callback<KeyValue> callback) { final ListView lv = (ListView)activity.findViewById(R.id.lstSidebarList); lv.setAdapter(mainAdapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> vadapter, View v, int position, long id) { dismissSidebar(activity); KeyValue result = (KeyValue)mainAdapter.getItem(position); callback.onResult(result); } }); final ListView lvBottom = (ListView)activity.findViewById(R.id.lstSidebarBottom); lvBottom.setAdapter(secondaryAdapter); lvBottom.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> vadapter, View v, int position, long id) { dismissSidebar(activity); KeyValue result = (KeyValue)secondaryAdapter.getItem(position); callback.onResult(result); } }); activity.findViewById(R.id.modal_sidebar).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismissSidebar(activity); } }); lv.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { lv.setItemChecked(-1, false); } } }); lvBottom.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { lvBottom.setItemChecked(-1, false); } } }); openSidebar(activity, lv); } private static void openSidebar(Activity activity, final ListView lv) { setDialogVisible(activity, R.id.modal_sidebar, true); View sidebar = activity.findViewById(R.id.sidebar); AnimationSet animationSet = new AnimationSet(true); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setDuration(500); Animation fadeIn = new AlphaAnimation(0.25f, 1); TranslateAnimation animation = new TranslateAnimation(-sidebar.getWidth(), 0, 0, 0); animationSet.addAnimation(fadeIn); animationSet.addAnimation(animation); sidebar.setAnimation(animationSet); animationSet.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { lv.setSelection(0); lv.setFocusable(true); lv.setFocusableInTouchMode(true); lv.requestFocus(); } }); sidebar.startAnimation(animationSet); } public static void dismissSidebar(final Activity activity) { View sidebar = activity.findViewById(R.id.sidebar); AnimationSet animationSet = new AnimationSet(true); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setDuration(300); Animation fadeIn = new AlphaAnimation(1, 0); TranslateAnimation animation = new TranslateAnimation(0, -sidebar.getWidth(), 0, 0); animationSet.addAnimation(fadeIn); animationSet.addAnimation(animation); animationSet.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { setDialogVisible(activity, R.id.modal_sidebar, false); } }); sidebar.startAnimation(animationSet); } private static void setDialogVisible(Activity activity, int id, boolean visible) { activity.findViewById(id).setVisibility(visible?View.VISIBLE:View.INVISIBLE); } public static class FileChooserConfig { public String title; public VirtualFile initialDir; public List<String> matchList; public Callback<VirtualFile> callback; public Callback<VirtualFile> browseCallback; public boolean isDirOnly; public boolean isDirOptional; } public static void showFileChooserDialog(final Activity activity, final VirtualFile sysRoot, final FileChooserConfig config) { final Callback<VirtualFile> listCallback = new Callback<VirtualFile>() { @Override public void onResult(final VirtualFile result) { closeDialog(activity, R.id.modal_dialog_chooser, new SimpleCallback() { @Override public void onResult() { config.callback.onResult(result); config.callback.onFinally(); } }); } @Override public void onError() { closeDialog(activity, R.id.modal_dialog_chooser, new SimpleCallback(){ @Override public void onResult() { config.callback.onError(); config.callback.onFinally(); } }); } }; activity.findViewById(R.id.modal_dialog_chooser).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listCallback.onError(); } }); TextView txtTitle = (TextView)activity.findViewById(R.id.txtDialogChooserTitle); if (Utils.isEmptyString(config.title)) { txtTitle.setVisibility(View.GONE); } else { txtTitle.setText(config.title); txtTitle.setVisibility(View.VISIBLE); } RetroBoxUtils.runOnBackground(activity, new ThreadedBackgroundTask() { @Override public void onBackground() { if (config.initialDir == null) return; try { if (config.initialDir.exists()) return; } catch (IOException e) { e.printStackTrace(); } config.initialDir = null; } @Override public void onUIThread() { final ListView lv = (ListView)activity.findViewById(R.id.lstDialogChooser); TextView txtStatus1 = (TextView)activity.findViewById(R.id.txtPanelStatus1); TextView txtStatus2 = (TextView)activity.findViewById(R.id.txtPanelStatus2); TextView txtStorage = (TextView)activity.findViewById(R.id.txtStorage); ImageView imgStorage = (ImageView)activity.findViewById(R.id.imgStorage); FilesPanel filesPanel = new FilesPanel(activity, sysRoot, lv, txtStorage, imgStorage, txtStatus1, txtStatus2, listCallback, config); filesPanel.refresh(); openDialog(activity, R.id.modal_dialog_chooser, new SimpleCallback() { @Override public void onResult() { if (lv.getChildCount()>0) { lv.setSelection(0); } lv.setFocusable(true); lv.setFocusableInTouchMode(true); lv.requestFocus(); } }); } }); } }
package org.zstack.compute.vm; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.cascade.CascadeConstant; import org.zstack.core.cascade.CascadeFacade; import org.zstack.core.cloudbus.*; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.thread.ChainTask; import org.zstack.core.thread.SyncTaskChain; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.allocator.AllocateHostDryRunReply; import org.zstack.header.allocator.DesignatedAllocateHostMsg; import org.zstack.header.allocator.HostAllocatorConstant; import org.zstack.header.allocator.HostAllocatorError; import org.zstack.header.configuration.*; import org.zstack.header.core.Completion; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.NopeCompletion; import org.zstack.header.core.ReturnValueCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.host.*; import org.zstack.header.image.ImageConstant.ImageMediaType; import org.zstack.header.image.ImageEO; import org.zstack.header.image.ImageInventory; import org.zstack.header.image.ImageVO; import org.zstack.header.message.*; import org.zstack.header.network.l3.*; import org.zstack.header.storage.primary.CreateTemplateFromVolumeOnPrimaryStorageMsg; import org.zstack.header.storage.primary.CreateTemplateFromVolumeOnPrimaryStorageReply; import org.zstack.header.storage.primary.PrimaryStorageConstant; import org.zstack.header.tag.SystemTagVO; import org.zstack.header.tag.SystemTagVO_; import org.zstack.header.vm.*; import org.zstack.header.vm.ChangeVmMetaDataMsg.AtomicHostUuid; import org.zstack.header.vm.ChangeVmMetaDataMsg.AtomicVmState; import org.zstack.header.vm.VmAbnormalLifeCycleStruct.VmAbnormalLifeCycleOperation; import org.zstack.header.vm.VmInstanceConstant.Params; import org.zstack.header.vm.VmInstanceConstant.VmOperation; import org.zstack.header.vm.VmInstanceDeletionPolicyManager.VmInstanceDeletionPolicy; import org.zstack.header.vm.VmInstanceSpec.HostName; import org.zstack.header.vm.VmInstanceSpec.IsoSpec; import org.zstack.header.volume.*; import org.zstack.identity.AccountManager; import org.zstack.utils.*; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.function.Function; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import javax.persistence.TypedQuery; import java.util.*; import static org.zstack.utils.CollectionDSL.e; import static org.zstack.utils.CollectionDSL.list; import static org.zstack.utils.CollectionDSL.map; public class VmInstanceBase extends AbstractVmInstance { protected static final CLogger logger = Utils.getLogger(VmInstanceBase.class); @Autowired protected CloudBus bus; @Autowired protected DatabaseFacade dbf; @Autowired protected ThreadFacade thdf; @Autowired protected VmInstanceManager vmMgr; @Autowired protected VmInstanceExtensionPointEmitter extEmitter; @Autowired protected VmInstanceNotifyPointEmitter notfiyEmitter; @Autowired protected CascadeFacade casf; @Autowired protected AccountManager acntMgr; @Autowired protected EventFacade evtf; @Autowired protected PluginRegistry pluginRgty; @Autowired protected VmInstanceDeletionPolicyManager deletionPolicyMgr; protected VmInstanceVO self; protected VmInstanceVO originalCopy; protected String syncThreadName; private void checkState(final String hostUuid, final NoErrorCompletion completion) { CheckVmStateOnHypervisorMsg msg = new CheckVmStateOnHypervisorMsg(); msg.setVmInstanceUuids(list(self.getUuid())); msg.setHostUuid(hostUuid); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid); bus.send(msg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { //TODO logger.warn(String.format("unable to check state of the vm[uuid:%s] on the host[uuid:%s], %s. Put the vm to Unknown state", self.getUuid(), hostUuid, reply.getError())); self = dbf.reload(self); changeVmStateInDb(VmInstanceStateEvent.unknown); completion.done(); return; } CheckVmStateOnHypervisorReply r = reply.castReply(); String state = r.getStates().get(self.getUuid()); self = dbf.reload(self); if (VmInstanceState.Running.toString().equals(state)) { self.setHostUuid(hostUuid); changeVmStateInDb(VmInstanceStateEvent.running); } else if (VmInstanceState.Stopped.toString().equals(state)) { changeVmStateInDb(VmInstanceStateEvent.stopped); } else { throw new CloudRuntimeException(String.format("CheckVmStateOnHypervisorMsg should only reprot states[Running or Stopped]," + "but it reports %s for the vm[uuid:%s] on the host[uuid:%s]", state, self.getUuid(), hostUuid)); } completion.done(); } }); } protected void destroy(final VmInstanceDeletionPolicy deletionPolicy, final Completion completion){ if (VmInstanceState.Created == self.getState()) { // the vm is only created in DB, no need to go through normal destroying process completion.success(); return; } final VmInstanceInventory inv = VmInstanceInventory.valueOf(self); VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Destroy); self = changeVmStateInDb(VmInstanceStateEvent.destroying); FlowChain chain = getDestroyVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("destroy-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.getData().put(Params.DeletionPolicy, deletionPolicy); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { if (originalCopy.getState() == VmInstanceState.Running) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self = dbf.reload(self); changeVmStateInDb(VmInstanceStateEvent.unknown); completion.fail(errCode); } } }).start(); } protected VmInstanceVO getSelf() { return self; } protected VmInstanceInventory getSelfInventory() { return VmInstanceInventory.valueOf(self); } public VmInstanceBase(VmInstanceVO vo) { this.self = vo; this.syncThreadName = "Vm-" + vo.getUuid(); this.originalCopy = ObjectUtils.newAndCopy(vo, vo.getClass()); } protected VmInstanceVO refreshVO() { return refreshVO(false); } protected VmInstanceVO refreshVO(boolean noException) { VmInstanceVO vo = self; self = dbf.findByUuid(self.getUuid(), VmInstanceVO.class); if (self == null && noException) { return null; } if (self == null) { throw new OperationFailureException(errf.stringToOperationError(String.format("vm[uuid:%s, name:%s] has been deleted", vo.getUuid(), vo.getName()))); } originalCopy = ObjectUtils.newAndCopy(vo, vo.getClass()); return self; } protected FlowChain getCreateVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getCreateVmWorkFlowChain(inv); } protected FlowChain getStopVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getStopVmWorkFlowChain(inv); } protected FlowChain getRebootVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getRebootVmWorkFlowChain(inv); } protected FlowChain getStartVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getStartVmWorkFlowChain(inv); } protected FlowChain getDestroyVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getDestroyVmWorkFlowChain(inv); } protected FlowChain getExpungeVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getExpungeVmWorkFlowChain(inv); } protected FlowChain getMigrateVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getMigrateVmWorkFlowChain(inv); } protected FlowChain getAttachUninstantiatedVolumeWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getAttachUninstantiatedVolumeWorkFlowChain(inv); } protected FlowChain getAttachIsoWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getAttachIsoWorkFlowChain(inv); } protected FlowChain getDetachIsoWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getDetachIsoWorkFlowChain(inv); } protected VmInstanceVO changeVmStateInDb(VmInstanceStateEvent stateEvent) { VmInstanceState bs = self.getState(); final VmInstanceState state = self.getState().nextState(stateEvent); self.setState(state); self = dbf.updateAndRefresh(self); if (bs != state) { logger.debug(String.format("vm[uuid:%s] changed state from %s to %s", self.getUuid(), bs, self.getState())); VmCanonicalEvents.VmStateChangedData data = new VmCanonicalEvents.VmStateChangedData(); data.setVmUuid(self.getUuid()); data.setOldState(bs.toString()); data.setNewState(state.toString()); data.setInventory(getSelfInventory()); evtf.fire(VmCanonicalEvents.VM_FULL_STATE_CHANGED_PATH, data); //TODO: remove this notfiyEmitter.notifyVmStateChange(VmInstanceInventory.valueOf(self), bs, state); } return self; } @Override @MessageSafe public void handleMessage(final Message msg) { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } protected void handleLocalMessage(Message msg) { if (msg instanceof StartNewCreatedVmInstanceMsg) { handle((StartNewCreatedVmInstanceMsg) msg); } else if (msg instanceof StartVmInstanceMsg) { handle((StartVmInstanceMsg) msg); } else if (msg instanceof StopVmInstanceMsg) { handle((StopVmInstanceMsg) msg); } else if (msg instanceof RebootVmInstanceMsg) { handle((RebootVmInstanceMsg) msg); } else if (msg instanceof ChangeVmStateMsg) { handle((ChangeVmStateMsg) msg); } else if (msg instanceof DestroyVmInstanceMsg) { handle((DestroyVmInstanceMsg)msg); } else if (msg instanceof AttachNicToVmMsg) { handle((AttachNicToVmMsg)msg); } else if (msg instanceof CreateTemplateFromVmRootVolumeMsg) { handle((CreateTemplateFromVmRootVolumeMsg) msg); } else if (msg instanceof VmInstanceDeletionMsg) { handle((VmInstanceDeletionMsg) msg); } else if (msg instanceof VmAttachNicMsg) { handle((VmAttachNicMsg) msg); } else if (msg instanceof MigrateVmMsg) { handle((MigrateVmMsg) msg); } else if (msg instanceof DetachDataVolumeFromVmMsg) { handle((DetachDataVolumeFromVmMsg) msg); } else if (msg instanceof AttachDataVolumeToVmMsg) { handle((AttachDataVolumeToVmMsg) msg); } else if (msg instanceof GetVmMigrationTargetHostMsg) { handle((GetVmMigrationTargetHostMsg) msg); } else if (msg instanceof ChangeVmMetaDataMsg) { handle((ChangeVmMetaDataMsg) msg); } else if (msg instanceof LockVmInstanceMsg) { handle((LockVmInstanceMsg) msg); } else if (msg instanceof DetachNicFromVmMsg) { handle((DetachNicFromVmMsg) msg); } else if (msg instanceof VmStateChangedOnHostMsg) { handle((VmStateChangedOnHostMsg) msg); } else if (msg instanceof VmCheckOwnStateMsg) { handle((VmCheckOwnStateMsg) msg); } else if (msg instanceof ExpungeVmMsg) { handle((ExpungeVmMsg) msg); } else if (msg instanceof HaStartVmInstanceMsg) { handle((HaStartVmInstanceMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(final HaStartVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { refreshVO(); HaStartVmJudger judger; try { Class clz = Class.forName(msg.getJudgerClassName()); judger = (HaStartVmJudger) clz.newInstance(); } catch (Exception e) { throw new CloudRuntimeException(e); } final HaStartVmInstanceReply reply = new HaStartVmInstanceReply(); if (!judger.whetherStartVm(getSelfInventory())) { bus.reply(msg, reply); chain.next(); return; } logger.debug(String.format("HaStartVmJudger[%s] says the VM[uuid:%s, name:%s] is qualified for HA start, now we are starting it", judger.getClass(), self.getUuid(), self.getName())); self.setState(VmInstanceState.Stopped); dbf.update(self); startVm(msg, new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "ha-start-vm"; } }); } private void changeVmIp(final String l3Uuid, final String ip, final Completion completion) { final VmNicVO targetNic = CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return l3Uuid.equals(arg.getL3NetworkUuid()) ? arg : null; } }); if (targetNic == null) { throw new OperationFailureException(errf.stringToOperationError( String.format("the vm[uuid:%s] has no nic on the L3 network[uuid:%s]", self.getUuid(), l3Uuid) )); } final FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("change-vm-ip-to-%s-l3-%s-vm-%s", ip, l3Uuid, self.getUuid())); chain.then(new ShareFlow() { UsedIpInventory newIp; String oldIpUuid = targetNic.getUsedIpUuid(); @Override public void setup() { flow(new Flow() { String __name__ = "acquire-new-ip"; @Override public void run(final FlowTrigger trigger, Map data) { AllocateIpMsg amsg = new AllocateIpMsg(); amsg.setL3NetworkUuid(l3Uuid); amsg.setRequiredIp(ip); bus.makeTargetServiceIdByResourceUuid(amsg, L3NetworkConstant.SERVICE_ID, l3Uuid); bus.send(amsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); } else { AllocateIpReply r = reply.castReply(); newIp = r.getIpInventory(); trigger.next(); } } }); } @Override public void rollback(FlowRollback trigger, Map data) { if (newIp != null) { ReturnIpMsg rmsg = new ReturnIpMsg(); rmsg.setL3NetworkUuid(newIp.getL3NetworkUuid()); rmsg.setUsedIpUuid(newIp.getUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, L3NetworkConstant.SERVICE_ID, newIp.getL3NetworkUuid()); bus.send(rmsg); } trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = "change-ip-in-database"; @Override public void run(FlowTrigger trigger, Map data) { targetNic.setUsedIpUuid(newIp.getUuid()); targetNic.setGateway(newIp.getGateway()); targetNic.setNetmask(newIp.getNetmask()); targetNic.setIp(newIp.getIp()); dbf.update(targetNic); trigger.next(); } }); flow(new NoRollbackFlow() { String __name__ = "return-old-ip"; @Override public void run(FlowTrigger trigger, Map data) { ReturnIpMsg rmsg = new ReturnIpMsg(); rmsg.setUsedIpUuid(oldIpUuid); rmsg.setL3NetworkUuid(targetNic.getL3NetworkUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, L3NetworkConstant.SERVICE_ID, targetNic.getL3NetworkUuid()); bus.send(rmsg); trigger.next(); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } private void handle(final ExpungeVmMsg msg) { final ExpungeVmReply reply = new ExpungeVmReply(); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { expunge(msg, new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "expunge-vm"; } }); } private void expunge(Message msg, final Completion completion) { refreshVO(); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } VmInstanceInventory inv = getSelfInventory(); if (inv.getAllVolumes().size() > 1) { throw new CloudRuntimeException(String.format("why the deleted vm[uuid:%s] has data volumes??? %s", self.getUuid(), JSONObjectUtil.toJsonString(inv.getAllVolumes()))); } VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Expunge); FlowChain chain = getExpungeVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("destroy-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.getData().put(Params.DeletionPolicy, VmInstanceDeletionPolicy.Direct); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { dbf.removeCollection(self.getVmNics(), VmNicVO.class); dbf.remove(self); logger.debug(String.format("successfully expunged the vm[uuid:%s]", self.getUuid())); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } private void handle(final VmCheckOwnStateMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { refreshVO(); final VmCheckOwnStateReply reply = new VmCheckOwnStateReply(); if (self.getHostUuid() == null) { // no way to check bus.reply(msg, reply); chain.next(); return; } final CheckVmStateOnHypervisorMsg cmsg = new CheckVmStateOnHypervisorMsg(); cmsg.setVmInstanceUuids(list(self.getUuid())); cmsg.setHostUuid(self.getHostUuid()); bus.makeTargetServiceIdByResourceUuid(cmsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(cmsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply r) { if (!r.isSuccess()) { reply.setError(r.getError()); bus.reply(msg, r); chain.next(); return; } CheckVmStateOnHypervisorReply cr = r.castReply(); String s = cr.getStates().get(self.getUuid()); VmInstanceState state = VmInstanceState.valueOf(s); if (state != self.getState()) { VmStateChangedOnHostMsg vcmsg = new VmStateChangedOnHostMsg(); vcmsg.setHostUuid(self.getHostUuid()); vcmsg.setVmInstanceUuid(self.getUuid()); vcmsg.setStateOnHost(state); bus.makeTargetServiceIdByResourceUuid(vcmsg, VmInstanceConstant.SERVICE_ID, self.getUuid()); bus.send(vcmsg); } bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "check-state"; } }); } private void handle(final VmStateChangedOnHostMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { vmStateChangeOnHost(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("vm-%s-state-change-on-the-host-%s", self.getUuid(), msg.getHostUuid()); } }); } private VmAbnormalLifeCycleOperation getVmAbnormalLifeCycleOperation(String originalHostUuid, String currentHostUuid, VmInstanceState originalState, VmInstanceState currentState) { if (originalState == VmInstanceState.Stopped && currentState == VmInstanceState.Running) { return VmAbnormalLifeCycleOperation.VmRunningOnTheHost; } if (originalState == VmInstanceState.Running && currentState == VmInstanceState.Stopped && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmStoppedOnTheSameHost; } if (VmInstanceState.intermediateStates.contains(originalState) && currentState == VmInstanceState.Running) { return VmAbnormalLifeCycleOperation.VmRunningFromIntermediateState; } if (VmInstanceState.intermediateStates.contains(originalState) && currentState == VmInstanceState.Stopped) { return VmAbnormalLifeCycleOperation.VmStoppedFromIntermediateState; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Running && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmRunningFromUnknownStateHostNotChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Running && !currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmRunningFromUnknownStateHostChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Stopped && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmStoppedOnTheSameHost; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Stopped && originalHostUuid == null && currentHostUuid.equals(self.getLastHostUuid())) { return VmAbnormalLifeCycleOperation.VmStoppedFromUnknownStateHostNotChanged; } if (originalState == VmInstanceState.Running && originalState == currentState && !currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmMigrateToAnotherHost; } throw new CloudRuntimeException(String.format("unknown VM[uuid:%s] abnormal state combination[original state: %s, current state: %s, original host:%s, current host:%s]", self.getUuid(), originalState, currentState, originalHostUuid, currentHostUuid)); } private void vmStateChangeOnHost(final VmStateChangedOnHostMsg msg, final NoErrorCompletion completion) { refreshVO(); final VmStateChangedOnHostReply reply = new VmStateChangedOnHostReply(); if (msg.getVmStateAtTracingMoment() != null) { // the vm tracer periodically reports vms's state. It catches an old state // before an vm operation(start, stop, reboot, migrate) completes. Ignore this VmInstanceState expected = VmInstanceState.valueOf(msg.getVmStateAtTracingMoment()); if (expected != self.getState()) { bus.reply(msg, reply); completion.done(); return; } } final String originalHostUuid = self.getHostUuid(); final String currentHostUuid = msg.getHostUuid(); final VmInstanceState originalState = self.getState(); final VmInstanceState currentState = VmInstanceState.valueOf(msg.getStateOnHost()); if (originalState == currentState && originalHostUuid != null && currentHostUuid.equals(originalHostUuid)) { logger.debug(String.format("vm[uuid:%s]'s state[%s] is inline with its state on the host[uuid:%s], ignore VmStateChangeOnHostMsg", self.getUuid(), originalState, originalHostUuid)); bus.reply(msg, reply); completion.done(); return; } if (originalState == VmInstanceState.Stopped && currentState == VmInstanceState.Unknown) { bus.reply(msg, reply); completion.done(); return; } final Runnable fireEvent = new Runnable() { @Override public void run() { VmTracerCanonicalEvents.VmStateChangedOnHostData data = new VmTracerCanonicalEvents.VmStateChangedOnHostData(); data.setVmUuid(self.getUuid()); data.setFrom(originalState); data.setTo(self.getState()); data.setOriginalHostUuid(originalHostUuid); data.setCurrentHostUuid(self.getHostUuid()); evtf.fire(VmTracerCanonicalEvents.VM_STATE_CHANGED_PATH, data); } }; if (currentState == VmInstanceState.Unknown) { changeVmStateInDb(VmInstanceStateEvent.unknown); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } VmAbnormalLifeCycleOperation operation = getVmAbnormalLifeCycleOperation(originalHostUuid, currentHostUuid, originalState, currentState); if (operation == VmAbnormalLifeCycleOperation.VmRunningFromUnknownStateHostNotChanged) { // the vm is detected on the host again. It's largely because the host disconnected before // and now reconnected self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.running); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmStoppedFromUnknownStateHostNotChanged) { // the vm comes out of the unknown state to the stopped state // it happens when an operation failure led the vm from the stopped state to the unknown state, // and later on the vm was detected as stopped on the host again self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.stopped); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } List<VmAbnormalLifeCycleExtensionPoint> exts = pluginRgty.getExtensionList(VmAbnormalLifeCycleExtensionPoint.class); VmAbnormalLifeCycleStruct struct = new VmAbnormalLifeCycleStruct(); struct.setCurrentHostUuid(currentHostUuid); struct.setCurrentState(currentState); struct.setOriginalHostUuid(originalHostUuid); struct.setOriginalState(originalState); struct.setVmInstance(getSelfInventory()); struct.setOperation(operation); logger.debug(String.format("the vm[uuid:%s]'s state changed abnormally on the host[uuid:%s], ZStack is going to take the operation[%s]," + "[original state: %s, current state: %s, original host: %s, current host:%s]", self.getUuid(), currentHostUuid, operation, originalState, currentState, originalHostUuid, currentHostUuid)); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("handle-abnormal-lifecycle-of-vm-%s", self.getUuid())); chain.getData().put(Params.AbnormalLifeCycleStruct, struct); chain.allowEmptyFlow(); for (VmAbnormalLifeCycleExtensionPoint ext : exts) { Flow flow = ext.createVmAbnormalLifeCycleHandlingFlow(struct); chain.then(flow); } chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { if (currentState == VmInstanceState.Running) { self.setHostUuid(currentHostUuid); changeVmStateInDb(VmInstanceStateEvent.running); } else if (currentState == VmInstanceState.Stopped) { self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.stopped); } fireEvent.run(); bus.reply(msg, reply); completion.done(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { //TODO logger.warn(String.format("failed to handle abnormal lifecycle of the vm[uuid:%s, original state: %s, current state:%s," + "original host: %s, current host: %s], %s", self.getUuid(), originalState, currentState, originalHostUuid, currentHostUuid, errCode)); reply.setError(errCode); bus.reply(msg, reply); completion.done(); } }).start(); } private String buildUserdata() { String userdata = VmSystemTags.USERDATA.getTokenByResourceUuid(self.getUuid(), VmSystemTags.USERDATA_TOKEN); if (userdata != null) { return userdata; } String sshKey = VmSystemTags.SSHKEY.getTokenByResourceUuid(self.getUuid(), VmSystemTags.SSHKEY_TOKEN); String rootPassword = VmSystemTags.ROOT_PASSWORD.getTokenByResourceUuid(self.getUuid(), VmSystemTags.ROOT_PASSWORD_TOKEN); if (sshKey == null && rootPassword == null) { return null; } StringBuilder sb = new StringBuilder("#cloud-config"); if (sshKey != null) { sb.append("\nssh_authorized_keys:"); sb.append(String.format("\n - %s", sshKey)); sb.append("\ndisable_root: false"); } if (rootPassword != null) { sb.append("\nchpasswd:"); sb.append("\n list: |"); sb.append(String.format("\n root:%s", rootPassword)); sb.append("\n expire: False"); } return sb.toString(); } private void handle(final DetachNicFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final DetachNicFromVmReply reply = new DetachNicFromVmReply(); refreshVO(); if (self.getState() == VmInstanceState.Destroyed) { // the cascade framework may send this message when // the vm has been destroyed logger.debug(String.format("ignore detaching nic as the VM[uuid:%s] is deleted", self.getUuid())); bus.reply(msg, reply); chain.next(); return; } final ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { reply.setError(allowed); bus.reply(msg, reply); chain.next(); return; } detachNic(msg.getVmNicUuid(), new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "detach-nic"; } }); } private void handle(final LockVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { logger.debug(String.format("locked vm[uuid:%s] for %s", self.getUuid(), msg.getReason())); evtf.on(LockResourceMessage.UNLOCK_CANONICAL_EVENT_PATH, new AutoOffEventCallback() { @Override public boolean run(Map tokens, Object data) { if (msg.getUnlockKey().equals(data)) { logger.debug(String.format("unlocked vm[uuid:%s] that was locked by %s", self.getUuid(), msg.getReason())); chain.next(); return true; } return false; } }); LockVmInstanceReply reply = new LockVmInstanceReply(); bus.reply(msg, reply); } @Override public String getName() { return String.format("lock-vm-%s", self.getUuid()); } }); } private void handle(final ChangeVmMetaDataMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { changeMetaData(msg); chain.next(); } @Override public String getName() { return String.format("change-meta-data-of-vm-%s", self.getUuid()); } }); } private void changeMetaData(ChangeVmMetaDataMsg msg) { ChangeVmMetaDataReply reply = new ChangeVmMetaDataReply(); refreshVO(); if (self == null) { bus.reply(msg, reply); return; } AtomicVmState s = msg.getState(); AtomicHostUuid h = msg.getHostUuid(); if (msg.isNeedHostAndStateBothMatch()) { if (s != null && h != null && s.getExpected() == self.getState()) { if ((h.getExpected() == null && self.getHostUuid() == null) || (h.getExpected() != null && h.getExpected().equals(self.getHostUuid()))) { changeVmStateInDb(s.getValue().getDrivenEvent()); reply.setChangeStateDone(true); self.setHostUuid(h.getValue()); dbf.update(self); reply.setChangeHostUuidDone(true); } } } else { if (s != null && s.getExpected() == self.getState()) { changeVmStateInDb(s.getValue().getDrivenEvent()); reply.setChangeStateDone(true); } if (h != null) { if ((h.getExpected() == null && self.getHostUuid() == null) || (h.getExpected() != null && h.getExpected().equals(self.getHostUuid()))) { self.setHostUuid(h.getValue()); dbf.update(self); reply.setChangeHostUuidDone(true); } } } bus.reply(msg, reply); } private void getVmMigrationTargetHost(Message msg, final ReturnValueCompletion<List<HostInventory>> completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.MIGRATE_ERROR); if (allowed != null) { completion.fail(allowed); return; } final DesignatedAllocateHostMsg amsg = new DesignatedAllocateHostMsg(); amsg.setCpuCapacity(self.getCpuNum() * self.getCpuSpeed()); amsg.setMemoryCapacity(self.getMemorySize()); amsg.getAvoidHostUuids().add(self.getHostUuid()); if (msg instanceof GetVmMigrationTargetHostMsg) { GetVmMigrationTargetHostMsg gmsg = (GetVmMigrationTargetHostMsg) msg; if (gmsg.getAvoidHostUuids() != null) { amsg.getAvoidHostUuids().addAll(gmsg.getAvoidHostUuids()); } } amsg.setVmInstance(VmInstanceInventory.valueOf(self)); amsg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID)); amsg.setAllocatorStrategy(HostAllocatorConstant.MIGRATE_VM_ALLOCATOR_TYPE); amsg.setVmOperation(VmOperation.Migrate.toString()); amsg.setL3NetworkUuids(CollectionUtils.transformToList(self.getVmNics(), new Function<String, VmNicVO>() { @Override public String call(VmNicVO arg) { return arg.getL3NetworkUuid(); } })); amsg.setDryRun(true); bus.send(amsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply re) { if (!re.isSuccess()) { if (HostAllocatorError.NO_AVAILABLE_HOST.toString().equals(re.getError().getCode())) { completion.success(new ArrayList<HostInventory>()); } else { completion.fail(re.getError()); } } else { completion.success(((AllocateHostDryRunReply) re).getHosts()); } } }); } private void handle(final GetVmMigrationTargetHostMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final GetVmMigrationTargetHostReply reply = new GetVmMigrationTargetHostReply(); getVmMigrationTargetHost(msg, new ReturnValueCompletion<List<HostInventory>>(msg, chain) { @Override public void success(List<HostInventory> returnValue) { reply.setHosts(returnValue); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return String.format("get-migration-target-host-for-vm-%s", self.getUuid()); } }); } private void handle(final AttachDataVolumeToVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { attachVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("attach-volume-%s-to-vm-%s", msg.getVolume().getUuid(), msg.getVmInstanceUuid()); } }); } private void handle(final DetachDataVolumeFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { detachVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("detach-volume-%s-from-vm-%s", msg.getVolume().getUuid(), msg.getVmInstanceUuid()); } }); } private void handle(final MigrateVmMsg msg) { final MigrateVmReply reply = new MigrateVmReply(); thdf.chainSubmit(new ChainTask() { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { migrateVm(msg, new Completion(chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return String.format("migrate-vm-%s", self.getUuid()); } }); } private void attachNic(final Message msg, final String l3Uuid, final ReturnValueCompletion<VmNicInventory> completion) { thdf.chainSubmit(new ChainTask(completion) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { completion.fail(allowed); return; } class SetDefaultL3Network { boolean isSet = false; void set() { if (self.getDefaultL3NetworkUuid() == null) { self.setDefaultL3NetworkUuid(l3Uuid); self = dbf.updateAndRefresh(self); isSet = true; } } void rollback() { if (isSet) { self.setDefaultL3NetworkUuid(null); dbf.update(self); } } } final SetDefaultL3Network setDefaultL3Network = new SetDefaultL3Network(); setDefaultL3Network.set(); final VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.AttachNic); spec.setVmInventory(VmInstanceInventory.valueOf(self)); L3NetworkVO l3vo = dbf.findByUuid(l3Uuid, L3NetworkVO.class); spec.setL3Networks(list(L3NetworkInventory.valueOf(l3vo))); spec.setDestNics(new ArrayList<VmNicInventory>()); FlowChain flowChain = FlowChainBuilder.newSimpleFlowChain(); setFlowMarshaller(flowChain); flowChain.setName(String.format("attachNic-vm-%s-l3-%s", self.getUuid(), l3Uuid)); flowChain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); flowChain.then(new VmAllocateNicFlow()); flowChain.then(new VmSetDefaultL3NetworkOnAttachingFlow()); if (self.getState() == VmInstanceState.Running) { flowChain.then(new VmInstantiateResourceOnAttachingNicFlow()); flowChain.then(new VmAttachNicOnHypervisorFlow()); } flowChain.done(new FlowDoneHandler(chain) { @Override public void handle(Map data) { VmNicInventory nic = spec.getDestNics().get(0); completion.success(nic); chain.next(); } }).error(new FlowErrorHandler(chain) { @Override public void handle(ErrorCode errCode, Map data) { setDefaultL3Network.rollback(); completion.fail(errCode); chain.next(); } }).start(); } @Override public String getName() { return String.format("attachNic-vm-%s-l3-%s", self.getUuid(), l3Uuid); } }); } private void handle(final VmAttachNicMsg msg) { final VmAttachNicReply reply = new VmAttachNicReply(); attachNic(msg, msg.getL3NetworkUuid(), new ReturnValueCompletion<VmNicInventory>() { @Override public void success(VmNicInventory nic) { reply.setInventroy(nic); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } protected void doDestroy(final VmInstanceDeletionPolicy deletionPolicy, final Completion completion) { final VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.beforeDestroyVm(inv); destroy(deletionPolicy, new Completion(completion) { @Override public void success() { extEmitter.afterDestroyVm(inv); logger.debug(String.format("successfully deleted vm instance[name:%s, uuid:%s]", self.getName(), self.getUuid())); if (deletionPolicy == VmInstanceDeletionPolicy.Direct) { dbf.remove(getSelf()); } else if (deletionPolicy == VmInstanceDeletionPolicy.Delay) { self = dbf.reload(self); self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.destroyed); } else if (deletionPolicy == VmInstanceDeletionPolicy.Never) { logger.warn(String.format("the vm[uuid:%s] is deleted, but by it's deletion policy[Never], the root volume is not deleted on the primary storage", self.getUuid())); self = dbf.reload(self); self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.destroyed); } completion.success(); } @Override public void fail(ErrorCode errorCode) { extEmitter.failedToDestroyVm(inv, errorCode); logger.debug(String.format("failed to delete vm instance[name:%s, uuid:%s], because %s", self.getName(), self.getUuid(), errorCode)); completion.fail(errorCode); } }); } private void handle(final VmInstanceDeletionMsg msg) { final VmInstanceDeletionReply r = new VmInstanceDeletionReply(); self = dbf.findByUuid(self.getUuid(), VmInstanceVO.class); if (self == null || self.getState() == VmInstanceState.Destroyed) { // the vm has been destroyed, most likely by rollback bus.reply(msg, r); return; } final VmInstanceDeletionPolicy deletionPolicy = msg.getDeletionPolicy() == null ? deletionPolicyMgr.getDeletionPolicy(self.getUuid()) : VmInstanceDeletionPolicy.valueOf(msg.getDeletionPolicy()); destroyHook(deletionPolicy, new Completion(msg) { @Override public void success() { bus.reply(msg, r); } @Override public void fail(ErrorCode errorCode) { r.setError(errorCode); bus.reply(msg, r); } }); } protected void destroyHook(VmInstanceDeletionPolicy deletionPolicy, Completion completion) { doDestroy(deletionPolicy, completion); } private void handle(final RebootVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("reboot-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { rebootVm(msg, chain); } }); } private void rebootVm(final RebootVmInstanceMsg msg, final SyncTaskChain chain) { rebootVm(msg, new Completion(chain) { @Override public void success() { RebootVmInstanceReply reply = new RebootVmInstanceReply(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); reply.setInventory(inv); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { RebootVmInstanceReply reply = new RebootVmInstanceReply(); reply.setError(errf.instantiateErrorCode(VmErrors.REBOOT_ERROR, errorCode)); bus.reply(msg, reply); chain.next(); } }); } private void handle(final StopVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("stop-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { stopVm(msg, chain); } }); } private void stopVm(final StopVmInstanceMsg msg, final SyncTaskChain chain) { stopVm(msg, new Completion(chain) { @Override public void success() { StopVmInstanceReply reply = new StopVmInstanceReply(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); reply.setInventory(inv); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { StopVmInstanceReply reply = new StopVmInstanceReply(); reply.setError(errf.instantiateErrorCode(VmErrors.STOP_ERROR, errorCode)); bus.reply(msg, reply); chain.next(); } }); } private void handle(final StartVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("start-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { startVm(msg, chain); } }); } private void createTemplateFromRootVolume(final CreateTemplateFromVmRootVolumeMsg msg, final SyncTaskChain chain) { boolean callNext = true; try { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { bus.replyErrorByMessageType(msg, allowed); return; } final CreateTemplateFromVmRootVolumeReply reply = new CreateTemplateFromVmRootVolumeReply(); CreateTemplateFromVolumeOnPrimaryStorageMsg cmsg = new CreateTemplateFromVolumeOnPrimaryStorageMsg(); cmsg.setVolumeInventory(msg.getRootVolumeInventory()); cmsg.setBackupStorageUuid(msg.getBackupStorageUuid()); cmsg.setImageInventory(msg.getImageInventory()); bus.makeTargetServiceIdByResourceUuid(cmsg, PrimaryStorageConstant.SERVICE_ID, msg.getRootVolumeInventory().getPrimaryStorageUuid()); bus.send(cmsg, new CloudBusCallBack(chain) { private void fail(ErrorCode errorCode) { String err = String.format("failed to create template from root volume[uuid:%s] on primary storage[uuid:%s]", msg.getRootVolumeInventory().getUuid(), msg.getRootVolumeInventory().getPrimaryStorageUuid()); logger.warn(err); reply.setError(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, err, errorCode)); bus.reply(msg, reply); } @Override public void run(MessageReply r) { if (!r.isSuccess()) { fail(r.getError()); } else { CreateTemplateFromVolumeOnPrimaryStorageReply creply = (CreateTemplateFromVolumeOnPrimaryStorageReply) r; reply.setInstallPath(creply.getTemplateBackupStorageInstallPath()); reply.setFormat(creply.getFormat()); bus.reply(msg, reply); } chain.next(); } }); callNext = false; } finally { if (callNext) { chain.next(); } } } private void handle(final CreateTemplateFromVmRootVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("create-template-from-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { createTemplateFromRootVolume(msg, chain); } }); } private void handle(final AttachNicToVmMsg msg) { ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { bus.replyErrorByMessageType(msg, allowed); return; } AttachNicToVmOnHypervisorMsg amsg = new AttachNicToVmOnHypervisorMsg(); amsg.setVmUuid(self.getUuid()); amsg.setHostUuid(self.getHostUuid()); amsg.setNics(msg.getNics()); bus.makeTargetServiceIdByResourceUuid(amsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(amsg, new CloudBusCallBack(msg) { @Override public void run(MessageReply reply) { if (self.getDefaultL3NetworkUuid() == null) { self.setDefaultL3NetworkUuid(msg.getNics().get(0).getL3NetworkUuid()); self = dbf.updateAndRefresh(self); logger.debug(String.format("set the VM[uuid: %s]'s default L3 network[uuid:%s], as it doen't have one before", self.getUuid(), self.getDefaultL3NetworkUuid())); } AttachNicToVmReply r = new AttachNicToVmReply(); if (!reply.isSuccess()) { r.setError(errf.instantiateErrorCode(VmErrors.ATTACH_NETWORK_ERROR, r.getError())); } bus.reply(msg, r); } }); } private void handle(final DestroyVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("destroy-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain taskChain) { final DestroyVmInstanceReply reply = new DestroyVmInstanceReply(); final String issuer = VmInstanceVO.class.getSimpleName(); VmDeletionStruct s = new VmDeletionStruct(); s.setDeletionPolicy(deletionPolicyMgr.getDeletionPolicy(self.getUuid())); s.setInventory(getSelfInventory()); final List<VmDeletionStruct> ctx = list(s); final FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("destory-vm-%s", self.getUuid())); chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).done(new FlowDoneHandler(msg, taskChain) { @Override public void handle(Map data) { casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion()); bus.reply(msg, reply); taskChain.next(); } }).error(new FlowErrorHandler(msg, taskChain) { @Override public void handle(final ErrorCode errCode, Map data) { reply.setError(errCode); bus.reply(msg, reply); taskChain.next(); } }).start(); } }); } protected void handle(final ChangeVmStateMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("change-vm-state-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { refreshVO(); if (self == null) { // vm has been deleted by previous request // this happens when delete vm request queued before // change state request from vm tracer. // in this case, ignore change state request logger.debug(String.format(String.format("vm[uuid:%s] has been deleted, ignore change vm state request from vm tracer", msg.getVmInstanceUuid()))); chain.next(); return; } changeVmStateInDb(VmInstanceStateEvent.valueOf(msg.getStateEvent())); chain.next(); } }); } protected void setFlowMarshaller(FlowChain chain) { chain.setFlowMarshaller(new FlowMarshaller() { @Override public Flow marshalTheNextFlow(String previousFlowClassName, String nextFlowClassName, FlowChain chain, Map data) { Flow nflow = null; for (MarshalVmOperationFlowExtensionPoint mext : pluginRgty.getExtensionList(MarshalVmOperationFlowExtensionPoint.class)) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); nflow = mext.marshalVmOperationFlow(previousFlowClassName, nextFlowClassName, chain, spec); if (nflow != null) { logger.debug(String.format("a VM[uuid: %s, operation: %s] operation flow[%s] is changed to the flow[%s] by %s", self.getUuid(), spec.getCurrentVmOperation(), nextFlowClassName, nflow.getClass(), mext.getClass())); break; } } return nflow; } }); } protected void selectBootOrder(VmInstanceSpec spec) { if (spec.getCurrentVmOperation() == null) { throw new CloudRuntimeException("selectBootOrder must be called after VmOperation is set"); } if (spec.getCurrentVmOperation() == VmOperation.NewCreate && spec.getDestIso() != null) { spec.setBootOrders(list(VmBootDevice.CdRom.toString())); } else { String order = VmSystemTags.BOOT_ORDER.getTokenByResourceUuid(self.getUuid(), VmSystemTags.BOOT_ORDER_TOKEN); if (order == null) { spec.setBootOrders(list(VmBootDevice.HardDisk.toString())); } else { spec.setBootOrders(list(order.split(","))); } } } protected void startVmFromNewCreate(final StartNewCreatedVmInstanceMsg msg, final SyncTaskChain taskChain) { boolean callNext = true; try { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { bus.replyErrorByMessageType(msg, allowed); return; } ErrorCode preCreated = extEmitter.preStartNewCreatedVm(msg.getVmInstanceInventory()); if (preCreated != null) { bus.replyErrorByMessageType(msg, errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, preCreated)); return; } final VmInstanceSpec spec = new VmInstanceSpec(); spec.setMessage(msg); spec.setVmInventory(msg.getVmInstanceInventory()); if (msg.getL3NetworkUuids() != null && !msg.getL3NetworkUuids().isEmpty()) { SimpleQuery<L3NetworkVO> nwquery = dbf.createQuery(L3NetworkVO.class); nwquery.add(L3NetworkVO_.uuid, Op.IN, msg.getL3NetworkUuids()); List<L3NetworkVO> vos = nwquery.list(); List<L3NetworkInventory> nws = L3NetworkInventory.valueOf(vos); // order L3 networks by the order they specified in the API List<L3NetworkInventory> l3s = new ArrayList<L3NetworkInventory>(nws.size()); for (final String l3Uuid : msg.getL3NetworkUuids()) { L3NetworkInventory l3 = CollectionUtils.find(nws, new Function<L3NetworkInventory, L3NetworkInventory>() { @Override public L3NetworkInventory call(L3NetworkInventory arg) { return arg.getUuid().equals(l3Uuid) ? arg : null; } }); DebugUtils.Assert(l3 != null, "where is the L3???"); l3s.add(l3); } spec.setL3Networks(l3s); } else { spec.setL3Networks(new ArrayList<L3NetworkInventory>(0)); } if (msg.getDataDiskOfferingUuids() != null && !msg.getDataDiskOfferingUuids().isEmpty()) { SimpleQuery<DiskOfferingVO> dquery = dbf.createQuery(DiskOfferingVO.class); dquery.add(DiskOfferingVO_.uuid, SimpleQuery.Op.IN, msg.getDataDiskOfferingUuids()); List<DiskOfferingVO> vos = dquery.list(); // allow create multiple data volume from the same disk offering List<DiskOfferingInventory> disks = new ArrayList<DiskOfferingInventory>(); for (final String duuid : msg.getDataDiskOfferingUuids()) { DiskOfferingVO dvo = CollectionUtils.find(vos, new Function<DiskOfferingVO, DiskOfferingVO>() { @Override public DiskOfferingVO call(DiskOfferingVO arg) { if (duuid.equals(arg.getUuid())) { return arg; } return null; } }); disks.add(DiskOfferingInventory.valueOf(dvo)); } spec.setDataDiskOfferings(disks); } else { spec.setDataDiskOfferings(new ArrayList<DiskOfferingInventory>(0)); } if (msg.getRootDiskOfferingUuid() != null) { DiskOfferingVO rootDisk = dbf.findByUuid(msg.getRootDiskOfferingUuid(), DiskOfferingVO.class); spec.setRootDiskOffering(DiskOfferingInventory.valueOf(rootDisk)); } ImageVO imvo = dbf.findByUuid(spec.getVmInventory().getImageUuid(), ImageVO.class); if (imvo.getMediaType() == ImageMediaType.ISO) { VmSystemTags.ISO.createInherentTag(self.getUuid(), map(e(VmSystemTags.ISO_TOKEN, imvo.getUuid()))); IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(imvo.getUuid()); spec.setDestIso(isoSpec); } spec.getImageSpec().setInventory(ImageInventory.valueOf(imvo)); spec.setCurrentVmOperation(VmOperation.NewCreate); if (self.getZoneUuid() != null || self.getClusterUuid() != null || self.getHostUuid() != null) { spec.setHostAllocatorStrategy(HostAllocatorConstant.DESIGNATED_HOST_ALLOCATOR_STRATEGY_TYPE); } buildHostname(spec); spec.setUserdata(buildUserdata()); selectBootOrder(spec); changeVmStateInDb(VmInstanceStateEvent.starting); extEmitter.beforeStartNewCreatedVm(VmInstanceInventory.valueOf(self)); FlowChain chain = getCreateVmWorkFlowChain(msg.getVmInstanceInventory()); setFlowMarshaller(chain); chain.setName(String.format("create-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(msg, taskChain) { @Override public void handle(final Map data) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); self.setLastHostUuid(spec.getDestHost().getUuid()); self.setHostUuid(spec.getDestHost().getUuid()); self.setClusterUuid(spec.getDestHost().getClusterUuid()); self.setZoneUuid(spec.getDestHost().getZoneUuid()); self.setHypervisorType(spec.getDestHost().getHypervisorType()); self.setRootVolumeUuid(spec.getDestRootVolume().getUuid()); changeVmStateInDb(VmInstanceStateEvent.running); self = dbf.reload(self); logger.debug(String.format("vm[uuid:%s] is running ..", self.getUuid())); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterStartNewCreatedVm(inv); StartNewCreatedVmInstanceReply reply = new StartNewCreatedVmInstanceReply(); reply.setVmInventory(inv); bus.reply(msg, reply); taskChain.next(); } }).error(new FlowErrorHandler(msg, taskChain) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToStartNewCreatedVm(VmInstanceInventory.valueOf(self), errCode); dbf.remove(self); // clean up EO, otherwise API-retry may cause conflict if // the resource uuid is set dbf.eoCleanup(VmInstanceVO.class); StartNewCreatedVmInstanceReply reply = new StartNewCreatedVmInstanceReply(); reply.setError(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, errCode)); bus.reply(msg, reply); taskChain.next(); } }).start(); callNext = false; } finally { if (callNext) { taskChain.next(); } } } protected void handle(final StartNewCreatedVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("create-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { startVmFromNewCreate(msg, chain); } }); } protected void handleApiMessage(APIMessage msg) { if (msg instanceof APIStopVmInstanceMsg) { handle((APIStopVmInstanceMsg) msg); } else if (msg instanceof APIRebootVmInstanceMsg) { handle((APIRebootVmInstanceMsg) msg); } else if (msg instanceof APIDestroyVmInstanceMsg) { handle((APIDestroyVmInstanceMsg) msg); } else if (msg instanceof APIStartVmInstanceMsg) { handle((APIStartVmInstanceMsg) msg); } else if (msg instanceof APIMigrateVmMsg) { handle((APIMigrateVmMsg) msg); } else if (msg instanceof APIAttachL3NetworkToVmMsg) { handle((APIAttachL3NetworkToVmMsg) msg); } else if (msg instanceof APIGetVmMigrationCandidateHostsMsg) { handle((APIGetVmMigrationCandidateHostsMsg) msg); } else if (msg instanceof APIGetVmAttachableDataVolumeMsg) { handle((APIGetVmAttachableDataVolumeMsg) msg); } else if (msg instanceof APIUpdateVmInstanceMsg) { handle((APIUpdateVmInstanceMsg) msg); } else if (msg instanceof APIChangeInstanceOfferingMsg) { handle((APIChangeInstanceOfferingMsg) msg); } else if (msg instanceof APIDetachL3NetworkFromVmMsg) { handle((APIDetachL3NetworkFromVmMsg) msg); } else if (msg instanceof APIGetVmAttachableL3NetworkMsg) { handle((APIGetVmAttachableL3NetworkMsg) msg); } else if (msg instanceof APIAttachIsoToVmInstanceMsg) { handle((APIAttachIsoToVmInstanceMsg) msg); } else if (msg instanceof APIDetachIsoFromVmInstanceMsg) { handle((APIDetachIsoFromVmInstanceMsg) msg); } else if (msg instanceof APIExpungeVmInstanceMsg) { handle((APIExpungeVmInstanceMsg) msg); } else if (msg instanceof APIRecoverVmInstanceMsg) { handle((APIRecoverVmInstanceMsg) msg); } else if (msg instanceof APISetVmBootOrderMsg) { handle((APISetVmBootOrderMsg) msg); } else if (msg instanceof APIGetVmBootOrderMsg) { handle((APIGetVmBootOrderMsg) msg); } else if (msg instanceof APIGetVmConsoleAddressMsg) { handle((APIGetVmConsoleAddressMsg) msg); } else if (msg instanceof APISetVmHostnameMsg) { handle((APISetVmHostnameMsg) msg); } else if (msg instanceof APIDeleteVmHostnameMsg) { handle((APIDeleteVmHostnameMsg) msg); } else if (msg instanceof APISetVmStaticIpMsg) { handle((APISetVmStaticIpMsg) msg); } else if (msg instanceof APIDeleteVmStaticIpMsg) { handle((APIDeleteVmStaticIpMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(final APIDeleteVmStaticIpMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { APIDeleteVmStaticIpEvent evt = new APIDeleteVmStaticIpEvent(msg.getId()); VmSystemTags.STATIC_IP.delete(self.getUuid(), TagUtils.tagPatternToSqlPattern(VmSystemTags.STATIC_IP.instantiateTag( map(e(VmSystemTags.STATIC_IP_L3_UUID_TOKEN, msg.getL3NetworkUuid())) ))); bus.publish(evt); chain.next(); } @Override public String getName() { return "delete-static-ip"; } }); } private void handle(final APISetVmStaticIpMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { setStaticIp(msg, new NoErrorCompletion(msg, chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "set-static-ip"; } }); } private void setStaticIp(final APISetVmStaticIpMsg msg, final NoErrorCompletion completion) { refreshVO(); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } SimpleQuery<SystemTagVO> q = dbf.createQuery(SystemTagVO.class); q.select(SystemTagVO_.uuid); q.add(SystemTagVO_.resourceType, Op.EQ, VmInstanceVO.class.getSimpleName()); q.add(SystemTagVO_.resourceUuid, Op.EQ, self.getUuid()); q.add(SystemTagVO_.tag, Op.LIKE, TagUtils.tagPatternToSqlPattern(VmSystemTags.STATIC_IP.instantiateTag( map(e(VmSystemTags.STATIC_IP_L3_UUID_TOKEN, msg.getL3NetworkUuid())) ))); final String tagUuid = q.findValue(); final APISetVmStaticIpEvent evt = new APISetVmStaticIpEvent(msg.getId()); changeVmIp(msg.getL3NetworkUuid(), msg.getIp(), new Completion(msg, completion) { @Override public void success() { if (tagUuid == null) { VmSystemTags.STATIC_IP.createTag(self.getUuid(), map( e(VmSystemTags.STATIC_IP_L3_UUID_TOKEN, msg.getL3NetworkUuid()), e(VmSystemTags.STATIC_IP_TOKEN, msg.getIp()) )); } else { VmSystemTags.STATIC_IP.updateByTagUuid(tagUuid, VmSystemTags.STATIC_IP.instantiateTag(map( e(VmSystemTags.STATIC_IP_L3_UUID_TOKEN, msg.getL3NetworkUuid()), e(VmSystemTags.STATIC_IP_TOKEN, msg.getIp()) ))); } bus.publish(evt); completion.done(); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); completion.done(); } }); } private void handle(APIDeleteVmHostnameMsg msg) { APIDeleteVmHostnameEvent evt = new APIDeleteVmHostnameEvent(msg.getId()); VmSystemTags.HOSTNAME.delete(self.getUuid()); bus.publish(evt); } private void handle(APISetVmHostnameMsg msg) { if (!VmSystemTags.HOSTNAME.hasTag(self.getUuid())) { VmSystemTags.HOSTNAME.createTag(self.getUuid(), map( e(VmSystemTags.HOSTNAME_TOKEN, msg.getHostname()) )); } else { VmSystemTags.HOSTNAME.update(self.getUuid(), VmSystemTags.HOSTNAME.instantiateTag( map(e(VmSystemTags.HOSTNAME_TOKEN, msg.getHostname())) )); } APISetVmHostnameEvent evt = new APISetVmHostnameEvent(msg.getId()); bus.publish(evt); } private void handle(final APIGetVmConsoleAddressMsg msg) { ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } final APIGetVmConsoleAddressReply creply = new APIGetVmConsoleAddressReply(); GetVmConsoleAddressFromHostMsg hmsg = new GetVmConsoleAddressFromHostMsg(); hmsg.setHostUuid(self.getHostUuid()); hmsg.setVmInstanceUuid(self.getUuid()); bus.makeTargetServiceIdByResourceUuid(hmsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(hmsg, new CloudBusCallBack(msg) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { creply.setError(reply.getError()); } else { GetVmConsoleAddressFromHostReply hr = reply.castReply(); creply.setHostIp(hr.getHostIp()); creply.setPort(hr.getPort()); creply.setProtocol(hr.getProtocol()); } bus.reply(msg, creply); } }); } private void handle(APIGetVmBootOrderMsg msg) { APIGetVmBootOrderReply reply = new APIGetVmBootOrderReply(); String order = VmSystemTags.BOOT_ORDER.getTokenByResourceUuid(self.getUuid(), VmSystemTags.BOOT_ORDER_TOKEN); if (order == null) { reply.setOrder(list(VmBootDevice.HardDisk.toString())); } else { reply.setOrder(list(order.split(","))); } bus.reply(msg, reply); } private void handle(APISetVmBootOrderMsg msg) { APISetVmBootOrderEvent evt = new APISetVmBootOrderEvent(msg.getId()); if (msg.getBootOrder() != null) { VmSystemTags.BOOT_ORDER.recreateInherentTag(self.getUuid(), map(e(VmSystemTags.BOOT_ORDER_TOKEN, StringUtils.join(msg.getBootOrder(), ",")))); } else { VmSystemTags.BOOT_ORDER.deleteInherentTag(self.getUuid()); } evt.setInventory(getSelfInventory()); bus.publish(evt); } private void recoverVm(final Completion completion) { final VmInstanceInventory vm = getSelfInventory(); final List<RecoverVmExtensionPoint> exts = pluginRgty.getExtensionList(RecoverVmExtensionPoint.class); for (RecoverVmExtensionPoint ext : exts) { ext.preRecoverVm(vm); } CollectionUtils.forEach(exts, new ForEachFunction<RecoverVmExtensionPoint>() { @Override public void run(RecoverVmExtensionPoint ext) { ext.beforeRecoverVm(vm); } }); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("recover-vm-%s", self.getUuid())); chain.then(new ShareFlow() { @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "recover-root-volume"; @Override public void run(final FlowTrigger trigger, Map data) { RecoverVolumeMsg msg = new RecoverVolumeMsg(); msg.setVolumeUuid(self.getRootVolumeUuid()); bus.makeTargetServiceIdByResourceUuid(msg, VolumeConstant.SERVICE_ID, self.getRootVolumeUuid()); bus.send(msg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); } else { trigger.next(); } } }); } }); flow(new NoRollbackFlow() { String __name__ = "recover-vm"; @Override public void run(FlowTrigger trigger, Map data) { self = changeVmStateInDb(VmInstanceStateEvent.stopped); CollectionUtils.forEach(exts, new ForEachFunction<RecoverVmExtensionPoint>() { @Override public void run(RecoverVmExtensionPoint ext) { ext.afterRecoverVm(vm); } }); trigger.next(); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } private void handle(final APIRecoverVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIRecoverVmInstanceEvent evt = new APIRecoverVmInstanceEvent(msg.getId()); refreshVO(); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { evt.setErrorCode(error); bus.publish(evt); chain.next(); return; } recoverVm(new Completion(msg, chain) { @Override public void success() { evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "recover-vm"; } }); } private void handle(final APIExpungeVmInstanceMsg msg) { final APIExpungeVmInstanceEvent evt = new APIExpungeVmInstanceEvent(msg.getId()); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { expunge(msg, new Completion(msg, chain) { @Override public void success() { bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "expunge-vm-by-api"; } }); } private void handle(final APIDetachIsoFromVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIDetachIsoFromVmInstanceEvent evt = new APIDetachIsoFromVmInstanceEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { evt.setErrorCode(allowed); bus.publish(evt); chain.next(); return; } detachIso(new Completion(msg, chain) { @Override public void success() { self = dbf.reload(self); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return String.format("detach-iso-from-vm-%s", self.getUuid()); } }); } private void detachIso(final Completion completion) { if (self.getState() == VmInstanceState.Stopped) { VmSystemTags.ISO.deleteInherentTag(self.getUuid()); completion.success(); return; } if (!VmSystemTags.ISO.hasTag(self.getUuid())) { completion.success(); return; } VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.DetachIso); if (spec.getDestIso() == null) { // the image ISO has been deleted from backup storage // try to detach it from the VM anyway String isoUuid = VmSystemTags.ISO.getTokenByResourceUuid(self.getUuid(), VmSystemTags.ISO_TOKEN); IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(isoUuid); spec.setDestIso(isoSpec); logger.debug(String.format("the iso[uuid:%s] has been deleted, try to detach it from the VM[uuid:%s] anyway", isoUuid, self.getUuid())); } FlowChain chain = getDetachIsoWorkFlowChain(spec.getVmInventory()); chain.setName(String.format("detach-iso-%s-from-vm-%s", spec.getDestIso().getImageUuid(), self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); setFlowMarshaller(chain); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { VmSystemTags.ISO.deleteInherentTag(self.getUuid()); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } @Transactional(readOnly = true) private List<L3NetworkInventory> getAttachableL3Network(String accountUuid) { List<String> l3Uuids = acntMgr.getResourceUuidsCanAccessByAccount(accountUuid, L3NetworkVO.class); if (l3Uuids != null && l3Uuids.isEmpty()) { return new ArrayList<L3NetworkInventory>(); } String sql; TypedQuery<L3NetworkVO> q; if (self.getVmNics().isEmpty()) { if (l3Uuids == null) { // accessed by a system admin sql = "select l3 from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where vm.uuid = :uuid and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid and l2.uuid = l3.l2NetworkUuid and l3.state = :l3State group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); } else { // accessed by a normal account sql = "select l3 from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where vm.uuid = :uuid and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid and l2.uuid = l3.l2NetworkUuid and l3.state = :l3State and l3.uuid in (:l3uuids) group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); q.setParameter("l3uuids", l3Uuids); } } else { if (l3Uuids == null) { // accessed by a system admin sql = "select l3 from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where l3.uuid not in (select nic.l3NetworkUuid from VmNicVO nic where nic.vmInstanceUuid = :uuid) and vm.uuid = :uuid and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid and l2.uuid = l3.l2NetworkUuid and l3.state = :l3State group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); } else { // accessed by a normal account sql = "select l3 from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where l3.uuid not in (select nic.l3NetworkUuid from VmNicVO nic where nic.vmInstanceUuid = :uuid) and vm.uuid = :uuid and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid and l2.uuid = l3.l2NetworkUuid and l3.state = :l3State and l3.uuid in (:l3uuids) group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); q.setParameter("l3uuids", l3Uuids); } } q.setParameter("l3State", L3NetworkState.Enabled); q.setParameter("uuid", self.getUuid()); List<L3NetworkVO> l3s = q.getResultList(); return L3NetworkInventory.valueOf(l3s); } private void handle(APIGetVmAttachableL3NetworkMsg msg) { APIGetVmAttachableL3NetworkReply reply = new APIGetVmAttachableL3NetworkReply(); reply.setInventories(getAttachableL3Network(msg.getSession().getAccountUuid())); bus.reply(msg, reply); } private void handle(final APIAttachIsoToVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIAttachIsoToVmInstanceEvent evt = new APIAttachIsoToVmInstanceEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { evt.setErrorCode(allowed); bus.publish(evt); chain.next(); return; } attachIso(msg.getIsoUuid(), new Completion(msg, chain) { @Override public void success() { self = dbf.reload(self); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return String.format("attach-iso-%s-to-vm-%s", msg.getIsoUuid(), self.getUuid()); } }); } private void attachIso(final String isoUuid, final Completion completion) { if (self.getState() == VmInstanceState.Stopped) { VmSystemTags.ISO.createInherentTag(self.getUuid(), map(e(VmSystemTags.ISO_TOKEN, isoUuid))); completion.success(); return; } VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.AttachIso); IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(isoUuid); spec.setDestIso(isoSpec); FlowChain chain = getAttachIsoWorkFlowChain(spec.getVmInventory()); chain.setName(String.format("attach-iso-%s-to-vm-%s", isoUuid, self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); setFlowMarshaller(chain); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { VmSystemTags.ISO.createInherentTag(self.getUuid(), map(e(VmSystemTags.ISO_TOKEN, isoUuid))); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } private void handle(final APIDetachL3NetworkFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIDetachL3NetworkFromVmEvent evt = new APIDetachL3NetworkFromVmEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { evt.setErrorCode(allowed); bus.publish(evt); chain.next(); return; } detachNic(msg.getVmNicUuid(), new Completion(msg, chain) { @Override public void success() { self = dbf.reload(self); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "detach-nic"; } }); } private void detachNic(final String nicUuid, final Completion completion) { final VmNicInventory nic = VmNicInventory.valueOf( CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return arg.getUuid().equals(nicUuid) ? arg : null; } }) ); for (VmDetachNicExtensionPoint ext : pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class)) { ext.preDetachNic(nic); } CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class), new ForEachFunction<VmDetachNicExtensionPoint>() { @Override public void run(VmDetachNicExtensionPoint arg) { arg.beforeDetachNic(nic); } }); final VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.DetachNic); spec.setVmInventory(VmInstanceInventory.valueOf(self)); spec.setDestNics(list(nic)); spec.setL3Networks(list(L3NetworkInventory.valueOf(dbf.findByUuid(nic.getL3NetworkUuid(), L3NetworkVO.class)))); FlowChain flowChain = FlowChainBuilder.newSimpleFlowChain(); flowChain.setName(String.format("detachNic-vm-%s-nic-%s", self.getUuid(), nicUuid)); setFlowMarshaller(flowChain); flowChain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); if (self.getState() == VmInstanceState.Running) { flowChain.then(new VmDetachNicOnHypervisorFlow()); } flowChain.then(new VmReleaseResourceOnDetachingNicFlow()); flowChain.then(new VmDetachNicFlow()); flowChain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { selectDefaultL3(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class), new ForEachFunction<VmDetachNicExtensionPoint>() { @Override public void run(VmDetachNicExtensionPoint arg) { arg.afterDetachNic(nic); } }); completion.success(); } private void selectDefaultL3() { if (!self.getDefaultL3NetworkUuid().equals(nic.getL3NetworkUuid())) { return; } // the nic has been removed, reload self = dbf.reload(self); VmNicVO candidate = CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return arg.getL3NetworkUuid().equals(nic.getUuid()) ? null : arg; } }); if (candidate != null) { self.setDefaultL3NetworkUuid(candidate.getL3NetworkUuid()); logger.debug(String.format("after detaching the nic[uuid:%s, L3 uuid:%s], change the default L3 of the VM[uuid:%s]" + " to the L3 network[uuid: %s]", nic.getUuid(), nic.getL3NetworkUuid(), self.getUuid(), candidate.getL3NetworkUuid())); } else { self.setDefaultL3NetworkUuid(null); logger.debug(String.format("after detaching the nic[uuid:%s, L3 uuid:%s], change the default L3 of the VM[uuid:%s]" + " to null, as the VM has no other nics", nic.getUuid(), nic.getL3NetworkUuid(), self.getUuid())); } self = dbf.updateAndRefresh(self); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class), new ForEachFunction<VmDetachNicExtensionPoint>() { @Override public void run(VmDetachNicExtensionPoint arg) { arg.failedToDetachNic(nic, errCode); } }); completion.fail(errCode); } }).start(); } private void handle(final APIChangeInstanceOfferingMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { changeOffering(msg); chain.next(); } @Override public String getName() { return "change-instance-offering"; } }); } private void changeOffering(APIChangeInstanceOfferingMsg msg) { APIChangeInstanceOfferingEvent evt = new APIChangeInstanceOfferingEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { bus.replyErrorByMessageType(msg, allowed); return; } InstanceOfferingVO iovo = dbf.findByUuid(msg.getInstanceOfferingUuid(), InstanceOfferingVO.class); final InstanceOfferingInventory inv = InstanceOfferingInventory.valueOf(iovo); final VmInstanceInventory vm = getSelfInventory(); List<ChangeInstanceOfferingExtensionPoint> exts = pluginRgty.getExtensionList(ChangeInstanceOfferingExtensionPoint.class); for (ChangeInstanceOfferingExtensionPoint ext : exts) { ext.preChangeInstanceOffering(vm, inv); } CollectionUtils.safeForEach(exts, new ForEachFunction<ChangeInstanceOfferingExtensionPoint>() { @Override public void run(ChangeInstanceOfferingExtensionPoint arg) { arg.beforeChangeInstanceOffering(vm ,inv); } }); if (self.getState() == VmInstanceState.Stopped) { self.setInstanceOfferingUuid(iovo.getUuid()); self.setCpuNum(iovo.getCpuNum()); self.setCpuSpeed(iovo.getCpuSpeed()); self.setMemorySize(iovo.getMemorySize()); self = dbf.updateAndRefresh(self); } else { // the vm is running, make the capacity change pending, which will take effect the next // the vm starts Map m = new HashMap(); m.put(VmSystemTags.PENDING_CAPACITY_CHNAGE_CPU_NUM_TOKEN, iovo.getCpuNum()); m.put(VmSystemTags.PENDING_CAPACITY_CHNAGE_CPU_SPEED_TOKEN, iovo.getCpuSpeed()); m.put(VmSystemTags.PENDING_CAPACITY_CHNAGE_MEMORY_TOKEN, iovo.getMemorySize()); VmSystemTags.PENDING_CAPACITY_CHANGE.recreateInherentTag(self.getUuid(), m); self.setInstanceOfferingUuid(iovo.getUuid()); self = dbf.updateAndRefresh(self); } CollectionUtils.safeForEach(exts, new ForEachFunction<ChangeInstanceOfferingExtensionPoint>() { @Override public void run(ChangeInstanceOfferingExtensionPoint arg) { arg.afterChangeInstanceOffering(vm ,inv); } }); evt.setInventory(getSelfInventory()); bus.publish(evt); } private void handle(final APIUpdateVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { boolean update = false; if (msg.getName() != null) { self.setName(msg.getName()); update = true; } if (msg.getDescription() != null) { self.setDescription(msg.getDescription()); update = true; } if (msg.getState() != null) { self.setState(VmInstanceState.valueOf(msg.getState())); update = true; } if (msg.getDefaultL3NetworkUuid() != null) { self.setDefaultL3NetworkUuid(msg.getDefaultL3NetworkUuid()); update = true; } if (msg.getPlatform() != null) { self.setPlatform(msg.getPlatform()); update = true; } if (update) { self = dbf.updateAndRefresh(self); } APIUpdateVmInstanceEvent evt = new APIUpdateVmInstanceEvent(msg.getId()); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public String getName() { return "update-vm-info"; } }); } @Transactional(readOnly = true) private List<VolumeVO> getAttachableVolume(String accountUuid) { List<String> volUuids = acntMgr.getResourceUuidsCanAccessByAccount(accountUuid, VolumeVO.class); if (volUuids != null && volUuids.isEmpty()) { return new ArrayList<VolumeVO>(); } List<String> formats = VolumeFormat.getVolumeFormatSupportedByHypervisorTypeInString(self.getHypervisorType()); if (formats.isEmpty()) { throw new CloudRuntimeException(String.format("cannot find volume formats for the hypervisor type[%s]", self.getHypervisorType())); } String sql; List<VolumeVO> vos; if (volUuids == null) { // accessed by a system admin sql = "select vol from VolumeVO vol, VmInstanceVO vm, PrimaryStorageClusterRefVO ref where vol.type = :type and vol.state = :volState and vol.status = :volStatus and vol.format in (:formats) and vol.vmInstanceUuid is null and vm.clusterUuid = ref.clusterUuid and ref.primaryStorageUuid = vol.primaryStorageUuid group by vol.uuid"; TypedQuery<VolumeVO> q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volStatus", VolumeStatus.Ready); q.setParameter("formats", formats); q.setParameter("type", VolumeType.Data); vos = q.getResultList(); sql = "select vol from VolumeVO vol where vol.type = :type and vol.status = :volStatus and vol.state = :volState group by vol.uuid"; q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("type", VolumeType.Data); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volStatus", VolumeStatus.NotInstantiated); vos.addAll(q.getResultList()); } else { // accessed by a normal account sql = "select vol from VolumeVO vol, VmInstanceVO vm, PrimaryStorageClusterRefVO ref where vol.type = :type and vol.state = :volState and vol.status = :volStatus" + " and vol.format in (:formats) and vol.vmInstanceUuid is null and vm.clusterUuid = ref.clusterUuid and" + " ref.primaryStorageUuid = vol.primaryStorageUuid and vol.uuid in (:volUuids) group by vol.uuid"; TypedQuery<VolumeVO> q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volStatus", VolumeStatus.Ready); q.setParameter("formats", formats); q.setParameter("type", VolumeType.Data); q.setParameter("volUuids", volUuids); vos = q.getResultList(); sql = "select vol from VolumeVO vol where vol.type = :type and vol.status = :volStatus and" + " vol.state = :volState and vol.uuid in (:volUuids) group by vol.uuid"; q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("type", VolumeType.Data); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volUuids", volUuids); q.setParameter("volStatus", VolumeStatus.NotInstantiated); vos.addAll(q.getResultList()); } for (GetAttachableVolumeExtensionPoint ext : pluginRgty.getExtensionList(GetAttachableVolumeExtensionPoint.class)) { if (!vos.isEmpty()) { vos = ext.returnAttachableVolumes(getSelfInventory(), vos); } } return vos; } private void handle(APIGetVmAttachableDataVolumeMsg msg) { APIGetVmAttachableDataVolumeReply reply = new APIGetVmAttachableDataVolumeReply(); reply.setInventories(VolumeInventory.valueOf(getAttachableVolume(msg.getSession().getAccountUuid()))); bus.reply(msg, reply); } private void handle(final APIGetVmMigrationCandidateHostsMsg msg) { final APIGetVmMigrationCandidateHostsReply reply = new APIGetVmMigrationCandidateHostsReply(); getVmMigrationTargetHost(msg, new ReturnValueCompletion<List<HostInventory>>(msg) { @Override public void success(List<HostInventory> returnValue) { reply.setInventories(returnValue); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void handle(final APIAttachL3NetworkToVmMsg msg) { final APIAttachL3NetworkToVmEvent evt = new APIAttachL3NetworkToVmEvent(msg.getId()); attachNic(msg, msg.getL3NetworkUuid(), new ReturnValueCompletion<VmNicInventory>(msg) { @Override public void success(VmNicInventory returnValue) { self = dbf.reload(self); evt.setInventory(VmInstanceInventory.valueOf(self)); bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); } }); } private void detachVolume(final DetachDataVolumeFromVmMsg msg, final NoErrorCompletion completion) { final DetachDataVolumeFromVmReply reply = new DetachDataVolumeFromVmReply(); refreshVO(true); if (self == null || VmInstanceState.Destroyed == self.getState()) { // the vm is destroyed, the data volume must have been detached bus.reply(msg, reply); completion.done(); return; } ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.DETACH_VOLUME_ERROR); if (allowed != null) { throw new OperationFailureException(allowed); } final VolumeInventory volume = msg.getVolume(); extEmitter.preDetachVolume(getSelfInventory(), volume); extEmitter.beforeDetachVolume(getSelfInventory(), volume); if (self.getState() == VmInstanceState.Stopped) { extEmitter.afterDetachVolume(getSelfInventory(), volume); bus.reply(msg, reply); completion.done(); return; } // VmInstanceState.Running String hostUuid = self.getHostUuid(); DetachVolumeFromVmOnHypervisorMsg dmsg = new DetachVolumeFromVmOnHypervisorMsg(); dmsg.setVmInventory(VmInstanceInventory.valueOf(self)); dmsg.setInventory(volume); dmsg.setHostUuid(hostUuid); bus.makeTargetServiceIdByResourceUuid(dmsg, HostConstant.SERVICE_ID, hostUuid); bus.send(dmsg, new CloudBusCallBack(msg, completion) { @Override public void run(final MessageReply r) { if (!r.isSuccess()) { reply.setError(r.getError()); extEmitter.failedToDetachVolume(getSelfInventory(), volume, r.getError()); } else { extEmitter.afterDetachVolume(getSelfInventory(), volume); } bus.reply(msg, reply); completion.done(); } }); } protected void attachVolume(final AttachDataVolumeToVmMsg msg, final NoErrorCompletion completion) { final AttachDataVolumeToVmReply reply = new AttachDataVolumeToVmReply(); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.ATTACH_VOLUME_ERROR); if (allowed != null) { reply.setError(allowed); bus.reply(msg, reply); return; } final VolumeInventory volume = msg.getVolume(); extEmitter.preAttachVolume(getSelfInventory(), volume); extEmitter.beforeAttachVolume(getSelfInventory(), volume); VmInstanceSpec spec = new VmInstanceSpec(); spec.setMessage(msg); spec.setVmInventory(VmInstanceInventory.valueOf(self)); spec.setCurrentVmOperation(VmOperation.AttachVolume); spec.setDestDataVolumes(list(volume)); FlowChain chain; if (volume.getStatus().equals(VolumeStatus.Ready.toString())) { chain = FlowChainBuilder.newSimpleFlowChain(); chain.then(new VmAssignDeviceIdToAttachingVolumeFlow()); chain.then(new VmAttachVolumeOnHypervisorFlow()); } else { chain = getAttachUninstantiatedVolumeWorkFlowChain(spec.getVmInventory()); } setFlowMarshaller(chain); chain.setName(String.format("vm-%s-attach-volume-%s", self.getUuid(), volume.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.getData().put(VmInstanceConstant.Params.AttachingVolumeInventory.toString(), volume); chain.done(new FlowDoneHandler(msg, completion) { @Override public void handle(Map data) { extEmitter.afterAttachVolume(getSelfInventory(), volume); reply.setHypervisorType(self.getHypervisorType()); bus.reply(msg, reply); completion.done(); } }).error(new FlowErrorHandler(msg, completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToAttachVolume(getSelfInventory(), volume, errCode); reply.setError(errf.instantiateErrorCode(VmErrors.ATTACH_VOLUME_ERROR, errCode)); bus.reply(msg, reply); completion.done(); } }).start(); } protected void migrateVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.MIGRATE_ERROR); if (allowed != null) { completion.fail(allowed); return; } VmInstanceInventory pinv = getSelfInventory(); for (VmPreMigrationExtensionPoint ext : pluginRgty.getExtensionList(VmPreMigrationExtensionPoint.class)) { ext.preVmMigration(pinv); } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Migrate); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.migrating); spec.setMessage(msg); FlowChain chain = getMigrateVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("migrate-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(final Map data) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); HostInventory host = spec.getDestHost(); self.setZoneUuid(host.getZoneUuid()); self.setClusterUuid(host.getClusterUuid()); self.setLastHostUuid(self.getHostUuid()); self.setHostUuid(host.getUuid()); self = changeVmStateInDb(VmInstanceStateEvent.running); VmInstanceInventory vm = VmInstanceInventory.valueOf(self); extEmitter.afterMigrateVm(vm, vm.getLastHostUuid()); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToMigrateVm(VmInstanceInventory.valueOf(self), spec.getDestHost().getUuid(), errCode); if (HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void handle(final APIMigrateVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("migrate-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { migrateVm(msg, new Completion(chain) { @Override public void success() { APIMigrateVmEvent evt = new APIMigrateVmEvent(msg.getId()); evt.setInventory(VmInstanceInventory.valueOf(self)); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { APIMigrateVmEvent evt = new APIMigrateVmEvent(msg.getId()); evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } }); } protected void applyPendingCapacityChangeIfNeed() { String pendingCapacityChange = VmSystemTags.PENDING_CAPACITY_CHANGE.getTag(self.getUuid()); if (pendingCapacityChange != null) { // the instance offering had been changed, apply new capacity to myself Map<String, String> tokens = VmSystemTags.PENDING_CAPACITY_CHANGE.getTokensByTag(pendingCapacityChange); int cpuNum = Integer.valueOf(tokens.get(VmSystemTags.PENDING_CAPACITY_CHNAGE_CPU_NUM_TOKEN)); int cpuSpeed = Integer.valueOf(tokens.get(VmSystemTags.PENDING_CAPACITY_CHNAGE_CPU_SPEED_TOKEN)); long memory = Long.valueOf(tokens.get(VmSystemTags.PENDING_CAPACITY_CHNAGE_MEMORY_TOKEN)); self.setCpuNum(cpuNum); self.setCpuSpeed(cpuSpeed); self.setMemorySize(memory); self = dbf.updateAndRefresh(self); VmSystemTags.PENDING_CAPACITY_CHANGE.deleteInherentTag(self.getUuid()); } } protected void startVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } applyPendingCapacityChangeIfNeed(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); ErrorCode preStart = extEmitter.preStartVm(inv); if (preStart != null) { completion.fail(preStart); return; } final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Start); spec.setMessage(msg); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.starting); extEmitter.beforeStartVm(VmInstanceInventory.valueOf(self)); if (spec.getDestNics().isEmpty()) { throw new OperationFailureException(errf.stringToOperationError( String.format("unable to start the vm[uuid:%s]. It doesn't have any nic, please attach a nic and try again", self.getUuid()) )); } FlowChain chain = getStartVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("start-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(final Map data) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); // reload self because some nics may have been deleted in start phase because a former L3Network deletion. // reload to avoid JPA EntityNotFoundException self = dbf.reload(self); self.setLastHostUuid(self.getHostUuid()); self.setHostUuid(spec.getDestHost().getUuid()); self.setClusterUuid(spec.getDestHost().getClusterUuid()); self.setZoneUuid(spec.getDestHost().getZoneUuid()); self = changeVmStateInDb(VmInstanceStateEvent.running); logger.debug(String.format("vm[uuid:%s] is running ..", self.getUuid())); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterStartVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { // reload self because some nics may have been deleted in start phase because a former L3Network deletion. // reload to avoid JPA EntityNotFoundException self = dbf.reload(self); extEmitter.failedToStartVm(VmInstanceInventory.valueOf(self), errCode); VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); if (HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(spec.getDestHost().getUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void startVm(final StartVmInstanceMsg msg, final SyncTaskChain taskChain) { startVm(msg, new Completion(taskChain) { @Override public void success() { VmInstanceInventory inv = VmInstanceInventory.valueOf(self); StartVmInstanceReply reply = new StartVmInstanceReply(); reply.setInventory(inv); bus.reply(msg, reply); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { StartVmInstanceReply reply = new StartVmInstanceReply(); reply.setError(errf.instantiateErrorCode(VmErrors.START_ERROR, errorCode)); bus.reply(msg, reply); taskChain.next(); } }); } protected void startVm(final APIStartVmInstanceMsg msg, final SyncTaskChain taskChain) { startVm(msg, new Completion(taskChain) { @Override public void success() { VmInstanceInventory inv = VmInstanceInventory.valueOf(self); APIStartVmInstanceEvent evt = new APIStartVmInstanceEvent(msg.getId()); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIStartVmInstanceEvent evt = new APIStartVmInstanceEvent(msg.getId()); evt.setErrorCode(errf.instantiateErrorCode(VmErrors.START_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void handle(final APIStartVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("start-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { startVm(msg, chain); } }); } protected void handle(final APIDestroyVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("destroy-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIDestroyVmInstanceEvent evt = new APIDestroyVmInstanceEvent(msg.getId()); destroyVm(msg, new Completion(chain) { @Override public void success() { bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } }); } private void destroyVm(APIDestroyVmInstanceMsg msg, final Completion completion) { final String issuer = VmInstanceVO.class.getSimpleName(); final List<VmDeletionStruct> ctx = new ArrayList<VmDeletionStruct>(); VmDeletionStruct s = new VmDeletionStruct(); s.setInventory(getSelfInventory()); s.setDeletionPolicy(deletionPolicyMgr.getDeletionPolicy(self.getUuid())); ctx.add(s); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("delete-vm-%s", msg.getUuid())); if (msg.getDeletionMode() == APIDeleteMessage.DeletionMode.Permissive) { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_CHECK_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } else { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } chain.done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion()); completion.success(); } }).error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errf.instantiateErrorCode(SysErrors.DELETE_RESOURCE_ERROR, errCode)); } }).start(); } protected void buildHostname(VmInstanceSpec spec) { String defaultHostname = VmSystemTags.HOSTNAME.getTag(self.getUuid()); if (defaultHostname == null) { return; } HostName dhname = new HostName(); dhname.setL3NetworkUuid(self.getDefaultL3NetworkUuid()); dhname.setHostname(VmSystemTags.HOSTNAME.getTokenByTag(defaultHostname, VmSystemTags.HOSTNAME_TOKEN)); spec.getHostnames().add(dhname); } protected VmInstanceSpec buildSpecFromInventory(VmInstanceInventory inv, VmOperation operation) { VmInstanceSpec spec = new VmInstanceSpec(); spec.setUserdata(buildUserdata()); // for L3Network that has been deleted List<String> nicUuidToDel = CollectionUtils.transformToList(inv.getVmNics(), new Function<String, VmNicInventory>() { @Override public String call(VmNicInventory arg) { return arg.getL3NetworkUuid() == null ? arg.getUuid() : null; } }); if (!nicUuidToDel.isEmpty()) { dbf.removeByPrimaryKeys(nicUuidToDel, VmNicVO.class); self = dbf.findByUuid(inv.getUuid(), VmInstanceVO.class); inv = VmInstanceInventory.valueOf(self); } spec.setDestNics(inv.getVmNics()); List<String> l3Uuids = CollectionUtils.transformToList(inv.getVmNics(), new Function<String, VmNicInventory>() { @Override public String call(VmNicInventory arg) { return arg.getL3NetworkUuid(); } }); spec.setL3Networks(L3NetworkInventory.valueOf(dbf.listByPrimaryKeys(l3Uuids, L3NetworkVO.class))); String huuid = inv.getHostUuid() == null ? inv.getLastHostUuid() : inv.getHostUuid(); if (huuid != null) { HostVO hvo = dbf.findByUuid(huuid, HostVO.class); if (hvo != null) { spec.setDestHost(HostInventory.valueOf(hvo)); } } List<VolumeInventory> dataVols = new ArrayList<VolumeInventory>(); for (VolumeInventory vol : inv.getAllVolumes()) { if (vol.getUuid().equals(inv.getRootVolumeUuid())) { spec.setDestRootVolume(vol); } else { dataVols.add(vol); } } spec.setDestDataVolumes(dataVols); ImageVO imgvo = dbf.findByUuid(inv.getImageUuid(), ImageVO.class); ImageInventory imginv = null; if (imgvo == null) { // the image has been deleted, use EO instead ImageEO imgeo = dbf.findByUuid(inv.getImageUuid(), ImageEO.class); imginv = ImageInventory.valueOf(imgeo); } else { imginv = ImageInventory.valueOf(imgvo); } spec.getImageSpec().setInventory(imginv); spec.setVmInventory(inv); buildHostname(spec); String isoUuid = VmSystemTags.ISO.getTokenByResourceUuid(inv.getUuid(), VmSystemTags.ISO_TOKEN); if (isoUuid != null) { if (dbf.isExist(isoUuid, ImageVO.class)) { IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(isoUuid); spec.setDestIso(isoSpec); } else { //TODO logger.warn(String.format("iso[uuid:%s] is deleted, however, the VM[uuid:%s] still has it attached", isoUuid, self.getUuid())); } } spec.setCurrentVmOperation(operation); selectBootOrder(spec); return spec; } protected void rebootVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } applyPendingCapacityChangeIfNeed(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); ErrorCode preReboot = extEmitter.preRebootVm(inv); if (preReboot != null) { completion.fail(preReboot); return; } final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Reboot); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.rebooting); extEmitter.beforeRebootVm(VmInstanceInventory.valueOf(self)); spec.setMessage(msg); FlowChain chain = getRebootVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("reboot-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { self = changeVmStateInDb(VmInstanceStateEvent.running); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterRebootVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToRebootVm(VmInstanceInventory.valueOf(self), errCode); if (HostErrors.FAILED_TO_REBOOT_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void rebootVm(final APIRebootVmInstanceMsg msg, final SyncTaskChain taskChain) { rebootVm(msg, new Completion(taskChain) { @Override public void success() { APIRebootVmInstanceEvent evt = new APIRebootVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIRebootVmInstanceEvent evt = new APIRebootVmInstanceEvent(msg.getId()); evt.setErrorCode(errf.instantiateErrorCode(VmErrors.REBOOT_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void handle(final APIRebootVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("reboot-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { rebootVm(msg, chain); } }); } protected void stopVm(final APIStopVmInstanceMsg msg, final SyncTaskChain taskChain) { stopVm(msg, new Completion(taskChain) { @Override public void success() { APIStopVmInstanceEvent evt = new APIStopVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIStopVmInstanceEvent evt = new APIStopVmInstanceEvent(msg.getId()); evt.setErrorCode(errf.instantiateErrorCode(VmErrors.STOP_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } private void stopVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } if (self.getState() == VmInstanceState.Stopped) { completion.success(); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); ErrorCode preStop = extEmitter.preStopVm(inv); if (preStop != null) { completion.fail(preStop); return; } final VmInstanceSpec spec = buildSpecFromInventory(inv,VmOperation.Stop); spec.setMessage(msg); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.stopping); extEmitter.beforeStopVm(VmInstanceInventory.valueOf(self)); FlowChain chain = getStopVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("stop-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { self.setLastHostUuid(self.getHostUuid()); self.setHostUuid(null); self = changeVmStateInDb(VmInstanceStateEvent.stopped); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterStopVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.failedToStopVm(inv, errCode); if (HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void handle(final APIStopVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("stop-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { stopVm(msg, chain); } }); } }
package dta.pizzeria.test; import dta.pizzeria.backend.PizzeriaBackendConfig; import dta.pizzeria.backend.entity.Menu; import dta.pizzeria.backend.entity.Produits; import dta.pizzeria.backend.metier.MenuService; import dta.pizzeria.backend.metier.ProduitsService; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; /** * * @author MHayet */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = PizzeriaBackendConfig.class) @WebAppConfiguration public class TestServiceMenu { @Autowired private MenuService mService; @Autowired private ProduitsService pService; @Test public void avant() { pService.removeAllProduits(); mService.removeAllMenu(); Produits pizza1 = new Produits("Reina", 12F, "fgsupreme.jpg", Produits.Type_Produit.PIZZA, Produits.Taille.LARGE, null); Produits pizza2 = new Produits("Imperia", 15F,"speciale.jpg", Produits.Type_Produit.PIZZA, Produits.Taille.XLARGE, null); Produits boisson1 = new Produits("Coca", 2F, "coca.png",Produits.Type_Produit.BOISSON, null, Produits.Format.NORMAL); Produits boisson2 = new Produits("Pepsi", 3F, "sprite.png", Produits.Type_Produit.BOISSON, null, Produits.Format.XL); Produits dessert1 = new Produits("Eclair au Chocolat", 2F, "chocolat.jpg",Produits.Type_Produit.DESSERT, null, null); Produits dessert2 = new Produits("Religieuse au Café", 3F, "chocolat.jpg", Produits.Type_Produit.DESSERT, null, null); Menu menu1 = new Menu("PizzaReina", 15F, "Menu digne d'un Roi"); Menu menu2 = new Menu("PizzaImperia", 20F, "Menu digne d'un Empereur"); pService.setProduits(pizza1); pService.setProduits(pizza2); pService.setProduits(boisson1); pService.setProduits(boisson2); pService.setProduits(dessert1); pService.setProduits(dessert2); mService.setMenu(menu1); mService.setMenu(menu2); List<Produits> produits1 = new ArrayList<>(); produits1.add(pizza1); produits1.add(boisson1); produits1.add(dessert1); List<Produits> produits2 = new ArrayList<>(); produits1.add(pizza2); produits1.add(boisson2); produits1.add(dessert2); List<Menu> m1 = new ArrayList<>(); m1.add(menu1); m1.add(menu2); List<Menu> m2 = new ArrayList<>(); m2.add(menu2); pizza1.setMenus(m1); pizza2.setMenus(m2); boisson1.setMenus(m1); boisson2.setMenus(m2); dessert1.setMenus(m1); dessert2.setMenus(m2); menu1.setProduits(produits1); menu1.setProduits(produits2); pService.updateProduits(pizza1); pService.updateProduits(pizza2); pService.updateProduits(boisson1); pService.updateProduits(boisson2); pService.updateProduits(dessert1); pService.updateProduits(dessert2); mService.updateMenu(menu1); mService.updateMenu(menu2); } }
package eu.digitisation.io; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author rafa */ public class CharFilterTest { public CharFilterTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of translate method, of class CharFilter. * * @throws java.net.URISyntaxException */ @Test public void testTranslate_String() throws URISyntaxException { System.out.println("translate"); URL resourceUrl = getClass().getResource("/UnicodeCharEquivalences.txt"); File file = new File(resourceUrl.toURI()); CharFilter filter = new CharFilter(file); String s = "a\u0133"; String expResult = "aij"; String result = filter.translate(s); assertEquals(expResult.length(), result.length()); assertEquals(expResult, result); } @Test public void testCompatibilityMode() { System.out.println("compatibility"); CharFilter filter = new CharFilter(); String s = "\u0133"; String r = "ij"; assert (!r.equals(filter.translate(s))); filter.setCompatibility(true); assertEquals(r, filter.translate(s)); } }
package hudson.remoting; import junit.framework.Test; import org.jvnet.hudson.test.Issue; import org.objectweb.asm.ClassReader; import org.objectweb.asm.commons.EmptyVisitor; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Test class image forwarding. * * @author Kohsuke Kawaguchi */ public class ClassRemotingTest extends RmiTestBase { static final String TESTCALLABLE_TRANSFORMED_CLASSNAME = "hudson.rem0ting.TestCallable"; static final String TESTLINKAGE_TRANSFORMED_CLASSNAME = "hudson.rem0ting.TestLinkage"; public void test1() throws Throwable { // call a class that's only available on DummyClassLoader, so that on the remote channel // it will be fetched from this class loader and not from the system classloader. Callable<Object, Exception> callable = (Callable<Object, Exception>) DummyClassLoader.apply(TestCallable.class); Object[] result = (Object[]) channel.call(callable); assertTestCallableResults(result); assertEquals(TESTCALLABLE_TRANSFORMED_CLASSNAME, callable.getClass().getName()); } /** * Tests the use of user-defined classes in remote property access */ public void testRemoteProperty() throws Exception { // this test cannot run in the compatibility mode without the multi-classloader serialization support, // because it uses the class loader specified during proxy construction. if (channelRunner instanceof InProcessCompatibilityRunner) { return; } DummyClassLoader cl = new DummyClassLoader(TestCallable.class); Callable<Object, Exception> c = (Callable<Object, Exception>) cl.load(TestCallable.class); assertSame(c.getClass().getClassLoader(), cl); channel.setProperty("test",c); channel.call(new RemotePropertyVerifier()); } @Issue("JENKINS-6604") public void testRaceCondition() throws Throwable { DummyClassLoader parent = new DummyClassLoader(TestCallable.class); DummyClassLoader child1 = new DummyClassLoader(parent, TestCallable.Sub.class); final Callable<Object,Exception> c1 = (Callable<Object, Exception>) child1.load(TestCallable.Sub.class); assertEquals(child1, c1.getClass().getClassLoader()); assertEquals(parent, c1.getClass().getSuperclass().getClassLoader()); DummyClassLoader child2 = new DummyClassLoader(parent, TestCallable.Sub.class); final Callable<Object,Exception> c2 = (Callable<Object, Exception>) child2.load(TestCallable.Sub.class); assertEquals(child2, c2.getClass().getClassLoader()); assertEquals(parent, c2.getClass().getSuperclass().getClassLoader()); ExecutorService svc = Executors.newFixedThreadPool(2); RemoteClassLoader.TESTING_CLASS_LOAD = new SleepForASec(); java.util.concurrent.Future<Object> f1 = svc.submit(() -> channel.call(c1)); java.util.concurrent.Future<Object> f2 = svc.submit(() -> channel.call(c2)); Object result1 = f1.get(); Object result2 = f2.get(); assertTestCallableResults((Object[])result1); assertTestCallableResults((Object[])result2); } public void testClassCreation_TestCallable() throws Exception { DummyClassLoader dummyClassLoader = new DummyClassLoader(TestCallable.class); final Callable<Object, Exception> callable = (Callable<Object, Exception>) dummyClassLoader.load(TestCallable.class); java.util.concurrent.Future<Object> f1 = scheduleCallableLoad(channel, callable); Object result = f1.get(); assertTestCallableResults((Object[])result); Object loadResult = dummyClassLoader.load(TestCallable.class); assertEquals(TESTCALLABLE_TRANSFORMED_CLASSNAME, loadResult.getClass().getName()); } public void testClassCreation_TestLinkage() throws Exception { DummyClassLoader parent = new DummyClassLoader(TestLinkage.B.class); final DummyClassLoader child1 = new DummyClassLoader(parent, TestLinkage.A.class); final DummyClassLoader child2 = new DummyClassLoader(child1, TestLinkage.class); final Callable<Object, Exception> callable = (Callable<Object, Exception>) child2.load(TestLinkage.class); assertEquals(child2, callable.getClass().getClassLoader()); java.util.concurrent.Future<Object> f1 = scheduleCallableLoad(channel, callable); Object result = f1.get(); assertTestLinkageResults(channel, parent, child1, child2, callable, result); } @Issue("JENKINS-61103") public void testClassCreation_TestStaticResourceReference() throws Exception { final DummyClassLoader dcl = new DummyClassLoader(TestStaticResourceReference.class); final Callable<Object, Exception> callable = (Callable<Object, Exception>) dcl.load(TestStaticGetResources.class); Future<Object> f1 = ClassRemotingTest.scheduleCallableLoad(channel, callable); Object result = f1.get(); assertTestStaticResourceReferenceResults(channel, callable, result); } @Issue("JENKINS-61103") public void testClassCreation_TestFindResources() throws Exception { final DummyClassLoader dcl = new DummyClassLoader(TestStaticGetResources.class); final Callable<Object, Exception> callable = (Callable<Object, Exception>) dcl.load(TestStaticGetResources.class); Future<Object> f1 = ClassRemotingTest.scheduleCallableLoad(channel, callable); Object result = f1.get(); assertTestStaticResourceReferenceResults(channel, callable, result); } static void assertTestStaticResourceReferenceResults(Channel channel, Callable<Object, Exception> callable, Object result) throws Exception { assertEquals(String.class, channel.call(callable).getClass()); assertTrue(result.toString().contains("impossible")); } static Future<Object> scheduleCallableLoad(Channel channel, final Callable<Object, Exception> c) { ExecutorService svc = Executors.newSingleThreadExecutor(); return svc.submit(() -> channel.call(c)); } static void assertTestLinkageResults(Channel channel, DummyClassLoader parent, DummyClassLoader child1, DummyClassLoader child2, Callable<Object, Exception> callable, Object result) throws Exception { assertEquals(String.class, channel.call(callable).getClass()); assertTrue(result.toString().startsWith(TESTLINKAGE_TRANSFORMED_CLASSNAME + "$B")); Object loadResult = parent.load(TestLinkage.B.class); assertEquals(TESTLINKAGE_TRANSFORMED_CLASSNAME + "$B", loadResult.getClass().getName()); loadResult = child1.load(TestLinkage.A.class); assertEquals(TESTLINKAGE_TRANSFORMED_CLASSNAME + "$A", loadResult.getClass().getName()); loadResult = child2.load(TestLinkage.class); assertEquals(TESTLINKAGE_TRANSFORMED_CLASSNAME, loadResult.getClass().getName()); } private void assertTestCallableResults(Object[] result) { assertTrue(result[0].toString().startsWith("hudson.remoting.RemoteClassLoader@")); // make sure the bytes are what we are expecting ClassReader cr = new ClassReader((byte[])result[1]); cr.accept(new EmptyVisitor(),false); // make sure cache is taking effect assertEquals(result[2],result[3]); assertTrue(result[2].toString().contains(TESTCALLABLE_TRANSFORMED_CLASSNAME.replace(".", "/") + ".class")); } private static final class SleepForASec implements Runnable { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { // Nothing } } } public static Test suite() { return buildSuite(ClassRemotingTest.class); } private static class RemotePropertyVerifier extends CallableBase<Object, IOException> { public Object call() throws IOException { Object o = getOpenChannelOrFail().getRemoteProperty("test"); assertEquals(o.getClass().getName(), TESTCALLABLE_TRANSFORMED_CLASSNAME); assertNotSame(Channel.class.getClassLoader(), o.getClass().getClassLoader()); assertTrue(o.getClass().getClassLoader() instanceof RemoteClassLoader); return null; } private static final long serialVersionUID = 1L; } }
package net.slreynolds.ds.model; import static org.junit.Assert.*; import java.util.HashMap; import net.slreynolds.ds.ObjectSaver; import net.slreynolds.ds.model.Graph; import net.slreynolds.ds.model.GraphPoint; import net.slreynolds.ds.model.Named; import org.junit.Test; public class TestModel { public static class A { @SuppressWarnings("unused") private final B _b; public A(B b) { _b = b; } } public static class B { @SuppressWarnings("unused") private final C _c; public B(C c) { _c = c; } } public static class C { @SuppressWarnings("unused") private final int _i; public C(int i) { _i = i; } } @Test public void testObjectReferences() { C c = new C(2); B b = new B(c); A a = new A(b); ExporterStub exporter = new ExporterStub(); ObjectSaver saver = new ObjectSaver(exporter); saver.save(new Object[]{a},new String[]{"a"},new HashMap<String,Object>()); Graph g = exporter.getGraph(); assertEquals("num graph points",4,g.getGraphPoints().size()); GraphPoint gp = g.getPrimaryGraphPoint(); assertTrue("primary point isa symbol",gp.hasAttr(Named.SYMBOL)); assertTrue("primary point isa symbol",(Boolean)gp.getAttr(Named.SYMBOL)); assertEquals("primary has one link",1,gp.getNeighbors().size()); GraphPoint gp_a = gp.getNeighbors().get(0).getTo(); assertEquals("a has one link",1,gp_a.getNeighbors().size()); GraphPoint gp_b = gp_a.getNeighbors().get(0).getTo(); assertEquals("b has one link",1,gp_b.getNeighbors().size()); GraphPoint gp_c = gp_b.getNeighbors().get(0).getTo(); assertEquals("c has no links",0,gp_c.getNeighbors().size()); } public static class DummyClass { @SuppressWarnings("unused") private int one; @SuppressWarnings("unused") private double two; @SuppressWarnings("unused") private char three; @SuppressWarnings("unused") private float four; @SuppressWarnings("unused") private byte five; @SuppressWarnings("unused") private boolean six; public DummyClass(int one, double two, char three, float four, byte five, boolean six) { this.one = one; this.two = two; this.three = three; this.four = four; this.five = five; this.six = six; } } @Test public void testFields() { DummyClass dummy = new DummyClass(1,2.0,'c',4.0f,(byte)5,true); ExporterStub exporter = new ExporterStub(); ObjectSaver saver = new ObjectSaver(exporter); saver.save(new Object[]{dummy},new String[]{"um"},new HashMap<String,Object>()); Graph g = exporter.getGraph(); assertEquals("num graph points",2,g.getGraphPoints().size()); GraphPoint gp = g.getPrimaryGraphPoint(); assertTrue("primary point isa symbol",gp.hasAttr(Named.SYMBOL)); assertTrue("primary point isa symbol",(Boolean)gp.getAttr(Named.SYMBOL)); assertEquals("primary has one link",1,gp.getNeighbors().size()); GraphPoint gp_dummy = gp.getNeighbors().get(0).getTo(); assertEquals("dummy has no links",0,gp_dummy.getNeighbors().size()); assertEquals("dummy.one",1,gp_dummy.getAttr("one")); assertEquals("dummy.two",2.0,gp_dummy.getAttr("two")); assertEquals("dummy.three",'c',gp_dummy.getAttr("three")); assertEquals("dummy.four",4.0f,gp_dummy.getAttr("four")); assertEquals("dummy.five",(byte)5,gp_dummy.getAttr("five")); assertEquals("dummy.six",true,gp_dummy.getAttr("six")); } public static class D { @SuppressWarnings("unused") private Object _o; public D() { _o = null; } public void setO(Object o) { _o = o; } } @Test(timeout=500) public void testObjectCycle() { D d1 = new D(); D d2 = new D(); D d3 = new D(); d1.setO(d2); d2.setO(d3); d3.setO(d1); ExporterStub exporter = new ExporterStub(); ObjectSaver saver = new ObjectSaver(exporter); saver.save(new Object[]{d1},new String[]{"d1"},new HashMap<String,Object>()); Graph g = exporter.getGraph(); assertEquals("num graph points",4,g.getGraphPoints().size()); } }
package detective.core; import groovy.json.JsonBuilder; import groovy.json.JsonSlurper; import groovy.lang.Closure; import groovy.util.XmlSlurper; import groovy.xml.MarkupBuilder; import java.util.Arrays; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.hamcrest.core.AnyOf; import org.hamcrest.core.IsNot; import org.junit.Assert; import com.typesafe.config.Config; import detective.common.trace.TraceRecord; import detective.common.trace.TraceRecordBuilder; import detective.common.trace.TraceRecorder; import detective.common.trace.impl.TraceRecorderElasticSearchImpl; import detective.core.dsl.WrappedObject; import detective.core.dsl.builder.DslBuilder; import detective.core.matcher.IsEqual; import detective.core.matcher.Subset; import detective.core.runner.DslBuilderAndRun; import detective.core.services.DetectiveFactory; import detective.task.EchoTask; import detective.task.HttpClientTask; import detective.utils.StringUtils; /** * The Factory / Entry Point class for Detective Framework * * @author James Luo * */ public class Detective { private enum Recorder { INSTANCE; private final transient TraceRecorderElasticSearchImpl recorder = new TraceRecorderElasticSearchImpl(); public TraceRecorder getRecorder() { return recorder; } } public enum LogLevel{ FATAL, ERROR, WARN, INFO, DEBUG, TRACE; } public static DslBuilder story(){ return new DslBuilderAndRun(); } public static DslBuilder feature(){ return new DslBuilderAndRun(); } public static JsonBuilder jsonBuilder(){ return new JsonBuilder(); } public static JsonBuilder jsonBuilder(Closure c){ JsonBuilder builder = new JsonBuilder(); builder.call(c); return builder; } public static Object jsonParser(String json){ return (new JsonSlurper()).parseText(json); } public static MarkupBuilder xmlBuilder(Closure c){ MarkupBuilder builder = new MarkupBuilder(); return builder; } public static Object xmlParser(String xml){ try { return (new XmlSlurper()).parseText(xml); } catch (Throwable e) { throw new RuntimeException(e); } } public static TraceRecord record(TraceRecord record){ Recorder.INSTANCE.getRecorder().record(record); return record; } public static TraceRecord recordLog(LogLevel level, String message){ TraceRecord record = TraceRecordBuilder.newRecord().withSimpleDateAsHashKey().getRecord(); record.setType("log"); record.setCaption(message); return record(record); } public static TraceRecord info(String message){ return recordLog(LogLevel.INFO, message); } public static TraceRecord error(String message){ return recordLog(LogLevel.ERROR, message); } public static TraceRecord error(String message, Throwable e){ TraceRecord record = TraceRecordBuilder.newRecord() .withSimpleDateAsHashKey() .withException(e) .getRecord(); record.setType("log"); record.setCaption(message); return record(record); } public static TraceRecord debug(String message){ return recordLog(LogLevel.DEBUG, message); } public static EchoTask echoTask(){ return new EchoTask(); } public static HttpClientTask httpclientTask(){ return new HttpClientTask(); } public static <T> Matcher<T> equalTo(T operand) { return IsEqual.equalTo(operand); } public static <T> Matcher<T> subsetOf(T operand) { if (operand != null && operand instanceof WrappedObject){ operand = (T)((WrappedObject)operand).getValue(); } return Subset.subsetOf(operand); } public static <T> Matcher<T> not(T value) { return IsNot.not(equalTo(value)); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T>... matchers) { return AllOf.allOf(Arrays.asList(matchers)); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second) { return AllOf.allOf(first, second); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second, Matcher<? super T> third) { return AllOf.allOf(first, second, third); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second, Matcher<? super T> third, Matcher<? super T> fourth) { return AllOf.allOf(first, second, third, fourth); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second, Matcher<? super T> third, Matcher<? super T> fourth, Matcher<? super T> fifth) { return AllOf.allOf(first, second, third, fourth, fifth); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second, Matcher<? super T> third, Matcher<? super T> fourth, Matcher<? super T> fifth, Matcher<? super T> sixth) { return AllOf.allOf(first, second, third, fourth, fifth, sixth); } /** * Creates a matcher that matches if the examined object matches <b>Any</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", anyOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> anyOf(Matcher<? super T>... matchers) { return AnyOf.anyOf(Arrays.asList(matchers)); } /** * Asserts that <code>actual</code> satisfies the condition specified by * <code>matcher</code>. If not, an {@link AssertionError} is thrown with * information about the matcher and failing value. Example: * * <pre> * assertThat(0, is(1)); // fails: * // failure message: * // expected: is &lt;1&gt; * // got value: &lt;0&gt; * assertThat(0, is(not(1))) // passes * </pre> * * @param <T> * the static type accepted by the matcher (this can flag obvious * compile-time problems such as {@code assertThat(1, is("a"))} * @param actual * the computed value being compared * @param matcher * an expression, built of {@link Matcher}s, specifying allowed * values * * @see org.hamcrest.CoreMatchers * @see org.junit.matchers.JUnitMatchers */ public static <T> void assertThat(T actual, Matcher<T> matcher) { assertThat("", actual, matcher); } /** * Asserts that <code>actual</code> satisfies the condition specified by * <code>matcher</code>. If not, an {@link AssertionError} is thrown with * the reason and information about the matcher and failing value. Example: * * <pre> * : * assertThat(&quot;Help! Integers don't work&quot;, 0, is(1)); // fails: * // failure message: * // Help! Integers don't work * // expected: is &lt;1&gt; * // got value: &lt;0&gt; * assertThat(&quot;Zero is one&quot;, 0, is(not(1))) // passes * </pre> * * @param reason * additional information about the error * @param <T> * the static type accepted by the matcher (this can flag obvious * compile-time problems such as {@code assertThat(1, is("a"))} * @param actual * the computed value being compared * @param matcher * an expression, built of {@link Matcher}s, specifying allowed * values * * @see org.hamcrest.CoreMatchers * @see org.junit.matchers.JUnitMatchers */ public static <T> void assertThat(String reason, T actual, Matcher<T> matcher) { Assert.assertThat(reason, actual, matcher); } public static String randomId() { return StringUtils.randomBase64UUID(); } public static Config getConfig(){ return DetectiveFactory.INSTANCE.getConfig(); } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.anim; import java.util.ArrayList; import java.util.List; import pythagoras.f.XY; import react.Value; import playn.core.Asserts; import playn.core.GroupLayer; import playn.core.ImageLayer; import playn.core.Layer; import playn.core.PlayN; import playn.core.Sound; import tripleplay.sound.Playable; import tripleplay.util.Layers; /** * Handles creation and management of animations. Animations may involve the tweening of a * geometric property of a layer (x, y, rotation, scale, alpha), or simple delays, or performing * actions. Animations can also be sequenced to orchestrate complex correlated actions. */ public abstract class Animator { /** * Creates an instance of an animator. The caller is responsible for calling {@link #update} on * said animator to drive the animation process. */ public static Animator create () { return new Impl(); } /** * Registers an animation with this animator. It will be started on the next frame and continue * until cancelled or it reports that it has completed. */ public abstract <T extends Animation> T add (T anim); /** * Starts a tween on the supplied layer's x/y-translation. */ public Animation.Two tweenTranslation (Layer layer) { return tweenXY(layer); } /** * Starts a tween on the supplied layer's x/y-translation. */ public Animation.Two tweenXY (Layer layer) { return add(new Animation.Two(onX(layer), onY(layer))); } /** * Starts a tween on the supplied layer's x-translation. */ public Animation.One tweenX (Layer layer) { return tween(onX(layer)); } /** * Starts a tween on the supplied layer's y-translation. */ public Animation.One tweenY (Layer layer) { return tween(onY(layer)); } /** * Starts a tween on the supplied layer's rotation. */ public Animation.One tweenRotation (final Layer layer) { Asserts.checkNotNull(layer); return tween(new Animation.Value() { public float initial () { return layer.transform().rotation(); } public void set (float value) { layer.setRotation(value); } }); } /** * Starts a tween on the supplied layer's x/y-scale. */ public Animation.One tweenScale (final Layer layer) { Asserts.checkNotNull(layer); return tween(new Animation.Value() { public float initial () { return layer.transform().uniformScale(); } public void set (float value) { layer.setScale(value); } }); } /** * Starts a tween on the supplied layer's x/y-scale. */ public Animation.Two tweenScaleXY (Layer layer) { return add(new Animation.Two(onScaleX(layer), onScaleY(layer))); } /** * Starts a tween on the supplied layer's x-scale. */ public Animation.One tweenScaleX (Layer layer) { return tween(onScaleX(layer)); } /** * Starts a tween on the supplied layer's y-scale. */ public Animation.One tweenScaleY (Layer layer) { return tween(onScaleY(layer)); } /** * Starts a tween on the supplied layer's transparency. */ public Animation.One tweenAlpha (final Layer layer) { Asserts.checkNotNull(layer); return tween(new Animation.Value() { public float initial () { return layer.alpha(); } public void set (float value) { layer.setAlpha(value); } }); } /** * Starts a tween using the supplied custom value. {@link Animation.Value#initial} will be used * (if needed) to obtain the initial value before the tween begins. {@link Animation.Value#set} * will be called each time the tween is updated with the intermediate values. */ public Animation.One tween (Animation.Value value) { return add(new Animation.One(value)); } /** * Starts a flipbook animation that displays in {@code layer}. Note that the image layer in * question will have its translation adjusted based on the offset of the current frame. Thus * it should be placed into a {@link GroupLayer} if it is to be positioned and animated * separately. */ public Animation.Flip flipbook (ImageLayer layer, Flipbook book) { return add(new Animation.Flip(layer, book)); } /** * Starts a flipbook animation in a new image layer which is created and added to {@code box}. * When the flipbook animation is complete, the newly created image layer will not be destroyed * automatically. This allows the animation to be repeated, if desired. The caller must destroy * eventually the image layer, or more likely, destroy {@code box} which will cause the created * image layer to be destroyed. */ public Animation.Flip flipbook (GroupLayer box, Flipbook book) { ImageLayer image = PlayN.graphics().createImageLayer(); box.add(image); return flipbook(image, book); } /** * Starts a flipbook animation that displays the supplied {@code book} at the specified * position in the supplied parent. The intermediate layers created to display the flipbook * animation will be destroyed on completion. */ public Animation flipbookAt (GroupLayer parent, float x, float y, Flipbook book) { GroupLayer box = PlayN.graphics().createGroupLayer(); box.setTranslation(x, y); return add(parent, box).then().flipbook(box, book).then().destroy(box); } /** * Starts a flipbook animation that displays the supplied {@code book} at the specified * position in the supplied parent. The intermediate layers created to display the flipbook * animation will be destroyed on completion. */ public Animation flipbookAt (GroupLayer parent, XY pos, Flipbook book) { return flipbookAt(parent, pos.x(), pos.y(), book); } /** * Creates a shake animation on the specified layer. */ public Animation.Shake shake (Layer layer) { return add(new Animation.Shake(layer)); } /** * Creates an animation that delays for the specified number of seconds. */ public Animation.Delay delay (float seconds) { return add(new Animation.Delay(seconds)); } /** * Returns an animator which can be used to construct an animation that will be repeated until * the supplied layer has been removed from its parent. The layer must be added to a parent * before the next frame (if it's not already), or the cancellation will trigger immediately. */ public Animator repeat (Layer layer) { return add(new Animation.Repeat(layer)).then(); } /** * Creates an animation that executes the supplied runnable and immediately completes. */ public Animation.Action action (Runnable action) { return add(new Animation.Action(action)); } /** * Adds the supplied child to the supplied parent. This is generally done as the beginning of a * chain of animations, which itself may be delayed or subject to animation barriers. */ public Animation.Action add (final GroupLayer parent, final Layer child) { return action(new Runnable() { public void run () { parent.add(child); }}); } /** * Adds the supplied child to the supplied parent at the specified translation. This is * generally done as the beginning of a chain of animations, which itself may be delayed or * subject to animation barriers. */ public Animation.Action addAt (GroupLayer parent, Layer child, XY pos) { return addAt(parent, child, pos.x(), pos.y()); } /** * Adds the supplied child to the supplied parent at the specified translation. This is * generally done as the beginning of a chain of animations, which itself may be delayed or * subject to animation barriers. */ public Animation.Action addAt (final GroupLayer parent, final Layer child, final float x, final float y) { return action(new Runnable() { public void run () { parent.addAt(child, x, y); }}); } /** * Reparents the supplied child to the supplied new parent. This involves translating the * child's current coordinates to screen coordinates, moving it to its new parent layer and * translating its coordinates into the coordinate space of the new parent. Thus the child does * not change screen position, even though its coordinates relative to its parent will most * likely have changed. */ public Animation.Action reparent (final GroupLayer newParent, final Layer child) { return action(new Runnable() { public void run () { Layers.reparent(child, newParent); }}); } /** * Destroys the specified layer. This is generally done as the end of a chain of animations, * which culminate in the removal (destruction) of the target layer. */ public Animation.Action destroy (final Layer layer) { return action(new Runnable() { public void run () { layer.destroy(); }}); } /** * Sets the specified layer's depth to the specified value. */ public Animation.Action setDepth (final Layer layer, final float depth) { return action(new Runnable() { public void run () { layer.setDepth(depth); }}); } /** * Sets the specified layer to visible or not. */ public Animation.Action setVisible (final Layer layer, final boolean visible) { return action(new Runnable() { public void run () { layer.setVisible(visible); }}); } /** * Plays the supplied clip or loop. */ public Animation.Action play (final Playable sound) { return action(new Runnable() { public void run () { sound.play(); }}); } /** * Stops the supplied clip or loop. */ public Animation.Action stop (final Playable sound) { return action(new Runnable() { public void run () { sound.stop(); }}); } /** * Plays the supplied sound. */ public Animation.Action play (final Sound sound) { return action(new Runnable() { public void run () { sound.play(); }}); } /** * Tweens the volumne of the supplied sound. Useful for fade-ins and fade-outs. Note, this does * not play or stop the sound, those must be enacted separately. */ public Animation.One tweenVolume (final Sound sound) { Asserts.checkNotNull(sound); return tween(new Animation.Value() { public float initial () { return sound.volume(); } public void set (float value) { sound.setVolume(value); } }); } /** * Stops the supplied sound from playing. */ public Animation.Action stop (final Sound sound) { return action(new Runnable() { public void run () { sound.stop(); }}); } /** * Sets a value to the supplied constant. */ public <T> Animation.Action setValue (final Value<T> value, final T newValue) { return action(new Runnable() { public void run () { value.update(newValue); }}); } /** * Increments (or decrements if {@code amount} is negative} an int value. */ public Animation.Action increment (final Value<Integer> value, final int amount) { return action(new Runnable() { public void run () { value.update(value.get() + amount); }}); } /** * Causes this animator to delay the start of any subsequently registered animations until all * currently registered animations are complete. */ public void addBarrier () { addBarrier(0); } /** * Causes this animator to delay the start of any subsequently registered animations until the * specified delay has elapsed <em>after this barrier becomes active</em>. Any previously * registered barriers must first expire and this barrier must move to the head of the list * before its delay timer will be started. This is probably what you want. */ public void addBarrier (float delay) { throw new UnsupportedOperationException( "Barriers are only supported on the top-level animator."); } /** * Performs per-frame animation processing. * @param time a monotonically increasing seconds value. */ public void update (float time) { // nada by default } protected static Animation.Value onX (final Layer layer) { Asserts.checkNotNull(layer); return new Animation.Value() { public float initial () { return layer.transform().tx(); } public void set (float value) { layer.transform().setTx(value); } }; } protected static Animation.Value onY (final Layer layer) { Asserts.checkNotNull(layer); return new Animation.Value() { public float initial () { return layer.transform().ty(); } public void set (float value) { layer.transform().setTy(value); } }; } protected static Animation.Value onScaleX (final Layer layer) { Asserts.checkNotNull(layer); return new Animation.Value() { public float initial () { return layer.transform().scaleX(); } public void set (float value) { layer.transform().setScaleX(value); } }; } protected static Animation.Value onScaleY (final Layer layer) { Asserts.checkNotNull(layer); return new Animation.Value() { public float initial () { return layer.transform().scaleY(); } public void set (float value) { layer.transform().setScaleY(value); } }; } /** Implementation details, avert your eyes. */ protected static class Impl extends Animator { @Override public <T extends Animation> T add (T anim) { _accum.add(anim); return anim; } @Override public void addBarrier (float delay) { Barrier barrier = new Barrier(delay); _barriers.add(barrier); // pushing a barrier causes subsequent animations to be accumulated separately _accum = barrier.accum; } @Override public void update (float time) { // if we have any animations queued up to be added, add those now if (!_nanims.isEmpty()) { for (int ii = 0, ll = _nanims.size(); ii < ll; ii++) { _nanims.get(ii).init(time); } _anims.addAll(_nanims); _nanims.clear(); } // now process all of our registered animations for (int ii = 0, ll = _anims.size(); ii < ll; ii++) { if (_anims.get(ii).apply(this, time) <= 0) { _anims.remove(ii ll -= 1; } } // if we have no active animations, or a timed barrier has expired, unblock a barrier boolean noActiveAnims = _anims.isEmpty() && _nanims.isEmpty(); if (!_barriers.isEmpty() && (noActiveAnims || _barriers.get(0).expired(time))) { Barrier barrier = _barriers.remove(0); _nanims.addAll(barrier.accum); // if we just unblocked the last barrier, start accumulating back on _nanims if (_barriers.isEmpty()) { _accum = _nanims; } } } protected List<Animation> _anims = new ArrayList<Animation>(); protected List<Animation> _nanims = new ArrayList<Animation>(); protected List<Animation> _accum = _nanims; protected List<Barrier> _barriers = new ArrayList<Barrier>(); } /** Implementation details, avert your eyes. */ protected static class Barrier { public List<Animation> accum = new ArrayList<Animation>(); public float expireDelay; public float absoluteExpireTime; public Barrier (float expireDelay) { this.expireDelay = expireDelay; } public boolean expired (float time) { if (expireDelay == 0) return false; if (absoluteExpireTime == 0) absoluteExpireTime = time + expireDelay; return time > absoluteExpireTime; } } }
package org.xins.tests.server; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Set; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.xins.common.ProgrammingException; import org.xins.server.APIServlet; /** * Tests for class <code>APIServlet</code>. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) */ public class APIServletTests extends TestCase { // Class functions /** * Returns a test suite with all test cases defined by this class. * * @return * the test suite, never <code>null</code>. */ public static Test suite() { return new TestSuite(APIServletTests.class); } // Class fields // Constructor /** * Constructs a new <code>APIServletTests</code> test suite with * the specified name. The name will be passed to the superconstructor. * * @param name * the name for this test suite. */ public APIServletTests(String name) { super(name); } // Fields // Methods /** * Performs setup for the tests. */ protected void setUp() { // empty } public void testAPIServlet() throws Throwable { APIServlet servlet = new APIServlet(); assertTrue("Expected getServletConfig() to return null, initially.", servlet.getServletConfig() == null); String servletInfo = servlet.getServletInfo(); assertNotNull(servletInfo); assertTrue(servletInfo.indexOf("XINS") > -1); try { servlet.init(null); fail("Expected APIServlet.init(null) to throw an IllegalArgumentException."); return; } catch (IllegalArgumentException exception) { // as expected String msg = exception.getMessage(); assertNotNull(msg); assertTrue("Expected exception message (" + msg + ") to contain \"null\".", msg.indexOf("null") > -1); } try { servlet.initImpl(null); fail("Expected APIServlet.initImpl(null) to throw an IllegalArgumentException."); return; } catch (IllegalArgumentException exception) { // as expected String msg = exception.getMessage(); assertNotNull(msg); assertTrue("Expected exception message (" + msg + ") to contain \"null\".", msg.indexOf("null") > -1); } TestServletConfig config = new TestServletConfig(); try { servlet.init(config); fail("Expected APIServlet.init(ServletConfig) to throw an IllegalArgumentException if ServletConfig.getServletContext() == null."); return; } catch (IllegalArgumentException exception) { // as expected String msg = exception.getMessage(); assertNotNull(msg); assertTrue("Expected exception message (" + msg + ") to contain \"null\".", msg.indexOf("null") > -1); assertTrue("Expected exception message (" + msg + ") to contain \"onfig\".", msg.indexOf("onfig") > -1); } TestServletContext context = new TestServletContext(); context._major = 2; context._minor = 0; config = new TestServletConfig(); config._context = context; try { servlet.init(config); fail("Expected ProgrammingException."); return; } catch (ProgrammingException exception) { // as expected String msg = exception.getMessage(); assertNotNull(msg); assertTrue(msg.indexOf("getServerInfo()") > -1); assertTrue(msg.indexOf("null" ) > -1); } context._serverInfo = getClass().getName(); try { servlet.init(config); } catch (ServletException exception) { // as expected } // TODO } // Inner classes private class TestServletConfig extends Object implements ServletConfig { // Fields public ServletContext _context; // Methods public String getServletName() { return "servlet 1"; } public ServletContext getServletContext() { return _context; } public String getInitParameter(String name) { return null; } public Enumeration getInitParameterNames() { return null; } } private class TestServletContext extends Object implements ServletContext { // Constructors public TestServletContext() { // TODO } // Fields public int _major = 2; public int _minor = 4; public String _serverInfo; // Methods public ServletContext getContext(String uripath) { return null; } public int getMajorVersion() { return _major; } public int getMinorVersion() { return _minor; } public String getMimeType(String file) { return null; } public Set getResourcePaths(String path) { return null; } public URL getResource(String path) throws MalformedURLException { return null; } public InputStream getResourceAsStream(String path) { return null; } public RequestDispatcher getRequestDispatcher(String path) { return null; } public RequestDispatcher getNamedDispatcher(String name) { return null; } public Servlet getServlet(String name) { return null; } public Enumeration getServlets() { return null; } public Enumeration getServletNames() { return null; } public void log(String msg) { // empty } public void log(Exception exception, String msg) { // empty } public void log(String message, Throwable throwable) { // empty } public String getRealPath(String path) { return null; } public String getServerInfo() { return _serverInfo; } public String getInitParameter(String name) { return null; } public Enumeration getInitParameterNames() { return null; } public Object getAttribute(String name) { return null; } public Enumeration getAttributeNames() { return null; } public void setAttribute(String name, Object object) { // empty } public void removeAttribute(String name) { // empty } public String getServletContextName() { return "context 1"; } } }
package imagej.module; import imagej.Contextual; import imagej.MenuPath; import imagej.event.EventService; import imagej.input.Accelerator; import imagej.log.LogService; import imagej.module.event.ModulesAddedEvent; import imagej.module.event.ModulesRemovedEvent; import imagej.plugin.Parameter; import imagej.plugin.Plugin; import imagej.service.AbstractService; import imagej.service.Service; import imagej.thread.ThreadService; import imagej.util.ClassUtils; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * Default service for keeping track of and executing available modules. * * @author Curtis Rueden * @see Module * @see ModuleInfo */ @Plugin(type = Service.class) public class DefaultModuleService extends AbstractService implements ModuleService { @Parameter private LogService log; @Parameter private EventService eventService; @Parameter private ThreadService threadService; /** Index of registered modules. */ private ModuleIndex moduleIndex; // -- ModuleService methods -- @Override public ModuleIndex getIndex() { return moduleIndex; } @Override public void addModule(final ModuleInfo module) { if (moduleIndex.add(module)) { eventService.publish(new ModulesAddedEvent(module)); } } @Override public void removeModule(final ModuleInfo module) { if (moduleIndex.remove(module)) { eventService.publish(new ModulesRemovedEvent(module)); } } @Override public void addModules(final Collection<? extends ModuleInfo> modules) { if (moduleIndex.addAll(modules)) { eventService.publish(new ModulesAddedEvent(modules)); } } @Override public void removeModules(final Collection<? extends ModuleInfo> modules) { if (moduleIndex.removeAll(modules)) { eventService.publish(new ModulesRemovedEvent(modules)); } } @Override public List<ModuleInfo> getModules() { return moduleIndex.getAll(); } @Override public ModuleInfo getModuleForAccelerator(final Accelerator acc) { for (final ModuleInfo info : getModules()) { final MenuPath menuPath = info.getMenuPath(); if (menuPath == null || menuPath.isEmpty()) continue; if (acc.equals(menuPath.getLeaf().getAccelerator())) return info; } return null; } @Override public Future<Module> run(final ModuleInfo info, final Object... inputs) { return run(info, null, null, inputs); } @Override public Future<Module> run(final ModuleInfo info, final List<? extends ModulePreprocessor> pre, final List<? extends ModulePostprocessor> post, final Object... inputs) { return run(info, pre, post, createMap(inputs)); } @Override public Future<Module> run(final ModuleInfo info, final List<? extends ModulePreprocessor> pre, final List<? extends ModulePostprocessor> post, final Map<String, Object> inputMap) { try { final Module module = info.createModule(); if (module instanceof Contextual) { ((Contextual)module).setContext(getContext()); } return run(module, pre, post, inputMap); } catch (final ModuleException e) { log.error("Could not execute module: " + info, e); } return null; } @Override public Future<Module> run(final Module module, final Object... inputs) { return run(module, null, null, inputs); } @Override public <M extends Module> Future<M> run(final M module, final List<? extends ModulePreprocessor> pre, final List<? extends ModulePostprocessor> post, final Object... inputs) { return run(module, pre, post, createMap(inputs)); } @Override public <M extends Module> Future<M> run(final M module, final List<? extends ModulePreprocessor> pre, final List<? extends ModulePostprocessor> post, final Map<String, Object> inputMap) { assignInputs(module, inputMap); final ModuleRunner runner = new ModuleRunner(getContext(), module, pre, post); @SuppressWarnings("unchecked") final Callable<M> callable = (Callable<M>) runner; final Future<M> future = threadService.run(callable); return future; } @Override public <M extends Module> M waitFor(final Future<M> future) { try { return future.get(); } catch (final InterruptedException e) { log.error("Module execution interrupted", e); } catch (final ExecutionException e) { log.error("Error during module execution", e); } return null; } @Override public <T> ModuleItem<T> getSingleInput(final Module module, final Class<T> type) { return getSingleItem(module, type, module.getInfo().inputs()); } @Override public <T> ModuleItem<T> getSingleOutput(final Module module, final Class<T> type) { return getSingleItem(module, type, module.getInfo().outputs()); } // -- Service methods -- @Override public void initialize() { moduleIndex = new ModuleIndex(); } // -- Helper methods -- /** Converts the given list of name/value pairs into an input map. */ private Map<String, Object> createMap(final Object[] values) { if (values == null || values.length == 0) return null; final HashMap<String, Object> inputMap = new HashMap<String, Object>(); if (values.length % 2 != 0) { log.error("Ignoring extraneous argument: " + values[values.length - 1]); } // loop over list of key/value pairs int numPairs = values.length / 2; for (int i = 0; i < numPairs; i++) { final Object key = values[2 * i]; final Object value = values[2 * i + 1]; if (!(key instanceof String)) { log.error("Invalid input name: " + key); continue; } final String name = (String) key; inputMap.put(name, value); } return inputMap; } /** Sets the given module's input values to those in the given map. */ private void assignInputs(final Module module, final Map<String, Object> inputMap) { if (inputMap == null) return; // no inputs to assign for (final String name : inputMap.keySet()) { final ModuleItem<?> input = module.getInfo().getInput(name); if (input == null) { log.error("No such input: " + name); continue; } final Object value = inputMap.get(name); final Class<?> type = input.getType(); final Object converted = ClassUtils.convert(value, type); if (value != null && converted == null) { log.error("For input " + name + ": incompatible object " + value.getClass().getName() + " for type " + type.getName()); continue; } module.setInput(name, converted); module.setResolved(name, true); } } private <T> ModuleItem<T> getSingleItem(final Module module, final Class<T> type, final Iterable<ModuleItem<?>> items) { ModuleItem<T> result = null; for (final ModuleItem<?> item : items) { final String name = item.getName(); final boolean resolved = module.isResolved(name); if (resolved) continue; // skip resolved inputs if (!type.isAssignableFrom(item.getType())) continue; if (result != null) return null; // multiple matching items @SuppressWarnings("unchecked") final ModuleItem<T> typedItem = (ModuleItem<T>) item; result = typedItem; } return result; } }
package io.undertow.server.handlers; import java.util.Date; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.DateUtils; import io.undertow.util.Headers; public class DateHandler implements HttpHandler { private final HttpHandler next; private volatile String cachedDateString; private volatile long nextUpdateTime = -1; public DateHandler(final HttpHandler next) { this.next = next; } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { long time = System.currentTimeMillis(); if(time < nextUpdateTime) { exchange.getResponseHeaders().put(Headers.DATE, cachedDateString); } else { String dateString = DateUtils.toDateString(new Date(time)); cachedDateString = dateString; nextUpdateTime = time + 1000; exchange.getResponseHeaders().put(Headers.DATE, dateString); } next.handleRequest(exchange); } }
package org.bouncycastle.asn1.x9; import java.math.BigInteger; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.math.ec.ECAlgorithms; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.math.field.PolynomialExtensionField; /** * ASN.1 def for Elliptic-Curve ECParameters structure. See * X9.62, for further details. */ public class X9ECParameters extends ASN1Object implements X9ObjectIdentifiers { private static final BigInteger ONE = BigInteger.valueOf(1); private X9FieldID fieldID; private ECCurve curve; private ECPoint g; private BigInteger n; private BigInteger h; private byte[] seed; private X9ECParameters( ASN1Sequence seq) { if (!(seq.getObjectAt(0) instanceof ASN1Integer) || !((ASN1Integer)seq.getObjectAt(0)).getValue().equals(ONE)) { throw new IllegalArgumentException("bad version in X9ECParameters"); } X9Curve x9c = new X9Curve( X9FieldID.getInstance(seq.getObjectAt(1)), ASN1Sequence.getInstance(seq.getObjectAt(2))); this.curve = x9c.getCurve(); Object p = seq.getObjectAt(3); if (p instanceof X9ECPoint) { this.g = ((X9ECPoint)p).getPoint(); } else { this.g = new X9ECPoint(curve, (ASN1OctetString)p).getPoint(); } this.n = ((ASN1Integer)seq.getObjectAt(4)).getValue(); this.seed = x9c.getSeed(); if (seq.size() == 6) { this.h = ((ASN1Integer)seq.getObjectAt(5)).getValue(); } } public static X9ECParameters getInstance(Object obj) { if (obj instanceof X9ECParameters) { return (X9ECParameters)obj; } if (obj != null) { return new X9ECParameters(ASN1Sequence.getInstance(obj)); } return null; } public X9ECParameters( ECCurve curve, ECPoint g, BigInteger n) { this(curve, g, n, ONE, null); } public X9ECParameters( ECCurve curve, ECPoint g, BigInteger n, BigInteger h) { this(curve, g, n, h, null); } public X9ECParameters( ECCurve curve, ECPoint g, BigInteger n, BigInteger h, byte[] seed) { this.curve = curve; this.g = g.normalize(); this.n = n; this.h = h; this.seed = seed; if (ECAlgorithms.isFpCurve(curve)) { this.fieldID = new X9FieldID(curve.getField().getCharacteristic()); } else if (ECAlgorithms.isF2mCurve(curve)) { PolynomialExtensionField field = (PolynomialExtensionField)curve.getField(); int[] exponents = field.getMinimalPolynomial().getExponentsPresent(); if (exponents.length == 3) { this.fieldID = new X9FieldID(exponents[2], exponents[1]); } else if (exponents.length == 5) { this.fieldID = new X9FieldID(exponents[4], exponents[1], exponents[2], exponents[3]); } else { throw new IllegalArgumentException("Only trinomial and pentomial curves are supported"); } } else { throw new IllegalArgumentException("'curve' is of an unsupported type"); } } public ECCurve getCurve() { return curve; } public ECPoint getG() { return g; } public BigInteger getN() { return n; } public BigInteger getH() { if (h == null) { return ONE; // TODO - this should be calculated, it will cause issues with custom curves. } return h; } public byte[] getSeed() { return seed; } /** * Produce an object suitable for an ASN1OutputStream. * <pre> * ECParameters ::= SEQUENCE { * version INTEGER { ecpVer1(1) } (ecpVer1), * fieldID FieldID {{FieldTypes}}, * curve X9Curve, * base X9ECPoint, * order INTEGER, * cofactor INTEGER OPTIONAL * } * </pre> */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1Integer(1)); v.add(fieldID); v.add(new X9Curve(curve, seed)); v.add(new X9ECPoint(g)); v.add(new ASN1Integer(n)); if (h != null) { v.add(new ASN1Integer(h)); } return new DERSequence(v); } }
package org.bouncycastle.crypto.tls; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.SecureRandom; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.prng.RandomGenerator; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; /** * An implementation of all high level protocols in TLS 1.0/1.1. */ public abstract class TlsProtocol { protected static final Integer EXT_RenegotiationInfo = Integers.valueOf(ExtensionType.renegotiation_info); protected static final Integer EXT_SessionTicket = Integers.valueOf(ExtensionType.session_ticket); private static final String TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack"; /* * Our Connection states */ protected static final short CS_START = 0; protected static final short CS_CLIENT_HELLO = 1; protected static final short CS_SERVER_HELLO = 2; protected static final short CS_SERVER_SUPPLEMENTAL_DATA = 3; protected static final short CS_SERVER_CERTIFICATE = 4; protected static final short CS_CERTIFICATE_STATUS = 5; protected static final short CS_SERVER_KEY_EXCHANGE = 6; protected static final short CS_CERTIFICATE_REQUEST = 7; protected static final short CS_SERVER_HELLO_DONE = 8; protected static final short CS_CLIENT_SUPPLEMENTAL_DATA = 9; protected static final short CS_CLIENT_CERTIFICATE = 10; protected static final short CS_CLIENT_KEY_EXCHANGE = 11; protected static final short CS_CERTIFICATE_VERIFY = 12; protected static final short CS_CLIENT_FINISHED = 13; protected static final short CS_SERVER_SESSION_TICKET = 14; protected static final short CS_SERVER_FINISHED = 15; protected static final short CS_END = 16; /* * Queues for data from some protocols. */ private ByteQueue applicationDataQueue = new ByteQueue(); private ByteQueue alertQueue = new ByteQueue(2); private ByteQueue handshakeQueue = new ByteQueue(); // private ByteQueue heartbeatQueue = new ByteQueue(); /* * The Record Stream we use */ protected RecordStream recordStream; protected SecureRandom secureRandom; private TlsInputStream tlsInputStream = null; private TlsOutputStream tlsOutputStream = null; private volatile boolean closed = false; private volatile boolean failedWithError = false; private volatile boolean appDataReady = false; private volatile boolean splitApplicationDataRecords = true; private byte[] expected_verify_data = null; protected TlsSession tlsSession = null; protected SessionParameters sessionParameters = null; protected SecurityParameters securityParameters = null; protected Certificate peerCertificate = null; protected int[] offeredCipherSuites = null; protected short[] offeredCompressionMethods = null; protected Hashtable clientExtensions = null; protected Hashtable serverExtensions = null; protected short connection_state = CS_START; protected boolean resumedSession = false; protected boolean receivedChangeCipherSpec = false; protected boolean secure_renegotiation = false; protected boolean allowCertificateStatus = false; protected boolean expectSessionTicket = false; public TlsProtocol(InputStream input, OutputStream output, SecureRandom secureRandom) { this.recordStream = new RecordStream(this, input, output); this.secureRandom = secureRandom; } protected abstract AbstractTlsContext getContext(); protected abstract TlsPeer getPeer(); protected void handleChangeCipherSpecMessage() throws IOException { } protected abstract void handleHandshakeMessage(short type, byte[] buf) throws IOException; protected void handleWarningMessage(short description) throws IOException { } protected void cleanupHandshake() { if (this.expected_verify_data != null) { Arrays.fill(this.expected_verify_data, (byte)0); this.expected_verify_data = null; } this.securityParameters.clear(); this.peerCertificate = null; this.offeredCipherSuites = null; this.offeredCompressionMethods = null; this.clientExtensions = null; this.serverExtensions = null; this.resumedSession = false; this.receivedChangeCipherSpec = false; this.secure_renegotiation = false; this.allowCertificateStatus = false; this.expectSessionTicket = false; } protected void completeHandshake() throws IOException { try { /* * We will now read data, until we have completed the handshake. */ while (this.connection_state != CS_END) { if (this.closed) { // TODO What kind of exception/alert? } safeReadRecord(); } this.recordStream.finaliseHandshake(); this.splitApplicationDataRecords = !TlsUtils.isTLSv11(getContext()); /* * If this was an initial handshake, we are now ready to send and receive application data. */ if (!appDataReady) { this.appDataReady = true; this.tlsInputStream = new TlsInputStream(this); this.tlsOutputStream = new TlsOutputStream(this); } if (this.tlsSession != null) { if (this.sessionParameters == null) { this.sessionParameters = new SessionParameters.Builder() .setCipherSuite(this.securityParameters.cipherSuite) .setCompressionAlgorithm(this.securityParameters.compressionAlgorithm) .setMasterSecret(this.securityParameters.masterSecret) .setPeerCertificate(this.peerCertificate) // TODO Consider filtering extensions that aren't relevant to resumed sessions .setServerExtensions(this.serverExtensions) .build(); this.tlsSession = new TlsSessionImpl(this.tlsSession.getSessionID(), this.sessionParameters); } getContext().setResumableSession(this.tlsSession); } getPeer().notifyHandshakeComplete(); } finally { cleanupHandshake(); } } protected void processRecord(short protocol, byte[] buf, int offset, int len) throws IOException { /* * Have a look at the protocol type, and add it to the correct queue. */ switch (protocol) { case ContentType.alert: { alertQueue.addData(buf, offset, len); processAlert(); break; } case ContentType.application_data: { if (!appDataReady) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } applicationDataQueue.addData(buf, offset, len); processApplicationData(); break; } case ContentType.change_cipher_spec: { processChangeCipherSpec(buf, offset, len); break; } case ContentType.handshake: { handshakeQueue.addData(buf, offset, len); processHandshake(); break; } case ContentType.heartbeat: { if (!appDataReady) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } // TODO[RFC 6520] // heartbeatQueue.addData(buf, offset, len); // processHeartbeat(); } default: /* * Uh, we don't know this protocol. * * RFC2246 defines on page 13, that we should ignore this. */ } } private void processHandshake() throws IOException { boolean read; do { read = false; /* * We need the first 4 bytes, they contain type and length of the message. */ if (handshakeQueue.size() >= 4) { byte[] beginning = new byte[4]; handshakeQueue.read(beginning, 0, 4, 0); ByteArrayInputStream bis = new ByteArrayInputStream(beginning); short type = TlsUtils.readUint8(bis); int len = TlsUtils.readUint24(bis); /* * Check if we have enough bytes in the buffer to read the full message. */ if (handshakeQueue.size() >= (len + 4)) { /* * Read the message. */ byte[] buf = handshakeQueue.removeData(len, 4); /* * RFC 2246 7.4.9. The value handshake_messages includes all handshake messages * starting at client hello up to, but not including, this finished message. * [..] Note: [Also,] Hello Request messages are omitted from handshake hashes. */ switch (type) { case HandshakeType.hello_request: break; case HandshakeType.finished: { if (this.expected_verify_data == null) { this.expected_verify_data = createVerifyData(!getContext().isServer()); } // NB: Fall through to next case label } default: recordStream.updateHandshakeData(beginning, 0, 4); recordStream.updateHandshakeData(buf, 0, len); break; } /* * Now, parse the message. */ handleHandshakeMessage(type, buf); read = true; } } } while (read); } private void processApplicationData() { /* * There is nothing we need to do here. * * This function could be used for callbacks when application data arrives in the future. */ } private void processAlert() throws IOException { while (alertQueue.size() >= 2) { /* * An alert is always 2 bytes. Read the alert. */ byte[] tmp = alertQueue.removeData(2, 0); short level = tmp[0]; short description = tmp[1]; getPeer().notifyAlertReceived(level, description); if (level == AlertLevel.fatal) { /* * RFC 2246 7.2.1. The session becomes unresumable if any connection is terminated * without proper close_notify messages with level equal to warning. */ invalidateSession(); this.failedWithError = true; this.closed = true; recordStream.safeClose(); throw new IOException(TLS_ERROR_MESSAGE); } else { /* * RFC 5246 7.2.1. The other party MUST respond with a close_notify alert of its own * and close down the connection immediately, discarding any pending writes. */ // TODO Can close_notify be a fatal alert? if (description == AlertDescription.close_notify) { handleClose(false); } /* * If it is just a warning, we continue. */ handleWarningMessage(description); } } } /** * This method is called, when a change cipher spec message is received. * * @throws IOException If the message has an invalid content or the handshake is not in the correct * state. */ private void processChangeCipherSpec(byte[] buf, int off, int len) throws IOException { for (int i = 0; i < len; ++i) { short message = TlsUtils.readUint8(buf, off + i); if (message != ChangeCipherSpec.change_cipher_spec) { throw new TlsFatalAlert(AlertDescription.decode_error); } if (this.receivedChangeCipherSpec || alertQueue.size() > 0 || handshakeQueue.size() > 0) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } recordStream.receivedReadCipherSpec(); this.receivedChangeCipherSpec = true; handleChangeCipherSpecMessage(); } } protected int applicationDataAvailable() throws IOException { return applicationDataQueue.size(); } /** * Read data from the network. The method will return immediately, if there is still some data * left in the buffer, or block until some application data has been read from the network. * * @param buf The buffer where the data will be copied to. * @param offset The position where the data will be placed in the buffer. * @param len The maximum number of bytes to read. * @return The number of bytes read. * @throws IOException If something goes wrong during reading data. */ protected int readApplicationData(byte[] buf, int offset, int len) throws IOException { if (len < 1) { return 0; } while (applicationDataQueue.size() == 0) { /* * We need to read some data. */ if (this.closed) { if (this.failedWithError) { /* * Something went terribly wrong, we should throw an IOException */ throw new IOException(TLS_ERROR_MESSAGE); } /* * Connection has been closed, there is no more data to read. */ return -1; } safeReadRecord(); } len = Math.min(len, applicationDataQueue.size()); applicationDataQueue.removeData(buf, offset, len, 0); return len; } protected void safeReadRecord() throws IOException { try { if (!recordStream.readRecord()) { // TODO It would be nicer to allow graceful connection close if between records // this.failWithError(AlertLevel.warning, AlertDescription.close_notify); throw new EOFException(); } } catch (TlsFatalAlert e) { if (!this.closed) { this.failWithError(AlertLevel.fatal, e.getAlertDescription(), "Failed to read record", e); } throw e; } catch (IOException e) { if (!this.closed) { this.failWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to read record", e); } throw e; } catch (RuntimeException e) { if (!this.closed) { this.failWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to read record", e); } throw e; } } protected void safeWriteRecord(short type, byte[] buf, int offset, int len) throws IOException { try { recordStream.writeRecord(type, buf, offset, len); } catch (TlsFatalAlert e) { if (!this.closed) { this.failWithError(AlertLevel.fatal, e.getAlertDescription(), "Failed to write record", e); } throw e; } catch (IOException e) { if (!closed) { this.failWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to write record", e); } throw e; } catch (RuntimeException e) { if (!closed) { this.failWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to write record", e); } throw e; } } /** * Send some application data to the remote system. * <p/> * The method will handle fragmentation internally. * * @param buf The buffer with the data. * @param offset The position in the buffer where the data is placed. * @param len The length of the data. * @throws IOException If something goes wrong during sending. */ protected void writeData(byte[] buf, int offset, int len) throws IOException { if (this.closed) { if (this.failedWithError) { throw new IOException(TLS_ERROR_MESSAGE); } throw new IOException("Sorry, connection has been closed, you cannot write more data"); } while (len > 0) { /* * RFC 5246 6.2.1. Zero-length fragments of Application data MAY be sent as they are * potentially useful as a traffic analysis countermeasure. * * NOTE: Actually, implementations appear to have settled on 1/n-1 record splitting. */ if (this.splitApplicationDataRecords) { /* * Protect against known IV attack! * * DO NOT REMOVE THIS CODE, EXCEPT YOU KNOW EXACTLY WHAT YOU ARE DOING HERE. */ safeWriteRecord(ContentType.application_data, buf, offset, 1); ++offset; --len; } if (len > 0) { // Fragment data according to the current fragment limit. int toWrite = Math.min(len, recordStream.getPlaintextLimit()); safeWriteRecord(ContentType.application_data, buf, offset, toWrite); offset += toWrite; len -= toWrite; } } } protected void writeHandshakeMessage(byte[] buf, int off, int len) throws IOException { while (len > 0) { // Fragment data according to the current fragment limit. int toWrite = Math.min(len, recordStream.getPlaintextLimit()); safeWriteRecord(ContentType.handshake, buf, off, toWrite); off += toWrite; len -= toWrite; } } /** * @return An OutputStream which can be used to send data. */ public OutputStream getOutputStream() { return this.tlsOutputStream; } /** * @return An InputStream which can be used to read data. */ public InputStream getInputStream() { return this.tlsInputStream; } /** * Terminate this connection with an alert. Can be used for normal closure too. * * @param alertLevel * See {@link AlertLevel} for values. * @param alertDescription * See {@link AlertDescription} for values. * @throws IOException * If alert was fatal. */ protected void failWithError(short alertLevel, short alertDescription, String message, Exception cause) throws IOException { /* * Check if the connection is still open. */ if (!closed) { /* * Prepare the message */ this.closed = true; if (alertLevel == AlertLevel.fatal) { /* * RFC 2246 7.2.1. The session becomes unresumable if any connection is terminated * without proper close_notify messages with level equal to warning. */ // TODO This isn't quite in the right place. Also, as of TLS 1.1 the above is obsolete. invalidateSession(); this.failedWithError = true; } raiseAlert(alertLevel, alertDescription, message, cause); recordStream.safeClose(); if (alertLevel != AlertLevel.fatal) { return; } } throw new IOException(TLS_ERROR_MESSAGE); } protected void invalidateSession() { if (this.sessionParameters != null) { this.sessionParameters.clear(); this.sessionParameters = null; } if (this.tlsSession != null) { this.tlsSession.invalidate(); this.tlsSession = null; } } protected void processFinishedMessage(ByteArrayInputStream buf) throws IOException { byte[] verify_data = TlsUtils.readFully(expected_verify_data.length, buf); assertEmpty(buf); /* * Compare both checksums. */ if (!Arrays.constantTimeAreEqual(expected_verify_data, verify_data)) { /* * Wrong checksum in the finished message. */ throw new TlsFatalAlert(AlertDescription.decrypt_error); } } protected void raiseAlert(short alertLevel, short alertDescription, String message, Exception cause) throws IOException { getPeer().notifyAlertRaised(alertLevel, alertDescription, message, cause); byte[] error = new byte[2]; error[0] = (byte)alertLevel; error[1] = (byte)alertDescription; safeWriteRecord(ContentType.alert, error, 0, 2); } protected void raiseWarning(short alertDescription, String message) throws IOException { raiseAlert(AlertLevel.warning, alertDescription, message, null); } protected void sendCertificateMessage(Certificate certificate) throws IOException { if (certificate == null) { certificate = Certificate.EMPTY_CHAIN; } if (certificate.getLength() == 0) { TlsContext context = getContext(); if (!context.isServer()) { ProtocolVersion serverVersion = getContext().getServerVersion(); if (serverVersion.isSSL()) { String message = serverVersion.toString() + " client didn't provide credentials"; raiseWarning(AlertDescription.no_certificate, message); return; } } } HandshakeMessage message = new HandshakeMessage(HandshakeType.certificate); certificate.encode(message); message.writeToRecordStream(); } protected void sendChangeCipherSpecMessage() throws IOException { byte[] message = new byte[]{ 1 }; safeWriteRecord(ContentType.change_cipher_spec, message, 0, message.length); recordStream.sentWriteCipherSpec(); } protected void sendFinishedMessage() throws IOException { byte[] verify_data = createVerifyData(getContext().isServer()); HandshakeMessage message = new HandshakeMessage(HandshakeType.finished, verify_data.length); message.write(verify_data); message.writeToRecordStream(); } protected void sendSupplementalDataMessage(Vector supplementalData) throws IOException { HandshakeMessage message = new HandshakeMessage(HandshakeType.supplemental_data); writeSupplementalData(message, supplementalData); message.writeToRecordStream(); } protected byte[] createVerifyData(boolean isServer) { TlsContext context = getContext(); if (isServer) { return TlsUtils.calculateVerifyData(context, ExporterLabel.server_finished, getCurrentPRFHash(getContext(), recordStream.getHandshakeHash(), TlsUtils.SSL_SERVER)); } return TlsUtils.calculateVerifyData(context, ExporterLabel.client_finished, getCurrentPRFHash(getContext(), recordStream.getHandshakeHash(), TlsUtils.SSL_CLIENT)); } /** * Closes this connection. * * @throws IOException If something goes wrong during closing. */ public void close() throws IOException { handleClose(true); } protected void handleClose(boolean user_canceled) throws IOException { if (!closed) { if (user_canceled && !appDataReady) { raiseWarning(AlertDescription.user_canceled, "User canceled handshake"); } this.failWithError(AlertLevel.warning, AlertDescription.close_notify, "Connection closed", null); } } protected void flush() throws IOException { recordStream.flush(); } protected short processMaxFragmentLengthExtension(Hashtable clientExtensions, Hashtable serverExtensions, short alertDescription) throws IOException { short maxFragmentLength = TlsExtensionsUtils.getMaxFragmentLengthExtension(serverExtensions); if (maxFragmentLength >= 0 && !this.resumedSession) { if (maxFragmentLength != TlsExtensionsUtils.getMaxFragmentLengthExtension(clientExtensions)) { throw new TlsFatalAlert(alertDescription); } } return maxFragmentLength; } /** * Make sure the InputStream 'buf' now empty. Fail otherwise. * * @param buf The InputStream to check. * @throws IOException If 'buf' is not empty. */ protected static void assertEmpty(ByteArrayInputStream buf) throws IOException { if (buf.available() > 0) { throw new TlsFatalAlert(AlertDescription.decode_error); } } protected static byte[] createRandomBlock(boolean useGMTUnixTime, RandomGenerator randomGenerator) { byte[] result = new byte[32]; randomGenerator.nextBytes(result); if (useGMTUnixTime) { TlsUtils.writeGMTUnixTime(result, 0); } return result; } protected static byte[] createRenegotiationInfo(byte[] renegotiated_connection) throws IOException { return TlsUtils.encodeOpaque8(renegotiated_connection); } protected static void establishMasterSecret(TlsContext context, TlsKeyExchange keyExchange) throws IOException { byte[] pre_master_secret = keyExchange.generatePremasterSecret(); try { context.getSecurityParameters().masterSecret = TlsUtils.calculateMasterSecret(context, pre_master_secret); } finally { // TODO Is there a way to ensure the data is really overwritten? /* * RFC 2246 8.1. The pre_master_secret should be deleted from memory once the * master_secret has been computed. */ if (pre_master_secret != null) { Arrays.fill(pre_master_secret, (byte)0); } } } /** * 'sender' only relevant to SSLv3 */ protected static byte[] getCurrentPRFHash(TlsContext context, TlsHandshakeHash handshakeHash, byte[] sslSender) { Digest d = handshakeHash.forkPRFHash(); if (sslSender != null && TlsUtils.isSSL(context)) { d.update(sslSender, 0, sslSender.length); } byte[] bs = new byte[d.getDigestSize()]; d.doFinal(bs, 0); return bs; } protected static Hashtable readExtensions(ByteArrayInputStream input) throws IOException { if (input.available() < 1) { return null; } byte[] extBytes = TlsUtils.readOpaque16(input); assertEmpty(input); ByteArrayInputStream buf = new ByteArrayInputStream(extBytes); // Integer -> byte[] Hashtable extensions = new Hashtable(); while (buf.available() > 0) { Integer extension_type = Integers.valueOf(TlsUtils.readUint16(buf)); byte[] extension_data = TlsUtils.readOpaque16(buf); /* * RFC 3546 2.3 There MUST NOT be more than one extension of the same type. */ if (null != extensions.put(extension_type, extension_data)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } } return extensions; } protected static Vector readSupplementalDataMessage(ByteArrayInputStream input) throws IOException { byte[] supp_data = TlsUtils.readOpaque24(input); assertEmpty(input); ByteArrayInputStream buf = new ByteArrayInputStream(supp_data); Vector supplementalData = new Vector(); while (buf.available() > 0) { int supp_data_type = TlsUtils.readUint16(buf); byte[] data = TlsUtils.readOpaque16(buf); supplementalData.addElement(new SupplementalDataEntry(supp_data_type, data)); } return supplementalData; } protected static void writeExtensions(OutputStream output, Hashtable extensions) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); Enumeration keys = extensions.keys(); while (keys.hasMoreElements()) { Integer key = (Integer)keys.nextElement(); int extension_type = key.intValue(); byte[] extension_data = (byte[])extensions.get(key); TlsUtils.checkUint16(extension_type); TlsUtils.writeUint16(extension_type, buf); TlsUtils.writeOpaque16(extension_data, buf); } byte[] extBytes = buf.toByteArray(); TlsUtils.writeOpaque16(extBytes, output); } protected static void writeSupplementalData(OutputStream output, Vector supplementalData) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); for (int i = 0; i < supplementalData.size(); ++i) { SupplementalDataEntry entry = (SupplementalDataEntry)supplementalData.elementAt(i); int supp_data_type = entry.getDataType(); TlsUtils.checkUint16(supp_data_type); TlsUtils.writeUint16(supp_data_type, buf); TlsUtils.writeOpaque16(entry.getData(), buf); } byte[] supp_data = buf.toByteArray(); TlsUtils.writeOpaque24(supp_data, output); } protected static int getPRFAlgorithm(TlsContext context, int ciphersuite) throws IOException { boolean isTLSv12 = TlsUtils.isTLSv12(context); switch (ciphersuite) { case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: { if (isTLSv12) { return PRFAlgorithm.tls_prf_sha256; } throw new TlsFatalAlert(AlertDescription.illegal_parameter); } case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: { if (isTLSv12) { return PRFAlgorithm.tls_prf_sha384; } throw new TlsFatalAlert(AlertDescription.illegal_parameter); } case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384: { if (isTLSv12) { return PRFAlgorithm.tls_prf_sha384; } return PRFAlgorithm.tls_prf_legacy; } default: { if (isTLSv12) { return PRFAlgorithm.tls_prf_sha256; } return PRFAlgorithm.tls_prf_legacy; } } } class HandshakeMessage extends ByteArrayOutputStream { HandshakeMessage(short handshakeType) throws IOException { this(handshakeType, 60); } HandshakeMessage(short handshakeType, int length) throws IOException { super(length + 4); TlsUtils.writeUint8(handshakeType, this); // Reserve space for length count += 3; } void writeToRecordStream() throws IOException { // Patch actual length back in int length = count - 4; TlsUtils.checkUint24(length); TlsUtils.writeUint24(length, buf, 1); writeHandshakeMessage(buf, 0, count); buf = null; } } }
package org.mskcc.cbio.oncokb.util; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.mskcc.cbio.oncokb.model.*; import java.text.SimpleDateFormat; import java.util.*; public class SummaryUtils { public static long lastUpdateVariantSummaries = new Date().getTime(); private static String[] SpecialMutations = {"amplification", "deletion", "fusion", "fusions", "activating mutations", "inactivating mutations", "all mutations", "truncating mutations"}; public static String variantTumorTypeSummary(Gene gene, List<Alteration> alterations, String queryAlteration, Set<OncoTreeType> relevantTumorTypes, String queryTumorType) { if (gene == null) { return ""; } String geneId = Integer.toString(gene.getEntrezGeneId()); String key = geneId + "&&" + queryAlteration + "&&" + queryTumorType; if (CacheUtils.isEnabled() && CacheUtils.containVariantSummary(gene.getEntrezGeneId(), key)) { return CacheUtils.getVariantSummary(gene.getEntrezGeneId(), key); } StringBuilder sb = new StringBuilder(); //Mutation summary (MUTATION_SUMMARY: Deprecated) // List<Evidence> mutationSummaryEvs = evidenceBo.findEvidencesByAlteration(alterations, Collections.singleton(EvidenceType.MUTATION_SUMMARY)); // if (!mutationSummaryEvs.isEmpty()) { // Evidence ev = mutationSummaryEvs.get(0); // String mutationSummary = ev.getShortDescription(); // if (mutationSummary == null) { // mutationSummary = ev.getDescription(); // if (mutationSummary != null) { // mutationSummary = StringEscapeUtils.escapeXml(mutationSummary).trim(); // sb.append(mutationSummary) // .append(" "); // } else { String os = oncogenicSummary(gene, alterations, queryAlteration, false); if (os != null && !os.equals("")) { sb.append(" " + os); } String ts = tumorTypeSummary(gene, queryAlteration, alterations, queryTumorType, relevantTumorTypes); if (ts != null && !ts.equals("")) { sb.append(" " + ts); } if (CacheUtils.isEnabled()) { CacheUtils.setVariantSummary(gene.getEntrezGeneId(), key, sb.toString().trim()); } return sb.toString().trim(); } public static String variantCustomizedSummary(Set<Gene> genes, List<Alteration> alterations, String queryAlteration, Set<OncoTreeType> relevantTumorTypes, String queryTumorType) { String geneId = Integer.toString(genes.iterator().next().getEntrezGeneId()); Gene gene = GeneUtils.getGeneByEntrezId(Integer.parseInt(geneId)); StringBuilder sb = new StringBuilder(); sb.append(geneSummary(genes.iterator().next())); String os = oncogenicSummary(gene, alterations, queryAlteration, false); if (os != null && !os.equals("")) { sb.append(" " + os); } return sb.toString().trim(); } public static String tumorTypeSummary(Gene gene, String queryAlteration, List<Alteration> alterations, String queryTumorType, Set<OncoTreeType> relevantTumorTypes) { //Tumor type summary Boolean ttSummaryNotGenerated = true; String tumorTypeSummary = null; queryTumorType = queryTumorType != null ? StringUtils.isAllUpperCase(queryTumorType) ? queryTumorType : queryTumorType.toLowerCase() : null; if (queryAlteration != null) { queryAlteration = queryAlteration.trim(); } if (queryTumorType != null) { queryTumorType = queryTumorType.trim(); if (queryTumorType.endsWith(" tumor")) { queryTumorType = queryTumorType.substring(0, queryTumorType.lastIndexOf(" tumor")) + " tumors"; } } if (isSpecialMutation(queryAlteration, true)) { queryAlteration = queryAlteration.toLowerCase(); } if (AlterationUtils.isSingularGeneralAlteration(queryAlteration)) { queryAlteration = queryAlteration + "s"; } Boolean appendThe = appendThe(queryAlteration); if (gene == null || alterations == null || relevantTumorTypes == null) { return ""; } if (CacheUtils.isEnabled() && CacheUtils.containVariantTumorTypeSummary(gene.getEntrezGeneId(), queryAlteration, queryTumorType)) { return CacheUtils.getVariantTumorTypeSummary(gene.getEntrezGeneId(), queryAlteration, queryTumorType); } if (gene.getHugoSymbol().equals("KIT")) { tumorTypeSummary = getKITtumorTypeSummaries(queryAlteration, alterations, queryTumorType, relevantTumorTypes); } else { // Get all tumor type summary evidences specifically for the alteration if (tumorTypeSummary == null) { Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration); if (alteration != null) { tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), relevantTumorTypes, null)); // Get Other Tumor Types summary within this alteration if (tumorTypeSummary == null) { tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null)); } } } // Get all tumor type summary evidences for the alternate alleles if (tumorTypeSummary == null) { Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration); if (alteration == null) { alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, null, null, null, null); AlterationUtils.annotateAlteration(alteration, queryAlteration); } if (alteration.getConsequence() != null) { if (alteration.getConsequence().getTerm().equals("missense_variant")) { List<Alteration> alternateAlleles = AlterationUtils.getAlleleAndRelevantAlterations(alteration); // Special case for PDGFRA: don't match D842V as alternative allele if (gene.getHugoSymbol().equals("PDGFRA") && alteration.getProteinStart() == 842) { Alteration specialAllele = AlterationUtils.findAlteration(gene, "D842V"); alternateAlleles.remove(specialAllele); } // Special case for AKT1 E17K alleles if (gene.getHugoSymbol().equals("AKT1") && alteration.getProteinStart().equals(17)) { OncoTreeType breastCancer = TumorTypeUtils.getOncoTreeCancerType("Breast Cancer"); OncoTreeType ovarianCancer = TumorTypeUtils.getOncoTreeCancerType("Ovarian Cancer"); if (relevantTumorTypes.contains(breastCancer)) { tumorTypeSummary = "There is compelling clinical data supporting the use of AKT-targeted inhibitors such as AZD-5363 in patients with AKT1 E17K mutant breast cancer. Therefore, [[gene]] [[mutation]] [[mutant]] breast cancer is considered likely sensitive to the same inhibitors."; } else if (relevantTumorTypes.contains(ovarianCancer)) { tumorTypeSummary = "There is compelling clinical data supporting the use of AKT-targeted inhibitors such as AZD-5363 in patients with AKT1 E17K mutant ovarian cancer. Therefore, [[gene]] [[mutation]] [[mutant]] ovarian cancer is considered likely sensitive to the same inhibitors."; } else { tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(AlterationUtils.findAlteration(gene, "E17K")), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null)); } } else if (gene.getHugoSymbol().equals("ARAF") && alteration.getProteinStart().equals(214)) { // Special case for ARAF S214A/F OncoTreeType histiocytosis = TumorTypeUtils.getOncoTreeCancerType("Histiocytosis"); OncoTreeType NSCLC = TumorTypeUtils.getOncoTreeCancerType("Non-Small Cell Lung Cancer"); if (relevantTumorTypes.contains(histiocytosis)) { tumorTypeSummary = "There is compelling clinical data supporting the use of sorafenib in patients with ARAF S214A mutant non-Langherhans cell histiocytic disease. Therefore, [[gene]] [[mutation]] [[mutant]] non-Langherhans cell histiocytic disease is considered likely sensitive to this inhibitor."; } else if (relevantTumorTypes.contains(NSCLC)) { tumorTypeSummary = "There is compelling clinical data supporting the use of sorafenib in patients with ARAF S214F mutant lung cancer. Therefore, [[gene]] [[mutation]] [[mutant]] lung cancer is considered likely sensitive to this inhibitor."; } else { tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(AlterationUtils.findAlteration(gene, "S214A")), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null)); } } else if (gene.getHugoSymbol().equals("MTOR") && alteration.getProteinStart().equals(2014)) { // Special case for MTOR E2014K OncoTreeType bladderCancer = TumorTypeUtils.getOncoTreeCancerType("Bladder Cancer"); if (relevantTumorTypes.contains(bladderCancer)) { tumorTypeSummary = "There is compelling clinical data supporting the use of everolimus in patients with MTOR E2014K mutant bladder cancer. Therefore, [[gene]] [[mutation]] [[mutant]] bladder cancer is considered likely sensitive to the same inhibitor."; } else { tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(AlterationUtils.findAlteration(gene, "E2014K")), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null)); } } else { for (Alteration allele : alternateAlleles) { tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(allele), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), relevantTumorTypes, null)); if (tumorTypeSummary != null) { break; } // Get Other Tumor Types summary tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(allele), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null)); if (tumorTypeSummary != null) { break; } } } } else if (alteration.getConsequence().getTerm().equals("synonymous_variant")) { // No summary for synonymous variant return ""; } } } // Get all tumor type summary evidence for relevant alterations if (tumorTypeSummary == null) { // Base on the priority of relevant alterations for (Alteration alteration : alterations) { tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), relevantTumorTypes, null)); if (tumorTypeSummary != null) { break; } // Get Other Tumor Types summary tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null)); if (tumorTypeSummary != null) { break; } } } } if (tumorTypeSummary == null) { tumorTypeSummary = "There are no FDA-approved or NCCN-compendium listed treatments specifically for patients with [[variant]]."; } tumorTypeSummary = replaceSpecialCharacterInTumorTypeSummary(tumorTypeSummary, gene, queryAlteration, queryTumorType); if (CacheUtils.isEnabled()) { CacheUtils.setVariantTumorTypeSummary(gene.getEntrezGeneId(), queryAlteration, queryTumorType, tumorTypeSummary); } return tumorTypeSummary; } public static String unknownOncogenicSummary(Gene gene) { String str = gene == null ? "variant" : (gene.getHugoSymbol() + " alteration"); return "The oncogenic activity of this " + str + " is unknown as it has not specifically been investigated by the OncoKB team."; } public static String synonymousSummary() { return "This is a synonymous mutation and is not annotated by OncoKB."; } public static String oncogenicSummary(Gene gene, List<Alteration> alterations, String queryAlteration, Boolean addition) { StringBuilder sb = new StringBuilder(); if (gene == null || alterations == null || alterations.isEmpty() || AlterationUtils.excludeVUS(alterations).size() == 0) { if (gene != null && queryAlteration != null) { Alteration alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, AlterationType.MUTATION.label(), null, null, null); if (alteration == null) { alteration = new Alteration(); alteration.setGene(gene); alteration.setAlterationType(AlterationType.MUTATION); alteration.setAlteration(queryAlteration); alteration.setName(queryAlteration); AlterationUtils.annotateAlteration(alteration, queryAlteration); } if (alteration.getConsequence() != null && alteration.getConsequence().getTerm().equals("synonymous_variant")) { sb.append(synonymousSummary()); } else if (AlterationUtils.hasAlleleAlterations(alteration)) { sb.append(alleleSummary(alteration)); } else if (AlterationUtils.excludeVUS(alterations).size() == 0) { List<Evidence> evidences = EvidenceUtils.getEvidence(alterations, Collections.singleton(EvidenceType.VUS), null); Date lastEdit = null; for (Evidence evidence : evidences) { if (evidence.getLastEdit() == null) { continue; } if (lastEdit == null) { lastEdit = evidence.getLastEdit(); } else if (lastEdit.compareTo(evidence.getLastEdit()) < 0) { lastEdit = evidence.getLastEdit(); } } if (lastEdit == null) { sb.append(unknownOncogenicSummary(gene)); } else { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); sb.append("As of " + sdf.format(lastEdit) + ", no functional data about this alteration was available."); } } else { sb.append(unknownOncogenicSummary(gene)); } } else { sb.append(unknownOncogenicSummary(gene)); } } else { if (isSpecialMutation(queryAlteration, false)) { if (isSpecialMutation(queryAlteration, true)) { queryAlteration = queryAlteration.substring(0, 1).toUpperCase() + queryAlteration.substring(1); } } String altName = getGeneMutationNameInVariantSummary(gene, queryAlteration); if (gene == null || alterations == null) { return null; } String geneId = Integer.toString(gene.getEntrezGeneId()); String key = geneId + "&&" + queryAlteration + "&&" + addition.toString(); if (CacheUtils.isEnabled() && CacheUtils.containVariantSummary(gene.getEntrezGeneId(), key)) { return CacheUtils.getVariantSummary(gene.getEntrezGeneId(), key); } Boolean appendThe = appendThe(queryAlteration); Boolean isPlural = false; if (queryAlteration.toLowerCase().contains("fusions")) { isPlural = true; } int oncogenic = -1; for (Alteration a : alterations) { List<Evidence> oncogenicEvidences = EvidenceUtils.getEvidence(Collections.singletonList(a), Collections.singleton(EvidenceType.ONCOGENIC), null); if (oncogenicEvidences != null && oncogenicEvidences.size() > 0) { Evidence evidence = oncogenicEvidences.iterator().next(); if (evidence != null && evidence.getKnownEffect() != null && Integer.parseInt(evidence.getKnownEffect()) >= 0) { oncogenic = Integer.parseInt(evidence.getKnownEffect()); break; } } } if (oncogenic >= 0) { if (appendThe) { sb.append("The "); } sb.append(altName); if (isPlural) { sb.append(" are"); } else { sb.append(" is"); } if (oncogenic == 0) { sb.append(" likely neutral."); } else { if (oncogenic == 2) { sb.append(" likely"); } else if (oncogenic == 1) { sb.append(" known to be"); } sb.append(" oncogenic."); } } else { sb.append("It is unknown whether "); if (appendThe) { sb.append("the "); } sb.append(altName); if (isPlural) { sb.append(" are"); } else { sb.append(" is"); } sb.append(" oncogenic."); } if (addition) { List<Evidence> oncogenicEvs = EvidenceUtils.getEvidence(alterations, Collections.singleton(EvidenceType.ONCOGENIC), null); List<String> clinicalSummaries = new ArrayList<>(); for (Evidence evidence : oncogenicEvs) { if (evidence.getDescription() != null && !evidence.getDescription().isEmpty()) { clinicalSummaries.add(evidence.getDescription()); } } if (clinicalSummaries.size() > 1) { sb.append("Warning: variant has multiple clinical summaries."); } else if (clinicalSummaries.size() == 1) { sb.append(clinicalSummaries.get(0)); } } if (CacheUtils.isEnabled()) { CacheUtils.setVariantSummary(gene.getEntrezGeneId(), key, sb.toString().trim()); } } return sb.toString(); } public static String geneSummary(Gene gene) { Set<Evidence> geneSummaryEvs = EvidenceUtils.getEvidenceByGeneAndEvidenceTypes(gene, Collections.singleton(EvidenceType.GENE_SUMMARY)); String summary = ""; if (!geneSummaryEvs.isEmpty()) { Evidence ev = geneSummaryEvs.iterator().next(); if (ev != null) { summary = ev.getDescription(); if (summary != null) { summary = StringEscapeUtils.escapeXml(summary).trim(); } } } summary = summary.trim(); summary = summary.endsWith(".") ? summary : summary + "."; return summary; } public static String fullSummary(Gene gene, List<Alteration> alterations, String queryAlteration, Set<OncoTreeType> relevantTumorTypes, String queryTumorType) { StringBuilder sb = new StringBuilder(); sb.append(geneSummary(gene)); String vts = SummaryUtils.variantTumorTypeSummary(gene, alterations, queryAlteration, relevantTumorTypes, queryTumorType); if (vts != null && !vts.equals("")) { sb.append(" " + vts); } return sb.toString(); } public static String alleleSummary(Alteration alteration) { StringBuilder sb = new StringBuilder(); String altStr = getGeneMutationNameInVariantSummary(alteration.getGene(), alteration.getAlteration()); sb.append("The " + altStr + " has not been functionally or clinically validated."); Set<Alteration> alleles = new HashSet<>(AlterationUtils.getAlleleAndRelevantAlterations(alteration)); Map<String, Object> map = geAlterationsWithHighestOncogenicity(new HashSet<>(alleles)); Oncogenicity highestOncogenicity = (Oncogenicity) map.get("oncogenicity"); Set<Alteration> highestAlts = (Set<Alteration>) map.get("alterations"); if (highestOncogenicity != null && (highestOncogenicity.getOncogenic().equals("1") || highestOncogenicity.getOncogenic().equals("2"))) { sb.append(" However, "); sb.append(alteration.getGene().getHugoSymbol() + " " + allelesToStr(highestAlts)); sb.append((highestAlts.size() > 1 ? " are" : " is")); if (highestOncogenicity.getOncogenic().equals("1")) { sb.append(" known to be " + highestOncogenicity.getDescription().toLowerCase()); } else { sb.append(" " + highestOncogenicity.getDescription().toLowerCase()); } sb.append(", and therefore " + alteration.getGene().getHugoSymbol() + " " + alteration.getAlteration() + " is considered likely oncogenic."); } return sb.toString(); } private static String alleleNamesStr(Set<Alteration> alterations) { if (alterations != null && alterations.size() > 0) { Alteration tmp = alterations.iterator().next(); String residue = tmp.getRefResidues(); String location = Integer.toString(tmp.getProteinStart()); Set<String> variantResidue = new TreeSet<>(); Set<Alteration> withoutVariantResidues = new HashSet<>(); for (Alteration alteration : alterations) { if (alteration.getVariantResidues() == null) { withoutVariantResidues.add(alteration); } else { variantResidue.add(alteration.getVariantResidues()); } } StringBuilder sb = new StringBuilder(); if (variantResidue.size() > 0) { sb.append(residue + location + StringUtils.join(variantResidue, "/")); } if (withoutVariantResidues.size() > 0) { List<String> alterationNames = new ArrayList<>(); for (Alteration alteration : withoutVariantResidues) { alterationNames.add(alteration.getName()); } if (variantResidue.size() > 0) { sb.append(", "); } sb.append(MainUtils.listToString(alterationNames, ", ")); } return sb.toString(); } else { return ""; } } private static String allelesToStr(Set<Alteration> alterations) { List<String> alterationNames = new ArrayList<>(); Map<Integer, Set<Alteration>> locationBasedAlts = new HashMap<>(); for (Alteration alteration : alterations) { if (!locationBasedAlts.containsKey(alteration.getProteinStart())) locationBasedAlts.put(alteration.getProteinStart(), new HashSet<Alteration>()); locationBasedAlts.get(alteration.getProteinStart()).add(alteration); } for (Map.Entry entry : locationBasedAlts.entrySet()) { alterationNames.add(alleleNamesStr((Set<Alteration>) entry.getValue())); } return MainUtils.listToString(alterationNames, " and "); } private static Map<String, Object> geAlterationsWithHighestOncogenicity(Set<Alteration> alleles) { Map<Oncogenicity, Set<Alteration>> oncoCate = new HashMap<>(); // Get oncogenicity info in alleles for (Alteration alt : alleles) { Set<EvidenceType> evidenceTypes = new HashSet<>(); evidenceTypes.add(EvidenceType.ONCOGENIC); List<Evidence> allelesOnco = EvidenceUtils.getEvidence(Collections.singletonList(alt), evidenceTypes, null); for (Evidence evidence : allelesOnco) { String oncoStr = evidence.getKnownEffect(); if (oncoStr == null) continue; Oncogenicity oncogenicity = Oncogenicity.getByLevel(oncoStr); if (!oncoCate.containsKey(oncogenicity)) oncoCate.put(oncogenicity, new HashSet<Alteration>()); oncoCate.get(oncogenicity).add(alt); } } Oncogenicity oncogenicity = MainUtils.findHighestOncogenic(oncoCate.keySet()); Map<String, Object> result = new HashMap<>(); result.put("oncogenicity", oncogenicity); result.put("alterations", oncoCate != null ? oncoCate.get(oncogenicity) : new HashSet<>()); return result; } private static Map<LevelOfEvidence, List<Evidence>> groupEvidencesByLevel(List<Evidence> evidences) { Map<LevelOfEvidence, List<Evidence>> map = new EnumMap<LevelOfEvidence, List<Evidence>>(LevelOfEvidence.class); for (LevelOfEvidence level : LevelOfEvidence.values()) { map.put(level, new ArrayList<Evidence>()); } for (Evidence ev : evidences) { if (ev.getLevelOfEvidence() == null || ev.getTreatments().isEmpty()) continue; map.get(ev.getLevelOfEvidence()).add(ev); } return map; } // According to following rules // include // e.g. While the drugs dabrafenib, trametinib and vemurafenib are FDA-approved for patients with BRAF V600E mutant melanoma, bladder or breast cancer, the clinical utility for these agents in patients with BRAF V600E mutant low grade gliomas is unknown. // IF >2 SAME drug for >2 different cancer types // include // While there are FDA-approved drugs for patients with specific cancers harboring the BRAF V600E mutation (please refer to FDA-approved drugs in Other Tumor types section), the clinical utility for these agents in patients with BRAF V600E mutant low grade gliomas is unknown. // IF <2 DIFFERENT drugs for <2 different tumor types // While there are FDA-approved drugs for patients with lung and colorectal cancers harboring the EGFR L858R mutation (please refer to FDA-approved drugs in Other Tumor types section), the clinical utility for these agents in patients with EGFR L858R mutant low grade gliomas is unknown. private static String treatmentsToStringByTumorType(List<Evidence> evidences, String queryAlteration, String queryTumorType, boolean capFirstLetter, boolean fda, boolean nccn, boolean inOtherTumorType) { // Tumor type -> drug -> LevelOfEvidence and alteration set Map<String, Map<String, Map<String, Object>>> map = new TreeMap<>(); Set<String> drugs = new HashSet<>(); Map<String, Set<String>> levelZeroDrugs = new HashMap<>(); List<String> list = new ArrayList<String>(); for (Evidence ev : evidences) { String tt = null; if (ev.getSubtype() != null) { tt = ev.getSubtype().toLowerCase(); } else if (ev.getCancerType() != null) { tt = ev.getCancerType().toLowerCase(); } if (tt == null) { continue; } Map<String, Map<String, Object>> ttMap = map.get(tt); if (ttMap == null && !ev.getLevelOfEvidence().equals(LevelOfEvidence.LEVEL_0)) { ttMap = new TreeMap<String, Map<String, Object>>(); map.put(tt, ttMap); } for (Treatment t : ev.getTreatments()) { for (Drug drug : t.getDrugs()) { String drugName = drug.getDrugName().toLowerCase(); if (ev.getLevelOfEvidence().equals(LevelOfEvidence.LEVEL_0)) { if (!levelZeroDrugs.containsKey(drugName)) { levelZeroDrugs.put(drugName, new HashSet<String>()); } if (!levelZeroDrugs.get(drugName).contains(tt)) { levelZeroDrugs.get(drugName).add(tt); } } else { Map<String, Object> drugMap = ttMap.get(drugName); if (!drugs.contains(drugName)) { drugs.add(drugName); } if (drugMap == null) { drugMap = new TreeMap<>(); ttMap.put(drugName, drugMap); // drugMap.put("approvedIndications", t.getApprovedIndications()); drugMap.put("level", ev.getLevelOfEvidence()); drugMap.put("alteration", ev.getAlterations()); } } } } } if (map.size() > 2) { list.add(treatmentsToStringAboveLimit(drugs, capFirstLetter, fda, nccn, null)); } else { boolean first = true; for (Map.Entry<String, Map<String, Map<String, Object>>> entry : map.entrySet()) { String tt = entry.getKey(); list.add(treatmentsToString(entry.getValue(), tt, queryAlteration, first & capFirstLetter, fda, nccn)); first = false; } } // if(levelZeroDrugs.size() > 0) { // list.add(treatmentsToStringLevelZero(levelZeroDrugs, list.size()==0 & capFirstLetter)); return MainUtils.listToString(list, " and "); } private static String treatmentsToStringLevelZero(Map<String, Set<String>> drugs, Boolean capFirstLetter) { StringBuilder sb = new StringBuilder(); Set<String> tumorTypes = new HashSet<>(); boolean sameDrugs = true; for (String drugName : drugs.keySet()) { if (tumorTypes.isEmpty()) { tumorTypes = drugs.get(drugName); } else { if (tumorTypes.size() != drugs.get(drugName).size()) { sameDrugs = false; break; } for (String tt : drugs.get(drugName)) { if (!tumorTypes.contains(tt)) { sameDrugs = false; break; } } } } if (sameDrugs) { sb.append(drugStr(drugs.keySet(), capFirstLetter, true, false, null)); } else { sb.append(capFirstLetter ? "T" : "t") .append("here are multiple FDA-approved agents"); } sb.append(" for treatment of patients with "); sb.append(tumorTypes.size() > 2 ? "different tumor types" : MainUtils.listToString(new ArrayList<String>(tumorTypes), " and ")) .append(" irrespective of mutation status"); return sb.toString(); } private static String treatmentsToStringAboveLimit(Set<String> drugs, boolean capFirstLetter, boolean fda, boolean nccn, String approvedIndication) { StringBuilder sb = new StringBuilder(); sb.append(drugStr(drugs, capFirstLetter, fda, nccn, null)); sb.append(" for treatment of patients with different tumor types harboring specific mutations"); return sb.toString(); } private static String treatmentsToString(Map<String, Map<String, Object>> map, String tumorType, String alteration, boolean capFirstLetter, boolean fda, boolean nccn) { Set<String> drugs = map.keySet(); Map<String, Object> drugAltMap = drugsAreSameByAlteration(map); StringBuilder sb = new StringBuilder(); Map<String, Object> drugMap = map.get(drugs.iterator().next()); // Set<String> approvedIndications = (Set<String>) drugMap.get("approvedIndications"); String aiStr = null; // for (String ai : approvedIndications) { // if (ai != null && !ai.isEmpty()) { // aiStr = ai; // break; sb.append(drugStr(drugs, capFirstLetter, fda, nccn, aiStr)) .append(" for treatment of patients ") .append(tumorType == null ? "" : ("with " + tumorType + " ")) .append("harboring "); if (alteration != null) { sb.append("the ").append(alteration); } else if ((Boolean) drugAltMap.get("isSame")) { Set<Alteration> alterations = (Set<Alteration>) drugAltMap.get("alterations"); if (alterations.size() <= 2) { sb.append("the ").append(alterationsToString(alterations)); } else { sb.append("specific mutations"); } } else { sb.append("specific mutations"); } return sb.toString(); } private static String drugStr(Set<String> drugs, boolean capFirstLetter, boolean fda, boolean nccn, String approvedIndication) { int drugLimit = 3; StringBuilder sb = new StringBuilder(); if (drugs.size() > drugLimit) { sb.append(capFirstLetter ? "T" : "t").append("here"); } else { sb.append(capFirstLetter ? "T" : "t").append("he drug"); if (drugs.size() > 1) { sb.append("s"); } sb.append(" "); sb.append(MainUtils.listToString(new ArrayList<String>(drugs), " and ")); } if (fda || nccn) { sb.append(" "); if (drugs.size() > 1) { sb.append("are"); } else { sb.append("is"); } } if (fda) { sb.append(" FDA-approved"); } else if (nccn) { if (approvedIndication != null) { sb.append(" FDA-approved for the treatment of ") .append(approvedIndication) .append(" and"); } if (drugs.size() > drugLimit || approvedIndication != null) { sb.append(" NCCN-compendium listed"); } else if (drugs.size() <= drugLimit) { sb.append(" listed by NCCN-compendium"); } } if (drugs.size() > drugLimit) { sb.append(" drugs"); } return sb.toString(); } private static Map<String, Object> drugsAreSameByAlteration(Map<String, Map<String, Object>> drugs) { Set<Alteration> alterations = new HashSet<>(); Map<String, Object> map = new HashMap<>(); map.put("isSame", true); map.put("alterations", alterations); for (String drugName : drugs.keySet()) { Map<String, Object> drug = drugs.get(drugName); Set<Alteration> alts = (Set<Alteration>) drug.get("alteration"); if (alterations.isEmpty()) { alterations = alts; } else { if (alterations.size() != alts.size()) { map.put("isSame", false); return map; } for (Alteration alt : alts) { if (!alterations.contains(alt)) { map.put("isSame", false); return map; } } } } map.put("alterations", alterations); return map; } private static String alterationsToString(Collection<Alteration> alterations) { Map<Gene, Set<String>> mapGeneVariants = new HashedMap(); for (Alteration alteration : alterations) { Gene gene = alteration.getGene(); Set<String> variants = mapGeneVariants.get(gene); if (variants == null) { variants = new HashSet<>(); mapGeneVariants.put(gene, variants); } variants.add(alteration.getName()); } List<String> list = new ArrayList<>(); for (Map.Entry<Gene, Set<String>> entry : mapGeneVariants.entrySet()) { for (String variant : entry.getValue()) { list.add(getGeneMutationNameInVariantSummary(alterations.iterator().next().getGene(), variant)); } } String ret = MainUtils.listToString(list, " or "); return ret; } private static Boolean isSpecialMutation(String mutationStr, Boolean exactMatch) { exactMatch = exactMatch || false; mutationStr = mutationStr.toString(); if (exactMatch) { return stringIsFromList(mutationStr, SpecialMutations); } else if (stringContainsItemFromList(mutationStr, SpecialMutations) && itemFromListAtEndString(mutationStr, SpecialMutations)) { return true; } return false; } private static Boolean appendThe(String queryAlteration) { Boolean appendThe = true; if (queryAlteration.toLowerCase().contains("deletion") || queryAlteration.toLowerCase().contains("amplification") || queryAlteration.toLowerCase().contains("fusions")) { appendThe = false; } return appendThe; } private static String getTumorTypeSummaryFromEvidences(List<Evidence> evidences) { String summary = null; if (evidences != null && evidences.size() > 0) { // Sort all tumor type summaries, the more specific tumor type summary will be picked. Collections.sort(evidences, new Comparator<Evidence>() { public int compare(Evidence x, Evidence y) { if (x.getAlterations() == null) { return 1; } if (y.getAlterations() == null) { return -1; } return x.getAlterations().size() - y.getAlterations().size(); } }); Evidence ev = evidences.get(0); String tumorTypeSummary = ev.getDescription(); if (tumorTypeSummary != null) { summary = StringEscapeUtils.escapeXml(tumorTypeSummary).trim(); } } return summary; } private static String getGeneMutationNameInVariantSummary(Gene gene, String queryAlteration) { StringBuilder sb = new StringBuilder(); Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration); if (alteration == null) { alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, null, null, null, null); AlterationUtils.annotateAlteration(alteration, queryAlteration); } if (isSpecialMutation(queryAlteration, true)) { sb.append(gene.getHugoSymbol() + " " + queryAlteration.toLowerCase()); } else if (StringUtils.containsIgnoreCase(queryAlteration, "fusion")) { queryAlteration = queryAlteration.replace("Fusion", "fusion"); sb.append(queryAlteration); } else if (isSpecialMutation(queryAlteration, false) || (alteration.getConsequence() != null && (alteration.getConsequence().getTerm().equals("inframe_deletion") || alteration.getConsequence().getTerm().equals("inframe_insertion"))) || StringUtils.containsIgnoreCase(queryAlteration, "indel") || StringUtils.containsIgnoreCase(queryAlteration, "dup") || StringUtils.containsIgnoreCase(queryAlteration, "delins") || StringUtils.containsIgnoreCase(queryAlteration, "splice")) { sb.append(gene.getHugoSymbol() + " " + queryAlteration + " alteration"); } else { sb.append(gene.getHugoSymbol() + " " + queryAlteration + " mutation"); } return sb.toString(); } private static String getGeneMutationNameInTumorTypeSummary(Gene gene, String queryAlteration) { StringBuilder sb = new StringBuilder(); Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration); if (alteration == null) { alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, null, null, null, null); AlterationUtils.annotateAlteration(alteration, queryAlteration); } if (StringUtils.containsIgnoreCase(queryAlteration, "fusion")) { if (queryAlteration.toLowerCase().equals("fusions")) { queryAlteration = gene.getHugoSymbol() + " fusion"; } queryAlteration = queryAlteration.replace("Fusion", "fusion"); sb.append(queryAlteration + " positive"); } else { sb.append(gene.getHugoSymbol() + " "); if (isSpecialMutation(queryAlteration, true)) { sb.append(queryAlteration.toLowerCase()); } else if (isSpecialMutation(queryAlteration, false) || (alteration.getConsequence() != null && (alteration.getConsequence().getTerm().equals("inframe_deletion") || alteration.getConsequence().getTerm().equals("inframe_insertion"))) || StringUtils.containsIgnoreCase(queryAlteration, "indel") || StringUtils.containsIgnoreCase(queryAlteration, "dup") || StringUtils.containsIgnoreCase(queryAlteration, "delins") || StringUtils.containsIgnoreCase(queryAlteration, "splice") ) { sb.append(queryAlteration + " altered"); } else { sb.append(queryAlteration + " mutant"); } } return sb.toString(); } private static String replaceSpecialCharacterInTumorTypeSummary(String summary, Gene gene, String queryAlteration, String queryTumorType) { String altName = getGeneMutationNameInTumorTypeSummary(gene, queryAlteration); String alterationName = getGeneMutationNameInVariantSummary(gene, queryAlteration); summary = summary.replace("[[variant]]", altName + " " + queryTumorType); summary = summary.replace("[[gene]] [[mutation]] [[[mutation]]]", alterationName); // In case of miss typed summary = summary.replace("[[gene]] [[mutation]] [[mutation]]", alterationName); summary = summary.replace("[[gene]] [[mutation]] [[mutant]]", altName); summary = summary.replace("[[gene]]", gene.getHugoSymbol()); summary = summary.replace("[[mutation]] [[mutant]]", altName); summary = summary.replace("[[mutation]] [[[mutation]]]", alterationName); // In case of miss typed summary = summary.replace("[[mutation]] [[mutation]]", alterationName); summary = summary.replace("[[mutation]]", queryAlteration); summary = summary.replace("[[tumorType]]", queryTumorType); summary = summary.replace("[[tumor type]]", queryTumorType); summary = summary.replace("[[fusion name]]", altName); summary = summary.replace("[[fusion name]]", altName); return summary; } private static String getTumorTypeSummaryFromPickedTreatment(Gene gene, Alteration alteration, Set<OncoTreeType> relevantTumorTypes) { String tumorTypeSummary = null; List<Evidence> evidences = EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), relevantTumorTypes, null); Evidence pickedTreatment = pickSpecialGeneTreatmentEvidence(gene, EvidenceUtils.getEvidence(Collections.singletonList(alteration), MainUtils.getTreatmentEvidenceTypes(), relevantTumorTypes, null)); for (Evidence evidence : evidences) { if (evidence.getAlterations().equals(pickedTreatment.getAlterations())) { tumorTypeSummary = getTumorTypeSummaryFromEvidences(Collections.singletonList(evidence)); if (tumorTypeSummary != null) { break; } } } if (tumorTypeSummary == null) { evidences = EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null); for (Evidence evidence : evidences) { tumorTypeSummary = getTumorTypeSummaryFromEvidences(Collections.singletonList(evidence)); if (tumorTypeSummary != null) { break; } } } return tumorTypeSummary; } private static String getKITtumorTypeSummaries(String queryAlteration, List<Alteration> alterations, String queryTumorType, Set<OncoTreeType> relevantTumorTypes) { Gene gene = GeneUtils.getGeneByHugoSymbol("KIT"); String tumorTypeSummary = null; Evidence pickedTreatment = null; // Get all tumor type summary evidences specifically for the alteration if (tumorTypeSummary == null) { Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration); if (alteration != null) { tumorTypeSummary = getTumorTypeSummaryFromPickedTreatment(gene, alteration, relevantTumorTypes); } } // Get all tumor type summary evidences for the alternate alleles if (tumorTypeSummary == null) { Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration); if (alteration == null) { alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, null, null, null, null); AlterationUtils.annotateAlteration(alteration, queryAlteration); } if (alteration.getConsequence() != null) { if (alteration.getConsequence().getTerm().equals("missense_variant")) { List<Alteration> alternateAlleles = AlterationUtils.getAlleleAndRelevantAlterations(alteration); // Send all allele tumor types treatment to pick up the unique one. pickedTreatment = pickSpecialGeneTreatmentEvidence(gene, EvidenceUtils.getEvidence(alternateAlleles, MainUtils.getTreatmentEvidenceTypes(), relevantTumorTypes, null)); if (pickedTreatment != null) { tumorTypeSummary = getTumorTypeSummaryFromPickedTreatment(gene, (Alteration) CollectionUtils.intersection(alternateAlleles, new ArrayList<>(pickedTreatment.getAlterations())).iterator().next(), relevantTumorTypes); if (tumorTypeSummary != null) { // Only keep the first sentence for alternate allele tumorTypeSummary = tumorTypeSummary.split("\\.")[0] + "."; } } else { // If all alternate alleles don't have any treatment, check whether they have tumor type summaries. for (Alteration allele : alternateAlleles) { tumorTypeSummary = getTumorTypeSummaryFromPickedTreatment(gene, allele, relevantTumorTypes); if (tumorTypeSummary != null) { // Only keep the first sentence for alternate allele tumorTypeSummary = tumorTypeSummary.split("\\.")[0] + "."; break; } } } } else if (alteration.getConsequence().getTerm().equals("synonymous_variant")) { // No summary for synonymous variant return ""; } } } // Get all tumor type summary evidence for relevant alterations if (tumorTypeSummary == null) { // Base on the priority of relevant alterations for (Alteration alteration : alterations) { tumorTypeSummary = getTumorTypeSummaryFromPickedTreatment(gene, alteration, relevantTumorTypes); if (tumorTypeSummary != null) { break; } } } return tumorTypeSummary; } private static Evidence pickSpecialGeneTreatmentEvidence(Gene gene, List<Evidence> treatments) { Evidence pickedTreatment = null; if (gene != null && treatments != null) { List<String> TREATMENTS = null; String hugoSymbol = gene.getHugoSymbol(); if (hugoSymbol.equals("KIT")) { TREATMENTS = Arrays.asList("imatinib", "sunitinib", "regorafenib", "sorafenib", "nilotinib", "dasatinib"); } Integer index = 1000; for (Evidence treatment : treatments) { String treatmentName = TreatmentUtils.getTreatmentName(treatment.getTreatments(), false); if (treatmentName != null) { Integer _index = TREATMENTS.indexOf(treatmentName.toLowerCase()); if (_index != -1 && _index < index) { index = _index; pickedTreatment = treatment; } } } } return pickedTreatment; } public static boolean stringContainsItemFromList(String inputString, String[] items) { for (int i = 0; i < items.length; i++) { if (inputString.contains(items[i])) { return true; } } return false; } public static boolean stringIsFromList(String inputString, String[] items) { for (int i = 0; i < items.length; i++) { if (inputString.equalsIgnoreCase(items[i])) { return true; } } return false; } public static boolean itemFromListAtEndString(String inputString, String[] items) { for (int i = 0; i < items.length; i++) { if (inputString.endsWith(items[i])) { return true; } } return false; } }
package jade.domain; //#MIDP_EXCLUDE_FILE import java.lang.reflect.Method; import java.util.Vector; import jade.util.leap.HashMap; import jade.util.leap.ArrayList; import jade.util.leap.List; import jade.util.leap.Iterator; import jade.util.leap.Properties; import java.net.InetAddress; import jade.core.AID; import jade.core.Agent; import jade.core.Profile; import jade.core.ProfileImpl; import jade.core.behaviours.*; import jade.domain.FIPAAgentManagement.*; import jade.domain.FIPAAgentManagement.InternalError; import jade.domain.JADEAgentManagement.*; import jade.domain.KBManagement.*; import jade.domain.DFGUIManagement.*; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.gui.GuiAgent; import jade.gui.GuiEvent; import jade.proto.SubscriptionResponder; import jade.content.*; import jade.content.lang.*; import jade.content.lang.sl.*; import jade.content.onto.*; import jade.content.onto.basic.*; import jade.content.abs.*; /** Standard <em>Directory Facilitator</em> agent. This class implements <em><b>FIPA</b></em> <em>DF</em> agent. <b>JADE</b> applications cannot use this class directly, but interact with it through <em>ACL</em> message passing. More <em>DF</em> agents can be created by application programmers to divide a platform into many <em><b>Agent Domains</b></em>. Each DF has a GUI but, by default, it is not visible. The GUI of the agent platform includes a menu item that allows to show the GUI of the default DF. In order to show the GUI, you should simply send the following message to each DF agent: <code>(request :content (action DFName (SHOWGUI)) :ontology jade-extensions :protocol fipa-request)</code> @author Giovanni Rimassa - Universita` di Parma @author Tiziana Trucco - TILAB S.p.A. @author Elisabetta Cortese - TILAB S.p.A. @version $Date$ $Revision$ */ public class df extends GuiAgent implements DFGUIAdapter { private class RecursiveSearchBehaviour extends RequestFIPAServiceBehaviour { RecursiveSearchHandler rsh; RecursiveSearchBehaviour(RecursiveSearchHandler rsh, AID children, DFAgentDescription dfd, SearchConstraints constraints) throws FIPAException { super(df.this, children, FIPAManagementOntology.SEARCH, dfd, constraints); this.rsh = rsh; } protected void handleInform(ACLMessage reply) { super.handleInform(reply); try{ // Convert search result from array to list Object[] r = getSearchResults(); List l = new ArrayList(); for (int i = 0; i < r.length; ++i) { l.add(r[i]); } rsh.addResults(this, l); }catch (FIPAException e){ e.printStackTrace(); }catch(NotYetReady nyr){ nyr.printStackTrace();} } protected void handleRefuse(ACLMessage reply) { super.handleRefuse(reply); try{ rsh.addResults(this,new ArrayList(0)); }catch(FIPAException e){e.printStackTrace();} } protected void handleFailure(ACLMessage reply) { super.handleFailure(reply); try{ rsh.addResults(this,new ArrayList(0)); }catch(FIPAException e){e.printStackTrace();} } protected void handleNotUnderstood(ACLMessage reply) { super.handleNotUnderstood(reply); try{ rsh.addResults(this,new ArrayList(0)); }catch(FIPAException e){e.printStackTrace();} } //send a not understood message if an out of sequence message arrives. protected void handleOutOfSequence(ACLMessage reply){ super.handleOutOfSequence(reply); try{ rsh.addResults(this,new ArrayList(0)); ACLMessage res = reply.createReply(); res.setPerformative(ACLMessage.NOT_UNDERSTOOD); UnexpectedAct ua = new UnexpectedAct(ACLMessage.getPerformative(reply.getPerformative())); String cont = "( (action "+reply.getSender()+" "+reply+") "+ua.getMessage()+")"; res.setContent(cont); myAgent.send(res); }catch(FIPAException e){e.printStackTrace();} } //called when the timeout is expired. protected void handleAllResponses(Vector reply){ super.handleAllResponses(reply); try{ if(reply.size() == 0) //the timeout has expired: no replies received. rsh.addResults(this,new ArrayList(0)); }catch(FIPAException e){e.printStackTrace();} } }//End class RecursiveSearchBehaviour /** This method called into the DFFIPAAgentManagementBehaviour add the behaviours for a recursive search. return true if the Df has children, false otherwise */ protected boolean performRecursiveSearch(List l, SearchConstraints constraints, DFAgentDescription dfd, ACLMessage request, Action action){ boolean out = false; Long maxResults=constraints.getMaxResults(); RecursiveSearchHandler rsh = new RecursiveSearchHandler(l, constraints, dfd, request, action); SearchConstraints newConstr = new SearchConstraints(); newConstr.setMaxDepth(new Long ((new Integer(constraints.getMaxDepth().intValue()-1)).longValue())); if(maxResults != null) newConstr.setMaxResults(new Long((new Integer(constraints.getMaxResults().intValue() - l.size())).longValue())); Iterator childIt = children.iterator(); while(childIt.hasNext()){ try{ out = true; RecursiveSearchBehaviour b = new RecursiveSearchBehaviour(rsh,(AID)childIt.next(), dfd, newConstr); addBehaviour(b); rsh.addChildren(b); }catch(FIPAException e){} } return out; } private class RecursiveSearchHandler { List children; long deadline; List results; SearchConstraints constraints; DFAgentDescription dfd; ACLMessage request; Action action; int DEFAULTTIMEOUT = 300000; // 5 minutes long MAXRESULTS = 100; //Maximum number of results if not set //constructor RecursiveSearchHandler(List l, SearchConstraints c, DFAgentDescription dfd, ACLMessage msg, Action a) { this.results = l; this.constraints = new SearchConstraints(); constraints.setMaxDepth(c.getMaxDepth()); //MaxDepth is not null by definition of this point of the code if(c.getMaxResults() != null) constraints.setMaxResults(c.getMaxResults()); // else // constraints.setMaxResults(new Long(MAXRESULTS)); this.dfd = dfd; this.request = msg; this.children = new ArrayList(); //the replybyDate should have been set; if not the recursive handler set a deadline after 5 minutes. if (this.request.getReplyByDate() == null) this.deadline = System.currentTimeMillis() + DEFAULTTIMEOUT; else this.deadline = this.request.getReplyByDate().getTime(); this.action = a; } void addChildren(Behaviour b) { this.children.add(b); } void removeChildren(Behaviour b) { this.children.remove(b); } void addResults(Behaviour b, List localResults) throws FIPAException { this.children.remove(b); if(constraints.getMaxResults() != null){ //number of results still missing int remainder = constraints.getMaxResults().intValue() - results.size(); if(remainder > 0){ //add the local result to fill the list of results Iterator it = localResults.iterator(); for(int i =0; i < remainder && it.hasNext(); i++){ results.add(it.next()); } } } else {// add all the results returned by the children. for (Iterator i=localResults.iterator(); i.hasNext(); ) results.add(i.next()); } if ((System.currentTimeMillis() >= deadline) || (children.size() == 0)) { ACLMessage inform = request.createReply(); inform.setPerformative(ACLMessage.INFORM); Result rs = new Result(action, results); try { getContentManager().fillContent(inform, rs); } catch (Exception e) { throw new FIPAException(e.getMessage()); } send(inform); } } } //performs the ShowGui action: show the GUI of the DF. protected void showGuiAction(Action a) throws FailureException{ //no AGREE sent if (!showGui()){ throw new FailureException("Gui_is_being_shown_already"); } } //this method return an ACLMessage that will be sent to the applet to know the parent with which this df is federated. protected ACLMessage getParentAction(Action a,ACLMessage request)throws FailureException{ try { ACLMessage inform = request.createReply(); inform.setPerformative(ACLMessage.INFORM); Result rs = new Result(a, parents); try { getContentManager().fillContent(inform, rs); } catch (Exception e) { throw new FIPAException(e.getMessage()); } return inform; } catch(FIPAException e) { //FIXME no exception predicate in the DFApplet ontology throw new InternalError("Impossible_to_provide_the_needed_information"); } } //Returns the description of this df. //Used to reply to a request from the applet protected ACLMessage getDescriptionOfThisDFAction(Action a,ACLMessage request) throws FailureException{ try{ ACLMessage inform = request.createReply(); inform.setPerformative(ACLMessage.INFORM); List tmp = new ArrayList(); tmp.add(thisDF); Result rs = new Result(a, tmp); try { getContentManager().fillContent(inform, rs); }catch (Exception e) { throw new FIPAException(e.getMessage()); } return inform; }catch(FIPAException e) { //FIXME no exception predicate in the DFApplet ontology throw new InternalError("Impossible_to_provide_the_needed_information"); } } //this behaviour send the reply to the dfproxy private class ThirdStep extends SimpleBehaviour { private boolean finished = false; private GUIRequestDFServiceBehaviour previousStep; private String token; private ACLMessage request; ThirdStep(GUIRequestDFServiceBehaviour b, String action,ACLMessage msg) { super(df.this); previousStep = b; token = action; request = msg; } public void action() { System.out.println("Agent: " + getName() + "in ThirdStep...Token: " + token); ACLMessage reply = request.createReply(); if(previousStep.correctly) { if(token.equalsIgnoreCase(DFAppletOntology.SEARCHON)) { try{ reply.setPerformative(ACLMessage.INFORM); // Convert search result from array to list Object[] r = previousStep.getSearchResults(); List result = new ArrayList(); for (int i = 0; i < r.length; ++i) { result.add(r[i]); } try { Action a = (Action) getContentManager().extractContent(request); Result rs = new Result(a, result); getContentManager().fillContent(reply, rs); } catch (Exception e) { throw new FIPAException(e.getMessage()); } } catch(FIPAException e){ //FIXME no exception predicate in the DFApplet ontology reply.setPerformative(ACLMessage.FAILURE); reply.setContent("( ( action " + myAgent.getLocalName() + " "+ token + " )" +" action_not_possible )"); } catch(RequestFIPAServiceBehaviour.NotYetReady nyr){ reply.setPerformative(ACLMessage.FAILURE); reply.setContent("( ( action " + myAgent.getLocalName() + " "+ token + " )" +" action_not_possible )"); } } else { reply.setPerformative(ACLMessage.INFORM); try { Action a = (Action) getContentManager().extractContent(request); Done d = new Done(a); getContentManager().fillContent(reply, d); } catch (Exception e) { // Try in any case to send back something meaningful reply.setContent("( ( done ( action " + myAgent.getLocalName() + " " + token + " ) ) )" ); } } } else { reply.setPerformative(ACLMessage.FAILURE); reply.setContent("( ( action " + myAgent.getLocalName() + " "+ token + " )" +" action_not_possible )"); } send(reply); finished = true; } public boolean done() { return finished; } } // request another DF to federate this DF (require by the applet) protected void federateWithAction(Action a, ACLMessage request){ FederateWithBehaviour fwb = new FederateWithBehaviour(a,request); addBehaviour(fwb); } //This behaviour allows the federation of this df with another df required by the APPLET private class FederateWithBehaviour extends SequentialBehaviour { FederateWithBehaviour(Action action, ACLMessage msg) { super(df.this); String token = DFAppletOntology.FEDERATEWITH; try{ Federate f = (Federate)action.getAction(); AID parentDF = (AID)f.getParentDF(); DFAgentDescription dfd = (DFAgentDescription)f.getChildrenDF(); if (dfd == null) dfd = getDescriptionOfThisDF(); //send request to parentDF GUIRequestDFServiceBehaviour secondStep = new GUIRequestDFServiceBehaviour(parentDF,FIPAManagementOntology.REGISTER,dfd,null,gui); addSubBehaviour(secondStep); addSubBehaviour(new ThirdStep(secondStep,token,msg)); }catch(FIPAException e){ //FIXME: set the content of the failure message System.err.println(e.getMessage()); ACLMessage failure = msg.createReply(); failure.setPerformative(ACLMessage.FAILURE); msg.setContent(createExceptionalMsgContent(action, e)); send(failure); } } }//end FederateWithBehaviour //This returns the description of this df. //It is used to reply to a request from the applet protected ACLMessage getDescriptionUsedAction(Action a, ACLMessage request) throws FailureException{ try{ GetDescriptionUsed act = (GetDescriptionUsed)a.getAction(); AID parent = (AID)act.getParentDF(); ACLMessage inform = request.createReply(); inform.setPerformative(ACLMessage.INFORM); List tmp = new ArrayList(); tmp.add(dscDFParentMap.get(parent)); Result rs = new Result(a, tmp); try { getContentManager().fillContent(inform, rs); } catch (Exception e) { throw new FIPAException(e.getMessage()); } return inform; }catch(FIPAException e) { //FIXME no exception predicate in the DFApplet ontology throw new InternalError("Impossible_to_provide_the_needed_information"); } } protected void deregisterFromAction(Action a, ACLMessage request){ DeregisterFromBehaviour dfb = new DeregisterFromBehaviour(a,request); addBehaviour(dfb); } //This behaviour allow the applet to required the df to deregister itself from a parent of the federation private class DeregisterFromBehaviour extends SequentialBehaviour{ DeregisterFromBehaviour(Action action, ACLMessage msg) { String token = DFAppletOntology.DEREGISTERFROM; try{ DeregisterFrom f = (DeregisterFrom)action.getAction(); AID parentDF = (AID)f.getParentDF(); DFAgentDescription dfd = (DFAgentDescription)f.getChildrenDF(); //send request to parentDF GUIRequestDFServiceBehaviour secondStep = new GUIRequestDFServiceBehaviour(parentDF,FIPAManagementOntology.DEREGISTER,dfd,null,gui); addSubBehaviour(secondStep); addSubBehaviour(new ThirdStep(secondStep,token,msg)); }catch(FIPAException e){ //FIXME no exception predicate in the DFApplet ontology //FIXME: send a failure ACLMessage failure = msg.createReply(); failure.setPerformative(ACLMessage.FAILURE); failure.setContent(createExceptionalMsgContent(action, e)); send(failure); System.err.println(e.getMessage()); } } } // End of DeregisterFromBehaviour protected void registerWithAction(Action a, ACLMessage request){ RegisterWithBehaviour rwb = new RegisterWithBehaviour(a,request); addBehaviour(rwb); } //This behaviour allow the applet to require the df to register an agent with another df federated with it private class RegisterWithBehaviour extends SequentialBehaviour{ RegisterWithBehaviour(Action a, ACLMessage msg){ String token = DFAppletOntology.REGISTERWITH; try{ RegisterWith rf = (RegisterWith)a.getAction(); AID df = rf.getDf(); DFAgentDescription dfd = rf.getDescription(); //send request to the DF indicated GUIRequestDFServiceBehaviour secondStep = new GUIRequestDFServiceBehaviour(df,FIPAManagementOntology.REGISTER,dfd,null,gui); addSubBehaviour(secondStep); addSubBehaviour(new ThirdStep(secondStep,token,msg)); }catch(FIPAException e){ //FIXME no exception predicate in the DFApplet ontology //FIXME: send a failure ACLMessage failure = msg.createReply(); failure.setPerformative(ACLMessage.FAILURE); failure.setContent(createExceptionalMsgContent(a, e)); send(failure); System.err.println(e.getMessage()); } } } // End of RegisterWithBehaviour protected void modifyOnAction(Action a, ACLMessage request){ ModifyOnBehaviour mob = new ModifyOnBehaviour(a, request); addBehaviour(mob); } //This behaviour allow the applet to require the df to modify the DFAgentDescription of an agent register with another df private class ModifyOnBehaviour extends SequentialBehaviour{ ModifyOnBehaviour(Action a, ACLMessage msg){ String token = DFAppletOntology.MODIFYON; try{ ModifyOn mod = (ModifyOn)a.getAction(); AID df = mod.getDf(); DFAgentDescription dfd = mod.getDescription(); //send request to the DF indicated GUIRequestDFServiceBehaviour secondStep = new GUIRequestDFServiceBehaviour(df,FIPAManagementOntology.MODIFY,dfd,null,gui); addSubBehaviour(secondStep); addSubBehaviour(new ThirdStep(secondStep,token,msg)); }catch(FIPAException e){ //FIXME no exception predicate in the DFApplet ontology // send a failure ACLMessage failure = msg.createReply(); failure.setPerformative(ACLMessage.FAILURE); failure.setContent(createExceptionalMsgContent(a, e)); send(failure); System.err.println(e.getMessage()); } } } // End of ModifyOnBehaviour protected void searchOnAction(Action a, ACLMessage request){ SearchOnBehaviour sob = new SearchOnBehaviour(a,request); addBehaviour(sob); } //this class is used to request an agent to perform a search. Used for the applet. private class SearchOnBehaviour extends SequentialBehaviour{ SearchOnBehaviour(Action a, ACLMessage msg) { String token = DFAppletOntology.SEARCHON; try{ SearchOn s = (SearchOn)a.getAction(); AID df = s.getDf(); DFAgentDescription dfd = s.getDescription(); SearchConstraints sc = s.getConstraints(); //send request to the DF GUIRequestDFServiceBehaviour secondStep = new GUIRequestDFServiceBehaviour(df,FIPAManagementOntology.SEARCH,dfd,sc,gui); addSubBehaviour(secondStep); addSubBehaviour(new ThirdStep(secondStep,token,msg)); }catch(FIPAException e){ //FIXME no exception predicate in the DFApplet ontology //FIXME: send a failure // send a failure ACLMessage failure = msg.createReply(); failure.setPerformative(ACLMessage.FAILURE); failure.setContent(createExceptionalMsgContent(a, e)); send(failure); System.err.println(e.getMessage()); } } } // End of SearchOnBehaviour /** All the actions requested via the DFGUI to another df extends this behaviour **/ private class GUIRequestDFServiceBehaviour extends RequestFIPAServiceBehaviour { String actionName; DFGUIInterface gui; AID receiverDF; DFAgentDescription dfd; boolean correctly = false; //used to verify if the protocol finish correctly GUIRequestDFServiceBehaviour(AID receiverDF, String actionName, DFAgentDescription dfd, SearchConstraints constraints, DFGUIInterface gui) throws FIPAException{ super(df.this,receiverDF,actionName,dfd,constraints); this.actionName = actionName; this.gui = gui; this.receiverDF = receiverDF; this.dfd = dfd; } protected void handleInform(ACLMessage msg) { super.handleInform(msg); correctly =true; if(actionName.equalsIgnoreCase(FIPAManagementOntology.SEARCH)) { try{ if(gui != null) { //the applet can request a search on a different df so the gui can be null //the lastSearchResult table is update also in this case. gui.showStatusMsg("Search request Processed. Ready for new request"); // Convert search result from array to list Object[] r = getSearchResults(); List result = new ArrayList(); for (int i = 0; i < r.length; ++i) { result.add(r[i]); } gui.refreshLastSearchResults(result, msg.getSender()); } }catch (Exception e){ e.printStackTrace();// should never happen } } else if(actionName.equalsIgnoreCase(FIPAManagementOntology.REGISTER)) { try{ if(gui != null) //this control is needed since this behaviour is used to handle the registration request by an applet. //so the gui can be null and an exception can be thrown. gui.showStatusMsg("Request Processed. Ready for new request"); if(dfd.getName().equals(df.this.getAID())) { //if what I register is myself then I have federated with a parent addParent(receiverDF,dfd); } }catch (Exception e){ e.printStackTrace();// should never happen } } else if(actionName.equalsIgnoreCase(FIPAManagementOntology.DEREGISTER)) { try { //this control is needed since the request could be made by the applet. if(gui != null) gui.showStatusMsg("Deregister request Processed. Ready for new request"); // this behaviour is never used to deregister an agent of this DF // but only to deregister a parent or an agent that was registered with // one of my parents or my children if(dfd.getName().equals(df.this.getAID())) { //I deregister myself from a parent removeParent(receiverDF); } else { if(gui != null) //the deregistration can be requested by the applet gui.removeSearchResult(dfd.getName()); } }catch (Exception e){ e.printStackTrace();// should never happen } } else if(actionName.equalsIgnoreCase(FIPAManagementOntology.MODIFY)) { try{ gui.showStatusMsg("Modify request processed. Ready for new request"); }catch(Exception e){ e.printStackTrace(); } } } protected void handleRefuse(ACLMessage msg) { super.handleRefuse(msg); try{ gui.showStatusMsg("Request Refused: " + msg.getContent()); }catch(Exception e) {} } protected void handleFailure(ACLMessage msg) { super.handleFailure(msg); try{ gui.showStatusMsg("Request Failed: " + msg.getContent()); }catch(Exception e){} } protected void handleNotUnderstood(ACLMessage msg) { super.handleNotUnderstood(msg); try{ gui.showStatusMsg("Request not understood: " + msg.getContent()); }catch(Exception e){} } protected void handleOutOfSequence(ACLMessage msg){ super.handleOutOfSequence(msg); try{ //the receiver replied with an out of sequence message. gui.showStatusMsg("Out of sequence response." ); } catch(Exception e){} } //called when the timeout is expired. protected void handleAllResponses(Vector reply){ super.handleAllResponses(reply); try{ if(reply.size() == 0) gui.showStatusMsg("Timeout expired for request"); }catch(Exception e){} } } /** DFSubscriptionResponder BAHAVIOUR. An extended version of the SubscriptionResponder that manages the CANCEL message */ private class DFSubscriptionResponder extends SubscriptionResponder { private static final String HANDLE_CANCEL = "Handle-cancel"; public SubscriptionManager mySubscriptionManager = null; // patch to allow compiling with JDK1.2 DFSubscriptionResponder(Agent a, MessageTemplate mt, SubscriptionManager sm) { super(a, MessageTemplate.or(mt, MessageTemplate.MatchPerformative(ACLMessage.CANCEL)), sm); mySubscriptionManager = sm; registerTransition(RECEIVE_SUBSCRIPTION, HANDLE_CANCEL, ACLMessage.CANCEL); registerDefaultTransition(HANDLE_CANCEL, RECEIVE_SUBSCRIPTION); // HANDLE_CANCEL Behaviour b = new OneShotBehaviour(myAgent) { public void action() { DataStore ds = getDataStore(); // If we are in this state the SUBSCRIPTION_KEY actually contains a CANCEL message ACLMessage cancel = (ACLMessage) ds.get(SUBSCRIPTION_KEY); try { Action act = (Action) getContentManager().extractContent(cancel); ACLMessage subsMsg = (ACLMessage)act.getAction(); mySubscriptionManager.deregister(new SubscriptionResponder.Subscription(DFSubscriptionResponder.this, subsMsg)); } catch(Exception e) { e.printStackTrace(); } } }; b.setDataStore(getDataStore()); registerState(b, HANDLE_CANCEL); } } private List children = new ArrayList(); private List parents = new ArrayList(); private HashMap dscDFParentMap = new HashMap(); //corrispondence parent --> dfd description (of this df) used to federate. private DFGUIInterface gui; // Current description of this df private DFAgentDescription thisDF = null; private Codec codec = new SLCodec(); private DFFipaAgentManagementBehaviour fipaRequestResponder; private DFJadeAgentManagementBehaviour jadeRequestResponder; private DFAppletManagementBehaviour appletRequestResponder; private DFSubscriptionResponder dfSubscriptionResponder; // Configuration parameter keys private static final String VERBOSITY = "jade.domain.df.verbosity"; private static final String DB_DRIVER = "jade.domain.df.db-driver"; private static final String DB_URL = "jade.domain.df.db-url"; private static final String DB_USERNAME = "jade.domain.df.db-username"; private static final String DB_PASSWORD = "jade.domain.df.db-password"; private static final String MAX_RESULTS = "jade.domain.df.maxres"; private static final String DEFAULT_MAX_RESULTS = "10"; private int verbosity = 0; private KB agentDescriptions = null; private KBSubscriptionManager subManager = null; /** This method starts all behaviours needed by <em>DF</em> agent to perform its role within <em><b>JADE</b></em> agent platform. */ protected void setup() { // Set verbosity level try { verbosity = Integer.parseInt(getProperty(VERBOSITY, "0")); } catch (Exception e) { // Keep default (0) } Object[] args = this.getArguments(); // Read configuration: // If an argument is specified, it indicates the name of a properties // file where to read DF configuration from. Otherwise configuration // properties are read from the Profile String sMaxResults = null; String dbUrl = null; String dbDriver = null; String dbUsername = null; String dbPassword = null; if(args != null && args.length > 0) { Properties p = new Properties(); try { p.load((String) args[0]); sMaxResults = p.getProperty(MAX_RESULTS, DEFAULT_MAX_RESULTS); dbUrl = p.getProperty(DB_URL, null); dbDriver = p.getProperty(DB_DRIVER, null); dbUsername = p.getProperty(DB_USERNAME, null); dbPassword = p.getProperty(DB_PASSWORD, null); } catch (Exception e) { log("Error loading configuration from file "+args[0]+" ["+e+"]. Use all defaults", 0); } } else { sMaxResults = getProperty(MAX_RESULTS, DEFAULT_MAX_RESULTS); dbUrl = getProperty(DB_URL, null); dbDriver = getProperty(DB_DRIVER, null); dbUsername = getProperty(DB_USERNAME, null); dbPassword = getProperty(DB_PASSWORD, null); } int maxResult = Integer.parseInt(DEFAULT_MAX_RESULTS); try { maxResult = Integer.parseInt(sMaxResults); } catch (Exception e) { // Keep default } // Instantiate the knowledge base log("DF KB configuration:", 2); log("- Max search result = "+maxResult, 2); if (dbUrl != null) { log("- Type = persistent", 2); log("- DB url = "+dbUrl, 2); log("- DB driver = "+dbDriver, 2); log("- DB username = "+dbUsername, 2); log("- DB password = "+dbPassword, 2); try { agentDescriptions = new DFDBKB(maxResult, dbDriver, dbUrl, dbUsername, dbPassword); } catch (Exception e) { log("Error creating persistent KB ["+e+"]. Use a volatile KB.", 0); } } if (agentDescriptions == null) { log("- Type = volatile", 2); agentDescriptions = new DFMemKB(maxResult); } // Initiate the SubscriptionManager used by the DF subManager = new KBSubscriptionManager(agentDescriptions); subManager.setContentManager(getContentManager()); // Register languages and ontologies getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL0); getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL1); getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL2); getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL); getContentManager().registerOntology(FIPAManagementOntology.getInstance()); getContentManager().registerOntology(JADEManagementOntology.getInstance()); getContentManager().registerOntology(DFAppletOntology.getInstance()); // Create and add behaviours MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST); MessageTemplate mt1 = null; // Behaviour dealing with FIPA management actions mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(FIPAManagementOntology.getInstance().getName())); fipaRequestResponder = new DFFipaAgentManagementBehaviour(this, mt1); addBehaviour(fipaRequestResponder); // Behaviour dealing with JADE management actions mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(JADEManagementOntology.getInstance().getName())); jadeRequestResponder = new DFJadeAgentManagementBehaviour(this, mt1); addBehaviour(jadeRequestResponder); // Behaviour dealing with DFApplet management actions mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(DFAppletOntology.getInstance().getName())); appletRequestResponder = new DFAppletManagementBehaviour(this, mt1); addBehaviour(appletRequestResponder); // Behaviour dealing with subscriptions mt1 = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.SUBSCRIBE), MessageTemplate.MatchOntology(FIPAManagementOntology.getInstance().getName())); dfSubscriptionResponder = new DFSubscriptionResponder(this, mt1, subManager); addBehaviour(dfSubscriptionResponder); // Set the DFDescription of thie DF setDescriptionOfThisDF(getDefaultDescription()); // Set lease policy and subscription responder to the knowledge base agentDescriptions.setLeaseManager(new DFLeaseManager()); agentDescriptions.setSubscriptionResponder(dfSubscriptionResponder); } // End of method setup() /** Cleanup <em>DF</em> on exit. This method performs all necessary cleanup operations during agent shutdown. */ protected void takeDown() { if(gui != null) { gui.disposeAsync(); } DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); Iterator it = parents.iterator(); while(it.hasNext()) { AID parentName = (AID)it.next(); try { DFService.deregister(this, parentName, dfd); } catch(FIPAException fe) { fe.printStackTrace(); } } } /** * Create the content for a so-called "exceptional" message, i.e. * one of NOT_UNDERSTOOD, FAILURE, REFUSE message * @param a is the Action that generated the exception * @param e is the generated Exception * @return a String containing the content to be sent back in the reply * message; in case an exception is thrown somewhere, the method * try to return anyway a valid content with a best-effort strategy **/ //FIXME. This method is only used for create the reply to the APPLET request. private String createExceptionalMsgContent(Action a, FIPAException e) { return e.getMessage(); // FIXME: The following code is hard to port to the new Ontology support /* ACLMessage temp = new ACLMessage(ACLMessage.NOT_UNDERSTOOD); temp.setLanguage(FIPANames.ContentLanguage.FIPA_SL0); temp.setOntology(FIPAManagementOntology.getInstance().getName()); List l = new ArrayList(); if (a == null) { a = new Action(); a.set_0(getAID()); a.set_1("UnknownAction"); } l.add(a); l.add(e); try { fillMsgContent(temp,l); } catch (Exception ee) { // in any case try to return some good content return e.getMessage(); } return temp.getContent();*/ } /** This method make visible the GUI of the DF. @return true if the GUI was not visible already, false otherwise. */ public boolean showGui() { if (gui == null) { try{ Class c = Class.forName("jade.tools.dfgui.DFGUI"); gui = (DFGUIInterface)c.newInstance(); gui.setAdapter(df.this); //this method must be called to avoid reflection (the constructor of the df gui has no parameters). DFAgentDescription matchEverything = new DFAgentDescription(); List agents = agentDescriptions.search(matchEverything); List AIDList = new ArrayList(); Iterator it = agents.iterator(); while(it.hasNext()) AIDList.add(((DFAgentDescription)it.next()).getName()); gui.refresh(AIDList.iterator(), parents.iterator(), children.iterator()); gui.setVisible(true); return true; }catch(Exception e){e.printStackTrace();} } return false; } private boolean isADF(DFAgentDescription dfd) { try { return ((ServiceDescription)dfd.getAllServices().next()).getType().equalsIgnoreCase("fipa-df"); } catch (Exception e) { return false; } } /** * checks that all the mandatory slots for a register/modify/deregister action * are present. * @param actionName is the name of the action (one of * <code>FIPAManagementOntology.REGISTER</code>, * <code>FIPAManagementOntology.MODIFY</code>, * <code>FIPAManagementOntology.DEREGISTER</code>) * @param dfd is the DFAgentDescription to be checked for * @throws MissingParameter if one of the mandatory slots is missing **/ void checkMandatorySlots(String actionName, DFAgentDescription dfd) throws MissingParameter { try { if (dfd.getName().getName().length() == 0) throw new MissingParameter(FIPAManagementOntology.DFAGENTDESCRIPTION, FIPAManagementOntology.DFAGENTDESCRIPTION_NAME); } catch (Exception e) { throw new MissingParameter(FIPAManagementOntology.DFAGENTDESCRIPTION, FIPAManagementOntology.DFAGENTDESCRIPTION_NAME); } if (!actionName.equalsIgnoreCase(FIPAManagementOntology.DEREGISTER)) for (Iterator i=dfd.getAllServices(); i.hasNext();) { ServiceDescription sd =(ServiceDescription)i.next(); try { if (sd.getName().length() == 0) throw new MissingParameter(FIPAManagementOntology.SERVICEDESCRIPTION, FIPAManagementOntology.SERVICEDESCRIPTION_NAME); } catch (Exception e) { throw new MissingParameter(FIPAManagementOntology.SERVICEDESCRIPTION, FIPAManagementOntology.SERVICEDESCRIPTION_NAME); } try { if (sd.getType().length() == 0) throw new MissingParameter(FIPAManagementOntology.SERVICEDESCRIPTION, FIPAManagementOntology.SERVICEDESCRIPTION_TYPE); } catch (Exception e) { throw new MissingParameter(FIPAManagementOntology.SERVICEDESCRIPTION, FIPAManagementOntology.SERVICEDESCRIPTION_TYPE); } } //end of for } private String kbResource ="default"; void DFRegister(DFAgentDescription dfd) throws AlreadyRegistered { //checkMandatorySlots(FIPAAgentManagementOntology.REGISTER, dfd); Object old = agentDescriptions.register(dfd.getName(), dfd); if(old != null) throw new AlreadyRegistered(); if(isADF(dfd)) { children.add(dfd.getName()); try { gui.addChildren(dfd.getName()); } catch (Exception ex) {} } // for subscriptions subManager.handleChange(dfd); try{ //refresh the GUI if shown, exception thrown if the GUI was not shown gui.addAgentDesc(dfd.getName()); gui.showStatusMsg("Registration of agent: " + dfd.getName().getName() + " done."); }catch(Exception ex){} } //this method is called into the prepareResponse of the DFFipaAgentManagementBehaviour to perform a Deregister action void DFDeregister(DFAgentDescription dfd) throws NotRegistered { //checkMandatorySlots(FIPAAgentManagementOntology.DEREGISTER, dfd); Object old = agentDescriptions.deregister(dfd.getName()); if(old == null) throw new NotRegistered(); if (children.remove(dfd.getName())) try { gui.removeChildren(dfd.getName()); } catch (Exception e) {} try{ // refresh the GUI if shown, exception thrown if the GUI was not shown // this refresh must be here, otherwise the GUI is not synchronized with // registration/deregistration made without using the GUI gui.removeAgentDesc(dfd.getName(),df.this.getAID()); gui.showStatusMsg("Deregistration of agent: " + dfd.getName().getName() +" done."); }catch(Exception e1){} } void DFModify(DFAgentDescription dfd) throws NotRegistered { // checkMandatorySlots(FIPAAgentManagementOntology.MODIFY, dfd); Object old = agentDescriptions.deregister(dfd.getName()); if(old == null) throw new NotRegistered(); agentDescriptions.register(dfd.getName(), dfd); // for subscription subManager.handleChange(dfd); try{ gui.removeAgentDesc(dfd.getName(), df.this.getAID()); gui.addAgentDesc(dfd.getName()); gui.showStatusMsg("Modify of agent: "+dfd.getName().getName() + " done."); }catch(Exception e){} } List DFSearch(DFAgentDescription dfd, SearchConstraints constraints, ACLMessage reply){ // Search has no mandatory slots return agentDescriptions.search(dfd); } // GUI EVENTS protected void onGuiEvent(GuiEvent ev) { try { switch(ev.getType()) { case DFGUIAdapter.EXIT: gui.disposeAsync(); gui = null; doDelete(); break; case DFGUIAdapter.CLOSEGUI: gui.disposeAsync(); gui = null; break; case DFGUIAdapter.REGISTER: if (ev.getParameter(0).equals(getName()) || ev.getParameter(0).equals(getLocalName())) { // Register an agent with this DF DFAgentDescription dfd = (DFAgentDescription)ev.getParameter(1); checkMandatorySlots(FIPAManagementOntology.REGISTER, dfd); DFRegister(dfd); } else { // Register an agent with another DF. try { gui.showStatusMsg("Process your request & waiting for result..."); addBehaviour(new GUIRequestDFServiceBehaviour((AID)ev.getParameter(0),FIPAManagementOntology.REGISTER,(DFAgentDescription)ev.getParameter(1),null,gui)); }catch (FIPAException fe) { fe.printStackTrace(); //it should never happen } catch(Exception ex){} //Might happen if the gui has been closed } break; case DFGUIAdapter.DEREGISTER: if(ev.getParameter(0).equals(getName()) || ev.getParameter(0).equals(getLocalName())) { // Deregister an agent with this DF DFAgentDescription dfd = (DFAgentDescription)ev.getParameter(1); checkMandatorySlots(FIPAManagementOntology.DEREGISTER, dfd); DFDeregister(dfd); } else { // Deregister an agent with another DF. try { gui.showStatusMsg("Process your request & waiting for result..."); addBehaviour(new GUIRequestDFServiceBehaviour((AID)ev.getParameter(0),FIPAManagementOntology.DEREGISTER,(DFAgentDescription)ev.getParameter(1),null,gui)); }catch (FIPAException fe) { fe.printStackTrace(); //it should never happen } catch(Exception ex){} //Might happen if the gui has been closed } break; case DFGUIAdapter.MODIFY: if(ev.getParameter(0).equals(getName()) || ev.getParameter(0).equals(getLocalName())) { // Modify the description of an agent with this DF DFAgentDescription dfd = (DFAgentDescription)ev.getParameter(1); checkMandatorySlots(FIPAManagementOntology.MODIFY, dfd); DFModify(dfd); } else { // Modify the description of an agent with another DF try{ gui.showStatusMsg("Process your request & waiting for result.."); addBehaviour(new GUIRequestDFServiceBehaviour((AID)ev.getParameter(0), FIPAManagementOntology.MODIFY, (DFAgentDescription)ev.getParameter(1),null,gui)); }catch(FIPAException fe1){ fe1.printStackTrace(); }//it should never happen catch(Exception ex){} //Might happen if the gui has been closed } break; case DFGUIAdapter.SEARCH: try{ gui.showStatusMsg("Process your request & waiting for result..."); addBehaviour(new GUIRequestDFServiceBehaviour((AID)ev.getParameter(0),FIPAManagementOntology.SEARCH,(DFAgentDescription)ev.getParameter(1),(SearchConstraints)ev.getParameter(2),gui)); }catch(FIPAException fe){ fe.printStackTrace(); }catch(Exception ex1){} //Might happen if the gui has been closed. break; case DFGUIAdapter.FEDERATE: try { gui.showStatusMsg("Process your request & waiting for result..."); if(ev.getParameter(0).equals(getAID()) || ev.getParameter(0).equals(getLocalName())) gui.showStatusMsg("Self Federation not allowed"); else addBehaviour(new GUIRequestDFServiceBehaviour((AID)ev.getParameter(0),FIPAManagementOntology.REGISTER,(DFAgentDescription)ev.getParameter(1),null,gui)); }catch (FIPAException fe) { fe.printStackTrace(); //it should never happen } catch(Exception ex){} //Might happen if the gui has been closed break; } // END of switch } // END of try catch(FIPAException fe) { fe.printStackTrace(); } } /** This method returns the descriptor of an agent registered with the df. */ public DFAgentDescription getDFAgentDsc(AID name) throws FIPAException { DFAgentDescription template = new DFAgentDescription(); template.setName(name); List l = agentDescriptions.search(template); if(l.isEmpty()) return null; else return (DFAgentDescription)l.get(0); } /** * This method creates the DFAgent descriptor for this df used to federate with other df. */ private DFAgentDescription getDefaultDescription() { DFAgentDescription out = new DFAgentDescription(); out.setName(getAID()); out.addOntologies(FIPAManagementOntology.getInstance().getName()); out.addLanguages(FIPANames.ContentLanguage.FIPA_SL0); out.addProtocols(FIPANames.InteractionProtocol.FIPA_REQUEST); ServiceDescription sd = new ServiceDescription(); sd.setName("df-service"); sd.setType("fipa-df"); sd.addOntologies(FIPAManagementOntology.getInstance().getName()); sd.addLanguages(FIPANames.ContentLanguage.FIPA_SL0); sd.addProtocols(FIPANames.InteractionProtocol.FIPA_REQUEST); try{ sd.setOwnership(InetAddress.getLocalHost().getHostName()); }catch (java.net.UnknownHostException uhe){ sd.setOwnership("unknown"); } out.addServices(sd); return out; } /** * This method set the kbResource variable to inform the DF * what kind of knoledge base (hashmap or database) it must use * to store its DFAgentDescriptions * If resourceName==none the the DF will use default: HashMap; * otherwise resourceName will be the file name where are the * configuration to use the DB */ /*public void setKBResource(String resourceName){ System.out.println("RISORSA UTILIZZATA DEFAULT: "+kbResource); if(!resourceName.equalsIgnoreCase("none")) kbResource = resourceName; System.out.println("RISORSA UTILIZZATA: "+kbResource); }*/ /** * This method set the description of the df according to the DFAgentDescription passed. * The programmers can call this method to provide a different initialization of the description of the df they are implementing. * The method is called inside the setup of the agent and set the df description using a default description. */ public void setDescriptionOfThisDF(DFAgentDescription dfd) { thisDF = dfd; } /** * This method returns the current description of this DF */ public DFAgentDescription getDescriptionOfThisDF() { thisDF.setName(getAID()); return thisDF; } /** * This method returns the description of this df used to federate with the given parent */ public DFAgentDescription getDescriptionOfThisDF(AID parent) { return (DFAgentDescription)dscDFParentMap.get(parent); } /** * This method can be used to add a parent (a DF with which the this DF is federated). * @param dfName the parent df (the df with which this df has been registered) * @param dfd the description used by this df to register with the parent. */ public void addParent(AID dfName, DFAgentDescription dfd) { parents.add(dfName); if(gui != null) // the gui can be null if this method is called in order to manage a request made by the df-applet. gui.addParent(dfName); dscDFParentMap.put(dfName,dfd); //update the table of corrispondence between parents and description of this df used to federate. } /** this method can be used to remove a parent (a DF with which this DF is federated). */ public void removeParent(AID dfName) { parents.remove(dfName); if(gui != null) //the gui can be null is this method is called in order to manage a request from the df applet gui.removeParent(dfName); dscDFParentMap.remove(dfName); } private void log(String s, int level) { if (verbosity >= level) { System.out.println("DF-log: "+s); } } }
package tech.tablesaw.api.ml.classification; import com.google.common.base.Preconditions; import smile.classification.KNN; import tech.tablesaw.api.BooleanColumn; import tech.tablesaw.api.CategoryColumn; import tech.tablesaw.api.IntColumn; import tech.tablesaw.api.NumericColumn; import tech.tablesaw.api.ShortColumn; import tech.tablesaw.util.DoubleArrays; import java.util.SortedSet; import java.util.TreeSet; public class Knn extends AbstractClassifier { private final KNN<double[]> classifierModel; private Knn(KNN<double[]> classifierModel) { this.classifierModel = classifierModel; } public static Knn learn(int k, ShortColumn labels, NumericColumn... predictors) { KNN<double[]> classifierModel = KNN.learn(DoubleArrays.to2dArray(predictors), labels.toIntArray(), k); return new Knn(classifierModel); } public static Knn learn(int k, IntColumn labels, NumericColumn... predictors) { KNN<double[]> classifierModel = KNN.learn(DoubleArrays.to2dArray(predictors), labels.data().toIntArray(), k); return new Knn(classifierModel); } public static Knn learn(int k, BooleanColumn labels, NumericColumn... predictors) { KNN<double[]> classifierModel = KNN.learn(DoubleArrays.to2dArray(predictors), labels.toIntArray(), k); return new Knn(classifierModel); } public static Knn learn(int k, CategoryColumn labels, NumericColumn... predictors) { KNN<double[]> classifierModel = KNN.learn(DoubleArrays.to2dArray(predictors), labels.data().toIntArray(), k); return new Knn(classifierModel); } public int predict(double[] data) { return classifierModel.predict(data); } public ConfusionMatrix predictMatrix(ShortColumn labels, NumericColumn... predictors) { Preconditions.checkArgument(predictors.length > 0); SortedSet<Object> labelSet = new TreeSet<>(labels.asSet()); ConfusionMatrix confusion = new StandardConfusionMatrix(labelSet); populateMatrix(labels.toIntArray(), confusion, predictors); return confusion; } public ConfusionMatrix predictMatrix(IntColumn labels, NumericColumn... predictors) { Preconditions.checkArgument(predictors.length > 0); SortedSet<Object> labelSet = new TreeSet<>(labels.asSet()); ConfusionMatrix confusion = new StandardConfusionMatrix(labelSet); populateMatrix(labels.data().toIntArray(), confusion, predictors); return confusion; } public ConfusionMatrix predictMatrix(BooleanColumn labels, NumericColumn... predictors) { Preconditions.checkArgument(predictors.length > 0); SortedSet<Object> labelSet = new TreeSet<>(labels.asSet()); ConfusionMatrix confusion = new StandardConfusionMatrix(labelSet); populateMatrix(labels.toIntArray(), confusion, predictors); return confusion; } public ConfusionMatrix predictMatrix(CategoryColumn labels, NumericColumn... predictors) { Preconditions.checkArgument(predictors.length > 0); SortedSet<String> labelSet = new TreeSet<>(labels.asSet()); ConfusionMatrix confusion = new CategoryConfusionMatrix(labels, labelSet); populateMatrix(labels.data().toIntArray(), confusion, predictors); return confusion; } public int[] predict(NumericColumn... predictors) { Preconditions.checkArgument(predictors.length > 0); int[] predictedLabels = new int[predictors[0].size()]; for (int row = 0; row < predictors[0].size(); row++) { double[] data = new double[predictors.length]; for (int col = 0; col < predictors.length; col++) { data[row] = predictors[col].getFloat(row); } predictedLabels[row] = classifierModel.predict(data); } return predictedLabels; } @Override int predictFromModel(double[] data) { //TODO(lwhite): Better tests /* if (data[0] == 5.0) System.out.println(Arrays.toString(data)); */ return classifierModel.predict(data); } }
package org.treetank.access; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicLong; import org.treetank.access.conf.ResourceConfiguration; import org.treetank.access.conf.SessionConfiguration; import org.treetank.api.INodeReadTrx; import org.treetank.api.INodeWriteTrx; import org.treetank.api.IPageWriteTrx; import org.treetank.api.ISession; import org.treetank.exception.AbsTTException; import org.treetank.exception.TTIOException; import org.treetank.exception.TTThreadedException; import org.treetank.io.EStorage; import org.treetank.io.IReader; import org.treetank.io.IStorage; import org.treetank.io.IWriter; import org.treetank.page.PageReference; import org.treetank.page.UberPage; /** * <h1>Session</h1> * * <p> * Makes sure that there only is a single session instance bound to a TreeTank file. * </p> */ public final class Session implements ISession { /** Session configuration. */ protected final ResourceConfiguration mResourceConfig; /** Session configuration. */ protected final SessionConfiguration mSessionConfig; /** Database for centralized closure of related Sessions. */ private final Database mDatabase; /** Write semaphore to assure only one exclusive write transaction exists. */ private final Semaphore mWriteSemaphore; /** Read semaphore to control running read transactions. */ private final Semaphore mReadSemaphore; /** Strong reference to uber page before the begin of a write transaction. */ private UberPage mLastCommittedUberPage; /** Remember all running transactions (both read and write). */ private final Map<Long, INodeReadTrx> mTransactionMap; /** Remember the write seperatly because of the concurrent writes. */ private final Map<Long, IPageWriteTrx> mWriteTransactionStateMap; /** abstract factory for all interaction to the storage. */ private final IStorage mFac; /** Atomic counter for concurrent generation of transaction id. */ private final AtomicLong mTransactionIDCounter; /** Determines if session was closed. */ private transient boolean mClosed; /** * Hidden constructor. * * @param paramDatabase * Database for centralized operations on related sessions. * @param paramDatabaseConf * DatabaseConfiguration for general setting about the storage * @param paramSessionConf * SessionConfiguration for handling this specific session * @throws AbsTTException * Exception if something weird happens */ protected Session(final Database paramDatabase, final ResourceConfiguration paramResourceConf, final SessionConfiguration paramSessionConf) throws AbsTTException { mDatabase = paramDatabase; mResourceConfig = paramResourceConf; mSessionConfig = paramSessionConf; mTransactionMap = new ConcurrentHashMap<Long, INodeReadTrx>(); mWriteTransactionStateMap = new ConcurrentHashMap<Long, IPageWriteTrx>(); mTransactionIDCounter = new AtomicLong(); // Init session members. mWriteSemaphore = new Semaphore(paramSessionConf.mWtxAllowed); mReadSemaphore = new Semaphore(paramSessionConf.mRtxAllowed); mFac = EStorage.getStorage(mResourceConfig); if (!mFac.exists()) { // Bootstrap uber page and make sure there already is a root // node. mLastCommittedUberPage = new UberPage(); } else { final IReader reader = mFac.getReader(); final PageReference firstRef = reader.readFirstReference(); mLastCommittedUberPage = (UberPage)firstRef.getPage(); reader.close(); } mClosed = false; } /** * {@inheritDoc} */ public INodeReadTrx beginNodeReadTransaction() throws AbsTTException { return beginNodeReadTransaction(mLastCommittedUberPage.getRevisionNumber()); } /** * {@inheritDoc} */ public synchronized INodeReadTrx beginNodeReadTransaction(final long paramRevisionKey) throws AbsTTException { assertAccess(paramRevisionKey); // Make sure not to exceed available number of read transactions. try { mReadSemaphore.acquire(); } catch (final InterruptedException exc) { throw new TTThreadedException(exc); } INodeReadTrx rtx = null; // Create new read transaction. rtx = new NodeReadTrx(this, mTransactionIDCounter.incrementAndGet(), new PageReadTrx(this, mLastCommittedUberPage, paramRevisionKey, mFac.getReader())); return rtx; } /** * {@inheritDoc} */ public synchronized INodeWriteTrx beginNodeWriteTransaction() throws AbsTTException { assertAccess(mLastCommittedUberPage.getRevision()); // Make sure not to exceed available number of write transactions. if (mWriteSemaphore.availablePermits() == 0) { throw new IllegalStateException("There already is a running exclusive write transaction."); } try { mWriteSemaphore.acquire(); } catch (final InterruptedException exc) { throw new TTThreadedException(exc); } final long currentID = mTransactionIDCounter.incrementAndGet(); final IPageWriteTrx wtxState = beginPageWriteTransaction(currentID, mLastCommittedUberPage.getRevisionNumber(), mLastCommittedUberPage.getRevisionNumber()); // Create new write transaction. final INodeWriteTrx wtx = new NodeWriteTrx(currentID, this, wtxState); // Remember transaction for debugging and safe close. if (mTransactionMap.put(currentID, wtx) != null || mWriteTransactionStateMap.put(currentID, wtxState) != null) { throw new TTThreadedException("ID generation is bogus because of duplicate ID."); } return wtx; } protected IPageWriteTrx beginPageWriteTransaction(final long mId, final long mRepresentRevision, final long mStoreRevision) throws TTIOException { final IWriter writer = mFac.getWriter(); return new PageWriteTrx(this, new UberPage(mLastCommittedUberPage, mStoreRevision + 1), writer, mRepresentRevision, mStoreRevision); } /** * {@inheritDoc} */ @Override public synchronized void close() throws AbsTTException { if (!mClosed) { // Forcibly close all open transactions. for (final INodeReadTrx rtx : mTransactionMap.values()) { if (rtx instanceof INodeWriteTrx) { ((INodeWriteTrx)rtx).abort(); } rtx.close(); } // Immediately release all ressources. mLastCommittedUberPage = null; mTransactionMap.clear(); mWriteTransactionStateMap.clear(); mFac.close(); mDatabase.removeSession(mResourceConfig.mPath); mClosed = true; } } protected void assertAccess(final long paramRevision) { if (mClosed) { throw new IllegalStateException("Session is already closed."); } if (paramRevision < 0) { throw new IllegalArgumentException("Revision must be at least 0"); } else if (paramRevision > mLastCommittedUberPage.getRevision()) { throw new IllegalArgumentException(new StringBuilder("Revision must not be bigger than").append( Long.toString(mLastCommittedUberPage.getRevision())).toString()); } } protected void closeWriteTransaction(final long mTransactionID) { // Purge transaction from internal state. mTransactionMap.remove(mTransactionID); // Removing the write from the own internal mapping mWriteTransactionStateMap.remove(mTransactionID); // Make new transactions available. mWriteSemaphore.release(); } protected void closeReadTransaction(final long mTransactionID) { // Purge transaction from internal state. mTransactionMap.remove(mTransactionID); // Make new transactions available. mReadSemaphore.release(); } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(this.mSessionConfig); return builder.toString(); } protected void setLastCommittedUberPage(final UberPage paramPage) { this.mLastCommittedUberPage = paramPage; } }
import java.util.HashMap; import java.util.Stack; public class ValidParentheses { public static void main(String[] args) { // TODO Auto-generated method stub String strs=new String("([)]"); if(isValidParentheses(strs)){ System.out.println(""); }else{ System.out.println(""); } } public static boolean isValidParentheses(String strs){ HashMap<Character, Character> map=new HashMap<>(); map .put('(', ')'); map.put('[', ']'); map.put('{', '}'); Stack<Character> stack=new Stack<>(); for(int i=0;i<strs.length();i++){ if(map.keySet().contains(strs.charAt(i))){ stack.push(strs.charAt(i)); }else{ if(!stack.empty() && map.get(stack.peek())==strs.charAt(i)){ stack.pop(); }else{ return false; } } } return stack.empty(); } }
import java.util.ArrayList; import java.util.LinkedList; public class LevelOrderTraversal { public static void main(String[] args) { // TODO Auto-generated method stub // 9 20 // 15 7 TreeNode root=new TreeNode(3); root.left=new TreeNode(9); root.right=new TreeNode(20); root.right.left=new TreeNode(15); root.right.left=new TreeNode(7); System.out.println(""+levelOrderTraversal(root)); } public static class TreeNode{ int val; TreeNode left; TreeNode right; public TreeNode(int val){ this.val=val; } } public static ArrayList<ArrayList<Integer>> levelOrderTraversal(TreeNode root){ ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>(); if(root==null){ return result; } LinkedList<TreeNode> queue=new LinkedList<>(); ArrayList<Integer> levelResult=new ArrayList<>(); int curLevelCount=1; int nextLevelCount=0; queue.add(root); while(!queue.isEmpty()){ TreeNode cur=queue.poll(); curLevelCount levelResult.add(cur.val); if(cur.left!=null){ nextLevelCount++; queue.add(cur.left); } if(cur.right!=null){ nextLevelCount++; queue.add(cur.right); } if(curLevelCount==0){ curLevelCount=nextLevelCount; nextLevelCount=0; result.add(levelResult); levelResult=new ArrayList<Integer>(); } } return result; } }
package org.hyperic.sigar.cmd; import java.util.Arrays; import java.util.Collection; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.NetInterfaceConfig; import org.hyperic.sigar.NetInterfaceStat; import org.hyperic.sigar.NetFlags; /** * Display network interface configuration and metrics. */ public class Ifconfig extends SigarCommandBase { public Ifconfig(Shell shell) { super(shell); } public Ifconfig() { super(); } protected boolean validateArgs(String[] args) { return args.length <= 1; } public String getSyntaxArgs() { return "[interface]"; } public String getUsageShort() { return "Network interface information"; } public Collection getCompletions() { String[] ifNames; try { ifNames = this.proxy.getNetInterfaceList(); } catch (SigarException e) { return super.getCompletions(); } return Arrays.asList(ifNames); } public void output(String[] args) throws SigarException { String[] ifNames; if (args.length == 1) { ifNames = args; } else { ifNames = this.proxy.getNetInterfaceList(); } for (int i=0; i<ifNames.length; i++) { try { output(ifNames[i]); } catch (SigarException e) { println(ifNames[i] + "\t" + e.getMessage()); } } } public void output(String name) throws SigarException { NetInterfaceConfig ifconfig = this.sigar.getNetInterfaceConfig(name); long flags = ifconfig.getFlags(); String hwaddr = ""; if (!NetFlags.NULL_HWADDR.equals(ifconfig.getHwaddr())) { hwaddr = " HWaddr " + ifconfig.getHwaddr(); } if (!ifconfig.getName().equals(ifconfig.getDescription())) { println(ifconfig.getDescription()); } println(ifconfig.getName() + "\t" + "Link encap:" + ifconfig.getType() + hwaddr); String ptp = ""; if ((flags & NetFlags.IFF_POINTOPOINT) > 0) { ptp = " P-t-P:" + ifconfig.getDestination(); } String bcast = ""; if ((flags & NetFlags.IFF_BROADCAST) > 0) { bcast = " Bcast:" + ifconfig.getBroadcast(); } println("\t" + "inet addr:" + ifconfig.getAddress() + ptp + //unlikely bcast + " Mask:" + ifconfig.getNetmask()); if (ifconfig.getPrefix6Length() != 0) { println("\t" + "inet6 addr: " + ifconfig.getAddress6() + "/" + ifconfig.getPrefix6Length() + " Scope:" + NetFlags.getScopeString(ifconfig.getScope6())); } println("\t" + NetFlags.getIfFlagsString(flags) + " MTU:" + ifconfig.getMtu() + " Metric:" + ifconfig.getMetric()); try { NetInterfaceStat ifstat = this.sigar.getNetInterfaceStat(name); println("\t" + "RX packets:" + ifstat.getRxPackets() + " errors:" + ifstat.getRxErrors() + " dropped:" + ifstat.getRxDropped() + " overruns:" + ifstat.getRxOverruns() + " frame:" + ifstat.getRxFrame()); println("\t" + "TX packets:" + ifstat.getTxPackets() + " errors:" + ifstat.getTxErrors() + " dropped:" + ifstat.getTxDropped() + " overruns:" + ifstat.getTxOverruns() + " carrier:" + ifstat.getTxCarrier()); println("\t" + "collisions:" + ifstat.getTxCollisions()); long rxBytes = ifstat.getRxBytes(); long txBytes = ifstat.getTxBytes(); println("\t" + "RX bytes:" + rxBytes + " (" + Sigar.formatSize(rxBytes) + ")" + " " + "TX bytes:" + txBytes + " (" + Sigar.formatSize(txBytes) + ")"); } catch (SigarException e) { } println(""); } public static void main(String[] args) throws Exception { new Ifconfig().processCommand(args); } }
package git4idea.history; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.OpenTHashSet; import com.intellij.vcs.log.*; import com.intellij.vcs.log.impl.HashImpl; import com.intellij.vcs.log.impl.LogDataImpl; import com.intellij.vcs.log.util.StopWatch; import git4idea.GitCommit; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.branch.GitBranchUtil; import git4idea.commands.*; import git4idea.config.GitVersionSpecialty; import git4idea.log.GitLogProvider; import git4idea.log.GitRefManager; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static git4idea.history.GitLogParser.GitLogOption.*; @ApiStatus.Internal public class GitLogUtil { private static final Logger LOG = Logger.getInstance(GitLogUtil.class); public static final String GRAFTED = "grafted"; public static final String REPLACED = "replaced"; /** * A parameter to {@code git log} which is equivalent to {@code --all}, but doesn't show the stuff from index or stash. */ public static final List<String> LOG_ALL = ContainerUtil.immutableList(GitUtil.HEAD, "--branches", "--remotes", "--tags"); public static final String STDIN = "--stdin"; static final GitLogParser.GitLogOption[] COMMIT_METADATA_OPTIONS = { HASH, PARENTS, COMMIT_TIME, COMMITTER_NAME, COMMITTER_EMAIL, AUTHOR_NAME, AUTHOR_TIME, AUTHOR_EMAIL, SUBJECT, BODY, RAW_BODY }; public static void readTimedCommits(@NotNull Project project, @NotNull VirtualFile root, @NotNull List<String> parameters, @Nullable Consumer<? super VcsUser> userConsumer, @Nullable Consumer<? super VcsRef> refConsumer, @NotNull Consumer<? super TimedVcsCommit> commitConsumer) throws VcsException { VcsLogObjectsFactory factory = getObjectsFactoryWithDisposeCheck(project); if (factory == null) { return; } GitLineHandler handler = createGitHandler(project, root, Collections.emptyList(), false); List<GitLogParser.GitLogOption> options = ContainerUtil.newArrayList(HASH, PARENTS, COMMIT_TIME); if (userConsumer != null) { options.add(AUTHOR_NAME); options.add(AUTHOR_EMAIL); } if (refConsumer != null) { options.add(REF_NAMES); } GitLogParser<GitLogRecord> parser = GitLogParser.createDefaultParser(project, options.toArray(new GitLogParser.GitLogOption[0])); handler.setStdoutSuppressed(true); handler.addParameters(parser.getPretty(), "--encoding=UTF-8"); handler.addParameters("--decorate=full"); handler.addParameters(parameters); handler.endOptions(); GitLogOutputSplitter<GitLogRecord> handlerListener = new GitLogOutputSplitter<>(handler, parser, record -> { Hash hash = HashImpl.build(record.getHash()); List<Hash> parents = ContainerUtil.map(record.getParentsHashes(), factory::createHash); commitConsumer.consume(factory.createTimedCommit(hash, parents, record.getCommitTime())); if (refConsumer != null) { for (VcsRef ref : parseRefs(record.getRefs(), hash, factory, root)) { refConsumer.consume(ref); } } if (userConsumer != null) userConsumer.consume(factory.createUser(record.getAuthorName(), record.getAuthorEmail())); }); Git.getInstance().runCommandWithoutCollectingOutput(handler); handlerListener.reportErrors(); } @NotNull public static List<? extends VcsCommitMetadata> collectMetadata(@NotNull Project project, @NotNull GitVcs vcs, @NotNull VirtualFile root, @NotNull List<String> hashes) throws VcsException { if (hashes.isEmpty()) { return Collections.emptyList(); } VcsLogObjectsFactory factory = getObjectsFactoryWithDisposeCheck(project); if (factory == null) { return Collections.emptyList(); } GitLineHandler h = createGitHandler(project, root); GitLogParser<GitLogRecord> parser = GitLogParser.createDefaultParser(project, COMMIT_METADATA_OPTIONS); h.setSilent(true); // git show can show either -p, or --name-status, or --name-only, but we need nothing, just details => using git log --no-walk h.addParameters(getNoWalkParameter(vcs)); h.addParameters(parser.getPretty(), "--encoding=UTF-8"); h.addParameters(STDIN); h.endOptions(); sendHashesToStdin(vcs, hashes, h); String output = Git.getInstance().runCommand(h).getOutputOrThrow(); List<GitLogRecord> records = parser.parse(output); return ContainerUtil.map(records, record -> { List<Hash> parents = new SmartList<>(); for (String parent : record.getParentsHashes()) { parents.add(HashImpl.build(parent)); } record.setUsedHandler(h); return factory.createCommitMetadata(HashImpl.build(record.getHash()), parents, record.getCommitTime(), root, record.getSubject(), record.getAuthorName(), record.getAuthorEmail(), record.getFullMessage(), record.getCommitterName(), record.getCommitterEmail(), record.getAuthorTimeStamp()); }); } @NotNull public static VcsLogProvider.DetailedLogData collectMetadata(@NotNull Project project, @NotNull VirtualFile root, String... params) throws VcsException { VcsLogObjectsFactory factory = getObjectsFactoryWithDisposeCheck(project); if (factory == null) { return LogDataImpl.empty(); } Set<VcsRef> refs = new OpenTHashSet<>(GitLogProvider.DONT_CONSIDER_SHA); List<VcsCommitMetadata> commits = new ArrayList<>(); Consumer<GitLogRecord> recordConsumer = record -> { VcsCommitMetadata commit = createMetadata(root, record, factory); commits.add(commit); Collection<VcsRef> refsInRecord = parseRefs(record.getRefs(), commit.getId(), factory, root); for (VcsRef ref : refsInRecord) { if (!refs.add(ref)) { VcsRef otherRef = ContainerUtil.find(refs, r -> GitLogProvider.DONT_CONSIDER_SHA.equals(r, ref)); LOG.error("Adding duplicate element " + ref + " to the set containing " + otherRef); } } }; try { GitLineHandler handler = createGitHandler(project, root, Collections.emptyList(), false); GitLogParser.GitLogOption[] options = ArrayUtil.append(COMMIT_METADATA_OPTIONS, REF_NAMES); GitLogParser<GitLogRecord> parser = GitLogParser.createDefaultParser(project, options); handler.setStdoutSuppressed(true); handler.addParameters(params); handler.addParameters(parser.getPretty(), "--encoding=UTF-8"); handler.addParameters("--decorate=full"); handler.endOptions(); StopWatch sw = StopWatch.start("loading commit metadata in [" + root.getName() + "]"); GitLogOutputSplitter<GitLogRecord> handlerListener = new GitLogOutputSplitter<>(handler, parser, recordConsumer); Git.getInstance().runCommandWithoutCollectingOutput(handler).throwOnError(); handlerListener.reportErrors(); sw.report(); } catch (VcsException e) { if (commits.isEmpty()) { throw e; } LOG.warn("Error during loading details, returning partially loaded commits\n", e); } return new LogDataImpl(refs, commits); } public static void readFullDetails(@NotNull Project project, @NotNull VirtualFile root, @NotNull Consumer<? super GitCommit> commitConsumer, String @NotNull ... parameters) throws VcsException { new GitFullDetailsCollector(project, root, new InternedGitLogRecordBuilder()) .readFullDetails(commitConsumer, GitCommitRequirements.DEFAULT, false, parameters); } public static void readFullDetailsForHashes(@NotNull Project project, @NotNull VirtualFile root, @NotNull List<String> hashes, @NotNull GitCommitRequirements requirements, @NotNull Consumer<? super GitCommit> commitConsumer) throws VcsException { if (hashes.isEmpty()) { return; } new GitFullDetailsCollector(project, root, new InternedGitLogRecordBuilder()) .readFullDetailsForHashes(hashes, requirements, false, commitConsumer); } @NotNull private static Collection<VcsRef> parseRefs(@NotNull Collection<String> refs, @NotNull Hash hash, @NotNull VcsLogObjectsFactory factory, @NotNull VirtualFile root) { return ContainerUtil.mapNotNull(refs, refName -> { if (refName.equals(GRAFTED) || refName.equals(REPLACED)) return null; VcsRefType type = GitRefManager.getRefType(refName); refName = GitBranchUtil.stripRefsPrefix(refName); return refName.equals(GitUtil.ORIGIN_HEAD) ? null : factory.createRef(hash, refName, type, root); }); } @Nullable public static VcsLogObjectsFactory getObjectsFactoryWithDisposeCheck(@NotNull Project project) { return ReadAction.compute(() -> { if (!project.isDisposed()) { return ServiceManager.getService(project, VcsLogObjectsFactory.class); } return null; }); } @NotNull static VcsCommitMetadata createMetadata(@NotNull VirtualFile root, @NotNull GitLogRecord record, @NotNull VcsLogObjectsFactory factory) { List<Hash> parents = ContainerUtil.map(record.getParentsHashes(), factory::createHash); return factory.createCommitMetadata(factory.createHash(record.getHash()), parents, record.getCommitTime(), root, record.getSubject(), record.getAuthorName(), record.getAuthorEmail(), record.getFullMessage(), record.getCommitterName(), record.getCommitterEmail(), record.getAuthorTimeStamp()); } static void sendHashesToStdin(@NotNull GitVcs vcs, @NotNull Collection<String> hashes, @NotNull GitHandler handler) { // if we close this stream, RunnerMediator won't be able to send ctrl+c to the process in order to softly kill it // see RunnerMediator.sendCtrlEventThroughStream handler.setInputProcessor(GitHandlerInputProcessorUtil.writeLines(hashes, "\n", handler.getCharset(), true)); } @NotNull static String getNoWalkParameter(@NotNull GitVcs vcs) { return GitVersionSpecialty.NO_WALK_UNSORTED.existsIn(vcs) ? "--no-walk=unsorted" : "--no-walk"; } @NotNull static GitLineHandler createGitHandler(@NotNull Project project, @NotNull VirtualFile root) { return createGitHandler(project, root, Collections.emptyList(), false); } @NotNull static GitLineHandler createGitHandler(@NotNull Project project, @NotNull VirtualFile root, @NotNull List<String> configParameters, boolean lowPriorityProcess) { GitLineHandler handler = new GitLineHandler(project, root, GitCommand.LOG, configParameters); if (lowPriorityProcess) handler.withLowPriority(); handler.setWithMediator(false); return handler; } }
package org.builditbreakit.seada.logappend; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; public class App { private static void applyCommand(String[] args, GalleryUpdateManager gum) throws IOException, SecurityException { // This line with throw if cmdline syntax is bad. AppendCommand cmd = new AppendCommand(args); // This line will throw if token is bad or logfile is corrupt/uncreatable. GalleryUpdate item = gum.getGalleryFor(cmd); // This switch statement should throw if a guest name is used as an employee name, // a timestamp isn't >= previous value, etc. switch (cmd.getEvent()) { case ARRIVAL: if (cmd.getRoom() == -1) { item.state.arriveAtBuilding(cmd.getTimestamp(), cmd.getVisitorName(), cmd.getVisitorType()); } else { item.state.arriveAtRoom(cmd.getTimestamp(), cmd.getVisitorName(), cmd.getVisitorType(), cmd.getRoom()); } break; case DEPARTURE: if (cmd.getRoom() == -1) { item.state.departBuilding(cmd.getTimestamp(), cmd.getVisitorName(), cmd.getVisitorType()); } else { item.state.departRoom(cmd.getTimestamp(), cmd.getVisitorName(), cmd.getVisitorType(), cmd.getRoom()); } break; default: throw new IllegalArgumentException("bad event type (neither arrival nor departure)"); } item.modified = true; } /** * @return Number of commands that modified model. */ private static void processBatch(GalleryUpdateManager gum, String batchFilePath) throws IOException { BatchProcessor b = new BatchProcessor(batchFilePath); while (b.hasNextLine()) { String[] args = b.nextLine(); try { applyCommand(args, gum); } catch (SecurityException e) { logError(e, args); System.out.println("integrity violation"); } catch (Throwable e) { logError(e, args); System.out.println("invalid"); } } } private static final boolean PRINT_ERRORS = true; // disable before final build private static void logError(Throwable e, String[] args) { try { File tempFile = File.createTempFile("seada-logappend", "tmp"); FileOutputStream fout = new FileOutputStream(tempFile); PrintWriter out = new PrintWriter(fout); out.print("Error with"); for (String arg: args) { out.print(' '); out.print(arg); } out.println("\n"); e.printStackTrace(out); } catch (IOException e1) { } } public static void main(String[] args) { int exitCodeForErrors = 255; try { GalleryUpdateManager gum = new GalleryUpdateManager(); if (args.length == 2 && args[0].equals("-B")) { exitCodeForErrors = 0; processBatch(gum, args[1]); } else { applyCommand(args, gum); } gum.save(); System.exit(0); } catch (SecurityException e) { logError(e, args); System.out.println("integrity violation"); System.exit(exitCodeForErrors); } catch (Throwable e) { logError(e, args); System.out.println("invalid"); System.exit(exitCodeForErrors); } } }
package net.sf.cglib.proxy; import java.io.*; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; /** * * this code returns Enhanced Vector to intercept all methods for tracing * <pre> * java.util.Vector vector = (java.util.Vector)Enhancer.enhance( * java.util.Vector.<b>class</b>, * new Class[]{java.util.List.<b>class</b>}, * * new MethodInterceptor(){ * * * <b>public boolean invokeSuper</b>( Object obj,java.lang.reflect.Method method, * Object args[]) * throws java.lang.Throwable{ * return true; * } * * * <b>public</b> Object <b>afterReturn</b>( Object obj, java.lang.reflect.Method method, * Object args[], * boolean invokedSuper, Object retValFromSuper, * java.lang.Throwable e )throws java.lang.Throwable{ * System.out.println(method); * return retValFromSuper;//return the same as supper * } * * }); * </pre> *@author Juozas Baliuka <a href="mailto:baliuka@mwm.lt"> * baliuka@mwm.lt</a> *@version $Id: Enhancer.java,v 1.17 2002-09-30 18:36:16 baliuka Exp $ */ public class Enhancer implements org.apache.bcel.Constants { static final String INTERCEPTOR_CLASS_NAME = MethodInterceptor.class.getName(); static final ObjectType BOOLEAN_OBJECT = new ObjectType(Boolean.class.getName()); static final ObjectType INTEGER_OBJECT = new ObjectType(Integer.class.getName()); static final ObjectType CHARACTER_OBJECT = new ObjectType(Character.class.getName()); static final ObjectType BYTE_OBJECT = new ObjectType(Byte.class.getName()); static final ObjectType SHORT_OBJECT = new ObjectType(Short.class.getName()); static final ObjectType LONG_OBJECT = new ObjectType(Long.class.getName()); static final ObjectType DOUBLE_OBJECT = new ObjectType(Double.class.getName()); static final ObjectType FLOAT_OBJECT = new ObjectType(Float.class.getName()); static final ObjectType METHOD_OBJECT = new ObjectType(java.lang.reflect.Method.class.getName()); static final ObjectType CLASS_OBJECT = new ObjectType(Class.class.getName()); static final ObjectType NUMBER_OBJECT = new ObjectType(Number.class.getName()); static final String CONSTRUCTOR_NAME = "<init>"; static final String FIELD_NAME = "h"; static final String SOURCE_FILE = "<generated>"; static final String CLASS_SUFIX = "$$EnhancedByCGLIB$$"; static final String CLASS_PREFIX = "net.sf.cglib.proxy"; static int index = 0; static java.util.Map factories = new java.util.HashMap(); private static int addAfterConstructionRef(ConstantPoolGen cp) { return cp.addMethodref( Enhancer.class.getName(), "handleConstruction", "(Ljava/lang/Object;[Ljava/lang/Object;)V"); } private static int addNewInstanceRef(ConstantPoolGen cp,String name) { return cp.addMethodref( name, "<init>", "(L"+ INTERCEPTOR_CLASS_NAME.replace('.','/') +";)V"); } private static int addWriteReplace(ConstantPoolGen cp){ return cp.addMethodref( Enhancer.InternalReplace.class.getName(), "writeReplace", "(Ljava/lang/Object;)Ljava/lang/Object;"); } private static int addAfterRef(ConstantPoolGen cp) { return cp.addInterfaceMethodref( INTERCEPTOR_CLASS_NAME, "afterReturn", "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;ZLjava/lang/Object;Ljava/lang/Throwable;)Ljava/lang/Object;"); } private static int addInvokeSupperRef(ConstantPoolGen cp) { return cp.addInterfaceMethodref( INTERCEPTOR_CLASS_NAME, "invokeSuper", "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Z"); } private static java.util.List costructionHandlers = new java.util.Vector(); private static java.util.Map cache = new java.util.WeakHashMap(); private Enhancer() {} public static MethodInterceptor getMethodInterceptor(Object enhanced){ try{ return (MethodInterceptor) enhanced.getClass().getField(FIELD_NAME).get( enhanced); }catch( NoSuchFieldException nsfe){ throw new NoSuchFieldError(enhanced + " is not enhanced :" + nsfe.getMessage()); }catch( java.lang.IllegalAccessException iae ){ throw new IllegalAccessError(enhanced.getClass().getName() + ":" + iae.getMessage()); } } /** * implemented as * return enhance(cls,interfaces,ih, null); */ public static Object enhance( Class cls, Class interfaces[], MethodInterceptor ih) throws Throwable { return enhance( cls, interfaces, ih, null); } /** enhances public not final class, * source class must have public no args constructor. * Code generated for protected and public not final methods, * package scope methods supported from source class package. * Defines new class in source class package, if it not java*. * @param cls class to extend, uses Object.class if null * @param interfaces interfaces to implement, can be null * @param ih valid interceptor implementation * @param loader classloater for enhanced class, uses "current" if null * @throws Throwable on error * @return instanse of enhanced class */ public synchronized static Object enhance( Class cls, Class interfaces[], MethodInterceptor ih, ClassLoader loader) throws Throwable { if( ih == null ){ throw new NullPointerException("invalid interceptior"); } if (cls == null) { cls = Object.class; } if( loader == null ){ loader = Enhancer.class.getClassLoader(); } StringBuffer keyBuff = new StringBuffer(cls.getName() + ";"); if(interfaces != null){ for(int i = 0; i< interfaces.length; i++ ){ keyBuff .append(interfaces[i].getName() + ";"); } } String key = keyBuff.toString(); java.util.Map map = (java.util.Map) cache.get(loader); if ( map == null ) { map = new java.util.Hashtable(); cache.put(loader, map); } Class result = (Class) map.get(key); if ( result == null ) { try{ loader.loadClass(cls.getName()); if( interfaces != null ){ for( int i = 0; i< interfaces.length; i++ ){ loader.loadClass( interfaces[i].getName() ); } } }catch( ClassNotFoundException cnfe ){ throw new IllegalArgumentException( cnfe.getMessage() ); } String class_name = cls.getName() + CLASS_SUFIX; if (class_name.startsWith("java")) { class_name = CLASS_PREFIX + class_name; } class_name += index++; JavaClass clazz = enhance(cls, class_name, interfaces ); byte b[] = clazz.getBytes(); java.lang.reflect.Method m = ClassLoader.class.getDeclaredMethod( "defineClass", new Class[] { String.class, byte[].class, int.class, int.class }); // protected method invocaton boolean flag = m.isAccessible(); m.setAccessible(true); result = (Class) m.invoke( loader, new Object[] { clazz.getClassName(), b, new Integer(0), new Integer(b.length)}); m.setAccessible(flag); map.put(key, result); } Factory factory = (Factory)factories.get(result); if( factory == null ){ factory = (Factory)result.getConstructor( new Class[] { Class.forName(MethodInterceptor.class.getName(), true, loader) }).newInstance(new Object[] { null }); factories.put(result,factory); } return factory.newInstance(ih); } private static void addConstructor(ClassGen cg) throws Throwable { //single arg constructor String parentClass = cg.getSuperclassName(); InstructionFactory factory = new InstructionFactory(cg); ConstantPoolGen cp = cg.getConstantPool(); // cg creates constant pool InstructionList il = new InstructionList(); MethodGen costructor = new MethodGen(ACC_PUBLIC, // access flags Type.VOID, // return type new Type[] { // argument types new ObjectType(INTERCEPTOR_CLASS_NAME)}, null, // arg names CONSTRUCTOR_NAME, cg.getClassName(), il, cp); il.append(new ALOAD(0)); il.append( factory.createInvoke( parentClass, CONSTRUCTOR_NAME, Type.VOID, new Type[] {}, INVOKESPECIAL)); il.append(new ALOAD(0)); il.append(new ALOAD(1)); il.append( factory.createFieldAccess( cg.getClassName(), FIELD_NAME, new ObjectType(INTERCEPTOR_CLASS_NAME), PUTFIELD)); il.append(new RETURN()); cg.addMethod(getMethod(costructor)); //factory sometimes usefull and has meaning for performance il = new InstructionList(); MethodGen newInstance = toMethodGen( Factory.class.getMethod("newInstance", new Class[]{ MethodInterceptor.class } ), cg.getClassName(), il, cp ); il.append( new NEW(cp.addClass( new ObjectType(cg.getClassName()) )) ); il.append( new DUP()); il.append( new ALOAD(1) ); il.append( new INVOKESPECIAL( addNewInstanceRef(cp, cg.getClassName()) ) ) ; il.append( new ARETURN()); cg.addMethod(getMethod(newInstance)); //serialization support il = new InstructionList(); MethodGen writeReplace = new MethodGen(ACC_PRIVATE, // access flags Type.OBJECT, // return type new Type[] {}, null, // arg names "writeReplace", cg.getClassName(), il, cp); il.append(new ALOAD(0)); il.append(new INVOKESTATIC( addWriteReplace(cp) ) ); il.append(new ARETURN()); cg.addMethod(getMethod(writeReplace)); } private static void addHandlerField(ClassGen cg) { // TODO: ACC_PRIVATE ConstantPoolGen cp = cg.getConstantPool(); FieldGen fg = new FieldGen(ACC_PUBLIC, new ObjectType(INTERCEPTOR_CLASS_NAME), FIELD_NAME, cp); cg.addField(fg.getField()); } private static ClassGen getClassGen( String class_name, Class parentClass, Class[] interfaces) { ClassGen gen = new ClassGen(class_name, parentClass.getName(), SOURCE_FILE, ACC_PUBLIC | ACC_FINAL , null ); if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { gen.addInterface(interfaces[i].getName()); } } gen.addInterface( Factory.class.getName() ); return gen; } private static JavaClass enhance( Class parentClass, String class_name, Class interfaces[] ) throws Throwable { java.util.HashMap methodTable = new java.util.HashMap(); ClassGen cg = getClassGen(class_name, parentClass, interfaces); ConstantPoolGen cp = cg.getConstantPool(); // cg creates constant pool addHandlerField(cg); addConstructor(cg); int after = addAfterRef(cp); int invokeSuper = addInvokeSupperRef(cp); java.util.Set methodSet = new java.util.HashSet(); java.util.List allMethods = new java.util.ArrayList(); String packageName = getPackageName( class_name ); // Order is very important: must add parentClass, then // its superclass chain, then each interface and // its superinterfaces. addDeclaredMethods(allMethods, parentClass); if (interfaces != null) { for (int j = 0; j < interfaces.length; j++) { addDeclaredMethods(allMethods, interfaces[j]); } } for (java.util.Iterator i = allMethods.iterator(); i.hasNext(); ) { java.lang.reflect.Method m = (java.lang.reflect.Method) i.next(); int mod = m.getModifiers(); if (!java.lang.reflect.Modifier.isStatic(mod) && !java.lang.reflect.Modifier.isFinal(mod) && isVisible( m , packageName ) ) { methodSet.add(new MethodWrapper(m)); } } int cntr = 0; for (java.util.Iterator i = methodSet.iterator(); i.hasNext();) { java.lang.reflect.Method method = ((MethodWrapper) i.next()).method; String fieldName = "METHOD_" + (cntr++); cg.addMethod(generateMethod(method, fieldName, cg, after, invokeSuper)); methodTable.put(fieldName, method); } generateClInit(cg, cp, methodTable); JavaClass jcl = cg.getJavaClass(); return jcl; } private static String getPackageName( String className ) throws Throwable{ int index = className.lastIndexOf('.'); if( index == -1 ){ return ""; } return className.substring( 0, index ); } private static boolean isVisible(java.lang.reflect.Method m , String packageName )throws Throwable{ int mod = m.getModifiers(); if( java.lang.reflect.Modifier.isPrivate( mod )){ return false; } if( java.lang.reflect.Modifier.isProtected( mod ) || java.lang.reflect.Modifier.isPublic( mod ) ){ return true; } //package scope: return getPackageName( m.getDeclaringClass().getName() ).equals( packageName ); } private static void addDeclaredMethods(java.util.List methodList, Class clazz) { methodList.addAll(java.util.Arrays.asList(clazz.getDeclaredMethods())); if (clazz.isInterface()) { Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { addDeclaredMethods(methodList, interfaces[i]); } } else { Class superclazz = clazz.getSuperclass(); if (superclazz != null) { addDeclaredMethods(methodList, superclazz); } } } private static void addMethodField(String fieldName, ClassGen cg) { ConstantPoolGen cp = cg.getConstantPool(); FieldGen fg = new FieldGen( ACC_FINAL | ACC_STATIC, METHOD_OBJECT, fieldName, cp ); cg.addField(fg.getField()); } private static int createArgArray( InstructionList il, InstructionFactory factory, ConstantPoolGen cp, Type[] args) { int argCount = args.length; if (argCount > 5) il.append(new BIPUSH((byte) argCount)); else il.append(new ICONST((byte) argCount)); il.append(new ANEWARRAY(cp.addClass(Type.OBJECT))); int load = 1; for (int i = 0; i < argCount; i++) { il.append(new DUP()); if (i > 5) il.append(new BIPUSH((byte) i)); else il.append(new ICONST((byte) i)); if (args[i] instanceof BasicType) { if (args[i].equals(Type.BOOLEAN)) { il.append(new NEW(cp.addClass(BOOLEAN_OBJECT))); il.append(new DUP()); il.append(new ILOAD(load++)); il.append( new INVOKESPECIAL( cp.addMethodref(Boolean.class.getName(), CONSTRUCTOR_NAME, "(Z)V"))); } else if (args[i].equals(Type.INT)) { il.append(new NEW(cp.addClass(INTEGER_OBJECT))); il.append(new DUP()); il.append(new ILOAD(load++)); il.append( new INVOKESPECIAL( cp.addMethodref(Integer.class.getName(), CONSTRUCTOR_NAME, "(I)V"))); } else if (args[i].equals(Type.CHAR)) { il.append(new NEW(cp.addClass(CHARACTER_OBJECT))); il.append(new DUP()); il.append(new ILOAD(load++)); il.append( new INVOKESPECIAL( cp.addMethodref(Character.class.getName(), CONSTRUCTOR_NAME, "(C)V"))); } else if (args[i].equals(Type.BYTE)) { il.append(new NEW(cp.addClass(BYTE_OBJECT))); il.append(new DUP()); il.append(new ILOAD(load++)); il.append( new INVOKESPECIAL( cp.addMethodref(Byte.class.getName(), CONSTRUCTOR_NAME, "(B)V"))); } else if (args[i].equals(Type.SHORT)) { il.append(new NEW(cp.addClass(SHORT_OBJECT))); il.append(new DUP()); il.append(new ILOAD(load++)); il.append( new INVOKESPECIAL( cp.addMethodref(Short.class.getName(), CONSTRUCTOR_NAME, "(S)V"))); } else if (args[i].equals(Type.LONG)) { il.append(new NEW(cp.addClass(LONG_OBJECT))); il.append(new DUP()); il.append(new LLOAD(load)); load += 2; il.append( new INVOKESPECIAL( cp.addMethodref(Long.class.getName(), CONSTRUCTOR_NAME, "(J)V"))); } else if (args[i].equals(Type.DOUBLE)) { il.append(new NEW(cp.addClass(DOUBLE_OBJECT))); il.append(new DUP()); il.append(new DLOAD(load)); load += 2; il.append( new INVOKESPECIAL( cp.addMethodref(Double.class.getName(), CONSTRUCTOR_NAME, "(D)V"))); } else if (args[i].equals(Type.FLOAT)) { il.append(new NEW(cp.addClass(FLOAT_OBJECT))); il.append(new DUP()); il.append(new FLOAD(load++)); il.append( new INVOKESPECIAL( cp.addMethodref(Float.class.getName(), CONSTRUCTOR_NAME, "(F)V"))); } il.append(new AASTORE()); } else { il.append(new ALOAD(load++)); il.append(new AASTORE()); } } return load; } private static Method getMethod(MethodGen mg) { mg.stripAttributes(true); mg.setMaxLocals(); mg.setMaxStack(); return mg.getMethod(); } private static InstructionHandle generateReturnValue( InstructionList il, InstructionFactory factory, ConstantPoolGen cp, Type returnType, int stack) { if (returnType.equals(Type.VOID)) { return il.append(new RETURN()); } il.append(new ASTORE(stack)); il.append(new ALOAD(stack)); if ((returnType instanceof ObjectType) || ( returnType instanceof ArrayType) ) { if (returnType instanceof ArrayType){ il.append(new CHECKCAST(cp.addArrayClass((ArrayType)returnType))); return il.append(new ARETURN()); } if (!returnType.equals(Type.OBJECT)){ il.append(new CHECKCAST(cp.addClass((ObjectType) returnType))); return il.append(new ARETURN()); }else { return il.append(new ARETURN()); } } if (returnType instanceof BasicType) { if (returnType.equals(Type.BOOLEAN)) { IFNONNULL ifNNull = new IFNONNULL(null); il.append(ifNNull); il.append(new ICONST(0) ); il.append(new IRETURN()); ifNNull.setTarget(il.append(new ALOAD(stack))); il.append(new CHECKCAST(cp.addClass(BOOLEAN_OBJECT))); il.append( factory.createInvoke( Boolean.class.getName(), "booleanValue", Type.BOOLEAN, new Type[] {}, INVOKEVIRTUAL)); return il.append(new IRETURN()); } else if (returnType.equals(Type.CHAR)) { IFNONNULL ifNNull = new IFNONNULL(null); il.append(ifNNull); il.append(new ICONST(0) ); il.append(new IRETURN()); ifNNull.setTarget(il.append(new ALOAD(stack))); il.append(new CHECKCAST(cp.addClass(CHARACTER_OBJECT))); il.append( factory.createInvoke( Character.class.getName(), "charValue", Type.CHAR, new Type[] {}, INVOKEVIRTUAL)); return il.append(new IRETURN()); } else if (returnType.equals(Type.LONG)) { IFNONNULL ifNNull = new IFNONNULL(null); il.append(ifNNull); il.append(new LCONST(0) ); il.append(new LRETURN()); ifNNull.setTarget(il.append(new ALOAD(stack))); il.append(new CHECKCAST(cp.addClass(NUMBER_OBJECT))); il.append( factory.createInvoke( Number.class.getName(), "longValue", Type.LONG, new Type[] {}, INVOKEVIRTUAL)); return il.append(new LRETURN()); } else if (returnType.equals(Type.DOUBLE)) { IFNONNULL ifNNull = new IFNONNULL(null); il.append(ifNNull); il.append(new DCONST(0) ); il.append(new DRETURN()); ifNNull.setTarget(il.append(new ALOAD(stack))); il.append(new CHECKCAST(cp.addClass(NUMBER_OBJECT))); il.append( factory.createInvoke( Number.class.getName(), "doubleValue", Type.DOUBLE, new Type[] {}, INVOKEVIRTUAL)); return il.append(new DRETURN()); } else if (returnType.equals(Type.FLOAT)) { IFNONNULL ifNNull = new IFNONNULL(null); il.append(ifNNull); il.append(new FCONST(0) ); il.append(new FRETURN()); ifNNull.setTarget(il.append(new ALOAD(stack))); il.append(new CHECKCAST(cp.addClass(NUMBER_OBJECT))); il.append( factory.createInvoke( java.lang.Number.class.getName(), "floatValue", Type.FLOAT, new Type[] {}, INVOKEVIRTUAL)); return il.append(new FRETURN()); } else { IFNONNULL ifNNull = new IFNONNULL(null); il.append(ifNNull); il.append(new ICONST(0) ); il.append(new IRETURN()); ifNNull.setTarget(il.append(new ALOAD(stack))); il.append(new CHECKCAST(cp.addClass(NUMBER_OBJECT))); il.append( factory.createInvoke( Number.class.getName(), "intValue", Type.INT, new Type[] {}, INVOKEVIRTUAL)); return il.append(new IRETURN()); } } throw new java.lang.InternalError(returnType.toString()); } private static Instruction newWrapper(Type type, ConstantPoolGen cp) { if (type instanceof BasicType) { if (type.equals(Type.BOOLEAN)) { return new NEW(cp.addClass(BOOLEAN_OBJECT)); } else if (type.equals(Type.INT)) { return new NEW(cp.addClass(INTEGER_OBJECT)); } else if (type.equals(Type.CHAR)) { return new NEW(cp.addClass(CHARACTER_OBJECT)); } else if (type.equals(Type.BYTE)) { return new NEW(cp.addClass(BYTE_OBJECT)); } else if (type.equals(Type.SHORT)) { return new NEW(cp.addClass(SHORT_OBJECT)); } else if (type.equals(Type.LONG)) { return new NEW(cp.addClass(LONG_OBJECT)); } else if (type.equals(Type.DOUBLE)) { return new NEW(cp.addClass(DOUBLE_OBJECT)); } else if (type.equals(Type.FLOAT)) { return new NEW(cp.addClass(FLOAT_OBJECT)); } } return null; } private static Instruction initWrapper(Type type, ConstantPoolGen cp) { if (type instanceof BasicType) { if (type.equals(Type.BOOLEAN)) { return new INVOKESPECIAL( cp.addMethodref(Boolean.class.getName(), CONSTRUCTOR_NAME, "(Z)V")); } else if (type.equals(Type.INT)) { return new INVOKESPECIAL( cp.addMethodref(Integer.class.getName(), CONSTRUCTOR_NAME, "(I)V")); } else if (type.equals(Type.CHAR)) { return new INVOKESPECIAL( cp.addMethodref(Character.class.getName(), CONSTRUCTOR_NAME, "(C)V")); } else if (type.equals(Type.BYTE)) { return new INVOKESPECIAL( cp.addMethodref(Byte.class.getName(), CONSTRUCTOR_NAME, "(B)V")); } else if (type.equals(Type.SHORT)) { return new INVOKESPECIAL( cp.addMethodref(Short.class.getName(), CONSTRUCTOR_NAME, "(S)V")); } else if (type.equals(Type.LONG)) { return new INVOKESPECIAL( cp.addMethodref(Long.class.getName(), CONSTRUCTOR_NAME, "(J)V")); } else if (type.equals(Type.DOUBLE)) { return new INVOKESPECIAL( cp.addMethodref(Double.class.getName(), CONSTRUCTOR_NAME, "(D)V")); } else if (type.equals(Type.FLOAT)) { return new INVOKESPECIAL( cp.addMethodref(Float.class.getName(), CONSTRUCTOR_NAME, "(F)V")); } } throw new InternalError(type.toString()); } private static int loadArg(InstructionList il, Type t, int index, int pos) { if (t instanceof BasicType) { if (t.equals(Type.LONG)) { il.append(new LLOAD(pos)); pos += 2; return pos; } else if (t.equals(Type.DOUBLE)) { il.append(new DLOAD(pos)); pos += 2; return pos; } else if (t.equals(Type.FLOAT)) { il.append(new FLOAD(pos)); return ++pos; } else { il.append(new ILOAD(pos)); return ++pos; } } else { il.append(new ALOAD(pos)); return ++pos; } } private static Type[] toType(Class cls[]) { Type tp[] = new Type[cls.length]; for (int i = 0; i < cls.length; i++) { tp[i] = toType(cls[i]); } return tp; } private static Type toType(Class cls) { if (cls.equals(void.class)) { return Type.VOID; } if (cls.isPrimitive()) { if (int.class.equals(cls)) { return Type.INT; } else if (char.class.equals(cls)) { return Type.CHAR; } else if (short.class.equals(cls)) { return Type.SHORT; } else if (byte.class.equals(cls)) { return Type.BYTE; } else if (long.class.equals(cls)) { return Type.LONG; } else if (float.class.equals(cls)) { return Type.FLOAT; } else if (double.class.equals(cls)) { return Type.DOUBLE; } else if (boolean.class.equals(cls)) { return Type.BOOLEAN; } } else if (cls.isArray()) { return new ArrayType( toType(cls.getComponentType()),cls.getName().lastIndexOf('[') + 1); } else return new ObjectType(cls.getName()); throw new java.lang.InternalError(cls.getName()); } private static void invokeSuper(ClassGen cg, MethodGen mg, Type args[]) { ConstantPoolGen cp = cg.getConstantPool(); InstructionList il = mg.getInstructionList(); int pos = 1; il.append(new ALOAD(0)); //this for (int i = 0; i < args.length; i++) { //load args to stack pos = loadArg(il, args[i], i, pos); } il.append( new INVOKESPECIAL( cp.addMethodref(cg.getSuperclassName(), mg.getName(), mg.getSignature()))); } private static void invokeStatic( String className, ClassGen cg, MethodGen mg, Type args[]) { ConstantPoolGen cp = cg.getConstantPool(); InstructionList il = mg.getInstructionList(); int pos = 1; for (int i = 0; i < args.length; i++) { //load args to stack pos = loadArg(il, args[i], i, pos); } il.append( new INVOKESTATIC( cp.addMethodref(className, mg.getName(), mg.getSignature()))); } private static MethodGen toMethodGen( java.lang.reflect.Method mtd, String className, InstructionList il, ConstantPoolGen cp) { MethodGen mg = new MethodGen( ACC_FINAL | ( mtd.getModifiers() & ~ACC_ABSTRACT & ~ACC_NATIVE & ~ACC_SYNCHRONIZED ), toType(mtd.getReturnType()), toType(mtd.getParameterTypes()), null, mtd.getName(), className, il, cp); Class [] exeptions = mtd.getExceptionTypes(); for( int i = 0 ; i< exeptions.length; i++ ){ mg.addException( exeptions[i].getName() ); } return mg; } private static Method generateMethod( java.lang.reflect.Method method, String fieldName, ClassGen cg, int after, int invokeSuper) { InstructionList il = new InstructionList(); InstructionFactory factory = new InstructionFactory(cg); ConstantPoolGen cp = cg.getConstantPool(); MethodGen mg = toMethodGen(method, cg.getClassName(), il, cp); Type types[] = mg.getArgumentTypes(); int argCount = types.length; addMethodField(fieldName, cg); boolean returnsValue = !mg.getReturnType().equals(Type.VOID); boolean abstractM = java.lang.reflect.Modifier.isAbstract(method.getModifiers()); InstructionHandle ehEnd = null; GOTO gotoHandled = null; IFEQ ifInvoke = null; InstructionHandle condition = null; InstructionHandle ehHandled = null; InstructionHandle ehStart = null; InstructionHandle start = il.getStart(); //GENERATE ARG ARRAY //generates: /* Object args[]= new Object[]{ arg1, new Integer(arg2) }; */ int loaded = createArgArray(il, factory, cp, mg.getArgumentTypes()); int argArray = loaded; il.append(new ASTORE(argArray)); //DEFINE LOCAL VARIABLES il.append(new ACONST_NULL()); int resultFromSuper = ++loaded; il.append(new ASTORE(resultFromSuper)); il.append(new ICONST(0)); int superInvoked = ++loaded; il.append(new ISTORE(superInvoked)); il.append(new ACONST_NULL()); int error = ++loaded; il.append(new ASTORE(error)); if (!abstractM) { il.append(new ALOAD(0)); //this.handler il.append( factory.createFieldAccess( cg.getClassName(), FIELD_NAME, new ObjectType(INTERCEPTOR_CLASS_NAME), GETFIELD)); //GENERATE INVOKE SUPER il.append(new ALOAD(0)); //this il.append(factory.createGetStatic(cg.getClassName(), fieldName, METHOD_OBJECT)); il.append(new ALOAD(argArray)); il.append(new INVOKEINTERFACE(invokeSuper, 4)); //test returned true ifInvoke = new IFEQ(null); condition = il.append(ifInvoke); il.append(new ICONST(1)); ehStart = il.append(new ISTORE(superInvoked)); // Ivoked = true Instruction wrapper = newWrapper(mg.getReturnType(), cp); if (wrapper != null) { ehStart = il.append(wrapper); il.append(new DUP()); } invokeSuper(cg, mg, types); if (wrapper != null) { il.append(initWrapper(mg.getReturnType(), cp)); } if (returnsValue) { ehEnd = il.append(new ASTORE(resultFromSuper)); } gotoHandled = new GOTO(null); if (!returnsValue) { ehEnd = il.append(gotoHandled); } else { il.append(gotoHandled); } ehHandled = il.append(new ASTORE(error)); } InstructionHandle endif = il.append(new ALOAD(0)); //this.handler if (!abstractM) { ifInvoke.setTarget(endif); gotoHandled.setTarget(endif); } il.append( factory.createFieldAccess( cg.getClassName(), FIELD_NAME, new ObjectType(INTERCEPTOR_CLASS_NAME), GETFIELD)); // INVOKE AFTER RETURN il.append(new ALOAD(0)); //this il.append(factory.createGetStatic(cg.getClassName(), fieldName, METHOD_OBJECT)); il.append(new ALOAD(argArray)); il.append(new ILOAD(superInvoked)); il.append(new ALOAD(resultFromSuper)); il.append(new ALOAD(error)); il.append(new INVOKEINTERFACE(after, 7)); //GENERATE RETURN VALUE //generates : /* if( result == null ){ return 0; } else { return ((Number)result).intValue(); } */ InstructionHandle exitMethod = generateReturnValue(il, factory, cp, mg.getReturnType(), ++loaded); if (!abstractM) { mg.addExceptionHandler(ehStart, ehEnd, ehHandled, Type.THROWABLE); } //Exception handlers: /* }catch( RuntimeException re ){ throw re; } */ ehHandled = il.append( new ASTORE( ++loaded ) ); ehEnd = ehHandled; ehStart = il.getStart(); il.append( new ALOAD(loaded) ); il.append( new ATHROW() ); mg.addExceptionHandler(ehStart, ehEnd, ehHandled, new ObjectType(RuntimeException.class.getName()) ); //Error : ehHandled = il.append( new ASTORE( ++loaded ) ); il.append( new ALOAD(loaded) ); il.append( new ATHROW() ); mg.addExceptionHandler(ehStart, ehEnd, ehHandled, new ObjectType(Error.class.getName()) ); Class exeptions[] = method.getExceptionTypes(); for( int i = 0; i < exeptions.length; i++ ){ // generates : /* }catch( DeclaredException re ){ throw re; } */ ehHandled = il.append( new ASTORE( ++loaded ) ); il.append( new ALOAD(loaded) ); il.append( new ATHROW() ); mg.addExceptionHandler(ehStart, ehEnd, ehHandled, new ObjectType(exeptions[i].getName()) ); } //generates : /* }catch( Exception e){ throw new java.lang.reflect.UndeclaredThrowableException(e); }*/ ehHandled = il.append( new ASTORE( ++loaded ) ); il.append( new NEW( cp.addClass("java.lang.reflect.UndeclaredThrowableException") ) ); il.append( new DUP() ); il.append( new ALOAD(loaded ) ); il.append( new INVOKESPECIAL( cp.addMethodref("java.lang.reflect.UndeclaredThrowableException", "<init>","(Ljava/lang/Throwable;)V") ) ); il.append( new ATHROW() ); mg.addExceptionHandler(ehStart, ehEnd, ehHandled, new ObjectType(Throwable.class.getName()) ); mg.setMaxStack(); mg.setMaxLocals(); Method result = getMethod(mg); return result; } private static void loadClass(InstructionList il, ClassGen cg, ConstantPoolGen cp,Class cls ){ Instruction instruction = null; String cln = "Ljava/lang/Class;"; String t = "TYPE"; if(cls == int.class){ instruction = new GETSTATIC( cp.addFieldref(Integer.class.getName(), t, cln )); } if(cls == byte.class){ instruction = new GETSTATIC( cp.addFieldref(Byte.class.getName(), t, cln )); } if(cls == char.class){ instruction = new GETSTATIC( cp.addFieldref(Character.class.getName(), t, cln )); } if( cls == short.class){ instruction = new GETSTATIC( cp.addFieldref(Short.class.getName(), t, cln )); } if( cls == boolean.class){ instruction = new GETSTATIC( cp.addFieldref( Boolean.class.getName(), t, cln) ); } if( cls == long.class){ instruction = new GETSTATIC( cp.addFieldref( Long.class.getName(), t, cln) ); } if( cls == float.class ){ instruction = new GETSTATIC( cp.addFieldref( Float.class.getName(), t, cln) ); } if( cls == double.class ){ instruction = new GETSTATIC( cp.addFieldref( Double.class.getName(), t, cln )); } if( instruction != null ){ il.append(instruction); }else{ il.append( new LDC( cp.addString( cls.getName()) ) ); il.append( new INVOKESTATIC( cp.addMethodref( cg.getClassName(), "findClass","(Ljava/lang/String;)Ljava/lang/Class;") ) ) ; } } private static void generateClInit(ClassGen cg, ConstantPoolGen cp, java.util.HashMap methods){ //generates : /* static{ Class [] args; Class cls = findClass("java.lang.Object"); args = new Class[0]; METHOD_1 = cls.getDeclaredMethod("toString", args ); ............. } */ InstructionList il = new InstructionList(); MethodGen cinit = new MethodGen( ACC_STATIC , // access flags Type.VOID, // return type new Type[] { }, null, // arg names "<clinit>", cg.getClassName(), il, cp ); MethodGen findClass = generateFindClass( cg, cp ); for( java.util.Iterator i = methods.keySet().iterator(); i.hasNext(); ){ String fieldName = (String)i.next(); java.lang.reflect.Method method = (java.lang.reflect.Method)methods.get( fieldName ); Class[] args = method.getParameterTypes(); String declaring = method.getDeclaringClass().getName(); il.append( new LDC( cp.addString(declaring) )); il.append( new INVOKESTATIC( cp.addMethodref( findClass ) ) ); il.append( new ASTORE(1) ); il.append( new ICONST( args.length ) ); il.append( new ANEWARRAY( cp.addClass( CLASS_OBJECT ) ) ); for( int j = 0; j < args.length; j++ ){ il.append( new DUP() ); il.append( new ICONST(j) ); loadClass( il, cg, cp, args[j] ); il.append( new AASTORE() ); } il.append( new ASTORE(0) ); il.append( new ALOAD(1) ); il.append( new LDC( cp.addString(method.getName() ) ) ); il.append( new ALOAD(0) ); il.append( new INVOKEVIRTUAL( cp.addMethodref("java.lang.Class","getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;") ) ); il.append( new PUTSTATIC( cp.addFieldref( cg.getClassName(), fieldName, "Ljava/lang/reflect/Method;" ) ) ); } il.append( new RETURN() ); cg.addMethod( getMethod( cinit ) ); } private static MethodGen generateFindClass( ClassGen cg, ConstantPoolGen cp ){ // generates: /* static private Class findClass(String name ) throws Exception{ try{ return Class.forName(name); }catch( java.lang.ClassNotFoundException cne ){ throw new java.lang.NoClassDefFoundError( cne.getMessage() ); } } */ InstructionList il = new InstructionList(); MethodGen findClass = new MethodGen( ACC_PRIVATE | ACC_STATIC , // access flags CLASS_OBJECT, // return type new Type[] { Type.STRING }, null, // arg names "findClass", cg.getClassName(), il, cp); InstructionHandle start = il.append( new ALOAD(0)); il.append( new INVOKESTATIC( cp.addMethodref("java.lang.Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;" ) ) ); InstructionHandle h1 = il.append( new ARETURN() ); InstructionHandle h2 = il.append( new ASTORE(1) ); il.append( new NEW(cp.addClass("java.lang.NoClassDefFoundError") ) ); il.append( new DUP() ); il.append( new ALOAD(1) ); il.append( new INVOKEVIRTUAL( cp.addMethodref("java.lang.ClassNotFoundException", "getMessage","()Ljava/lang/String;") ) ); il.append( new INVOKESPECIAL( cp.addMethodref("java.lang.NoClassDefFoundError", CONSTRUCTOR_NAME, "(Ljava/lang/String;)V" )) ); il.append( new ATHROW() ); findClass.addExceptionHandler( start, h1, h2, new ObjectType("java.lang.ClassNotFoundException") ); cg.addMethod( getMethod( findClass ) ); return findClass; } static public class InternalReplace implements java.io.Serializable{ private String parentClassName; private String [] interfaceNameList; private MethodInterceptor mi; public InternalReplace(){ } private InternalReplace( String parentClassName, String [] interfaceList, MethodInterceptor mi ){ this.parentClassName = parentClassName; this.interfaceNameList = interfaceNameList; this.mi = mi; } static public Object writeReplace( Object enhanced ) throws ObjectStreamException{ MethodInterceptor mi = Enhancer.getMethodInterceptor( enhanced ); String parentClassName = enhanced.getClass().getSuperclass().getName(); Class interfaces[] = enhanced.getClass().getInterfaces(); String [] interfaceNameList = new String[ interfaces.length ]; for( int i = 0 ; i < interfaces.length; i++ ) { interfaceNameList[i] = interfaces[i].getName(); } return new InternalReplace( parentClassName, interfaceNameList, mi ); } Object readResolve() throws ObjectStreamException{ try{ ClassLoader loader = this.getClass().getClassLoader(); Class parent = loader.loadClass(parentClassName); Class interfaceList[] = null; if( interfaceNameList != null ){ interfaceList = new Class[interfaceNameList.length]; for( int i = 0; i< interfaceNameList.length; i++ ){ interfaceList[i] = loader.loadClass( interfaceNameList[i] ); } } return Enhancer.enhance( parent, interfaceList, mi, loader ); }catch( Throwable t ){ throw new ObjectStreamException(t.getMessage()){}; } } } static class MethodWrapper { java.lang.reflect.Method method; MethodWrapper(java.lang.reflect.Method method) { if (method == null) { throw new NullPointerException(); } this.method = method; } public boolean equals(Object obj) { if (obj == null || !(obj instanceof MethodWrapper)) { return false; } return Enhancer.equals(method, ((MethodWrapper) obj).method ); } public int hashCode() { return method.getName().hashCode(); } } private static boolean equals( java.lang.reflect.Method m1, java.lang.reflect.Method m2) { if (m1 == m2) { return true; } if (m1.getName().equals(m2.getName())) { Class[] params1 = m1.getParameterTypes(); Class[] params2 = m2.getParameterTypes(); if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { if (!params1[i].getName().equals( params2[i].getName() ) ) { return false; } } if(!m1.getReturnType().getName(). equals(m2.getReturnType().getName()) ){ throw new java.lang.IllegalStateException( "Can't implement:\n" + m1.getDeclaringClass().getName() + "\n and\n" + m2.getDeclaringClass().getName() + "\n"+ m1.toString() + "\n" + m2.toString()); } return true; } } return false; } }
package lispy; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class Compiler { public static String jsNamespace = "lispy"; public static String prelude(String namespace) { StringBuilder builder = new StringBuilder(); builder.append(jsNamespace + "={"); builder.append("'=' : function(a,b){ return a == b; },"); builder.append("'+' : function(a,b){ return a + b; },"); builder.append("'-' : function(a,b){ return a - b; },"); builder.append("'*' : function(a,b){ return a * b; },"); builder.append("'/' : function(a,b){ return a / b; },"); builder.append("'<' : function(a,b){ return (a < b); },"); builder.append("'<=': function(a,b){ return (a <= b); },"); builder.append("'>=': function(a,b){ return (a >= b); },"); builder.append("'>' : function(a,b){ return (a > b); },"); // TODO add the rest of the built-in functions builder.append("'display': function(s){ if (console){ console.log(s); }; return null; }"); builder.append("};"); return builder.toString(); }; // Produce nested Javascript objects to simulate a namespace for the given name public static String getNamespaceDefinition(String namespace) { if (namespace.contains(".")) { String[] components = namespace.split("\\."); String result = components[0] + "={"; for (int i = 1; i < components.length; i++) { result += components[i] + ":{"; } for (int i = 1; i < components.length; i++) { result += "}"; } result += "};"; return result; } else { return String.format("%s ||= {};", namespace); } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java lispy.Compiler path/to/file.scm\nOutputs 'file.js' in the current directory."); return; } String sourceFile = args[0]; String namespace = sourceFile.substring(0, sourceFile.lastIndexOf(".")); if (namespace.contains("/")) { namespace = namespace.substring(1 + namespace.lastIndexOf("/")); } Compiler.jsNamespace = namespace; String targetFile = String.format("%s.js", namespace); System.out.println(String.format("Output: %s", targetFile)); BufferedReader reader = new BufferedReader(new FileReader(sourceFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, false)); writer.write(getNamespaceDefinition(namespace) + "\n"); writer.write(prelude(namespace) + "\n"); String line; Environment env = Environment.getGlobalEnvironment(); while ((line = reader.readLine()) != null) { String output = Eval.emit(line, env); writer.write(output + "\n"); } reader.close(); writer.flush(); writer.close(); } }
package dr.app.tools; import dr.app.beast.BeastVersion; import dr.app.util.Arguments; import dr.evolution.io.Importer; import dr.evolution.io.NexusImporter; import dr.evolution.io.TreeImporter; import dr.evolution.tree.MutableTree; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.Taxon; import dr.util.Version; import jam.console.ConsoleApplication; import javax.swing.*; import java.io.*; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Andrew Rambaut * @author Alexei Drummond * @version $Id:$ */ public class LogCombiner { private final static Version version = new BeastVersion(); public LogCombiner(int[] burnins, int resample, String[] inputFileNames, String outputFileName, boolean treeFiles, boolean convertToDecimal, boolean renumberOutput, boolean useScale, double scale) throws IOException { System.out.println("Creating combined " + (treeFiles ? "tree" : "log") + " file: '" + outputFileName); System.out.println(); PrintWriter writer = new PrintWriter(new FileOutputStream(outputFileName)); boolean firstFile = true; boolean firstTree = true; long stateCount = (renumberOutput ? -1 : 0); int stateStep = -1; int columnCount = 0; String[] titles = null; System.out.println(); for (int i = 0; i < inputFileNames.length; i++) { File inputFile = new File(inputFileNames[i]); if (!inputFile.exists()) { System.err.println(inputFileNames[i] + " does not exist!"); return; } else if (inputFile.isDirectory()) { System.err.println(inputFileNames[i] + " is a directory."); return; } int burnin = burnins[0]; if (burnins.length > i) { burnin = burnins[i]; } if (burnin > 0) { System.out.print("Combining file: '" + inputFileNames[i] + "' removing burnin: " + burnin); } else { System.out.print("Combining file: '" + inputFileNames[i] + "' without removing burnin"); } if (resample > 0) { System.out.print(", resampling with frequency: " + resample); } if (useScale) { System.out.println(", rescaling by: " + scale); } else { System.out.println(); } if (treeFiles) { TreeImporter importer = new NexusImporter(new FileReader(inputFile)); try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (firstTree) { startLog(tree, writer); firstTree = false; } String name = tree.getId(); // split on underscore in STATE_xxxx String[] bits = name.split("_"); int state = Integer.parseInt(bits[1]); if (stateStep < 0 && state > 0) { stateStep = state; } if (state >= burnin * (stateStep>0?stateStep : 1)) { if (stateStep > 0) { if (!renumberOutput) { stateCount += stateStep; } else { stateCount += 1; } } if (resample < 0) { if (resample % stateStep != 0) { System.err.println("ERROR: Resampling frequency is not a multiple of existing sampling frequency"); return; } if (useScale) { rescaleTree(tree, scale); } writeTree(stateCount, tree, convertToDecimal, writer); } } } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } } else { BufferedReader reader = new BufferedReader(new FileReader(inputFile)); //int lineCount = 1; String line = reader.readLine(); // lines starting with [ are ignored, assuming comments in MrBayes file // lines starting with # are ignored, assuming comments in Migrate or BEAST file while (line.startsWith("[") || line.startsWith(" line = reader.readLine(); } if (firstFile) { titles = line.split("\t"); writer.println(line); } else { String[] newTitles = line.split("\t"); if (newTitles.length != titles.length) { System.err.println("ERROR: The number of columns in file, " + inputFileNames[i] + ", does not match that of the first file"); return; } for (int k = 0; k < newTitles.length; k++) { if (!newTitles[k].equals(titles[k])) { System.err.println("WARNING: The column heading, " + newTitles[k] + " in file, " + inputFileNames[i] + ", does not match the first file's heading, " + titles[k]); } } } line = reader.readLine(); //lineCount++; while (line != null) { String[] parts = line.split("\\s"); int state = -1; boolean skip = false; try { state = Integer.parseInt(parts[0]); } catch (NumberFormatException nfe) { skip = true; } if (!skip) { if (stateStep < 0 && state > 0) { stateStep = state; columnCount = parts.length; } // if the columnCount is not the same then perhaps the line is corrupt so skip it. if (state >= burnin && parts.length == columnCount) { for (int j = 1; j < parts.length; j++) { try { // attempt to convert the column value... double value = Double.valueOf(parts[j]); } catch (NumberFormatException nfe) { skip = true; break; } } if (!skip) { if (stateStep > 0) { if (!renumberOutput) { stateCount += stateStep; } else { stateCount += 1; } } if (resample < 0) { if (resample % stateStep != 0) { System.err.println("ERROR: Resampling frequency is not a multiple of existing sampling frequency"); return; } writer.print(stateCount); for (int j = 1; j < parts.length; j++) { String value = parts[j]; if (useScale) { if (titles[j].equals("clock.rate") || titles[j].startsWith("skyline.popSize")) { value = reformatNumbers(value, convertToDecimal, true, 1.0 / scale); } else if (titles[j].equals("treeModel.rootHeight")) { value = reformatNumbers(value, convertToDecimal, true, scale); } } else if (convertToDecimal) { value = reformatNumbers(value, convertToDecimal, false, 1.0); } writer.print("\t" + value); } writer.println(); } } } } line = reader.readLine(); //lineCount++; } } firstFile = false; } if (treeFiles) { stopLog(writer); } writer.close(); } private void rescaleTree(Tree tree, double scale) { if (tree instanceof MutableTree) { MutableTree mutableTree = (MutableTree) tree; for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); if (node != tree.getRoot()) { double length = tree.getBranchLength(node); mutableTree.setBranchLength(node, length * scale); } } } else { throw new IllegalArgumentException("Tree not mutable"); } } private final Map<String, Integer> taxonMap = new HashMap<String, Integer>(); private void startLog(Tree tree, PrintWriter writer) { int taxonCount = tree.getTaxonCount(); writer.println("#NEXUS"); writer.println(""); writer.println("Begin taxa;"); writer.println("\tDimensions ntax=" + taxonCount + ";"); writer.println("\tTaxlabels"); for (int i = 0; i < taxonCount; i++) { String id = tree.getTaxon(i).getId(); if (id.matches(NexusExporter.SPECIAL_CHARACTERS_REGEX)) { id = "'" + id + "'"; } writer.println("\t\t" + id); } writer.println("\t\t;"); writer.println("End;"); writer.println(""); writer.println("Begin trees;"); // This is needed if the trees use numerical taxon labels writer.println("\tTranslate"); for (int i = 0; i < taxonCount; i++) { int k = i + 1; Taxon taxon = tree.getTaxon(i); taxonMap.put(taxon.getId(), k); String id = taxon.getId(); if (id.matches(NexusExporter.SPECIAL_CHARACTERS_REGEX)) { id = "'" + id + "'"; } writer.println("\t\t" + k + " " + id + (k < taxonCount ? "," : "")); } writer.println("\t\t;"); } private void writeTree(long state, Tree tree, boolean convertToDecimal, PrintWriter writer) { StringBuffer buffer = new StringBuffer("tree STATE_"); buffer.append(state); // Double lnP = (Double) tree.getAttribute("lnP"); // if (lnP != null) { // buffer.append(" [&lnP=").append(lnP).append("]"); boolean hasAttribute = false; Iterator iter = tree.getAttributeNames(); while (iter != null && iter.hasNext()) { String name = (String) iter.next(); Object value = tree.getAttribute(name); if (!hasAttribute) { buffer.append(" [&"); hasAttribute = true; } else { buffer.append(","); } buffer.append(name).append("=").append(formatValue(value)); } if (hasAttribute) { buffer.append("]"); } buffer.append(" = [&R] "); writeTree(tree, tree.getRoot(), taxonMap, convertToDecimal, buffer); buffer.append(";"); writer.println(buffer.toString()); } private String formatValue(Object value) { if( value instanceof String ) { return (String) value; } else if (value instanceof Object[] ) { String val = "{"; for( Object v : (Object[]) value ) { val += formatValue(v); val += ','; } return val.substring(0, val.length() - 1 ) + '}'; } return value.toString(); } private void writeTree(Tree tree, NodeRef node, Map taxonMap, boolean convertToDecimal, StringBuffer buffer) { NodeRef parent = tree.getParent(node); if (tree.isExternal(node)) { String taxon = tree.getNodeTaxon(node).getId(); Integer taxonNo = (Integer) taxonMap.get(taxon); if (taxonNo == null) { throw new IllegalArgumentException("Taxon, " + taxon + ", not recognized from first tree file"); } buffer.append(taxonNo); } else { buffer.append("("); writeTree(tree, tree.getChild(node, 0), taxonMap, convertToDecimal, buffer); for (int i = 1; i < tree.getChildCount(node); i++) { buffer.append(","); writeTree(tree, tree.getChild(node, i), taxonMap, convertToDecimal, buffer); } buffer.append(")"); } boolean hasAttribute = false; Iterator iter = tree.getNodeAttributeNames(node); while (iter != null && iter.hasNext()) { String name = (String) iter.next(); Object value = tree.getNodeAttribute(node, name); if (!hasAttribute) { buffer.append("[&"); hasAttribute = true; } else { buffer.append(","); } buffer.append(name).append("=").append(formatValue(value)); } if (hasAttribute) { buffer.append("]"); } if (parent != null) { buffer.append(":"); double length = tree.getBranchLength(node); buffer.append(convertToDecimal ? decimalFormatter.format(length) : scientificFormatter.format(length)); } } private void stopLog(PrintWriter writer) { writer.println("End;"); } private static final DecimalFormat decimalFormatter = new DecimalFormat(" private static final DecimalFormat scientificFormatter = new DecimalFormat(" private String reformatNumbers(String line, boolean convertDecimal, boolean useScale, double scale) { StringBuffer outLine = new StringBuffer(); Pattern pattern = Pattern.compile("\\d+\\.\\d+(E[\\-\\d\\.]+)?"); Matcher matcher = pattern.matcher(line); int lastEnd = 0; while (matcher.find()) { int start = matcher.start(); String token = matcher.group(); double value = Double.parseDouble(token); if (useScale) { value *= scale; } String outToken = (convertDecimal ? decimalFormatter.format(value) : scientificFormatter.format(value)); outLine.append(line.substring(lastEnd, start)); outLine.append(outToken); lastEnd = matcher.end(); } outLine.append(line.substring(lastEnd)); return outLine.toString(); } public static void printTitle() { System.out.println(); centreLine("LogCombiner " + version.getVersionString() + ", " + version.getDateString(), 60); centreLine("MCMC Output Combiner", 60); centreLine("by", 60); centreLine("Andrew Rambaut and Alexei J. Drummond", 60); System.out.println(); centreLine("Institute of Evolutionary Biology", 60); centreLine("University of Edinburgh", 60); centreLine("a.rambaut@ed.ac.uk", 60); System.out.println(); centreLine("Department of Computer Science", 60); centreLine("University of Auckland", 60); centreLine("alexei@cs.auckland.ac.nz", 60); System.out.println(); System.out.println(); } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { System.out.print(" "); } System.out.println(line); } public static void printUsage(Arguments arguments) { arguments.printUsage("logcombiner", "<input-file-name1> [<input-file-name2> ...] <output-file-name>"); System.out.println(); System.out.println(" Example: logcombiner test1.log test2.log combined.log"); System.out.println(" Example: logcombiner -burnin 10000 test1.log test2.log combined.log"); System.out.println(); } //Main method public static void main(String[] args) throws IOException { // There is a major issue with languages that use the comma as a decimal separator. // To ensure compatibility between programs in the package, enforce the US locale. Locale.setDefault(Locale.US); boolean treeFiles; boolean convertToDecimal; boolean renumberOutput; int burnin; int resample = -1; double scale = 1.0; boolean useScale = false; if (args.length == 0) { System.setProperty("com.apple.macos.useScreenMenuBar", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); java.net.URL url = LogCombiner.class.getResource("/images/utility.png"); javax.swing.Icon icon = null; if (url != null) { icon = new javax.swing.ImageIcon(url); } final String versionString = version.getVersionString(); String nameString = "LogCombiner " + versionString; String aboutString = "<html><center><p>" + versionString + ", " + version.getDateString() + "</p>" + "<p>by<br>" + "Andrew Rambaut and Alexei J. Drummond</p>" + "<p>Institute of Evolutionary Biology, University of Edinburgh<br>" + "<a href=\"mailto:a.rambaut@ed.ac.uk\">a.rambaut@ed.ac.uk</a></p>" + "<p>Department of Computer Science, University of Auckland<br>" + "<a href=\"mailto:alexei@cs.auckland.ac.nz\">alexei@cs.auckland.ac.nz</a></p>" + "<p>Part of the BEAST package:<br>" + "<a href=\"http: "</center></html>"; ConsoleApplication consoleApp = new ConsoleApplication(nameString, aboutString, icon, true); printTitle(); LogCombinerDialog dialog = new LogCombinerDialog(new JFrame()); if (!dialog.showDialog("LogCombiner " + versionString)) { return; } treeFiles = dialog.isTreeFiles(); convertToDecimal = dialog.convertToDecimal(); renumberOutput = dialog.renumberOutputStates(); if (dialog.isResampling()) { resample = dialog.getResampleFrequency(); } String[] inputFiles = dialog.getFileNames(); int[] burnins = dialog.getBurnins(); String outputFileName = dialog.getOutputFileName(); if (outputFileName == null) { System.err.println("No output file specified"); } try { new LogCombiner(burnins, resample, inputFiles, outputFileName, treeFiles, convertToDecimal, renumberOutput, useScale, scale); } catch (Exception ex) { System.err.println("Exception: " + ex.getMessage()); ex.printStackTrace(); } System.out.println("Finished - Quit program to exit."); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } else { printTitle(); Arguments arguments = new Arguments( new Arguments.Option[]{ new Arguments.Option("trees", "use this option to combine tree log files"), new Arguments.Option("decimal", "this option converts numbers from scientific to decimal notation"), new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"), new Arguments.IntegerOption("resample", "resample the log files to this frequency " + "(the original sampling frequency must be a factor of this value)"), new Arguments.RealOption("scale", "a scaling factor that will multiply any time units by this value"), new Arguments.Option("renumber", "this option renumbers output states consecutively"), new Arguments.Option("help", "option to print this message") }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { System.out.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption("help")) { printUsage(arguments); System.exit(0); } treeFiles = arguments.hasOption("trees"); convertToDecimal = arguments.hasOption("decimal"); renumberOutput = arguments.hasOption("renumber"); burnin = -1; if (arguments.hasOption("burnin")) { burnin = arguments.getIntegerOption("burnin"); } resample = -1; if (arguments.hasOption("resample")) { resample = arguments.getIntegerOption("resample"); } scale = 1.0; useScale = false; if (arguments.hasOption("scale")) { scale = arguments.getRealOption("scale"); useScale = true; } String[] args2 = arguments.getLeftoverArguments(); if (args2.length < 2) { System.err.println("Requires a minimum of 1 input filename and 1 output filename"); System.err.println(); printUsage(arguments); System.exit(1); } String[] inputFileNames = new String[args2.length - 1]; System.arraycopy(args2, 0, inputFileNames, 0, inputFileNames.length); String outputFileName = args2[args2.length - 1]; new LogCombiner(new int[]{burnin}, resample, inputFileNames, outputFileName, treeFiles, convertToDecimal, renumberOutput, useScale, scale); System.out.println("Finished."); } System.exit(0); } }
package cgeo.geocaching; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.connector.gc.Tile; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.LoadFlag; import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.list.AbstractList; import cgeo.geocaching.list.PseudoList; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.search.SearchSuggestionCursor; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.utils.FileUtils; import cgeo.geocaching.utils.Log; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.jdt.annotation.NonNull; import rx.android.observables.AndroidObservable; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.util.async.Async; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Resources; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.MatrixCursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; public class DataStore { private DataStore() { // utility class } public enum StorageLocation { HEAP, CACHE, DATABASE, } private static final Func1<Cursor,String> GET_STRING_0 = new Func1<Cursor, String>() { @Override public String call(final Cursor cursor) { return cursor.getString(0); } }; // Columns and indices for the cache data private static final String QUERY_CACHE_DATA = "SELECT " + "cg_caches.updated," + "cg_caches.reason," + "cg_caches.detailed," + "cg_caches.detailedupdate," + "cg_caches.visiteddate," + "cg_caches.geocode," + "cg_caches.cacheid," + "cg_caches.guid," + "cg_caches.type," + "cg_caches.name," + "cg_caches.owner," + "cg_caches.owner_real," + "cg_caches.hidden," + "cg_caches.hint," + "cg_caches.size," + "cg_caches.difficulty," + "cg_caches.direction," + "cg_caches.distance," + "cg_caches.terrain," + "cg_caches.location," + "cg_caches.personal_note," + "cg_caches.shortdesc," + "cg_caches.favourite_cnt," + "cg_caches.rating," + "cg_caches.votes," + "cg_caches.myvote," + "cg_caches.disabled," + "cg_caches.archived," + "cg_caches.members," + "cg_caches.found," + "cg_caches.favourite," + "cg_caches.inventoryunknown," + "cg_caches.onWatchlist," + "cg_caches.reliable_latlon," + "cg_caches.coordsChanged," + "cg_caches.latitude," + "cg_caches.longitude," + "cg_caches.finalDefined," + "cg_caches._id," + "cg_caches.inventorycoins," + "cg_caches.inventorytags," + "cg_caches.logPasswordRequired"; /** The list of fields needed for mapping. */ private static final String[] WAYPOINT_COLUMNS = new String[] { "_id", "geocode", "updated", "type", "prefix", "lookup", "name", "latitude", "longitude", "note", "own", "visited" }; /** Number of days (as ms) after temporarily saved caches are deleted */ private final static long DAYS_AFTER_CACHE_IS_DELETED = 3 * 24 * 60 * 60 * 1000; /** * holds the column indexes of the cache table to avoid lookups */ private static CacheCache cacheCache = new CacheCache(); private static SQLiteDatabase database = null; private static final int dbVersion = 68; public static final int customListIdOffset = 10; private static final @NonNull String dbName = "data"; private static final @NonNull String dbTableCaches = "cg_caches"; private static final @NonNull String dbTableLists = "cg_lists"; private static final @NonNull String dbTableAttributes = "cg_attributes"; private static final @NonNull String dbTableWaypoints = "cg_waypoints"; private static final @NonNull String dbTableSpoilers = "cg_spoilers"; private static final @NonNull String dbTableLogs = "cg_logs"; private static final @NonNull String dbTableLogCount = "cg_logCount"; private static final @NonNull String dbTableLogImages = "cg_logImages"; private static final @NonNull String dbTableLogsOffline = "cg_logs_offline"; private static final @NonNull String dbTableTrackables = "cg_trackables"; private static final @NonNull String dbTableSearchDestionationHistory = "cg_search_destination_history"; private static final @NonNull String dbCreateCaches = "" + "create table " + dbTableCaches + " (" + "_id integer primary key autoincrement, " + "updated long not null, " + "detailed integer not null default 0, " + "detailedupdate long, " + "visiteddate long, " + "geocode text unique not null, " + "reason integer not null default 0, " // cached, favorite... + "cacheid text, " + "guid text, " + "type text, " + "name text, " + "owner text, " + "owner_real text, " + "hidden long, " + "hint text, " + "size text, " + "difficulty float, " + "terrain float, " + "location text, " + "direction double, " + "distance double, " + "latitude double, " + "longitude double, " + "reliable_latlon integer, " + "personal_note text, " + "shortdesc text, " + "description text, " + "favourite_cnt integer, " + "rating float, " + "votes integer, " + "myvote float, " + "disabled integer not null default 0, " + "archived integer not null default 0, " + "members integer not null default 0, " + "found integer not null default 0, " + "favourite integer not null default 0, " + "inventorycoins integer default 0, " + "inventorytags integer default 0, " + "inventoryunknown integer default 0, " + "onWatchlist integer default 0, " + "coordsChanged integer default 0, " + "finalDefined integer default 0, " + "logPasswordRequired integer default 0" + "); "; private static final String dbCreateLists = "" + "create table " + dbTableLists + " (" + "_id integer primary key autoincrement, " + "title text not null, " + "updated long not null" + "); "; private static final String dbCreateAttributes = "" + "create table " + dbTableAttributes + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "attribute text " + "); "; private static final String dbCreateWaypoints = "" + "create table " + dbTableWaypoints + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type text not null default 'waypoint', " + "prefix text, " + "lookup text, " + "name text, " + "latitude double, " + "longitude double, " + "note text, " + "own integer default 0, " + "visited integer default 0" + "); "; private static final String dbCreateSpoilers = "" + "create table " + dbTableSpoilers + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "url text, " + "title text, " + "description text " + "); "; private static final String dbCreateLogs = "" + "create table " + dbTableLogs + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type integer not null default 4, " + "author text, " + "log text, " + "date long, " + "found integer not null default 0, " + "friend integer " + "); "; private static final String dbCreateLogCount = "" + "create table " + dbTableLogCount + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type integer not null default 4, " + "count integer not null default 0 " + "); "; private static final String dbCreateLogImages = "" + "create table " + dbTableLogImages + " (" + "_id integer primary key autoincrement, " + "log_id integer not null, " + "title text not null, " + "url text not null" + "); "; private static final String dbCreateLogsOffline = "" + "create table " + dbTableLogsOffline + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type integer not null default 4, " + "log text, " + "date long " + "); "; private static final String dbCreateTrackables = "" + "create table " + dbTableTrackables + " (" + "_id integer primary key autoincrement, " + "updated long not null, " // date of save + "tbcode text not null, " + "guid text, " + "title text, " + "owner text, " + "released long, " + "goal text, " + "description text, " + "geocode text " + "); "; private static final String dbCreateSearchDestinationHistory = "" + "create table " + dbTableSearchDestionationHistory + " (" + "_id integer primary key autoincrement, " + "date long not null, " + "latitude double, " + "longitude double " + "); "; private static boolean newlyCreatedDatabase = false; private static boolean databaseCleaned = false; public static void init() { if (database != null) { return; } synchronized(DataStore.class) { if (database != null) { return; } final DbHelper dbHelper = new DbHelper(new DBContext(CgeoApplication.getInstance())); try { database = dbHelper.getWritableDatabase(); } catch (final Exception e) { Log.e("DataStore.init: unable to open database for R/W", e); recreateDatabase(dbHelper); } } } /** * Attempt to recreate the database if opening has failed * * @param dbHelper dbHelper to use to reopen the database */ private static void recreateDatabase(final DbHelper dbHelper) { final File dbPath = databasePath(); final File corruptedPath = new File(LocalStorage.getStorage(), dbPath.getName() + ".corrupted"); if (LocalStorage.copy(dbPath, corruptedPath)) { Log.i("DataStore.init: renamed " + dbPath + " into " + corruptedPath); } else { Log.e("DataStore.init: unable to rename corrupted database"); } try { database = dbHelper.getWritableDatabase(); } catch (final Exception f) { Log.e("DataStore.init: unable to recreate database and open it for R/W", f); } } public static synchronized void closeDb() { if (database == null) { return; } cacheCache.removeAllFromCache(); PreparedStatements.clearPreparedStatements(); database.close(); database = null; } public static File getBackupFileInternal() { return new File(LocalStorage.getStorage(), "cgeo.sqlite"); } public static String backupDatabaseInternal() { if (!LocalStorage.isExternalStorageAvailable()) { Log.w("Database wasn't backed up: no external memory"); return null; } final File target = getBackupFileInternal(); closeDb(); final boolean backupDone = LocalStorage.copy(databasePath(), target); init(); if (!backupDone) { Log.e("Database could not be copied to " + target); return null; } Log.i("Database was copied to " + target); return target.getPath(); } /** * Move the database to/from external cgdata in a new thread, * showing a progress window * * @param fromActivity */ public static void moveDatabase(final Activity fromActivity) { final ProgressDialog dialog = ProgressDialog.show(fromActivity, fromActivity.getString(R.string.init_dbmove_dbmove), fromActivity.getString(R.string.init_dbmove_running), true, false); AndroidObservable.bindActivity(fromActivity, Async.fromCallable(new Func0<Boolean>() { @Override public Boolean call() { if (!LocalStorage.isExternalStorageAvailable()) { Log.w("Database was not moved: external memory not available"); return false; } closeDb(); final File source = databasePath(); final File target = databaseAlternatePath(); if (!LocalStorage.copy(source, target)) { Log.e("Database could not be moved to " + target); init(); return false; } if (!FileUtils.delete(source)) { Log.e("Original database could not be deleted during move"); } Settings.setDbOnSDCard(!Settings.isDbOnSDCard()); Log.i("Database was moved to " + target); init(); return true; } })).subscribeOn(Schedulers.io()).subscribe(new Action1<Boolean>() { @Override public void call(final Boolean success) { dialog.dismiss(); final String message = success ? fromActivity.getString(R.string.init_dbmove_success) : fromActivity.getString(R.string.init_dbmove_failed); Dialogs.message(fromActivity, R.string.init_dbmove_dbmove, message); } }); } private static File databasePath(final boolean internal) { return new File(internal ? LocalStorage.getInternalDbDirectory() : LocalStorage.getExternalDbDirectory(), dbName); } private static File databasePath() { return databasePath(!Settings.isDbOnSDCard()); } private static File databaseAlternatePath() { return databasePath(Settings.isDbOnSDCard()); } public static boolean restoreDatabaseInternal() { if (!LocalStorage.isExternalStorageAvailable()) { Log.w("Database wasn't restored: no external memory"); return false; } final File sourceFile = getBackupFileInternal(); closeDb(); final boolean restoreDone = LocalStorage.copy(sourceFile, databasePath()); init(); if (restoreDone) { Log.i("Database succesfully restored from " + sourceFile.getPath()); } else { Log.e("Could not restore database from " + sourceFile.getPath()); } return restoreDone; } private static class DBContext extends ContextWrapper { public DBContext(final Context base) { super(base); } /** * We override the default open/create as it doesn't work on OS 1.6 and * causes issues on other devices too. */ @Override public SQLiteDatabase openOrCreateDatabase(final String name, final int mode, final CursorFactory factory) { final File file = new File(name); FileUtils.mkdirs(file.getParentFile()); return SQLiteDatabase.openOrCreateDatabase(file, factory); } } private static class DbHelper extends SQLiteOpenHelper { private static boolean firstRun = true; DbHelper(final Context context) { super(context, databasePath().getPath(), null, dbVersion); } @Override public void onCreate(final SQLiteDatabase db) { newlyCreatedDatabase = true; db.execSQL(dbCreateCaches); db.execSQL(dbCreateLists); db.execSQL(dbCreateAttributes); db.execSQL(dbCreateWaypoints); db.execSQL(dbCreateSpoilers); db.execSQL(dbCreateLogs); db.execSQL(dbCreateLogCount); db.execSQL(dbCreateLogImages); db.execSQL(dbCreateLogsOffline); db.execSQL(dbCreateTrackables); db.execSQL(dbCreateSearchDestinationHistory); createIndices(db); } static private void createIndices(final SQLiteDatabase db) { db.execSQL("create index if not exists in_caches_geo on " + dbTableCaches + " (geocode)"); db.execSQL("create index if not exists in_caches_guid on " + dbTableCaches + " (guid)"); db.execSQL("create index if not exists in_caches_lat on " + dbTableCaches + " (latitude)"); db.execSQL("create index if not exists in_caches_lon on " + dbTableCaches + " (longitude)"); db.execSQL("create index if not exists in_caches_reason on " + dbTableCaches + " (reason)"); db.execSQL("create index if not exists in_caches_detailed on " + dbTableCaches + " (detailed)"); db.execSQL("create index if not exists in_caches_type on " + dbTableCaches + " (type)"); db.execSQL("create index if not exists in_caches_visit_detail on " + dbTableCaches + " (visiteddate, detailedupdate)"); db.execSQL("create index if not exists in_attr_geo on " + dbTableAttributes + " (geocode)"); db.execSQL("create index if not exists in_wpts_geo on " + dbTableWaypoints + " (geocode)"); db.execSQL("create index if not exists in_wpts_geo_type on " + dbTableWaypoints + " (geocode, type)"); db.execSQL("create index if not exists in_spoil_geo on " + dbTableSpoilers + " (geocode)"); db.execSQL("create index if not exists in_logs_geo on " + dbTableLogs + " (geocode)"); db.execSQL("create index if not exists in_logcount_geo on " + dbTableLogCount + " (geocode)"); db.execSQL("create index if not exists in_logsoff_geo on " + dbTableLogsOffline + " (geocode)"); db.execSQL("create index if not exists in_trck_geo on " + dbTableTrackables + " (geocode)"); } @Override public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start"); try { if (db.isReadOnly()) { return; } db.beginTransaction(); if (oldVersion <= 0) { // new table dropDatabase(db); onCreate(db); Log.i("Database structure created."); } if (oldVersion > 0) { db.execSQL("delete from " + dbTableCaches + " where reason = 0"); if (oldVersion < 52) { // upgrade to 52 try { db.execSQL(dbCreateSearchDestinationHistory); Log.i("Added table " + dbTableSearchDestionationHistory + "."); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 52", e); } } if (oldVersion < 53) { // upgrade to 53 try { db.execSQL("alter table " + dbTableCaches + " add column onWatchlist integer"); Log.i("Column onWatchlist added to " + dbTableCaches + "."); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 53", e); } } if (oldVersion < 54) { // update to 54 try { db.execSQL(dbCreateLogImages); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 54", e); } } if (oldVersion < 55) { // update to 55 try { db.execSQL("alter table " + dbTableCaches + " add column personal_note text"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 55", e); } } // make all internal attribute names lowercase // @see issue #299 if (oldVersion < 56) { // update to 56 try { db.execSQL("update " + dbTableAttributes + " set attribute = " + "lower(attribute) where attribute like \"%_yes\" " + "or attribute like \"%_no\""); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 56", e); } } // Create missing indices. See issue #435 if (oldVersion < 57) { // update to 57 try { db.execSQL("drop index in_a"); db.execSQL("drop index in_b"); db.execSQL("drop index in_c"); db.execSQL("drop index in_d"); db.execSQL("drop index in_e"); db.execSQL("drop index in_f"); createIndices(db); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 57", e); } } if (oldVersion < 58) { // upgrade to 58 try { db.beginTransaction(); final String dbTableCachesTemp = dbTableCaches + "_temp"; final String dbCreateCachesTemp = "" + "create table " + dbTableCachesTemp + " (" + "_id integer primary key autoincrement, " + "updated long not null, " + "detailed integer not null default 0, " + "detailedupdate long, " + "visiteddate long, " + "geocode text unique not null, " + "reason integer not null default 0, " + "cacheid text, " + "guid text, " + "type text, " + "name text, " + "own integer not null default 0, " + "owner text, " + "owner_real text, " + "hidden long, " + "hint text, " + "size text, " + "difficulty float, " + "terrain float, " + "location text, " + "direction double, " + "distance double, " + "latitude double, " + "longitude double, " + "reliable_latlon integer, " + "personal_note text, " + "shortdesc text, " + "description text, " + "favourite_cnt integer, " + "rating float, " + "votes integer, " + "myvote float, " + "disabled integer not null default 0, " + "archived integer not null default 0, " + "members integer not null default 0, " + "found integer not null default 0, " + "favourite integer not null default 0, " + "inventorycoins integer default 0, " + "inventorytags integer default 0, " + "inventoryunknown integer default 0, " + "onWatchlist integer default 0 " + "); "; db.execSQL(dbCreateCachesTemp); db.execSQL("insert into " + dbTableCachesTemp + " select _id,updated,detailed,detailedupdate,visiteddate,geocode,reason,cacheid,guid,type,name,own,owner,owner_real," + "hidden,hint,size,difficulty,terrain,location,direction,distance,latitude,longitude, 0," + "personal_note,shortdesc,description,favourite_cnt,rating,votes,myvote,disabled,archived,members,found,favourite,inventorycoins," + "inventorytags,inventoryunknown,onWatchlist from " + dbTableCaches); db.execSQL("drop table " + dbTableCaches); db.execSQL("alter table " + dbTableCachesTemp + " rename to " + dbTableCaches); final String dbTableWaypointsTemp = dbTableWaypoints + "_temp"; final String dbCreateWaypointsTemp = "" + "create table " + dbTableWaypointsTemp + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type text not null default 'waypoint', " + "prefix text, " + "lookup text, " + "name text, " + "latitude double, " + "longitude double, " + "note text " + "); "; db.execSQL(dbCreateWaypointsTemp); db.execSQL("insert into " + dbTableWaypointsTemp + " select _id, geocode, updated, type, prefix, lookup, name, latitude, longitude, note from " + dbTableWaypoints); db.execSQL("drop table " + dbTableWaypoints); db.execSQL("alter table " + dbTableWaypointsTemp + " rename to " + dbTableWaypoints); createIndices(db); db.setTransactionSuccessful(); Log.i("Removed latitude_string and longitude_string columns"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 58", e); } finally { db.endTransaction(); } } if (oldVersion < 59) { try { // Add new indices and remove obsolete cache files createIndices(db); removeObsoleteCacheDirectories(db); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 59", e); } } if (oldVersion < 60) { try { removeSecEmptyDirs(); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 60", e); } } if (oldVersion < 61) { try { db.execSQL("alter table " + dbTableLogs + " add column friend integer"); db.execSQL("alter table " + dbTableCaches + " add column coordsChanged integer default 0"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 61", e); } } // Introduces finalDefined on caches and own on waypoints if (oldVersion < 62) { try { db.execSQL("alter table " + dbTableCaches + " add column finalDefined integer default 0"); db.execSQL("alter table " + dbTableWaypoints + " add column own integer default 0"); db.execSQL("update " + dbTableWaypoints + " set own = 1 where type = 'own'"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 62", e); } } if (oldVersion < 63) { try { removeDoubleUnderscoreMapFiles(); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 63", e); } } if (oldVersion < 64) { try { // No cache should ever be stored into the ALL_CACHES list. Here we use hardcoded list ids // rather than symbolic ones because the fix must be applied with the values at the time // of the problem. The problem was introduced in release 2012.06.01. db.execSQL("update " + dbTableCaches + " set reason=1 where reason=2"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 64", e); } } if (oldVersion < 65) { try { // Set all waypoints where name is Original coordinates to type ORIGINAL db.execSQL("update " + dbTableWaypoints + " set type='original', own=0 where name='Original Coordinates'"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 65:", e); } } // Introduces visited feature on waypoints if (oldVersion < 66) { try { db.execSQL("alter table " + dbTableWaypoints + " add column visited integer default 0"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 66", e); } } // issue2662 OC: Leichtes Klettern / Easy climbing if (oldVersion < 67) { try { db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_yes' where geocode like 'OC%' and attribute = 'climbing_yes'"); db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_no' where geocode like 'OC%' and attribute = 'climbing_no'"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 67", e); } } // Introduces logPasswordRequired on caches if (oldVersion < 68) { try { db.execSQL("alter table " + dbTableCaches + " add column logPasswordRequired integer default 0"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 68", e); } } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": completed"); } @Override public void onOpen(final SQLiteDatabase db) { if (firstRun) { sanityChecks(db); firstRun = false; } } /** * Execute sanity checks that should be performed once per application after the database has been * opened. * * @param db the database to perform sanity checks against */ private static void sanityChecks(final SQLiteDatabase db) { // Check that the history of searches is well formed as some dates seem to be missing according // to NPE traces. final int staleHistorySearches = db.delete(dbTableSearchDestionationHistory, "date is null", null); if (staleHistorySearches > 0) { Log.w(String.format(Locale.getDefault(), "DataStore.dbHelper.onOpen: removed %d bad search history entries", staleHistorySearches)); } } /** * Method to remove static map files with double underscore due to issue#1670 * introduced with release on 2012-05-24. */ private static void removeDoubleUnderscoreMapFiles() { final File[] geocodeDirs = LocalStorage.getStorage().listFiles(); if (ArrayUtils.isNotEmpty(geocodeDirs)) { final FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(final File dir, final String filename) { return filename.startsWith("map_") && filename.contains("__"); } }; for (final File dir : geocodeDirs) { final File[] wrongFiles = dir.listFiles(filter); if (wrongFiles != null) { for (final File wrongFile : wrongFiles) { FileUtils.deleteIgnoringFailure(wrongFile); } } } } } } /** * Remove obsolete cache directories in c:geo private storage. */ public static void removeObsoleteCacheDirectories() { removeObsoleteCacheDirectories(database); } /** * Remove obsolete cache directories in c:geo private storage. * * @param db * the read-write database to use */ private static void removeObsoleteCacheDirectories(final SQLiteDatabase db) { final File[] files = LocalStorage.getStorage().listFiles(); if (ArrayUtils.isNotEmpty(files)) { final Pattern oldFilePattern = Pattern.compile("^[GC|TB|EC|GK|O][A-Z0-9]{4,7}$"); final SQLiteStatement select = db.compileStatement("select count(*) from " + dbTableCaches + " where geocode = ?"); final ArrayList<File> toRemove = new ArrayList<>(files.length); for (final File file : files) { if (file.isDirectory()) { final String geocode = file.getName(); if (oldFilePattern.matcher(geocode).find()) { select.bindString(1, geocode); if (select.simpleQueryForLong() == 0) { toRemove.add(file); } } } } // Use a background thread for the real removal to avoid keeping the database locked // if we are called from within a transaction. new Thread(new Runnable() { @Override public void run() { for (final File dir : toRemove) { Log.i("Removing obsolete cache directory for " + dir.getName()); LocalStorage.deleteDirectory(dir); } } }).start(); } } /* * Remove empty directories created in the secondary storage area. */ private static void removeSecEmptyDirs() { final File[] files = LocalStorage.getStorageSec().listFiles(); if (ArrayUtils.isNotEmpty(files)) { for (final File file : files) { if (file.isDirectory()) { // This will silently fail if the directory is not empty. FileUtils.deleteIgnoringFailure(file); } } } } private static void dropDatabase(final SQLiteDatabase db) { db.execSQL("drop table if exists " + dbTableCaches); db.execSQL("drop table if exists " + dbTableAttributes); db.execSQL("drop table if exists " + dbTableWaypoints); db.execSQL("drop table if exists " + dbTableSpoilers); db.execSQL("drop table if exists " + dbTableLogs); db.execSQL("drop table if exists " + dbTableLogCount); db.execSQL("drop table if exists " + dbTableLogsOffline); db.execSQL("drop table if exists " + dbTableTrackables); } public static boolean isThere(final String geocode, final String guid, final boolean detailed, final boolean checkTime) { init(); long dataUpdated = 0; long dataDetailedUpdate = 0; int dataDetailed = 0; try { Cursor cursor; if (StringUtils.isNotBlank(geocode)) { cursor = database.query( dbTableCaches, new String[]{"detailed", "detailedupdate", "updated"}, "geocode = ?", new String[]{geocode}, null, null, null, "1"); } else if (StringUtils.isNotBlank(guid)) { cursor = database.query( dbTableCaches, new String[]{"detailed", "detailedupdate", "updated"}, "guid = ?", new String[]{guid}, null, null, null, "1"); } else { return false; } if (cursor.moveToFirst()) { dataDetailed = cursor.getInt(0); dataDetailedUpdate = cursor.getLong(1); dataUpdated = cursor.getLong(2); } cursor.close(); } catch (final Exception e) { Log.e("DataStore.isThere", e); } if (detailed && dataDetailed == 0) { // we want details, but these are not stored return false; } if (checkTime && detailed && dataDetailedUpdate < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) { // we want to check time for detailed cache, but data are older than 3 hours return false; } if (checkTime && !detailed && dataUpdated < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) { // we want to check time for short cache, but data are older than 3 hours return false; } // we have some cache return true; } /** is cache stored in one of the lists (not only temporary) */ public static boolean isOffline(final String geocode, final String guid) { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { return false; } init(); try { final SQLiteStatement listId; final String value; if (StringUtils.isNotBlank(geocode)) { listId = PreparedStatements.getListIdOfGeocode(); value = geocode; } else { listId = PreparedStatements.getListIdOfGuid(); value = guid; } synchronized (listId) { listId.bindString(1, value); return listId.simpleQueryForLong() != StoredList.TEMPORARY_LIST.id; } } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (final Exception e) { Log.e("DataStore.isOffline", e); } return false; } public static String getGeocodeForGuid(final String guid) { if (StringUtils.isBlank(guid)) { return null; } init(); try { final SQLiteStatement description = PreparedStatements.getGeocodeOfGuid(); synchronized (description) { description.bindString(1, guid); return description.simpleQueryForString(); } } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (final Exception e) { Log.e("DataStore.getGeocodeForGuid", e); } return null; } /** * Save/store a cache to the CacheCache * * @param cache * the Cache to save in the CacheCache/DB * @param saveFlags * */ public static void saveCache(final Geocache cache, final Set<LoadFlags.SaveFlag> saveFlags) { saveCaches(Collections.singletonList(cache), saveFlags); } /** * Save/store a cache to the CacheCache * * @param caches * the caches to save in the CacheCache/DB * @param saveFlags * */ public static void saveCaches(final Collection<Geocache> caches, final Set<LoadFlags.SaveFlag> saveFlags) { if (CollectionUtils.isEmpty(caches)) { return; } final ArrayList<String> cachesFromDatabase = new ArrayList<>(); final HashMap<String, Geocache> existingCaches = new HashMap<>(); // first check which caches are in the memory cache for (final Geocache cache : caches) { final String geocode = cache.getGeocode(); final Geocache cacheFromCache = cacheCache.getCacheFromCache(geocode); if (cacheFromCache == null) { cachesFromDatabase.add(geocode); } else { existingCaches.put(geocode, cacheFromCache); } } // then load all remaining caches from the database in one step for (final Geocache cacheFromDatabase : loadCaches(cachesFromDatabase, LoadFlags.LOAD_ALL_DB_ONLY)) { existingCaches.put(cacheFromDatabase.getGeocode(), cacheFromDatabase); } final ArrayList<Geocache> toBeStored = new ArrayList<>(); // Merge with the data already stored in the CacheCache or in the database if // the cache had not been loaded before, and update the CacheCache. // Also, a DB update is required if the merge data comes from the CacheCache // (as it may be more recent than the version in the database), or if the // version coming from the database is different than the version we are entering // into the cache (that includes absence from the database). for (final Geocache cache : caches) { final String geocode = cache.getGeocode(); final Geocache existingCache = existingCaches.get(geocode); final boolean dbUpdateRequired = !cache.gatherMissingFrom(existingCache) || cacheCache.getCacheFromCache(geocode) != null; cache.addStorageLocation(StorageLocation.CACHE); cacheCache.putCacheInCache(cache); // Only save the cache in the database if it is requested by the caller and // the cache contains detailed information. if (saveFlags.contains(SaveFlag.DB) && cache.isDetailed() && dbUpdateRequired) { toBeStored.add(cache); } } for (final Geocache geocache : toBeStored) { storeIntoDatabase(geocache); } } private static boolean storeIntoDatabase(final Geocache cache) { cache.addStorageLocation(StorageLocation.DATABASE); cacheCache.putCacheInCache(cache); Log.d("Saving " + cache.toString() + " (" + cache.getListId() + ") to DB"); final ContentValues values = new ContentValues(); if (cache.getUpdated() == 0) { values.put("updated", System.currentTimeMillis()); } else { values.put("updated", cache.getUpdated()); } values.put("reason", cache.getListId()); values.put("detailed", cache.isDetailed() ? 1 : 0); values.put("detailedupdate", cache.getDetailedUpdate()); values.put("visiteddate", cache.getVisitedDate()); values.put("geocode", cache.getGeocode()); values.put("cacheid", cache.getCacheId()); values.put("guid", cache.getGuid()); values.put("type", cache.getType().id); values.put("name", cache.getName()); values.put("owner", cache.getOwnerDisplayName()); values.put("owner_real", cache.getOwnerUserId()); final Date hiddenDate = cache.getHiddenDate(); if (hiddenDate == null) { values.put("hidden", 0); } else { values.put("hidden", hiddenDate.getTime()); } values.put("hint", cache.getHint()); values.put("size", cache.getSize() == null ? "" : cache.getSize().id); values.put("difficulty", cache.getDifficulty()); values.put("terrain", cache.getTerrain()); values.put("location", cache.getLocation()); values.put("distance", cache.getDistance()); values.put("direction", cache.getDirection()); putCoords(values, cache.getCoords()); values.put("reliable_latlon", cache.isReliableLatLon() ? 1 : 0); values.put("shortdesc", cache.getShortDescription()); values.put("personal_note", cache.getPersonalNote()); values.put("description", cache.getDescription()); values.put("favourite_cnt", cache.getFavoritePoints()); values.put("rating", cache.getRating()); values.put("votes", cache.getVotes()); values.put("myvote", cache.getMyVote()); values.put("disabled", cache.isDisabled() ? 1 : 0); values.put("archived", cache.isArchived() ? 1 : 0); values.put("members", cache.isPremiumMembersOnly() ? 1 : 0); values.put("found", cache.isFound() ? 1 : 0); values.put("favourite", cache.isFavorite() ? 1 : 0); values.put("inventoryunknown", cache.getInventoryItems()); values.put("onWatchlist", cache.isOnWatchlist() ? 1 : 0); values.put("coordsChanged", cache.hasUserModifiedCoords() ? 1 : 0); values.put("finalDefined", cache.hasFinalDefined() ? 1 : 0); values.put("logPasswordRequired", cache.isLogPasswordRequired() ? 1 : 0); init(); //try to update record else insert fresh.. database.beginTransaction(); try { saveAttributesWithoutTransaction(cache); saveWaypointsWithoutTransaction(cache); saveSpoilersWithoutTransaction(cache); saveLogCountsWithoutTransaction(cache); saveInventoryWithoutTransaction(cache.getGeocode(), cache.getInventory()); final int rows = database.update(dbTableCaches, values, "geocode = ?", new String[] { cache.getGeocode() }); if (rows == 0) { // cache is not in the DB, insert it /* long id = */ database.insert(dbTableCaches, null, values); } database.setTransactionSuccessful(); return true; } catch (final Exception e) { Log.e("SaveCache", e); } finally { database.endTransaction(); } return false; } private static void saveAttributesWithoutTransaction(final Geocache cache) { final String geocode = cache.getGeocode(); // The attributes must be fetched first because lazy loading may load // a null set otherwise. final List<String> attributes = cache.getAttributes(); database.delete(dbTableAttributes, "geocode = ?", new String[]{geocode}); if (attributes.isEmpty()) { return; } final SQLiteStatement statement = PreparedStatements.getInsertAttribute(); final long timestamp = System.currentTimeMillis(); for (final String attribute : attributes) { statement.bindString(1, geocode); statement.bindLong(2, timestamp); statement.bindString(3, attribute); statement.executeInsert(); } } /** * Persists the given <code>destination</code> into the database. * * @param destination * a destination to save */ public static void saveSearchedDestination(final Destination destination) { init(); database.beginTransaction(); try { final SQLiteStatement insertDestination = PreparedStatements.getInsertSearchDestination(destination); insertDestination.executeInsert(); database.setTransactionSuccessful(); } catch (final Exception e) { Log.e("Updating searchedDestinations db failed", e); } finally { database.endTransaction(); } } public static boolean saveWaypoints(final Geocache cache) { init(); database.beginTransaction(); try { saveWaypointsWithoutTransaction(cache); database.setTransactionSuccessful(); return true; } catch (final Exception e) { Log.e("saveWaypoints", e); } finally { database.endTransaction(); } return false; } private static void saveWaypointsWithoutTransaction(final Geocache cache) { final String geocode = cache.getGeocode(); final List<Waypoint> waypoints = cache.getWaypoints(); if (CollectionUtils.isNotEmpty(waypoints)) { final ArrayList<String> currentWaypointIds = new ArrayList<>(); final ContentValues values = new ContentValues(); final long timeStamp = System.currentTimeMillis(); for (final Waypoint oneWaypoint : waypoints) { values.clear(); values.put("geocode", geocode); values.put("updated", timeStamp); values.put("type", oneWaypoint.getWaypointType() != null ? oneWaypoint.getWaypointType().id : null); values.put("prefix", oneWaypoint.getPrefix()); values.put("lookup", oneWaypoint.getLookup()); values.put("name", oneWaypoint.getName()); putCoords(values, oneWaypoint.getCoords()); values.put("note", oneWaypoint.getNote()); values.put("own", oneWaypoint.isUserDefined() ? 1 : 0); values.put("visited", oneWaypoint.isVisited() ? 1 : 0); if (oneWaypoint.getId() < 0) { final long rowId = database.insert(dbTableWaypoints, null, values); oneWaypoint.setId((int) rowId); } else { database.update(dbTableWaypoints, values, "_id = ?", new String[] { Integer.toString(oneWaypoint.getId(), 10) }); } currentWaypointIds.add(Integer.toString(oneWaypoint.getId())); } removeOutdatedWaypointsOfCache(cache, currentWaypointIds); } } /** * remove all waypoints of the given cache, where the id is not in the given list * * @param cache * @param remainingWaypointIds * ids of waypoints which shall not be deleted */ private static void removeOutdatedWaypointsOfCache(final @NonNull Geocache cache, final @NonNull Collection<String> remainingWaypointIds) { final String idList = StringUtils.join(remainingWaypointIds, ','); database.delete(dbTableWaypoints, "geocode = ? AND _id NOT in (" + idList + ")", new String[] { cache.getGeocode() }); } /** * Save coordinates into a ContentValues * * @param values * a ContentValues to save coordinates in * @param oneWaypoint * coordinates to save, or null to save empty coordinates */ private static void putCoords(final ContentValues values, final Geopoint coords) { values.put("latitude", coords == null ? null : coords.getLatitude()); values.put("longitude", coords == null ? null : coords.getLongitude()); } /** * Retrieve coordinates from a Cursor * * @param cursor * a Cursor representing a row in the database * @param indexLat * index of the latitude column * @param indexLon * index of the longitude column * @return the coordinates, or null if latitude or longitude is null or the coordinates are invalid */ private static Geopoint getCoords(final Cursor cursor, final int indexLat, final int indexLon) { if (cursor.isNull(indexLat) || cursor.isNull(indexLon)) { return null; } return new Geopoint(cursor.getDouble(indexLat), cursor.getDouble(indexLon)); } private static boolean saveWaypointInternal(final int id, final String geocode, final Waypoint waypoint) { if ((StringUtils.isBlank(geocode) && id <= 0) || waypoint == null) { return false; } init(); database.beginTransaction(); boolean ok = false; try { final ContentValues values = new ContentValues(); values.put("geocode", geocode); values.put("updated", System.currentTimeMillis()); values.put("type", waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null); values.put("prefix", waypoint.getPrefix()); values.put("lookup", waypoint.getLookup()); values.put("name", waypoint.getName()); putCoords(values, waypoint.getCoords()); values.put("note", waypoint.getNote()); values.put("own", waypoint.isUserDefined() ? 1 : 0); values.put("visited", waypoint.isVisited() ? 1 : 0); if (id <= 0) { final long rowId = database.insert(dbTableWaypoints, null, values); waypoint.setId((int) rowId); ok = true; } else { final int rows = database.update(dbTableWaypoints, values, "_id = " + id, null); ok = rows > 0; } database.setTransactionSuccessful(); } finally { database.endTransaction(); } return ok; } public static boolean deleteWaypoint(final int id) { if (id == 0) { return false; } init(); return database.delete(dbTableWaypoints, "_id = " + id, null) > 0; } private static void saveSpoilersWithoutTransaction(final Geocache cache) { final String geocode = cache.getGeocode(); database.delete(dbTableSpoilers, "geocode = ?", new String[]{geocode}); final List<Image> spoilers = cache.getSpoilers(); if (CollectionUtils.isNotEmpty(spoilers)) { final SQLiteStatement insertSpoiler = PreparedStatements.getInsertSpoiler(); final long timestamp = System.currentTimeMillis(); for (final Image spoiler : spoilers) { insertSpoiler.bindString(1, geocode); insertSpoiler.bindLong(2, timestamp); insertSpoiler.bindString(3, spoiler.getUrl()); insertSpoiler.bindString(4, spoiler.getTitle()); final String description = spoiler.getDescription(); if (description != null) { insertSpoiler.bindString(5, description); } else { insertSpoiler.bindNull(5); } insertSpoiler.executeInsert(); } } } public static void saveLogsWithoutTransaction(final String geocode, final Iterable<LogEntry> logs) { // TODO delete logimages referring these logs database.delete(dbTableLogs, "geocode = ?", new String[]{geocode}); final SQLiteStatement insertLog = PreparedStatements.getInsertLog(); final long timestamp = System.currentTimeMillis(); for (final LogEntry log : logs) { insertLog.bindString(1, geocode); insertLog.bindLong(2, timestamp); insertLog.bindLong(3, log.type.id); insertLog.bindString(4, log.author); insertLog.bindString(5, log.log); insertLog.bindLong(6, log.date); insertLog.bindLong(7, log.found); insertLog.bindLong(8, log.friend ? 1 : 0); final long logId = insertLog.executeInsert(); if (log.hasLogImages()) { final SQLiteStatement insertImage = PreparedStatements.getInsertLogImage(); for (final Image img : log.getLogImages()) { insertImage.bindLong(1, logId); insertImage.bindString(2, img.getTitle()); insertImage.bindString(3, img.getUrl()); insertImage.executeInsert(); } } } } private static void saveLogCountsWithoutTransaction(final Geocache cache) { final String geocode = cache.getGeocode(); database.delete(dbTableLogCount, "geocode = ?", new String[]{geocode}); final Map<LogType, Integer> logCounts = cache.getLogCounts(); if (MapUtils.isNotEmpty(logCounts)) { final Set<Entry<LogType, Integer>> logCountsItems = logCounts.entrySet(); final SQLiteStatement insertLogCounts = PreparedStatements.getInsertLogCounts(); final long timestamp = System.currentTimeMillis(); for (final Entry<LogType, Integer> pair : logCountsItems) { insertLogCounts.bindString(1, geocode); insertLogCounts.bindLong(2, timestamp); insertLogCounts.bindLong(3, pair.getKey().id); insertLogCounts.bindLong(4, pair.getValue()); insertLogCounts.executeInsert(); } } } public static void saveTrackable(final Trackable trackable) { init(); database.beginTransaction(); try { saveInventoryWithoutTransaction(null, Collections.singletonList(trackable)); database.setTransactionSuccessful(); } finally { database.endTransaction(); } } private static void saveInventoryWithoutTransaction(final String geocode, final List<Trackable> trackables) { if (geocode != null) { database.delete(dbTableTrackables, "geocode = ?", new String[]{geocode}); } if (CollectionUtils.isNotEmpty(trackables)) { final ContentValues values = new ContentValues(); final long timeStamp = System.currentTimeMillis(); for (final Trackable trackable : trackables) { final String tbCode = trackable.getGeocode(); if (StringUtils.isNotBlank(tbCode)) { database.delete(dbTableTrackables, "tbcode = ?", new String[] { tbCode }); } values.clear(); if (geocode != null) { values.put("geocode", geocode); } values.put("updated", timeStamp); values.put("tbcode", tbCode); values.put("guid", trackable.getGuid()); values.put("title", trackable.getName()); values.put("owner", trackable.getOwner()); if (trackable.getReleased() != null) { values.put("released", trackable.getReleased().getTime()); } else { values.put("released", 0L); } values.put("goal", trackable.getGoal()); values.put("description", trackable.getDetails()); database.insert(dbTableTrackables, null, values); saveLogsWithoutTransaction(tbCode, trackable.getLogs()); } } } public static Viewport getBounds(final Set<String> geocodes) { if (CollectionUtils.isEmpty(geocodes)) { return null; } final Set<Geocache> caches = loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB); return Viewport.containing(caches); } /** * Load a single Cache. * * @param geocode * The Geocode GCXXXX * @return the loaded cache (if found). Can be null */ public static Geocache loadCache(final String geocode, final EnumSet<LoadFlag> loadFlags) { if (StringUtils.isBlank(geocode)) { throw new IllegalArgumentException("geocode must not be empty"); } final Set<Geocache> caches = loadCaches(Collections.singleton(geocode), loadFlags); return caches.isEmpty() ? null : caches.iterator().next(); } /** * Load caches. * * @param geocodes * @return Set of loaded caches. Never null. */ public static Set<Geocache> loadCaches(final Collection<String> geocodes, final EnumSet<LoadFlag> loadFlags) { if (CollectionUtils.isEmpty(geocodes)) { return new HashSet<>(); } final Set<Geocache> result = new HashSet<>(geocodes.size()); final Set<String> remaining = new HashSet<>(geocodes); if (loadFlags.contains(LoadFlag.CACHE_BEFORE)) { for (final String geocode : new HashSet<>(remaining)) { final Geocache cache = cacheCache.getCacheFromCache(geocode); if (cache != null) { result.add(cache); remaining.remove(cache.getGeocode()); } } } if (loadFlags.contains(LoadFlag.DB_MINIMAL) || loadFlags.contains(LoadFlag.ATTRIBUTES) || loadFlags.contains(LoadFlag.WAYPOINTS) || loadFlags.contains(LoadFlag.SPOILERS) || loadFlags.contains(LoadFlag.LOGS) || loadFlags.contains(LoadFlag.INVENTORY) || loadFlags.contains(LoadFlag.OFFLINE_LOG)) { final Set<Geocache> cachesFromDB = loadCachesFromGeocodes(remaining, loadFlags); result.addAll(cachesFromDB); for (final Geocache cache : cachesFromDB) { remaining.remove(cache.getGeocode()); } } if (loadFlags.contains(LoadFlag.CACHE_AFTER)) { for (final String geocode : new HashSet<>(remaining)) { final Geocache cache = cacheCache.getCacheFromCache(geocode); if (cache != null) { result.add(cache); remaining.remove(cache.getGeocode()); } } } if (remaining.size() >= 1) { Log.d("DataStore.loadCaches(" + remaining.toString() + ") returned no results"); } return result; } /** * Load caches. * * @param geocodes * @param loadFlags * @return Set of loaded caches. Never null. */ private static Set<Geocache> loadCachesFromGeocodes(final Set<String> geocodes, final EnumSet<LoadFlag> loadFlags) { if (CollectionUtils.isEmpty(geocodes)) { return Collections.emptySet(); } // do not log the entire collection of geo codes to the debug log. This can be more than 100 KB of text for large lists! init(); final StringBuilder query = new StringBuilder(QUERY_CACHE_DATA); if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) { query.append(',').append(dbTableLogsOffline).append(".log"); } query.append(" FROM ").append(dbTableCaches); if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) { query.append(" LEFT OUTER JOIN ").append(dbTableLogsOffline).append(" ON ( ").append(dbTableCaches).append(".geocode == ").append(dbTableLogsOffline).append(".geocode) "); } query.append(" WHERE ").append(dbTableCaches).append('.'); query.append(DataStore.whereGeocodeIn(geocodes)); final Cursor cursor = database.rawQuery(query.toString(), null); try { final Set<Geocache> caches = new HashSet<>(); int logIndex = -1; while (cursor.moveToNext()) { final Geocache cache = createCacheFromDatabaseContent(cursor); if (loadFlags.contains(LoadFlag.ATTRIBUTES)) { cache.setAttributes(loadAttributes(cache.getGeocode())); } if (loadFlags.contains(LoadFlag.WAYPOINTS)) { final List<Waypoint> waypoints = loadWaypoints(cache.getGeocode()); if (CollectionUtils.isNotEmpty(waypoints)) { cache.setWaypoints(waypoints, false); } } if (loadFlags.contains(LoadFlag.SPOILERS)) { final List<Image> spoilers = loadSpoilers(cache.getGeocode()); cache.setSpoilers(spoilers); } if (loadFlags.contains(LoadFlag.LOGS)) { final Map<LogType, Integer> logCounts = loadLogCounts(cache.getGeocode()); if (MapUtils.isNotEmpty(logCounts)) { cache.getLogCounts().clear(); cache.getLogCounts().putAll(logCounts); } } if (loadFlags.contains(LoadFlag.INVENTORY)) { final List<Trackable> inventory = loadInventory(cache.getGeocode()); if (CollectionUtils.isNotEmpty(inventory)) { if (cache.getInventory() == null) { cache.setInventory(new ArrayList<Trackable>()); } else { cache.getInventory().clear(); } cache.getInventory().addAll(inventory); } } if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) { if (logIndex < 0) { logIndex = cursor.getColumnIndex("log"); } cache.setLogOffline(!cursor.isNull(logIndex)); } cache.addStorageLocation(StorageLocation.DATABASE); cacheCache.putCacheInCache(cache); caches.add(cache); } return caches; } finally { cursor.close(); } } /** * Builds a where for a viewport with the size enhanced by 50%. * * @param dbTable * @param viewport * @return */ private static StringBuilder buildCoordinateWhere(final String dbTable, final Viewport viewport) { return viewport.resize(1.5).sqlWhere(dbTable); } /** * creates a Cache from the cursor. Doesn't next. * * @param cursor * @return Cache from DB */ private static Geocache createCacheFromDatabaseContent(final Cursor cursor) { final Geocache cache = new Geocache(); cache.setUpdated(cursor.getLong(0)); cache.setListId(cursor.getInt(1)); cache.setDetailed(cursor.getInt(2) == 1); cache.setDetailedUpdate(cursor.getLong(3)); cache.setVisitedDate(cursor.getLong(4)); cache.setGeocode(cursor.getString(5)); cache.setCacheId(cursor.getString(6)); cache.setGuid(cursor.getString(7)); cache.setType(CacheType.getById(cursor.getString(8))); cache.setName(cursor.getString(9)); cache.setOwnerDisplayName(cursor.getString(10)); cache.setOwnerUserId(cursor.getString(11)); final long dateValue = cursor.getLong(12); if (dateValue != 0) { cache.setHidden(new Date(dateValue)); } // do not set cache.hint cache.setSize(CacheSize.getById(cursor.getString(14))); cache.setDifficulty(cursor.getFloat(15)); int index = 16; if (cursor.isNull(index)) { cache.setDirection(null); } else { cache.setDirection(cursor.getFloat(index)); } index = 17; if (cursor.isNull(index)) { cache.setDistance(null); } else { cache.setDistance(cursor.getFloat(index)); } cache.setTerrain(cursor.getFloat(18)); // do not set cache.location cache.setPersonalNote(cursor.getString(20)); // do not set cache.shortdesc // do not set cache.description cache.setFavoritePoints(cursor.getInt(22)); cache.setRating(cursor.getFloat(23)); cache.setVotes(cursor.getInt(24)); cache.setMyVote(cursor.getFloat(25)); cache.setDisabled(cursor.getInt(26) == 1); cache.setArchived(cursor.getInt(27) == 1); cache.setPremiumMembersOnly(cursor.getInt(28) == 1); cache.setFound(cursor.getInt(29) == 1); cache.setFavorite(cursor.getInt(30) == 1); cache.setInventoryItems(cursor.getInt(31)); cache.setOnWatchlist(cursor.getInt(32) == 1); cache.setReliableLatLon(cursor.getInt(33) > 0); cache.setUserModifiedCoords(cursor.getInt(34) > 0); cache.setCoords(getCoords(cursor, 35, 36)); cache.setFinalDefined(cursor.getInt(37) > 0); cache.setLogPasswordRequired(cursor.getInt(41) > 0); Log.d("Loading " + cache.toString() + " (" + cache.getListId() + ") from DB"); return cache; } public static List<String> loadAttributes(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } return queryToColl(dbTableAttributes, new String[]{"attribute"}, "geocode = ?", new String[]{geocode}, null, null, null, "100", new LinkedList<String>(), GET_STRING_0); } public static Waypoint loadWaypoint(final int id) { if (id == 0) { return null; } init(); final Cursor cursor = database.query( dbTableWaypoints, WAYPOINT_COLUMNS, "_id = ?", new String[]{Integer.toString(id)}, null, null, null, "1"); Log.d("DataStore.loadWaypoint(" + id + ")"); final Waypoint waypoint = cursor.moveToFirst() ? createWaypointFromDatabaseContent(cursor) : null; cursor.close(); return waypoint; } public static List<Waypoint> loadWaypoints(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } return queryToColl(dbTableWaypoints, WAYPOINT_COLUMNS, "geocode = ?", new String[]{geocode}, null, null, "_id", "100", new LinkedList<Waypoint>(), new Func1<Cursor, Waypoint>() { @Override public Waypoint call(final Cursor cursor) { return createWaypointFromDatabaseContent(cursor); } }); } private static Waypoint createWaypointFromDatabaseContent(final Cursor cursor) { final String name = cursor.getString(cursor.getColumnIndex("name")); final WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type"))); final boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0; final Waypoint waypoint = new Waypoint(name, type, own); waypoint.setVisited(cursor.getInt(cursor.getColumnIndex("visited")) != 0); waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id"))); waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode"))); waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix"))); waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup"))); waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude"))); waypoint.setNote(cursor.getString(cursor.getColumnIndex("note"))); return waypoint; } private static List<Image> loadSpoilers(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } return queryToColl(dbTableSpoilers, new String[]{"url", "title", "description"}, "geocode = ?", new String[]{geocode}, null, null, null, "100", new LinkedList<Image>(), new Func1<Cursor, Image>() { @Override public Image call(final Cursor cursor) { return new Image(cursor.getString(0), cursor.getString(1), cursor.getString(2)); } }); } /** * Loads the history of previously entered destinations from * the database. If no destinations exist, an {@link Collections#emptyList()} will be returned. * * @return A list of previously entered destinations or an empty list. */ public static List<Destination> loadHistoryOfSearchedLocations() { return queryToColl(dbTableSearchDestionationHistory, new String[]{"_id", "date", "latitude", "longitude"}, "latitude IS NOT NULL AND longitude IS NOT NULL", null, null, null, "date desc", "100", new LinkedList<Destination>(), new Func1<Cursor, Destination>() { @Override public Destination call(final Cursor cursor) { return new Destination(cursor.getLong(0), cursor.getLong(1), getCoords(cursor, 2, 3)); } }); } public static boolean clearSearchedDestinations() { init(); database.beginTransaction(); try { database.delete(dbTableSearchDestionationHistory, null, null); database.setTransactionSuccessful(); return true; } catch (final Exception e) { Log.e("Unable to clear searched destinations", e); } finally { database.endTransaction(); } return false; } /** * @param geocode * @return an immutable, non null list of logs */ @NonNull public static List<LogEntry> loadLogs(final String geocode) { final List<LogEntry> logs = new ArrayList<>(); if (StringUtils.isBlank(geocode)) { return logs; } init(); final Cursor cursor = database.rawQuery( /* 0 1 2 3 4 5 6 7 8 9 10 */ "SELECT cg_logs._id as cg_logs_id, type, author, log, date, found, friend, " + dbTableLogImages + "._id as cg_logImages_id, log_id, title, url" + " FROM " + dbTableLogs + " LEFT OUTER JOIN " + dbTableLogImages + " ON ( cg_logs._id = log_id ) WHERE geocode = ? ORDER BY date desc, cg_logs._id asc", new String[]{geocode}); LogEntry log = null; while (cursor.moveToNext() && logs.size() < 100) { if (log == null || log.id != cursor.getInt(0)) { log = new LogEntry( cursor.getString(2), cursor.getLong(4), LogType.getById(cursor.getInt(1)), cursor.getString(3)); log.id = cursor.getInt(0); log.found = cursor.getInt(5); log.friend = cursor.getInt(6) == 1; logs.add(log); } if (!cursor.isNull(7)) { log.addLogImage(new Image(cursor.getString(10), cursor.getString(9))); } } cursor.close(); return Collections.unmodifiableList(logs); } public static Map<LogType, Integer> loadLogCounts(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); final Map<LogType, Integer> logCounts = new EnumMap<>(LogType.class); final Cursor cursor = database.query( dbTableLogCount, new String[]{"type", "count"}, "geocode = ?", new String[]{geocode}, null, null, null, "100"); while (cursor.moveToNext()) { logCounts.put(LogType.getById(cursor.getInt(0)), cursor.getInt(1)); } cursor.close(); return logCounts; } private static List<Trackable> loadInventory(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); final List<Trackable> trackables = new ArrayList<>(); final Cursor cursor = database.query( dbTableTrackables, new String[]{"_id", "updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"}, "geocode = ?", new String[]{geocode}, null, null, "title COLLATE NOCASE ASC", "100"); while (cursor.moveToNext()) { trackables.add(createTrackableFromDatabaseContent(cursor)); } cursor.close(); return trackables; } public static Trackable loadTrackable(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); final Cursor cursor = database.query( dbTableTrackables, new String[]{"updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"}, "tbcode = ?", new String[]{geocode}, null, null, null, "1"); final Trackable trackable = cursor.moveToFirst() ? createTrackableFromDatabaseContent(cursor) : null; cursor.close(); return trackable; } private static Trackable createTrackableFromDatabaseContent(final Cursor cursor) { final Trackable trackable = new Trackable(); trackable.setGeocode(cursor.getString(cursor.getColumnIndex("tbcode"))); trackable.setGuid(cursor.getString(cursor.getColumnIndex("guid"))); trackable.setName(cursor.getString(cursor.getColumnIndex("title"))); trackable.setOwner(cursor.getString(cursor.getColumnIndex("owner"))); final String released = cursor.getString(cursor.getColumnIndex("released")); if (released != null) { try { final long releaseMilliSeconds = Long.parseLong(released); trackable.setReleased(new Date(releaseMilliSeconds)); } catch (final NumberFormatException e) { Log.e("createTrackableFromDatabaseContent", e); } } trackable.setGoal(cursor.getString(cursor.getColumnIndex("goal"))); trackable.setDetails(cursor.getString(cursor.getColumnIndex("description"))); trackable.setLogs(loadLogs(trackable.getGeocode())); return trackable; } /** * Number of caches stored for a given type and/or list * * @param cacheType * @param list * @return */ public static int getAllStoredCachesCount(final CacheType cacheType, final int list) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } if (list <= 0) { throw new IllegalArgumentException("list must be > 0"); } init(); try { final StringBuilder sql = new StringBuilder("select count(_id) from " + dbTableCaches + " where detailed = 1"); String typeKey; int reasonIndex; if (cacheType != CacheType.ALL) { sql.append(" and type = ?"); typeKey = cacheType.id; reasonIndex = 2; } else { typeKey = "all_types"; reasonIndex = 1; } String listKey; if (list == PseudoList.ALL_LIST.id) { sql.append(" and reason > 0"); listKey = "all_list"; } else { sql.append(" and reason = ?"); listKey = "list"; } final String key = "CountCaches_" + typeKey + "_" + listKey; final SQLiteStatement compiledStmnt = PreparedStatements.getStatement(key, sql.toString()); if (cacheType != CacheType.ALL) { compiledStmnt.bindString(1, cacheType.id); } if (list != PseudoList.ALL_LIST.id) { compiledStmnt.bindLong(reasonIndex, list); } return (int) compiledStmnt.simpleQueryForLong(); } catch (final Exception e) { Log.e("DataStore.loadAllStoredCachesCount", e); } return 0; } public static int getAllHistoryCachesCount() { init(); try { return (int) PreparedStatements.getCountHistoryCaches().simpleQueryForLong(); } catch (final Exception e) { Log.e("DataStore.getAllHistoricCachesCount", e); } return 0; } private static<T, U extends Collection<? super T>> U queryToColl(@NonNull final String table, final String[] columns, final String selection, final String[] selectionArgs, final String groupBy, final String having, final String orderBy, final String limit, final U result, final Func1<? super Cursor, ? extends T> func) { init(); final Cursor cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); return cursorToColl(cursor, result, func); } private static <T, U extends Collection<? super T>> U cursorToColl(final Cursor cursor, final U result, final Func1<? super Cursor, ? extends T> func) { try { while (cursor.moveToNext()) { result.add(func.call(cursor)); } return result; } finally { cursor.close(); } } /** * Return a batch of stored geocodes. * * @param coords * the current coordinates to sort by distance, or null to sort by geocode * @param cacheType * @param listId * @return a non-null set of geocodes */ private static Set<String> loadBatchOfStoredGeocodes(final Geopoint coords, final CacheType cacheType, final int listId) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } final StringBuilder selection = new StringBuilder(); selection.append("reason "); selection.append(listId != PseudoList.ALL_LIST.id ? "=" + Math.max(listId, 1) : ">= " + StoredList.STANDARD_LIST_ID); selection.append(" and detailed = 1 "); String[] selectionArgs = null; if (cacheType != CacheType.ALL) { selection.append(" and type = ?"); selectionArgs = new String[] { String.valueOf(cacheType.id) }; } try { if (coords != null) { return queryToColl(dbTableCaches, new String[]{"geocode", "(abs(latitude-" + String.format((Locale) null, "%.6f", coords.getLatitude()) + ") + abs(longitude-" + String.format((Locale) null, "%.6f", coords.getLongitude()) + ")) as dif"}, selection.toString(), selectionArgs, null, null, "dif", null, new HashSet<String>(), GET_STRING_0); } return queryToColl(dbTableCaches, new String[] { "geocode" }, selection.toString(), selectionArgs, null, null, "geocode", null, new HashSet<String>(), GET_STRING_0); } catch (final Exception e) { Log.e("DataStore.loadBatchOfStoredGeocodes", e); return Collections.emptySet(); } } private static Set<String> loadBatchOfHistoricGeocodes(final boolean detailedOnly, final CacheType cacheType) { final StringBuilder selection = new StringBuilder("visiteddate > 0"); if (detailedOnly) { selection.append(" and detailed = 1"); } String[] selectionArgs = null; if (cacheType != CacheType.ALL) { selection.append(" and type = ?"); selectionArgs = new String[] { String.valueOf(cacheType.id) }; } try { return queryToColl(dbTableCaches, new String[]{"geocode"}, selection.toString(), selectionArgs, null, null, "visiteddate", null, new HashSet<String>(), GET_STRING_0); } catch (final Exception e) { Log.e("DataStore.loadBatchOfHistoricGeocodes", e); } return Collections.emptySet(); } /** Retrieve all stored caches from DB */ public static SearchResult loadCachedInViewport(final Viewport viewport, final CacheType cacheType) { return loadInViewport(false, viewport, cacheType); } /** Retrieve stored caches from DB with listId >= 1 */ public static SearchResult loadStoredInViewport(final Viewport viewport, final CacheType cacheType) { return loadInViewport(true, viewport, cacheType); } /** * Loads the geocodes of caches in a viewport from CacheCache and/or Database * * @param stored * True - query only stored caches, False - query cached ones as well * @param centerLat * @param centerLon * @param spanLat * @param spanLon * @param cacheType * @return Set with geocodes */ private static SearchResult loadInViewport(final boolean stored, final Viewport viewport, final CacheType cacheType) { final Set<String> geocodes = new HashSet<>(); // if not stored only, get codes from CacheCache as well if (!stored) { geocodes.addAll(cacheCache.getInViewport(viewport, cacheType)); } // viewport limitation final StringBuilder selection = buildCoordinateWhere(dbTableCaches, viewport); // cacheType limitation String[] selectionArgs = null; if (cacheType != CacheType.ALL) { selection.append(" and type = ?"); selectionArgs = new String[] { String.valueOf(cacheType.id) }; } // offline caches only if (stored) { selection.append(" and reason >= " + StoredList.STANDARD_LIST_ID); } try { return new SearchResult(queryToColl(dbTableCaches, new String[]{"geocode"}, selection.toString(), selectionArgs, null, null, null, "500", geocodes, GET_STRING_0)); } catch (final Exception e) { Log.e("DataStore.loadInViewport", e); } return new SearchResult(); } /** * Remove caches with listId = 0 * * @param more * true = all caches false = caches stored 3 days or more before */ public static void clean(final boolean more) { if (databaseCleaned) { return; } Log.d("Database clean: started"); try { Set<String> geocodes = new HashSet<>(); if (more) { queryToColl(dbTableCaches, new String[]{"geocode"}, "reason = 0", null, null, null, null, null, geocodes, GET_STRING_0); } else { final long timestamp = System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED; final String timestampString = Long.toString(timestamp); queryToColl(dbTableCaches, new String[]{"geocode"}, "reason = 0 and detailed < ? and detailedupdate < ? and visiteddate < ?", new String[]{timestampString, timestampString, timestampString}, null, null, null, null, geocodes, GET_STRING_0); } geocodes = exceptCachesWithOfflineLog(geocodes); if (!geocodes.isEmpty()) { Log.d("Database clean: removing " + geocodes.size() + " geocaches from listId=0"); removeCaches(geocodes, LoadFlags.REMOVE_ALL); } // This cleanup needs to be kept in place for about one year so that older log images records are // cleaned. TO BE REMOVED AFTER 2015-03-24. Log.d("Database clean: removing obsolete log images records"); database.delete(dbTableLogImages, "log_id NOT IN (SELECT _id FROM " + dbTableLogs + ")", null); } catch (final Exception e) { Log.w("DataStore.clean", e); } Log.d("Database clean: finished"); databaseCleaned = true; } /** * remove all geocodes from the given list of geocodes where an offline log exists * * @param geocodes * @return */ private static Set<String> exceptCachesWithOfflineLog(final Set<String> geocodes) { if (geocodes.isEmpty()) { return geocodes; } final List<String> geocodesWithOfflineLog = queryToColl(dbTableLogsOffline, new String[] { "geocode" }, null, null, null, null, null, null, new LinkedList<String>(), GET_STRING_0); geocodes.removeAll(geocodesWithOfflineLog); return geocodes; } public static void removeAllFromCache() { // clean up CacheCache cacheCache.removeAllFromCache(); } public static void removeCache(final String geocode, final EnumSet<LoadFlags.RemoveFlag> removeFlags) { removeCaches(Collections.singleton(geocode), removeFlags); } /** * Drop caches from the tables they are stored into, as well as the cache files * * @param geocodes * list of geocodes to drop from cache */ public static void removeCaches(final Set<String> geocodes, final EnumSet<LoadFlags.RemoveFlag> removeFlags) { if (CollectionUtils.isEmpty(geocodes)) { return; } init(); if (removeFlags.contains(RemoveFlag.CACHE)) { for (final String geocode : geocodes) { cacheCache.removeCacheFromCache(geocode); } } if (removeFlags.contains(RemoveFlag.DB)) { // Drop caches from the database final ArrayList<String> quotedGeocodes = new ArrayList<>(geocodes.size()); for (final String geocode : geocodes) { quotedGeocodes.add(DatabaseUtils.sqlEscapeString(geocode)); } final String geocodeList = StringUtils.join(quotedGeocodes.toArray(), ','); final String baseWhereClause = "geocode in (" + geocodeList + ")"; database.beginTransaction(); try { database.delete(dbTableCaches, baseWhereClause, null); database.delete(dbTableAttributes, baseWhereClause, null); database.delete(dbTableSpoilers, baseWhereClause, null); database.delete(dbTableLogImages, "log_id IN (SELECT _id FROM " + dbTableLogs + " WHERE " + baseWhereClause + ")", null); database.delete(dbTableLogs, baseWhereClause, null); database.delete(dbTableLogCount, baseWhereClause, null); database.delete(dbTableLogsOffline, baseWhereClause, null); String wayPointClause = baseWhereClause; if (!removeFlags.contains(RemoveFlag.OWN_WAYPOINTS_ONLY_FOR_TESTING)) { wayPointClause += " and type <> 'own'"; } database.delete(dbTableWaypoints, wayPointClause, null); database.delete(dbTableTrackables, baseWhereClause, null); database.setTransactionSuccessful(); } finally { database.endTransaction(); } // Delete cache directories for (final String geocode : geocodes) { LocalStorage.deleteDirectory(LocalStorage.getStorageDir(geocode)); } } } public static boolean saveLogOffline(final String geocode, final Date date, final LogType type, final String log) { if (StringUtils.isBlank(geocode)) { Log.e("DataStore.saveLogOffline: cannot log a blank geocode"); return false; } if (LogType.UNKNOWN == type && StringUtils.isBlank(log)) { Log.e("DataStore.saveLogOffline: cannot log an unknown log type and no message"); return false; } init(); final ContentValues values = new ContentValues(); values.put("geocode", geocode); values.put("updated", System.currentTimeMillis()); values.put("type", type.id); values.put("log", log); values.put("date", date.getTime()); if (hasLogOffline(geocode)) { final int rows = database.update(dbTableLogsOffline, values, "geocode = ?", new String[] { geocode }); return rows > 0; } final long id = database.insert(dbTableLogsOffline, null, values); return id != -1; } public static LogEntry loadLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); final Cursor cursor = database.query( dbTableLogsOffline, new String[]{"_id", "type", "log", "date"}, "geocode = ?", new String[]{geocode}, null, null, "_id desc", "1"); LogEntry log = null; if (cursor.moveToFirst()) { log = new LogEntry(cursor.getLong(3), LogType.getById(cursor.getInt(1)), cursor.getString(2)); log.id = cursor.getInt(0); } cursor.close(); return log; } public static void clearLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return; } init(); database.delete(dbTableLogsOffline, "geocode = ?", new String[]{geocode}); } public static void clearLogsOffline(final List<Geocache> caches) { if (CollectionUtils.isEmpty(caches)) { return; } init(); final Set<String> geocodes = new HashSet<>(caches.size()); for (final Geocache cache : caches) { geocodes.add(cache.getGeocode()); cache.setLogOffline(false); } database.execSQL(String.format("DELETE FROM %s where %s", dbTableLogsOffline, whereGeocodeIn(geocodes))); } public static boolean hasLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return false; } init(); try { final SQLiteStatement logCount = PreparedStatements.getLogCountOfGeocode(); synchronized (logCount) { logCount.bindString(1, geocode); return logCount.simpleQueryForLong() > 0; } } catch (final Exception e) { Log.e("DataStore.hasLogOffline", e); } return false; } private static void setVisitDate(final List<String> geocodes, final long visitedDate) { if (geocodes.isEmpty()) { return; } init(); database.beginTransaction(); try { final SQLiteStatement setVisit = PreparedStatements.getUpdateVisitDate(); for (final String geocode : geocodes) { setVisit.bindLong(1, visitedDate); setVisit.bindString(2, geocode); setVisit.execute(); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } @NonNull public static List<StoredList> getLists() { init(); final Resources res = CgeoApplication.getInstance().getResources(); final List<StoredList> lists = new ArrayList<>(); lists.add(new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatements.getCountCachesOnStandardList().simpleQueryForLong())); try { final String query = "SELECT l._id as _id, l.title as title, COUNT(c._id) as count" + " FROM " + dbTableLists + " l LEFT OUTER JOIN " + dbTableCaches + " c" + " ON l._id + " + customListIdOffset + " = c.reason" + " GROUP BY l._id" + " ORDER BY l.title COLLATE NOCASE ASC"; lists.addAll(getListsFromCursor(database.rawQuery(query, null))); } catch (final Exception e) { Log.e("DataStore.readLists", e); } return lists; } private static ArrayList<StoredList> getListsFromCursor(final Cursor cursor) { final int indexId = cursor.getColumnIndex("_id"); final int indexTitle = cursor.getColumnIndex("title"); final int indexCount = cursor.getColumnIndex("count"); return cursorToColl(cursor, new ArrayList<StoredList>(), new Func1<Cursor, StoredList>() { @Override public StoredList call(final Cursor cursor) { final int count = indexCount != -1 ? cursor.getInt(indexCount) : 0; return new StoredList(cursor.getInt(indexId) + customListIdOffset, cursor.getString(indexTitle), count); } }); } public static StoredList getList(final int id) { init(); if (id >= customListIdOffset) { final Cursor cursor = database.query( dbTableLists, new String[]{"_id", "title"}, "_id = ? ", new String[] { String.valueOf(id - customListIdOffset) }, null, null, null); final ArrayList<StoredList> lists = getListsFromCursor(cursor); if (!lists.isEmpty()) { return lists.get(0); } } final Resources res = CgeoApplication.getInstance().getResources(); if (id == PseudoList.ALL_LIST.id) { return new StoredList(PseudoList.ALL_LIST.id, res.getString(R.string.list_all_lists), getAllCachesCount()); } // fall back to standard list in case of invalid list id if (id == StoredList.STANDARD_LIST_ID || id >= customListIdOffset) { return new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatements.getCountCachesOnStandardList().simpleQueryForLong()); } return null; } public static int getAllCachesCount() { return (int) PreparedStatements.getCountAllCaches().simpleQueryForLong(); } /** * Create a new list * * @param name * Name * @return new listId */ public static int createList(final String name) { int id = -1; if (StringUtils.isBlank(name)) { return id; } init(); database.beginTransaction(); try { final ContentValues values = new ContentValues(); values.put("title", name); values.put("updated", System.currentTimeMillis()); id = (int) database.insert(dbTableLists, null, values); database.setTransactionSuccessful(); } finally { database.endTransaction(); } return id >= 0 ? id + customListIdOffset : -1; } /** * @param listId * List to change * @param name * New name of list * @return Number of lists changed */ public static int renameList(final int listId, final String name) { if (StringUtils.isBlank(name) || StoredList.STANDARD_LIST_ID == listId) { return 0; } init(); database.beginTransaction(); int count = 0; try { final ContentValues values = new ContentValues(); values.put("title", name); values.put("updated", System.currentTimeMillis()); count = database.update(dbTableLists, values, "_id = " + (listId - customListIdOffset), null); database.setTransactionSuccessful(); } finally { database.endTransaction(); } return count; } /** * Remove a list. Caches in the list are moved to the standard list. * * @param listId * @return true if the list got deleted, false else */ public static boolean removeList(final int listId) { if (listId < customListIdOffset) { return false; } init(); database.beginTransaction(); boolean status = false; try { final int cnt = database.delete(dbTableLists, "_id = " + (listId - customListIdOffset), null); if (cnt > 0) { // move caches from deleted list to standard list final SQLiteStatement moveToStandard = PreparedStatements.getMoveToStandardList(); moveToStandard.bindLong(1, listId); moveToStandard.execute(); status = true; } database.setTransactionSuccessful(); } finally { database.endTransaction(); } return status; } public static void moveToList(final Geocache cache, final int listId) { moveToList(Collections.singletonList(cache), listId); } public static void moveToList(final List<Geocache> caches, final int listId) { final AbstractList list = AbstractList.getListById(listId); if (list == null) { return; } if (!list.isConcrete()) { return; } if (caches.isEmpty()) { return; } init(); final SQLiteStatement move = PreparedStatements.getMoveToList(); database.beginTransaction(); try { for (final Geocache cache : caches) { move.bindLong(1, listId); move.bindString(2, cache.getGeocode()); move.execute(); cache.setListId(listId); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } public static boolean isInitialized() { return database != null; } public static boolean removeSearchedDestination(final Destination destination) { if (destination == null) { return false; } init(); database.beginTransaction(); try { database.delete(dbTableSearchDestionationHistory, "_id = " + destination.getId(), null); database.setTransactionSuccessful(); return true; } catch (final Exception e) { Log.e("Unable to remove searched destination", e); } finally { database.endTransaction(); } return false; } /** * Load the lazily initialized fields of a cache and return them as partial cache (all other fields unset). * * @param geocode * @return */ public static Geocache loadCacheTexts(final String geocode) { final Geocache partial = new Geocache(); // in case of database issues, we still need to return a result to avoid endless loops partial.setDescription(StringUtils.EMPTY); partial.setShortDescription(StringUtils.EMPTY); partial.setHint(StringUtils.EMPTY); partial.setLocation(StringUtils.EMPTY); init(); try { final Cursor cursor = database.query( dbTableCaches, new String[] { "description", "shortdesc", "hint", "location" }, "geocode = ?", new String[] { geocode }, null, null, null, "1"); if (cursor.moveToFirst()) { partial.setDescription(StringUtils.defaultString(cursor.getString(0))); partial.setShortDescription(StringUtils.defaultString(cursor.getString(1))); partial.setHint(StringUtils.defaultString(cursor.getString(2))); partial.setLocation(StringUtils.defaultString(cursor.getString(3))); } cursor.close(); } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (final Exception e) { Log.e("DataStore.getCacheDescription", e); } return partial; } /** * checks if this is a newly created database */ public static boolean isNewlyCreatedDatebase() { return newlyCreatedDatabase; } /** * resets flag for newly created database to avoid asking the user multiple times */ public static void resetNewlyCreatedDatabase() { newlyCreatedDatabase = false; } /** * Creates the WHERE clause for matching multiple geocodes. This automatically converts all given codes to * UPPERCASE. */ private static StringBuilder whereGeocodeIn(final Collection<String> geocodes) { final StringBuilder whereExpr = new StringBuilder("geocode in ("); final Iterator<String> iterator = geocodes.iterator(); while (true) { DatabaseUtils.appendEscapedSQLString(whereExpr, StringUtils.upperCase(iterator.next())); if (!iterator.hasNext()) { break; } whereExpr.append(','); } return whereExpr.append(')'); } /** * Loads all Waypoints in the coordinate rectangle. * * @param excludeDisabled * @param excludeMine * @param type * @return */ public static Set<Waypoint> loadWaypoints(final Viewport viewport, final boolean excludeMine, final boolean excludeDisabled, final CacheType type) { final StringBuilder where = buildCoordinateWhere(dbTableWaypoints, viewport); if (excludeMine) { where.append(" and ").append(dbTableCaches).append(".found == 0"); } if (excludeDisabled) { where.append(" and ").append(dbTableCaches).append(".disabled == 0"); where.append(" and ").append(dbTableCaches).append(".archived == 0"); } if (type != CacheType.ALL) { where.append(" and ").append(dbTableCaches).append(".type == '").append(type.id).append('\''); } final StringBuilder query = new StringBuilder("SELECT "); for (int i = 0; i < WAYPOINT_COLUMNS.length; i++) { query.append(i > 0 ? ", " : "").append(dbTableWaypoints).append('.').append(WAYPOINT_COLUMNS[i]).append(' '); } query.append(" FROM ").append(dbTableWaypoints).append(", ").append(dbTableCaches).append(" WHERE ").append(dbTableWaypoints) .append(".geocode == ").append(dbTableCaches).append(".geocode and ").append(where) .append(" LIMIT " + (Settings.SHOW_WP_THRESHOLD_MAX * 2)); // Hardcoded limit to avoid memory overflow return cursorToColl(database.rawQuery(query.toString(), null), new HashSet<Waypoint>(), new Func1<Cursor, Waypoint>() { @Override public Waypoint call(final Cursor cursor) { return createWaypointFromDatabaseContent(cursor); } }); } public static void saveChangedCache(final Geocache cache) { DataStore.saveCache(cache, cache.getStorageLocation().contains(StorageLocation.DATABASE) ? LoadFlags.SAVE_ALL : EnumSet.of(SaveFlag.CACHE)); } private static class PreparedStatements { private static HashMap<String, SQLiteStatement> statements = new HashMap<>(); public static SQLiteStatement getMoveToStandardList() { return getStatement("MoveToStandardList", "UPDATE " + dbTableCaches + " SET reason = " + StoredList.STANDARD_LIST_ID + " WHERE reason = ?"); } public static SQLiteStatement getMoveToList() { return getStatement("MoveToList", "UPDATE " + dbTableCaches + " SET reason = ? WHERE geocode = ?"); } public static SQLiteStatement getUpdateVisitDate() { return getStatement("UpdateVisitDate", "UPDATE " + dbTableCaches + " SET visiteddate = ? WHERE geocode = ?"); } public static SQLiteStatement getInsertLogImage() { return getStatement("InsertLogImage", "INSERT INTO " + dbTableLogImages + " (log_id, title, url) VALUES (?, ?, ?)"); } public static SQLiteStatement getInsertLogCounts() { return getStatement("InsertLogCounts", "INSERT INTO " + dbTableLogCount + " (geocode, updated, type, count) VALUES (?, ?, ?, ?)"); } public static SQLiteStatement getInsertSpoiler() { return getStatement("InsertSpoiler", "INSERT INTO " + dbTableSpoilers + " (geocode, updated, url, title, description) VALUES (?, ?, ?, ?, ?)"); } public static SQLiteStatement getInsertSearchDestination(final Destination destination) { final SQLiteStatement statement = getStatement("InsertSearch", "INSERT INTO " + dbTableSearchDestionationHistory + " (date, latitude, longitude) VALUES (?, ?, ?)"); statement.bindLong(1, destination.getDate()); final Geopoint coords = destination.getCoords(); statement.bindDouble(2, coords.getLatitude()); statement.bindDouble(3, coords.getLongitude()); return statement; } private static void clearPreparedStatements() { for (final SQLiteStatement statement : statements.values()) { statement.close(); } statements.clear(); } private static synchronized SQLiteStatement getStatement(final String key, final String query) { SQLiteStatement statement = statements.get(key); if (statement == null) { init(); statement = database.compileStatement(query); statements.put(key, statement); } return statement; } public static SQLiteStatement getCountHistoryCaches() { return getStatement("HistoryCount", "select count(_id) from " + dbTableCaches + " where visiteddate > 0"); } private static SQLiteStatement getLogCountOfGeocode() { return getStatement("LogCountFromGeocode", "SELECT count(_id) FROM " + DataStore.dbTableLogsOffline + " WHERE geocode = ?"); } private static SQLiteStatement getCountCachesOnStandardList() { return getStatement("CountStandardList", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason = " + StoredList.STANDARD_LIST_ID); } private static SQLiteStatement getCountAllCaches() { return getStatement("CountAllLists", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason >= " + StoredList.STANDARD_LIST_ID); } private static SQLiteStatement getInsertLog() { return getStatement("InsertLog", "INSERT INTO " + dbTableLogs + " (geocode, updated, type, author, log, date, found, friend) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); } private static SQLiteStatement getInsertAttribute() { return getStatement("InsertAttribute", "INSERT INTO " + dbTableAttributes + " (geocode, updated, attribute) VALUES (?, ?, ?)"); } private static SQLiteStatement getListIdOfGeocode() { return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE geocode = ?"); } private static SQLiteStatement getListIdOfGuid() { return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE guid = ?"); } private static SQLiteStatement getGeocodeOfGuid() { return getStatement("geocodeFromGuid", "SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?"); } } public static void saveVisitDate(final String geocode) { setVisitDate(Collections.singletonList(geocode), System.currentTimeMillis()); } public static void markDropped(final List<Geocache> caches) { moveToList(caches, StoredList.TEMPORARY_LIST.id); } public static Viewport getBounds(final String geocode) { if (geocode == null) { return null; } return DataStore.getBounds(Collections.singleton(geocode)); } public static void clearVisitDate(final String[] selected) { setVisitDate(Arrays.asList(selected), 0); } public static SearchResult getBatchOfStoredCaches(final Geopoint coords, final CacheType cacheType, final int listId) { final Set<String> geocodes = DataStore.loadBatchOfStoredGeocodes(coords, cacheType, listId); return new SearchResult(geocodes, DataStore.getAllStoredCachesCount(cacheType, listId)); } public static SearchResult getHistoryOfCaches(final boolean detailedOnly, final CacheType cacheType) { final Set<String> geocodes = DataStore.loadBatchOfHistoricGeocodes(detailedOnly, cacheType); return new SearchResult(geocodes, DataStore.getAllHistoryCachesCount()); } public static boolean saveWaypoint(final int id, final String geocode, final Waypoint waypoint) { if (DataStore.saveWaypointInternal(id, geocode, waypoint)) { DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE)); return true; } return false; } public static Set<String> getCachedMissingFromSearch(final SearchResult searchResult, final Set<Tile> tiles, final IConnector connector, final int maxZoom) { // get cached CacheListActivity final Set<String> cachedGeocodes = new HashSet<>(); for (final Tile tile : tiles) { cachedGeocodes.addAll(cacheCache.getInViewport(tile.getViewport(), CacheType.ALL)); } // remove found in search result cachedGeocodes.removeAll(searchResult.getGeocodes()); // check remaining against viewports final Set<String> missingFromSearch = new HashSet<>(); for (final String geocode : cachedGeocodes) { if (connector.canHandle(geocode)) { final Geocache geocache = cacheCache.getCacheFromCache(geocode); // TODO: parallel searches seem to have the potential to make some caches be expunged from the CacheCache (see issue #3716). if (geocache != null && geocache.getCoordZoomLevel() <= maxZoom) { for (final Tile tile : tiles) { if (tile.containsPoint(geocache)) { missingFromSearch.add(geocode); break; } } } } } return missingFromSearch; } public static Cursor findSuggestions(final String searchTerm) { // require 3 characters, otherwise there are to many results if (StringUtils.length(searchTerm) < 3) { return null; } init(); final SearchSuggestionCursor resultCursor = new SearchSuggestionCursor(); try { final String selectionArg = getSuggestionArgument(searchTerm); findCaches(resultCursor, selectionArg); findTrackables(resultCursor, selectionArg); } catch (final Exception e) { Log.e("DataStore.loadBatchOfStoredGeocodes", e); } return resultCursor; } private static void findCaches(final SearchSuggestionCursor resultCursor, final String selectionArg) { final Cursor cursor = database.query( dbTableCaches, new String[] { "geocode", "name", "type" }, "geocode IS NOT NULL AND geocode != '' AND (geocode LIKE ? OR name LIKE ? OR owner LIKE ?)", new String[] { selectionArg, selectionArg, selectionArg }, null, null, "name"); while (cursor.moveToNext()) { final String geocode = cursor.getString(0); final String cacheName = cursor.getString(1); final String type = cursor.getString(2); resultCursor.addCache(geocode, cacheName, type); } cursor.close(); } private static String getSuggestionArgument(final String input) { return "%" + StringUtils.trim(input) + "%"; } private static void findTrackables(final MatrixCursor resultCursor, final String selectionArg) { final Cursor cursor = database.query( dbTableTrackables, new String[] { "tbcode", "title" }, "tbcode IS NOT NULL AND tbcode != '' AND (tbcode LIKE ? OR title LIKE ?)", new String[] { selectionArg, selectionArg }, null, null, "title"); while (cursor.moveToNext()) { final String tbcode = cursor.getString(0); resultCursor.addRow(new String[] { String.valueOf(resultCursor.getCount()), cursor.getString(1), tbcode, Intents.ACTION_TRACKABLE, tbcode, String.valueOf(R.drawable.trackable_all) }); } cursor.close(); } public static String[] getSuggestions(final String table, final String column, final String input) { try { final Cursor cursor = database.rawQuery("SELECT DISTINCT " + column + " FROM " + table + " WHERE " + column + " LIKE ?" + " ORDER BY " + column + " COLLATE NOCASE ASC;", new String[] { getSuggestionArgument(input) }); return cursorToColl(cursor, new LinkedList<String>(), GET_STRING_0).toArray(new String[cursor.getCount()]); } catch (final RuntimeException e) { Log.e("cannot get suggestions from " + table + "->" + column + " for input '" + input + "'", e); return new String[0]; } } public static String[] getSuggestionsOwnerName(final String input) { return getSuggestions(dbTableCaches, "owner_real", input); } public static String[] getSuggestionsTrackableCode(final String input) { return getSuggestions(dbTableTrackables, "tbcode", input); } public static String[] getSuggestionsFinderName(final String input) { return getSuggestions(dbTableLogs, "author", input); } public static String[] getSuggestionsGeocode(final String input) { return getSuggestions(dbTableCaches, "geocode", input); } public static String[] getSuggestionsKeyword(final String input) { return getSuggestions(dbTableCaches, "name", input); } /** * * @return list of last caches opened in the details view, ordered by most recent first */ public static ArrayList<Geocache> getLastOpenedCaches() { final List<String> geocodes = Settings.getLastOpenedCaches(); final Set<Geocache> cachesSet = DataStore.loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB); // order result set by time again final ArrayList<Geocache> caches = new ArrayList<>(cachesSet); Collections.sort(caches, new Comparator<Geocache>() { @Override public int compare(final Geocache lhs, final Geocache rhs) { final int lhsIndex = geocodes.indexOf(lhs.getGeocode()); final int rhsIndex = geocodes.indexOf(rhs.getGeocode()); return lhsIndex < rhsIndex ? -1 : (lhsIndex == rhsIndex ? 0 : 1); } }); return caches; } }
package election.tally; /** Data transfer structure for set of all valid ballots */ public class BallotBox { /** * List of valid ballot papers, already shuffled and mixed by the data loader * or returning officer. */ //@ public invariant \nonnullelements (ballots); // TODO JML warning: array nullity is invariant for assignment protected /*@ non_null spec_public @*/ Ballot[] ballots = new Ballot [Ballot.MAX_BALLOTS]; /** * Get the number of ballots in this box. * * @return the number of ballots in this ballot box */ /*@ public normal_behavior @ ensures 0 <= \result; @ ensures \result == numberOfBallots; @ ensures (ballots == null) ==> \result == 0; @*/ public /*@ pure @*/ int size(){ return numberOfBallots; } /** * The total number of ballots in this ballot box. */ /*@ public invariant 0 <= numberOfBallots; @ public invariant numberOfBallots <= Ballot.MAX_BALLOTS; @ public constraint \old (numberOfBallots) <= numberOfBallots; @*/ protected /*@ spec_public @*/ int numberOfBallots; /** * Number of ballots copied from box */ //@ public initially index == 0; //@ public invariant index <= size(); //@ public constraint \old(index) <= index; protected /*@ spec_public @*/ int index; /** * Create an empty ballot box. */ //@ assignable ballots, index, numberOfBallots; public /*@ pure @*/ BallotBox(){ index = 0; numberOfBallots = 0; final int[] preferences = new int[0]; for (int b=0; b < ballots.length; b++) { // TODO 2009.10.15 ESC assignable warning ballots[b] = new Ballot(preferences); //@ nowarn; } } /** * Accept an anonymous ballot paper. * <p> * The ballot ID number is regenerated. * <p> * @param ballot The ballot paper */ /*@ requires numberOfBallots < ballots.length; @ requires numberOfBallots < Ballot.MAX_BALLOTS; @ requires ballots[numberOfBallots].positionInList == 0; @ ensures \old(numberOfBallots) + 1 == numberOfBallots; @*/ public void accept (final /*@ non_null @*/ int[] preferences) { //@ assert ballots[numberOfBallots] != null; // TODO 2009.10.15 ESC type mismatch warning ballots[numberOfBallots++] = new Ballot(preferences); //@ nowarn; } /** * Is there another ballot paper? * @return <code>true</code>if there is */ //@ ensures \result <==> index < numberOfBallots; public /*@ pure @*/ boolean isNextBallot() { return index < numberOfBallots; } /** * Get the next ballot paper * @return The ballot paper */ //@ requires 0 <= index; //@ requires isNextBallot(); //@ requires index + 1 < ballots.length; //@ assignable index; //@ ensures \result == ballots[\old(index)]; public Ballot getNextBallot() { return ballots[index++]; } }
package cgeo.geocaching; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.connector.gc.Tile; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.LoadFlag; import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.list.AbstractList; import cgeo.geocaching.list.PseudoList; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.search.SearchSuggestionCursor; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.utils.FileUtils; import cgeo.geocaching.utils.Log; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.jdt.annotation.NonNull; import rx.android.observables.AndroidObservable; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.util.async.Async; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Resources; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.MatrixCursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; public class DataStore { private DataStore() { // utility class } public enum StorageLocation { HEAP, CACHE, DATABASE, } private static final Func1<Cursor,String> GET_STRING_0 = new Func1<Cursor, String>() { @Override public String call(final Cursor cursor) { return cursor.getString(0); } }; // Columns and indices for the cache data private static final String QUERY_CACHE_DATA = "SELECT " + "cg_caches.updated," + "cg_caches.reason," + "cg_caches.detailed," + "cg_caches.detailedupdate," + "cg_caches.visiteddate," + "cg_caches.geocode," + "cg_caches.cacheid," + "cg_caches.guid," + "cg_caches.type," + "cg_caches.name," + "cg_caches.owner," + "cg_caches.owner_real," + "cg_caches.hidden," + "cg_caches.hint," + "cg_caches.size," + "cg_caches.difficulty," + "cg_caches.direction," + "cg_caches.distance," + "cg_caches.terrain," + "cg_caches.latlon," + "cg_caches.location," + "cg_caches.personal_note," + "cg_caches.shortdesc," + "cg_caches.favourite_cnt," + "cg_caches.rating," + "cg_caches.votes," + "cg_caches.myvote," + "cg_caches.disabled," + "cg_caches.archived," + "cg_caches.members," + "cg_caches.found," + "cg_caches.favourite," + "cg_caches.inventoryunknown," + "cg_caches.onWatchlist," + "cg_caches.reliable_latlon," + "cg_caches.coordsChanged," + "cg_caches.latitude," + "cg_caches.longitude," + "cg_caches.finalDefined," + "cg_caches._id," + "cg_caches.inventorycoins," + "cg_caches.inventorytags," + "cg_caches.logPasswordRequired"; //TODO: remove "latlon" field from cache table /** The list of fields needed for mapping. */ private static final String[] WAYPOINT_COLUMNS = new String[] { "_id", "geocode", "updated", "type", "prefix", "lookup", "name", "latlon", "latitude", "longitude", "note", "own", "visited" }; /** Number of days (as ms) after temporarily saved caches are deleted */ private final static long DAYS_AFTER_CACHE_IS_DELETED = 3 * 24 * 60 * 60 * 1000; /** * holds the column indexes of the cache table to avoid lookups */ private static CacheCache cacheCache = new CacheCache(); private static SQLiteDatabase database = null; private static final int dbVersion = 68; public static final int customListIdOffset = 10; private static final @NonNull String dbName = "data"; private static final @NonNull String dbTableCaches = "cg_caches"; private static final @NonNull String dbTableLists = "cg_lists"; private static final @NonNull String dbTableAttributes = "cg_attributes"; private static final @NonNull String dbTableWaypoints = "cg_waypoints"; private static final @NonNull String dbTableSpoilers = "cg_spoilers"; private static final @NonNull String dbTableLogs = "cg_logs"; private static final @NonNull String dbTableLogCount = "cg_logCount"; private static final @NonNull String dbTableLogImages = "cg_logImages"; private static final @NonNull String dbTableLogsOffline = "cg_logs_offline"; private static final @NonNull String dbTableTrackables = "cg_trackables"; private static final @NonNull String dbTableSearchDestionationHistory = "cg_search_destination_history"; private static final @NonNull String dbCreateCaches = "" + "create table " + dbTableCaches + " (" + "_id integer primary key autoincrement, " + "updated long not null, " + "detailed integer not null default 0, " + "detailedupdate long, " + "visiteddate long, " + "geocode text unique not null, " + "reason integer not null default 0, " // cached, favorite... + "cacheid text, " + "guid text, " + "type text, " + "name text, " + "owner text, " + "owner_real text, " + "hidden long, " + "hint text, " + "size text, " + "difficulty float, " + "terrain float, " + "latlon text, " + "location text, " + "direction double, " + "distance double, " + "latitude double, " + "longitude double, " + "reliable_latlon integer, " + "personal_note text, " + "shortdesc text, " + "description text, " + "favourite_cnt integer, " + "rating float, " + "votes integer, " + "myvote float, " + "disabled integer not null default 0, " + "archived integer not null default 0, " + "members integer not null default 0, " + "found integer not null default 0, " + "favourite integer not null default 0, " + "inventorycoins integer default 0, " + "inventorytags integer default 0, " + "inventoryunknown integer default 0, " + "onWatchlist integer default 0, " + "coordsChanged integer default 0, " + "finalDefined integer default 0, " + "logPasswordRequired integer default 0" + "); "; private static final String dbCreateLists = "" + "create table " + dbTableLists + " (" + "_id integer primary key autoincrement, " + "title text not null, " + "updated long not null, " + "latitude double, " + "longitude double " + "); "; private static final String dbCreateAttributes = "" + "create table " + dbTableAttributes + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "attribute text " + "); "; private static final String dbCreateWaypoints = "" + "create table " + dbTableWaypoints + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type text not null default 'waypoint', " + "prefix text, " + "lookup text, " + "name text, " + "latlon text, " + "latitude double, " + "longitude double, " + "note text, " + "own integer default 0, " + "visited integer default 0" + "); "; private static final String dbCreateSpoilers = "" + "create table " + dbTableSpoilers + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "url text, " + "title text, " + "description text " + "); "; private static final String dbCreateLogs = "" + "create table " + dbTableLogs + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type integer not null default 4, " + "author text, " + "log text, " + "date long, " + "found integer not null default 0, " + "friend integer " + "); "; private static final String dbCreateLogCount = "" + "create table " + dbTableLogCount + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type integer not null default 4, " + "count integer not null default 0 " + "); "; private static final String dbCreateLogImages = "" + "create table " + dbTableLogImages + " (" + "_id integer primary key autoincrement, " + "log_id integer not null, " + "title text not null, " + "url text not null" + "); "; private static final String dbCreateLogsOffline = "" + "create table " + dbTableLogsOffline + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type integer not null default 4, " + "log text, " + "date long " + "); "; private static final String dbCreateTrackables = "" + "create table " + dbTableTrackables + " (" + "_id integer primary key autoincrement, " + "updated long not null, " // date of save + "tbcode text not null, " + "guid text, " + "title text, " + "owner text, " + "released long, " + "goal text, " + "description text, " + "geocode text " + "); "; private static final String dbCreateSearchDestinationHistory = "" + "create table " + dbTableSearchDestionationHistory + " (" + "_id integer primary key autoincrement, " + "date long not null, " + "latitude double, " + "longitude double " + "); "; private static boolean newlyCreatedDatabase = false; private static boolean databaseCleaned = false; public static void init() { if (database != null) { return; } synchronized(DataStore.class) { if (database != null) { return; } final DbHelper dbHelper = new DbHelper(new DBContext(CgeoApplication.getInstance())); try { database = dbHelper.getWritableDatabase(); } catch (final Exception e) { Log.e("DataStore.init: unable to open database for R/W", e); recreateDatabase(dbHelper); } } } /** * Attempt to recreate the database if opening has failed * * @param dbHelper dbHelper to use to reopen the database */ private static void recreateDatabase(final DbHelper dbHelper) { final File dbPath = databasePath(); final File corruptedPath = new File(LocalStorage.getStorage(), dbPath.getName() + ".corrupted"); if (LocalStorage.copy(dbPath, corruptedPath)) { Log.i("DataStore.init: renamed " + dbPath + " into " + corruptedPath); } else { Log.e("DataStore.init: unable to rename corrupted database"); } try { database = dbHelper.getWritableDatabase(); } catch (final Exception f) { Log.e("DataStore.init: unable to recreate database and open it for R/W", f); } } public static synchronized void closeDb() { if (database == null) { return; } cacheCache.removeAllFromCache(); PreparedStatements.clearPreparedStatements(); database.close(); database = null; } public static File getBackupFileInternal() { return new File(LocalStorage.getStorage(), "cgeo.sqlite"); } public static String backupDatabaseInternal() { if (!LocalStorage.isExternalStorageAvailable()) { Log.w("Database wasn't backed up: no external memory"); return null; } final File target = getBackupFileInternal(); closeDb(); final boolean backupDone = LocalStorage.copy(databasePath(), target); init(); if (!backupDone) { Log.e("Database could not be copied to " + target); return null; } Log.i("Database was copied to " + target); return target.getPath(); } /** * Move the database to/from external cgdata in a new thread, * showing a progress window * * @param fromActivity */ public static void moveDatabase(final Activity fromActivity) { final ProgressDialog dialog = ProgressDialog.show(fromActivity, fromActivity.getString(R.string.init_dbmove_dbmove), fromActivity.getString(R.string.init_dbmove_running), true, false); AndroidObservable.bindActivity(fromActivity, Async.fromCallable(new Func0<Boolean>() { @Override public Boolean call() { if (!LocalStorage.isExternalStorageAvailable()) { Log.w("Database was not moved: external memory not available"); return false; } closeDb(); final File source = databasePath(); final File target = databaseAlternatePath(); if (!LocalStorage.copy(source, target)) { Log.e("Database could not be moved to " + target); init(); return false; } if (!FileUtils.delete(source)) { Log.e("Original database could not be deleted during move"); } Settings.setDbOnSDCard(!Settings.isDbOnSDCard()); Log.i("Database was moved to " + target); init(); return true; } })).subscribeOn(Schedulers.io()).subscribe(new Action1<Boolean>() { @Override public void call(final Boolean success) { dialog.dismiss(); final String message = success ? fromActivity.getString(R.string.init_dbmove_success) : fromActivity.getString(R.string.init_dbmove_failed); Dialogs.message(fromActivity, R.string.init_dbmove_dbmove, message); } }); } private static File databasePath(final boolean internal) { return new File(internal ? LocalStorage.getInternalDbDirectory() : LocalStorage.getExternalDbDirectory(), dbName); } private static File databasePath() { return databasePath(!Settings.isDbOnSDCard()); } private static File databaseAlternatePath() { return databasePath(Settings.isDbOnSDCard()); } public static boolean restoreDatabaseInternal() { if (!LocalStorage.isExternalStorageAvailable()) { Log.w("Database wasn't restored: no external memory"); return false; } final File sourceFile = getBackupFileInternal(); closeDb(); final boolean restoreDone = LocalStorage.copy(sourceFile, databasePath()); init(); if (restoreDone) { Log.i("Database succesfully restored from " + sourceFile.getPath()); } else { Log.e("Could not restore database from " + sourceFile.getPath()); } return restoreDone; } private static class DBContext extends ContextWrapper { public DBContext(final Context base) { super(base); } /** * We override the default open/create as it doesn't work on OS 1.6 and * causes issues on other devices too. */ @Override public SQLiteDatabase openOrCreateDatabase(final String name, final int mode, final CursorFactory factory) { final File file = new File(name); FileUtils.mkdirs(file.getParentFile()); return SQLiteDatabase.openOrCreateDatabase(file, factory); } } private static class DbHelper extends SQLiteOpenHelper { private static boolean firstRun = true; DbHelper(final Context context) { super(context, databasePath().getPath(), null, dbVersion); } @Override public void onCreate(final SQLiteDatabase db) { newlyCreatedDatabase = true; db.execSQL(dbCreateCaches); db.execSQL(dbCreateLists); db.execSQL(dbCreateAttributes); db.execSQL(dbCreateWaypoints); db.execSQL(dbCreateSpoilers); db.execSQL(dbCreateLogs); db.execSQL(dbCreateLogCount); db.execSQL(dbCreateLogImages); db.execSQL(dbCreateLogsOffline); db.execSQL(dbCreateTrackables); db.execSQL(dbCreateSearchDestinationHistory); createIndices(db); } static private void createIndices(final SQLiteDatabase db) { db.execSQL("create index if not exists in_caches_geo on " + dbTableCaches + " (geocode)"); db.execSQL("create index if not exists in_caches_guid on " + dbTableCaches + " (guid)"); db.execSQL("create index if not exists in_caches_lat on " + dbTableCaches + " (latitude)"); db.execSQL("create index if not exists in_caches_lon on " + dbTableCaches + " (longitude)"); db.execSQL("create index if not exists in_caches_reason on " + dbTableCaches + " (reason)"); db.execSQL("create index if not exists in_caches_detailed on " + dbTableCaches + " (detailed)"); db.execSQL("create index if not exists in_caches_type on " + dbTableCaches + " (type)"); db.execSQL("create index if not exists in_caches_visit_detail on " + dbTableCaches + " (visiteddate, detailedupdate)"); db.execSQL("create index if not exists in_attr_geo on " + dbTableAttributes + " (geocode)"); db.execSQL("create index if not exists in_wpts_geo on " + dbTableWaypoints + " (geocode)"); db.execSQL("create index if not exists in_wpts_geo_type on " + dbTableWaypoints + " (geocode, type)"); db.execSQL("create index if not exists in_spoil_geo on " + dbTableSpoilers + " (geocode)"); db.execSQL("create index if not exists in_logs_geo on " + dbTableLogs + " (geocode)"); db.execSQL("create index if not exists in_logcount_geo on " + dbTableLogCount + " (geocode)"); db.execSQL("create index if not exists in_logsoff_geo on " + dbTableLogsOffline + " (geocode)"); db.execSQL("create index if not exists in_trck_geo on " + dbTableTrackables + " (geocode)"); } @Override public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start"); try { if (db.isReadOnly()) { return; } db.beginTransaction(); if (oldVersion <= 0) { // new table dropDatabase(db); onCreate(db); Log.i("Database structure created."); } if (oldVersion > 0) { db.execSQL("delete from " + dbTableCaches + " where reason = 0"); if (oldVersion < 52) { // upgrade to 52 try { db.execSQL(dbCreateSearchDestinationHistory); Log.i("Added table " + dbTableSearchDestionationHistory + "."); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 52", e); } } if (oldVersion < 53) { // upgrade to 53 try { db.execSQL("alter table " + dbTableCaches + " add column onWatchlist integer"); Log.i("Column onWatchlist added to " + dbTableCaches + "."); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 53", e); } } if (oldVersion < 54) { // update to 54 try { db.execSQL(dbCreateLogImages); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 54", e); } } if (oldVersion < 55) { // update to 55 try { db.execSQL("alter table " + dbTableCaches + " add column personal_note text"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 55", e); } } // make all internal attribute names lowercase // @see issue #299 if (oldVersion < 56) { // update to 56 try { db.execSQL("update " + dbTableAttributes + " set attribute = " + "lower(attribute) where attribute like \"%_yes\" " + "or attribute like \"%_no\""); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 56", e); } } // Create missing indices. See issue #435 if (oldVersion < 57) { // update to 57 try { db.execSQL("drop index in_a"); db.execSQL("drop index in_b"); db.execSQL("drop index in_c"); db.execSQL("drop index in_d"); db.execSQL("drop index in_e"); db.execSQL("drop index in_f"); createIndices(db); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 57", e); } } if (oldVersion < 58) { // upgrade to 58 try { db.beginTransaction(); final String dbTableCachesTemp = dbTableCaches + "_temp"; final String dbCreateCachesTemp = "" + "create table " + dbTableCachesTemp + " (" + "_id integer primary key autoincrement, " + "updated long not null, " + "detailed integer not null default 0, " + "detailedupdate long, " + "visiteddate long, " + "geocode text unique not null, " + "reason integer not null default 0, " + "cacheid text, " + "guid text, " + "type text, " + "name text, " + "own integer not null default 0, " + "owner text, " + "owner_real text, " + "hidden long, " + "hint text, " + "size text, " + "difficulty float, " + "terrain float, " + "latlon text, " + "location text, " + "direction double, " + "distance double, " + "latitude double, " + "longitude double, " + "reliable_latlon integer, " + "personal_note text, " + "shortdesc text, " + "description text, " + "favourite_cnt integer, " + "rating float, " + "votes integer, " + "myvote float, " + "disabled integer not null default 0, " + "archived integer not null default 0, " + "members integer not null default 0, " + "found integer not null default 0, " + "favourite integer not null default 0, " + "inventorycoins integer default 0, " + "inventorytags integer default 0, " + "inventoryunknown integer default 0, " + "onWatchlist integer default 0 " + "); "; db.execSQL(dbCreateCachesTemp); db.execSQL("insert into " + dbTableCachesTemp + " select _id,updated,detailed,detailedupdate,visiteddate,geocode,reason,cacheid,guid,type,name,own,owner,owner_real," + "hidden,hint,size,difficulty,terrain,latlon,location,direction,distance,latitude,longitude, 0," + "personal_note,shortdesc,description,favourite_cnt,rating,votes,myvote,disabled,archived,members,found,favourite,inventorycoins," + "inventorytags,inventoryunknown,onWatchlist from " + dbTableCaches); db.execSQL("drop table " + dbTableCaches); db.execSQL("alter table " + dbTableCachesTemp + " rename to " + dbTableCaches); final String dbTableWaypointsTemp = dbTableWaypoints + "_temp"; final String dbCreateWaypointsTemp = "" + "create table " + dbTableWaypointsTemp + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type text not null default 'waypoint', " + "prefix text, " + "lookup text, " + "name text, " + "latlon text, " + "latitude double, " + "longitude double, " + "note text " + "); "; db.execSQL(dbCreateWaypointsTemp); db.execSQL("insert into " + dbTableWaypointsTemp + " select _id, geocode, updated, type, prefix, lookup, name, latlon, latitude, longitude, note from " + dbTableWaypoints); db.execSQL("drop table " + dbTableWaypoints); db.execSQL("alter table " + dbTableWaypointsTemp + " rename to " + dbTableWaypoints); createIndices(db); db.setTransactionSuccessful(); Log.i("Removed latitude_string and longitude_string columns"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 58", e); } finally { db.endTransaction(); } } if (oldVersion < 59) { try { // Add new indices and remove obsolete cache files createIndices(db); removeObsoleteCacheDirectories(db); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 59", e); } } if (oldVersion < 60) { try { removeSecEmptyDirs(); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 60", e); } } if (oldVersion < 61) { try { db.execSQL("alter table " + dbTableLogs + " add column friend integer"); db.execSQL("alter table " + dbTableCaches + " add column coordsChanged integer default 0"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 61", e); } } // Introduces finalDefined on caches and own on waypoints if (oldVersion < 62) { try { db.execSQL("alter table " + dbTableCaches + " add column finalDefined integer default 0"); db.execSQL("alter table " + dbTableWaypoints + " add column own integer default 0"); db.execSQL("update " + dbTableWaypoints + " set own = 1 where type = 'own'"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 62", e); } } if (oldVersion < 63) { try { removeDoubleUnderscoreMapFiles(); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 63", e); } } if (oldVersion < 64) { try { // No cache should ever be stored into the ALL_CACHES list. Here we use hardcoded list ids // rather than symbolic ones because the fix must be applied with the values at the time // of the problem. The problem was introduced in release 2012.06.01. db.execSQL("update " + dbTableCaches + " set reason=1 where reason=2"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 64", e); } } if (oldVersion < 65) { try { // Set all waypoints where name is Original coordinates to type ORIGINAL db.execSQL("update " + dbTableWaypoints + " set type='original', own=0 where name='Original Coordinates'"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 65:", e); } } // Introduces visited feature on waypoints if (oldVersion < 66) { try { db.execSQL("alter table " + dbTableWaypoints + " add column visited integer default 0"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 66", e); } } // issue2662 OC: Leichtes Klettern / Easy climbing if (oldVersion < 67) { try { db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_yes' where geocode like 'OC%' and attribute = 'climbing_yes'"); db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_no' where geocode like 'OC%' and attribute = 'climbing_no'"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 67", e); } } // Introduces logPasswordRequired on caches if (oldVersion < 68) { try { db.execSQL("alter table " + dbTableCaches + " add column logPasswordRequired integer default 0"); } catch (final Exception e) { Log.e("Failed to upgrade to ver. 68", e); } } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": completed"); } @Override public void onOpen(final SQLiteDatabase db) { if (firstRun) { sanityChecks(db); firstRun = false; } } /** * Execute sanity checks that should be performed once per application after the database has been * opened. * * @param db the database to perform sanity checks against */ private static void sanityChecks(final SQLiteDatabase db) { // Check that the history of searches is well formed as some dates seem to be missing according // to NPE traces. final int staleHistorySearches = db.delete(dbTableSearchDestionationHistory, "date is null", null); if (staleHistorySearches > 0) { Log.w(String.format(Locale.getDefault(), "DataStore.dbHelper.onOpen: removed %d bad search history entries", staleHistorySearches)); } } /** * Method to remove static map files with double underscore due to issue#1670 * introduced with release on 2012-05-24. */ private static void removeDoubleUnderscoreMapFiles() { final File[] geocodeDirs = LocalStorage.getStorage().listFiles(); if (ArrayUtils.isNotEmpty(geocodeDirs)) { final FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(final File dir, final String filename) { return filename.startsWith("map_") && filename.contains("__"); } }; for (final File dir : geocodeDirs) { final File[] wrongFiles = dir.listFiles(filter); if (wrongFiles != null) { for (final File wrongFile : wrongFiles) { FileUtils.deleteIgnoringFailure(wrongFile); } } } } } } /** * Remove obsolete cache directories in c:geo private storage. */ public static void removeObsoleteCacheDirectories() { removeObsoleteCacheDirectories(database); } /** * Remove obsolete cache directories in c:geo private storage. * * @param db * the read-write database to use */ private static void removeObsoleteCacheDirectories(final SQLiteDatabase db) { final File[] files = LocalStorage.getStorage().listFiles(); if (ArrayUtils.isNotEmpty(files)) { final Pattern oldFilePattern = Pattern.compile("^[GC|TB|EC|GK|O][A-Z0-9]{4,7}$"); final SQLiteStatement select = db.compileStatement("select count(*) from " + dbTableCaches + " where geocode = ?"); final ArrayList<File> toRemove = new ArrayList<>(files.length); for (final File file : files) { if (file.isDirectory()) { final String geocode = file.getName(); if (oldFilePattern.matcher(geocode).find()) { select.bindString(1, geocode); if (select.simpleQueryForLong() == 0) { toRemove.add(file); } } } } // Use a background thread for the real removal to avoid keeping the database locked // if we are called from within a transaction. new Thread(new Runnable() { @Override public void run() { for (final File dir : toRemove) { Log.i("Removing obsolete cache directory for " + dir.getName()); LocalStorage.deleteDirectory(dir); } } }).start(); } } /* * Remove empty directories created in the secondary storage area. */ private static void removeSecEmptyDirs() { final File[] files = LocalStorage.getStorageSec().listFiles(); if (ArrayUtils.isNotEmpty(files)) { for (final File file : files) { if (file.isDirectory()) { // This will silently fail if the directory is not empty. FileUtils.deleteIgnoringFailure(file); } } } } private static void dropDatabase(final SQLiteDatabase db) { db.execSQL("drop table if exists " + dbTableCaches); db.execSQL("drop table if exists " + dbTableAttributes); db.execSQL("drop table if exists " + dbTableWaypoints); db.execSQL("drop table if exists " + dbTableSpoilers); db.execSQL("drop table if exists " + dbTableLogs); db.execSQL("drop table if exists " + dbTableLogCount); db.execSQL("drop table if exists " + dbTableLogsOffline); db.execSQL("drop table if exists " + dbTableTrackables); } public static boolean isThere(final String geocode, final String guid, final boolean detailed, final boolean checkTime) { init(); long dataUpdated = 0; long dataDetailedUpdate = 0; int dataDetailed = 0; try { Cursor cursor; if (StringUtils.isNotBlank(geocode)) { cursor = database.query( dbTableCaches, new String[]{"detailed", "detailedupdate", "updated"}, "geocode = ?", new String[]{geocode}, null, null, null, "1"); } else if (StringUtils.isNotBlank(guid)) { cursor = database.query( dbTableCaches, new String[]{"detailed", "detailedupdate", "updated"}, "guid = ?", new String[]{guid}, null, null, null, "1"); } else { return false; } if (cursor.moveToFirst()) { dataDetailed = cursor.getInt(0); dataDetailedUpdate = cursor.getLong(1); dataUpdated = cursor.getLong(2); } cursor.close(); } catch (final Exception e) { Log.e("DataStore.isThere", e); } if (detailed && dataDetailed == 0) { // we want details, but these are not stored return false; } if (checkTime && detailed && dataDetailedUpdate < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) { // we want to check time for detailed cache, but data are older than 3 hours return false; } if (checkTime && !detailed && dataUpdated < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) { // we want to check time for short cache, but data are older than 3 hours return false; } // we have some cache return true; } /** is cache stored in one of the lists (not only temporary) */ public static boolean isOffline(final String geocode, final String guid) { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { return false; } init(); try { final SQLiteStatement listId; final String value; if (StringUtils.isNotBlank(geocode)) { listId = PreparedStatements.getListIdOfGeocode(); value = geocode; } else { listId = PreparedStatements.getListIdOfGuid(); value = guid; } synchronized (listId) { listId.bindString(1, value); return listId.simpleQueryForLong() != StoredList.TEMPORARY_LIST_ID; } } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (final Exception e) { Log.e("DataStore.isOffline", e); } return false; } public static String getGeocodeForGuid(final String guid) { if (StringUtils.isBlank(guid)) { return null; } init(); try { final SQLiteStatement description = PreparedStatements.getGeocodeOfGuid(); synchronized (description) { description.bindString(1, guid); return description.simpleQueryForString(); } } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (final Exception e) { Log.e("DataStore.getGeocodeForGuid", e); } return null; } public static String getCacheidForGeocode(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); try { final SQLiteStatement description = PreparedStatements.getCacheIdOfGeocode(); synchronized (description) { description.bindString(1, geocode); return description.simpleQueryForString(); } } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (final Exception e) { Log.e("DataStore.getCacheidForGeocode", e); } return null; } /** * Save/store a cache to the CacheCache * * @param cache * the Cache to save in the CacheCache/DB * @param saveFlags * */ public static void saveCache(final Geocache cache, final EnumSet<LoadFlags.SaveFlag> saveFlags) { saveCaches(Collections.singletonList(cache), saveFlags); } /** * Save/store a cache to the CacheCache * * @param caches * the caches to save in the CacheCache/DB * @param saveFlags * */ public static void saveCaches(final Collection<Geocache> caches, final EnumSet<LoadFlags.SaveFlag> saveFlags) { if (CollectionUtils.isEmpty(caches)) { return; } final ArrayList<String> cachesFromDatabase = new ArrayList<>(); final HashMap<String, Geocache> existingCaches = new HashMap<>(); // first check which caches are in the memory cache for (final Geocache cache : caches) { final String geocode = cache.getGeocode(); final Geocache cacheFromCache = cacheCache.getCacheFromCache(geocode); if (cacheFromCache == null) { cachesFromDatabase.add(geocode); } else { existingCaches.put(geocode, cacheFromCache); } } // then load all remaining caches from the database in one step for (final Geocache cacheFromDatabase : loadCaches(cachesFromDatabase, LoadFlags.LOAD_ALL_DB_ONLY)) { existingCaches.put(cacheFromDatabase.getGeocode(), cacheFromDatabase); } final ArrayList<Geocache> toBeStored = new ArrayList<>(); // Merge with the data already stored in the CacheCache or in the database if // the cache had not been loaded before, and update the CacheCache. // Also, a DB update is required if the merge data comes from the CacheCache // (as it may be more recent than the version in the database), or if the // version coming from the database is different than the version we are entering // into the cache (that includes absence from the database). for (final Geocache cache : caches) { final String geocode = cache.getGeocode(); final Geocache existingCache = existingCaches.get(geocode); final boolean dbUpdateRequired = !cache.gatherMissingFrom(existingCache) || cacheCache.getCacheFromCache(geocode) != null; cache.addStorageLocation(StorageLocation.CACHE); cacheCache.putCacheInCache(cache); // Only save the cache in the database if it is requested by the caller and // the cache contains detailed information. if (saveFlags.contains(SaveFlag.DB) && cache.isDetailed() && dbUpdateRequired) { toBeStored.add(cache); } } for (final Geocache geocache : toBeStored) { storeIntoDatabase(geocache); } } private static boolean storeIntoDatabase(final Geocache cache) { cache.addStorageLocation(StorageLocation.DATABASE); cacheCache.putCacheInCache(cache); Log.d("Saving " + cache.toString() + " (" + cache.getListId() + ") to DB"); final ContentValues values = new ContentValues(); if (cache.getUpdated() == 0) { values.put("updated", System.currentTimeMillis()); } else { values.put("updated", cache.getUpdated()); } values.put("reason", cache.getListId()); values.put("detailed", cache.isDetailed() ? 1 : 0); values.put("detailedupdate", cache.getDetailedUpdate()); values.put("visiteddate", cache.getVisitedDate()); values.put("geocode", cache.getGeocode()); values.put("cacheid", cache.getCacheId()); values.put("guid", cache.getGuid()); values.put("type", cache.getType().id); values.put("name", cache.getName()); values.put("owner", cache.getOwnerDisplayName()); values.put("owner_real", cache.getOwnerUserId()); final Date hiddenDate = cache.getHiddenDate(); if (hiddenDate == null) { values.put("hidden", 0); } else { values.put("hidden", hiddenDate.getTime()); } values.put("hint", cache.getHint()); values.put("size", cache.getSize() == null ? "" : cache.getSize().id); values.put("difficulty", cache.getDifficulty()); values.put("terrain", cache.getTerrain()); values.put("location", cache.getLocation()); values.put("distance", cache.getDistance()); values.put("direction", cache.getDirection()); putCoords(values, cache.getCoords()); values.put("reliable_latlon", cache.isReliableLatLon() ? 1 : 0); values.put("shortdesc", cache.getShortDescription()); values.put("personal_note", cache.getPersonalNote()); values.put("description", cache.getDescription()); values.put("favourite_cnt", cache.getFavoritePoints()); values.put("rating", cache.getRating()); values.put("votes", cache.getVotes()); values.put("myvote", cache.getMyVote()); values.put("disabled", cache.isDisabled() ? 1 : 0); values.put("archived", cache.isArchived() ? 1 : 0); values.put("members", cache.isPremiumMembersOnly() ? 1 : 0); values.put("found", cache.isFound() ? 1 : 0); values.put("favourite", cache.isFavorite() ? 1 : 0); values.put("inventoryunknown", cache.getInventoryItems()); values.put("onWatchlist", cache.isOnWatchlist() ? 1 : 0); values.put("coordsChanged", cache.hasUserModifiedCoords() ? 1 : 0); values.put("finalDefined", cache.hasFinalDefined() ? 1 : 0); values.put("logPasswordRequired", cache.isLogPasswordRequired() ? 1 : 0); init(); //try to update record else insert fresh.. database.beginTransaction(); try { saveAttributesWithoutTransaction(cache); saveWaypointsWithoutTransaction(cache); saveSpoilersWithoutTransaction(cache); saveLogCountsWithoutTransaction(cache); saveInventoryWithoutTransaction(cache.getGeocode(), cache.getInventory()); final int rows = database.update(dbTableCaches, values, "geocode = ?", new String[] { cache.getGeocode() }); if (rows == 0) { // cache is not in the DB, insert it /* long id = */ database.insert(dbTableCaches, null, values); } database.setTransactionSuccessful(); return true; } catch (final Exception e) { Log.e("SaveCache", e); } finally { database.endTransaction(); } return false; } private static void saveAttributesWithoutTransaction(final Geocache cache) { final String geocode = cache.getGeocode(); // The attributes must be fetched first because lazy loading may load // a null set otherwise. final List<String> attributes = cache.getAttributes(); database.delete(dbTableAttributes, "geocode = ?", new String[]{geocode}); if (attributes.isEmpty()) { return; } final SQLiteStatement statement = PreparedStatements.getInsertAttribute(); final long timestamp = System.currentTimeMillis(); for (final String attribute : attributes) { statement.bindString(1, geocode); statement.bindLong(2, timestamp); statement.bindString(3, attribute); statement.executeInsert(); } } /** * Persists the given <code>destination</code> into the database. * * @param destination * a destination to save */ public static void saveSearchedDestination(final Destination destination) { init(); database.beginTransaction(); try { final SQLiteStatement insertDestination = PreparedStatements.getInsertSearchDestination(destination); insertDestination.executeInsert(); database.setTransactionSuccessful(); } catch (final Exception e) { Log.e("Updating searchedDestinations db failed", e); } finally { database.endTransaction(); } } public static boolean saveWaypoints(final Geocache cache) { init(); database.beginTransaction(); try { saveWaypointsWithoutTransaction(cache); database.setTransactionSuccessful(); return true; } catch (final Exception e) { Log.e("saveWaypoints", e); } finally { database.endTransaction(); } return false; } private static void saveWaypointsWithoutTransaction(final Geocache cache) { final String geocode = cache.getGeocode(); final List<Waypoint> waypoints = cache.getWaypoints(); if (CollectionUtils.isNotEmpty(waypoints)) { final ArrayList<String> currentWaypointIds = new ArrayList<>(); final ContentValues values = new ContentValues(); final long timeStamp = System.currentTimeMillis(); for (final Waypoint oneWaypoint : waypoints) { values.clear(); values.put("geocode", geocode); values.put("updated", timeStamp); values.put("type", oneWaypoint.getWaypointType() != null ? oneWaypoint.getWaypointType().id : null); values.put("prefix", oneWaypoint.getPrefix()); values.put("lookup", oneWaypoint.getLookup()); values.put("name", oneWaypoint.getName()); values.put("latlon", oneWaypoint.getLatlon()); putCoords(values, oneWaypoint.getCoords()); values.put("note", oneWaypoint.getNote()); values.put("own", oneWaypoint.isUserDefined() ? 1 : 0); values.put("visited", oneWaypoint.isVisited() ? 1 : 0); if (oneWaypoint.getId() < 0) { final long rowId = database.insert(dbTableWaypoints, null, values); oneWaypoint.setId((int) rowId); } else { database.update(dbTableWaypoints, values, "_id = ?", new String[] { Integer.toString(oneWaypoint.getId(), 10) }); } currentWaypointIds.add(Integer.toString(oneWaypoint.getId())); } removeOutdatedWaypointsOfCache(cache, currentWaypointIds); } } /** * remove all waypoints of the given cache, where the id is not in the given list * * @param cache * @param remainingWaypointIds * ids of waypoints which shall not be deleted */ private static void removeOutdatedWaypointsOfCache(final @NonNull Geocache cache, final @NonNull Collection<String> remainingWaypointIds) { final String idList = StringUtils.join(remainingWaypointIds, ','); database.delete(dbTableWaypoints, "geocode = ? AND _id NOT in (" + idList + ")", new String[] { cache.getGeocode() }); } /** * Save coordinates into a ContentValues * * @param values * a ContentValues to save coordinates in * @param oneWaypoint * coordinates to save, or null to save empty coordinates */ private static void putCoords(final ContentValues values, final Geopoint coords) { values.put("latitude", coords == null ? null : coords.getLatitude()); values.put("longitude", coords == null ? null : coords.getLongitude()); } /** * Retrieve coordinates from a Cursor * * @param cursor * a Cursor representing a row in the database * @param indexLat * index of the latitude column * @param indexLon * index of the longitude column * @return the coordinates, or null if latitude or longitude is null or the coordinates are invalid */ private static Geopoint getCoords(final Cursor cursor, final int indexLat, final int indexLon) { if (cursor.isNull(indexLat) || cursor.isNull(indexLon)) { return null; } return new Geopoint(cursor.getDouble(indexLat), cursor.getDouble(indexLon)); } private static boolean saveWaypointInternal(final int id, final String geocode, final Waypoint waypoint) { if ((StringUtils.isBlank(geocode) && id <= 0) || waypoint == null) { return false; } init(); database.beginTransaction(); boolean ok = false; try { final ContentValues values = new ContentValues(); values.put("geocode", geocode); values.put("updated", System.currentTimeMillis()); values.put("type", waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null); values.put("prefix", waypoint.getPrefix()); values.put("lookup", waypoint.getLookup()); values.put("name", waypoint.getName()); values.put("latlon", waypoint.getLatlon()); putCoords(values, waypoint.getCoords()); values.put("note", waypoint.getNote()); values.put("own", waypoint.isUserDefined() ? 1 : 0); values.put("visited", waypoint.isVisited() ? 1 : 0); if (id <= 0) { final long rowId = database.insert(dbTableWaypoints, null, values); waypoint.setId((int) rowId); ok = true; } else { final int rows = database.update(dbTableWaypoints, values, "_id = " + id, null); ok = rows > 0; } database.setTransactionSuccessful(); } finally { database.endTransaction(); } return ok; } public static boolean deleteWaypoint(final int id) { if (id == 0) { return false; } init(); return database.delete(dbTableWaypoints, "_id = " + id, null) > 0; } private static void saveSpoilersWithoutTransaction(final Geocache cache) { final String geocode = cache.getGeocode(); database.delete(dbTableSpoilers, "geocode = ?", new String[]{geocode}); final List<Image> spoilers = cache.getSpoilers(); if (CollectionUtils.isNotEmpty(spoilers)) { final SQLiteStatement insertSpoiler = PreparedStatements.getInsertSpoiler(); final long timestamp = System.currentTimeMillis(); for (final Image spoiler : spoilers) { insertSpoiler.bindString(1, geocode); insertSpoiler.bindLong(2, timestamp); insertSpoiler.bindString(3, spoiler.getUrl()); insertSpoiler.bindString(4, spoiler.getTitle()); final String description = spoiler.getDescription(); if (description != null) { insertSpoiler.bindString(5, description); } else { insertSpoiler.bindNull(5); } insertSpoiler.executeInsert(); } } } public static void saveLogsWithoutTransaction(final String geocode, final Iterable<LogEntry> logs) { // TODO delete logimages referring these logs database.delete(dbTableLogs, "geocode = ?", new String[]{geocode}); final SQLiteStatement insertLog = PreparedStatements.getInsertLog(); final long timestamp = System.currentTimeMillis(); for (final LogEntry log : logs) { insertLog.bindString(1, geocode); insertLog.bindLong(2, timestamp); insertLog.bindLong(3, log.type.id); insertLog.bindString(4, log.author); insertLog.bindString(5, log.log); insertLog.bindLong(6, log.date); insertLog.bindLong(7, log.found); insertLog.bindLong(8, log.friend ? 1 : 0); final long logId = insertLog.executeInsert(); if (log.hasLogImages()) { final SQLiteStatement insertImage = PreparedStatements.getInsertLogImage(); for (final Image img : log.getLogImages()) { insertImage.bindLong(1, logId); insertImage.bindString(2, img.getTitle()); insertImage.bindString(3, img.getUrl()); insertImage.executeInsert(); } } } } private static void saveLogCountsWithoutTransaction(final Geocache cache) { final String geocode = cache.getGeocode(); database.delete(dbTableLogCount, "geocode = ?", new String[]{geocode}); final Map<LogType, Integer> logCounts = cache.getLogCounts(); if (MapUtils.isNotEmpty(logCounts)) { final Set<Entry<LogType, Integer>> logCountsItems = logCounts.entrySet(); final SQLiteStatement insertLogCounts = PreparedStatements.getInsertLogCounts(); final long timestamp = System.currentTimeMillis(); for (final Entry<LogType, Integer> pair : logCountsItems) { insertLogCounts.bindString(1, geocode); insertLogCounts.bindLong(2, timestamp); insertLogCounts.bindLong(3, pair.getKey().id); insertLogCounts.bindLong(4, pair.getValue()); insertLogCounts.executeInsert(); } } } public static void saveTrackable(final Trackable trackable) { init(); database.beginTransaction(); try { saveInventoryWithoutTransaction(null, Collections.singletonList(trackable)); database.setTransactionSuccessful(); } finally { database.endTransaction(); } } private static void saveInventoryWithoutTransaction(final String geocode, final List<Trackable> trackables) { if (geocode != null) { database.delete(dbTableTrackables, "geocode = ?", new String[]{geocode}); } if (CollectionUtils.isNotEmpty(trackables)) { final ContentValues values = new ContentValues(); final long timeStamp = System.currentTimeMillis(); for (final Trackable trackable : trackables) { final String tbCode = trackable.getGeocode(); if (StringUtils.isNotBlank(tbCode)) { database.delete(dbTableTrackables, "tbcode = ?", new String[] { tbCode }); } values.clear(); if (geocode != null) { values.put("geocode", geocode); } values.put("updated", timeStamp); values.put("tbcode", tbCode); values.put("guid", trackable.getGuid()); values.put("title", trackable.getName()); values.put("owner", trackable.getOwner()); if (trackable.getReleased() != null) { values.put("released", trackable.getReleased().getTime()); } else { values.put("released", 0L); } values.put("goal", trackable.getGoal()); values.put("description", trackable.getDetails()); database.insert(dbTableTrackables, null, values); saveLogsWithoutTransaction(tbCode, trackable.getLogs()); } } } public static Viewport getBounds(final Set<String> geocodes) { if (CollectionUtils.isEmpty(geocodes)) { return null; } final Set<Geocache> caches = loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB); return Viewport.containing(caches); } /** * Load a single Cache. * * @param geocode * The Geocode GCXXXX * @return the loaded cache (if found). Can be null */ public static Geocache loadCache(final String geocode, final EnumSet<LoadFlag> loadFlags) { if (StringUtils.isBlank(geocode)) { throw new IllegalArgumentException("geocode must not be empty"); } final Set<Geocache> caches = loadCaches(Collections.singleton(geocode), loadFlags); return caches.isEmpty() ? null : caches.iterator().next(); } /** * Load caches. * * @param geocodes * @return Set of loaded caches. Never null. */ public static Set<Geocache> loadCaches(final Collection<String> geocodes, final EnumSet<LoadFlag> loadFlags) { if (CollectionUtils.isEmpty(geocodes)) { return new HashSet<>(); } final Set<Geocache> result = new HashSet<>(); final Set<String> remaining = new HashSet<>(geocodes); if (loadFlags.contains(LoadFlag.CACHE_BEFORE)) { for (final String geocode : new HashSet<>(remaining)) { final Geocache cache = cacheCache.getCacheFromCache(geocode); if (cache != null) { result.add(cache); remaining.remove(cache.getGeocode()); } } } if (loadFlags.contains(LoadFlag.DB_MINIMAL) || loadFlags.contains(LoadFlag.ATTRIBUTES) || loadFlags.contains(LoadFlag.WAYPOINTS) || loadFlags.contains(LoadFlag.SPOILERS) || loadFlags.contains(LoadFlag.LOGS) || loadFlags.contains(LoadFlag.INVENTORY) || loadFlags.contains(LoadFlag.OFFLINE_LOG)) { final Set<Geocache> cachesFromDB = loadCachesFromGeocodes(remaining, loadFlags); result.addAll(cachesFromDB); for (final Geocache cache : cachesFromDB) { remaining.remove(cache.getGeocode()); } } if (loadFlags.contains(LoadFlag.CACHE_AFTER)) { for (final String geocode : new HashSet<>(remaining)) { final Geocache cache = cacheCache.getCacheFromCache(geocode); if (cache != null) { result.add(cache); remaining.remove(cache.getGeocode()); } } } if (remaining.size() >= 1) { Log.d("DataStore.loadCaches(" + remaining.toString() + ") returned no results"); } return result; } /** * Load caches. * * @param geocodes * @param loadFlags * @return Set of loaded caches. Never null. */ private static Set<Geocache> loadCachesFromGeocodes(final Set<String> geocodes, final EnumSet<LoadFlag> loadFlags) { if (CollectionUtils.isEmpty(geocodes)) { return Collections.emptySet(); } // do not log the entire collection of geo codes to the debug log. This can be more than 100 KB of text for large lists! init(); final StringBuilder query = new StringBuilder(QUERY_CACHE_DATA); if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) { query.append(',').append(dbTableLogsOffline).append(".log"); } query.append(" FROM ").append(dbTableCaches); if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) { query.append(" LEFT OUTER JOIN ").append(dbTableLogsOffline).append(" ON ( ").append(dbTableCaches).append(".geocode == ").append(dbTableLogsOffline).append(".geocode) "); } query.append(" WHERE ").append(dbTableCaches).append('.'); query.append(DataStore.whereGeocodeIn(geocodes)); final Cursor cursor = database.rawQuery(query.toString(), null); try { final Set<Geocache> caches = new HashSet<>(); int logIndex = -1; while (cursor.moveToNext()) { final Geocache cache = DataStore.createCacheFromDatabaseContent(cursor); if (loadFlags.contains(LoadFlag.ATTRIBUTES)) { cache.setAttributes(loadAttributes(cache.getGeocode())); } if (loadFlags.contains(LoadFlag.WAYPOINTS)) { final List<Waypoint> waypoints = loadWaypoints(cache.getGeocode()); if (CollectionUtils.isNotEmpty(waypoints)) { cache.setWaypoints(waypoints, false); } } if (loadFlags.contains(LoadFlag.SPOILERS)) { final List<Image> spoilers = loadSpoilers(cache.getGeocode()); cache.setSpoilers(spoilers); } if (loadFlags.contains(LoadFlag.LOGS)) { final Map<LogType, Integer> logCounts = loadLogCounts(cache.getGeocode()); if (MapUtils.isNotEmpty(logCounts)) { cache.getLogCounts().clear(); cache.getLogCounts().putAll(logCounts); } } if (loadFlags.contains(LoadFlag.INVENTORY)) { final List<Trackable> inventory = loadInventory(cache.getGeocode()); if (CollectionUtils.isNotEmpty(inventory)) { if (cache.getInventory() == null) { cache.setInventory(new ArrayList<Trackable>()); } else { cache.getInventory().clear(); } cache.getInventory().addAll(inventory); } } if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) { if (logIndex < 0) { logIndex = cursor.getColumnIndex("log"); } cache.setLogOffline(!cursor.isNull(logIndex)); } cache.addStorageLocation(StorageLocation.DATABASE); cacheCache.putCacheInCache(cache); caches.add(cache); } return caches; } finally { cursor.close(); } } /** * Builds a where for a viewport with the size enhanced by 50%. * * @param dbTable * @param viewport * @return */ private static StringBuilder buildCoordinateWhere(final String dbTable, final Viewport viewport) { return viewport.resize(1.5).sqlWhere(dbTable); } /** * creates a Cache from the cursor. Doesn't next. * * @param cursor * @return Cache from DB */ private static Geocache createCacheFromDatabaseContent(final Cursor cursor) { final Geocache cache = new Geocache(); cache.setUpdated(cursor.getLong(0)); cache.setListId(cursor.getInt(1)); cache.setDetailed(cursor.getInt(2) == 1); cache.setDetailedUpdate(cursor.getLong(3)); cache.setVisitedDate(cursor.getLong(4)); cache.setGeocode(cursor.getString(5)); cache.setCacheId(cursor.getString(6)); cache.setGuid(cursor.getString(7)); cache.setType(CacheType.getById(cursor.getString(8))); cache.setName(cursor.getString(9)); cache.setOwnerDisplayName(cursor.getString(10)); cache.setOwnerUserId(cursor.getString(11)); final long dateValue = cursor.getLong(12); if (dateValue != 0) { cache.setHidden(new Date(dateValue)); } // do not set cache.hint cache.setSize(CacheSize.getById(cursor.getString(14))); cache.setDifficulty(cursor.getFloat(15)); int index = 16; if (cursor.isNull(index)) { cache.setDirection(null); } else { cache.setDirection(cursor.getFloat(index)); } index = 17; if (cursor.isNull(index)) { cache.setDistance(null); } else { cache.setDistance(cursor.getFloat(index)); } cache.setTerrain(cursor.getFloat(18)); // do not set cache.location cache.setCoords(getCoords(cursor, 36, 37)); cache.setPersonalNote(cursor.getString(21)); // do not set cache.shortdesc // do not set cache.description cache.setFavoritePoints(cursor.getInt(23)); cache.setRating(cursor.getFloat(24)); cache.setVotes(cursor.getInt(25)); cache.setMyVote(cursor.getFloat(26)); cache.setDisabled(cursor.getInt(27) == 1); cache.setArchived(cursor.getInt(28) == 1); cache.setPremiumMembersOnly(cursor.getInt(29) == 1); cache.setFound(cursor.getInt(30) == 1); cache.setFavorite(cursor.getInt(31) == 1); cache.setInventoryItems(cursor.getInt(32)); cache.setOnWatchlist(cursor.getInt(33) == 1); cache.setReliableLatLon(cursor.getInt(34) > 0); cache.setUserModifiedCoords(cursor.getInt(35) > 0); cache.setFinalDefined(cursor.getInt(38) > 0); cache.setLogPasswordRequired(cursor.getInt(42) > 0); Log.d("Loading " + cache.toString() + " (" + cache.getListId() + ") from DB"); return cache; } public static List<String> loadAttributes(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } return queryToColl(dbTableAttributes, new String[]{"attribute"}, "geocode = ?", new String[]{geocode}, null, null, null, "100", new LinkedList<String>(), GET_STRING_0); } public static Waypoint loadWaypoint(final int id) { if (id == 0) { return null; } init(); final Cursor cursor = database.query( dbTableWaypoints, WAYPOINT_COLUMNS, "_id = ?", new String[]{Integer.toString(id)}, null, null, null, "1"); Log.d("DataStore.loadWaypoint(" + id + ")"); final Waypoint waypoint = cursor.moveToFirst() ? createWaypointFromDatabaseContent(cursor) : null; cursor.close(); return waypoint; } public static List<Waypoint> loadWaypoints(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } return queryToColl(dbTableWaypoints, WAYPOINT_COLUMNS, "geocode = ?", new String[]{geocode}, null, null, "_id", "100", new LinkedList<Waypoint>(), new Func1<Cursor, Waypoint>() { @Override public Waypoint call(final Cursor cursor) { return createWaypointFromDatabaseContent(cursor); } }); } private static Waypoint createWaypointFromDatabaseContent(final Cursor cursor) { final String name = cursor.getString(cursor.getColumnIndex("name")); final WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type"))); final boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0; final Waypoint waypoint = new Waypoint(name, type, own); waypoint.setVisited(cursor.getInt(cursor.getColumnIndex("visited")) != 0); waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id"))); waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode"))); waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix"))); waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup"))); waypoint.setLatlon(cursor.getString(cursor.getColumnIndex("latlon"))); waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude"))); waypoint.setNote(cursor.getString(cursor.getColumnIndex("note"))); return waypoint; } private static List<Image> loadSpoilers(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } return queryToColl(dbTableSpoilers, new String[]{"url", "title", "description"}, "geocode = ?", new String[]{geocode}, null, null, null, "100", new LinkedList<Image>(), new Func1<Cursor, Image>() { @Override public Image call(final Cursor cursor) { return new Image(cursor.getString(0), cursor.getString(1), cursor.getString(2)); } }); } /** * Loads the history of previously entered destinations from * the database. If no destinations exist, an {@link Collections#emptyList()} will be returned. * * @return A list of previously entered destinations or an empty list. */ public static List<Destination> loadHistoryOfSearchedLocations() { return queryToColl(dbTableSearchDestionationHistory, new String[]{"_id", "date", "latitude", "longitude"}, "latitude IS NOT NULL AND longitude IS NOT NULL", null, null, null, "date desc", "100", new LinkedList<Destination>(), new Func1<Cursor, Destination>() { @Override public Destination call(final Cursor cursor) { return new Destination(cursor.getLong(0), cursor.getLong(1), getCoords(cursor, 2, 3)); } }); } public static boolean clearSearchedDestinations() { init(); database.beginTransaction(); try { database.delete(dbTableSearchDestionationHistory, null, null); database.setTransactionSuccessful(); return true; } catch (final Exception e) { Log.e("Unable to clear searched destinations", e); } finally { database.endTransaction(); } return false; } /** * @param geocode * @return an immutable, non null list of logs */ @NonNull public static List<LogEntry> loadLogs(final String geocode) { final List<LogEntry> logs = new ArrayList<>(); if (StringUtils.isBlank(geocode)) { return logs; } init(); final Cursor cursor = database.rawQuery( /* 0 1 2 3 4 5 6 7 8 9 10 */ "SELECT cg_logs._id as cg_logs_id, type, author, log, date, found, friend, " + dbTableLogImages + "._id as cg_logImages_id, log_id, title, url" + " FROM " + dbTableLogs + " LEFT OUTER JOIN " + dbTableLogImages + " ON ( cg_logs._id = log_id ) WHERE geocode = ? ORDER BY date desc, cg_logs._id asc", new String[]{geocode}); LogEntry log = null; while (cursor.moveToNext() && logs.size() < 100) { if (log == null || log.id != cursor.getInt(0)) { log = new LogEntry( cursor.getString(2), cursor.getLong(4), LogType.getById(cursor.getInt(1)), cursor.getString(3)); log.id = cursor.getInt(0); log.found = cursor.getInt(5); log.friend = cursor.getInt(6) == 1; logs.add(log); } if (!cursor.isNull(7)) { log.addLogImage(new Image(cursor.getString(10), cursor.getString(9))); } } cursor.close(); return Collections.unmodifiableList(logs); } public static Map<LogType, Integer> loadLogCounts(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); final Map<LogType, Integer> logCounts = new HashMap<>(); final Cursor cursor = database.query( dbTableLogCount, new String[]{"type", "count"}, "geocode = ?", new String[]{geocode}, null, null, null, "100"); while (cursor.moveToNext()) { logCounts.put(LogType.getById(cursor.getInt(0)), cursor.getInt(1)); } cursor.close(); return logCounts; } private static List<Trackable> loadInventory(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); final List<Trackable> trackables = new ArrayList<>(); final Cursor cursor = database.query( dbTableTrackables, new String[]{"_id", "updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"}, "geocode = ?", new String[]{geocode}, null, null, "title COLLATE NOCASE ASC", "100"); while (cursor.moveToNext()) { trackables.add(createTrackableFromDatabaseContent(cursor)); } cursor.close(); return trackables; } public static Trackable loadTrackable(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); final Cursor cursor = database.query( dbTableTrackables, new String[]{"updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"}, "tbcode = ?", new String[]{geocode}, null, null, null, "1"); final Trackable trackable = cursor.moveToFirst() ? createTrackableFromDatabaseContent(cursor) : null; cursor.close(); return trackable; } private static Trackable createTrackableFromDatabaseContent(final Cursor cursor) { final Trackable trackable = new Trackable(); trackable.setGeocode(cursor.getString(cursor.getColumnIndex("tbcode"))); trackable.setGuid(cursor.getString(cursor.getColumnIndex("guid"))); trackable.setName(cursor.getString(cursor.getColumnIndex("title"))); trackable.setOwner(cursor.getString(cursor.getColumnIndex("owner"))); final String released = cursor.getString(cursor.getColumnIndex("released")); if (released != null) { try { final long releaseMilliSeconds = Long.parseLong(released); trackable.setReleased(new Date(releaseMilliSeconds)); } catch (final NumberFormatException e) { Log.e("createTrackableFromDatabaseContent", e); } } trackable.setGoal(cursor.getString(cursor.getColumnIndex("goal"))); trackable.setDetails(cursor.getString(cursor.getColumnIndex("description"))); trackable.setLogs(loadLogs(trackable.getGeocode())); return trackable; } /** * Number of caches stored for a given type and/or list * * @param cacheType * @param list * @return */ public static int getAllStoredCachesCount(final CacheType cacheType, final int list) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } if (list <= 0) { throw new IllegalArgumentException("list must be > 0"); } init(); try { final StringBuilder sql = new StringBuilder("select count(_id) from " + dbTableCaches + " where detailed = 1"); String typeKey; int reasonIndex; if (cacheType != CacheType.ALL) { sql.append(" and type = ?"); typeKey = cacheType.id; reasonIndex = 2; } else { typeKey = "all_types"; reasonIndex = 1; } String listKey; if (list == PseudoList.ALL_LIST.id) { sql.append(" and reason > 0"); listKey = "all_list"; } else { sql.append(" and reason = ?"); listKey = "list"; } final String key = "CountCaches_" + typeKey + "_" + listKey; final SQLiteStatement compiledStmnt = PreparedStatements.getStatement(key, sql.toString()); if (cacheType != CacheType.ALL) { compiledStmnt.bindString(1, cacheType.id); } if (list != PseudoList.ALL_LIST.id) { compiledStmnt.bindLong(reasonIndex, list); } return (int) compiledStmnt.simpleQueryForLong(); } catch (final Exception e) { Log.e("DataStore.loadAllStoredCachesCount", e); } return 0; } public static int getAllHistoryCachesCount() { init(); try { return (int) PreparedStatements.getCountHistoryCaches().simpleQueryForLong(); } catch (final Exception e) { Log.e("DataStore.getAllHistoricCachesCount", e); } return 0; } private static<T, U extends Collection<? super T>> U queryToColl(@NonNull final String table, final String[] columns, final String selection, final String[] selectionArgs, final String groupBy, final String having, final String orderBy, final String limit, final U result, final Func1<? super Cursor, ? extends T> func) { init(); final Cursor cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); return cursorToColl(cursor, result, func); } private static <T, U extends Collection<? super T>> U cursorToColl(final Cursor cursor, final U result, final Func1<? super Cursor, ? extends T> func) { try { while (cursor.moveToNext()) { result.add(func.call(cursor)); } return result; } finally { cursor.close(); } } /** * Return a batch of stored geocodes. * * @param coords * the current coordinates to sort by distance, or null to sort by geocode * @param cacheType * @param listId * @return a non-null set of geocodes */ private static Set<String> loadBatchOfStoredGeocodes(final Geopoint coords, final CacheType cacheType, final int listId) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } final StringBuilder selection = new StringBuilder(); selection.append("reason "); selection.append(listId != PseudoList.ALL_LIST.id ? "=" + Math.max(listId, 1) : ">= " + StoredList.STANDARD_LIST_ID); selection.append(" and detailed = 1 "); String[] selectionArgs = null; if (cacheType != CacheType.ALL) { selection.append(" and type = ?"); selectionArgs = new String[] { String.valueOf(cacheType.id) }; } try { if (coords != null) { return queryToColl(dbTableCaches, new String[]{"geocode", "(abs(latitude-" + String.format((Locale) null, "%.6f", coords.getLatitude()) + ") + abs(longitude-" + String.format((Locale) null, "%.6f", coords.getLongitude()) + ")) as dif"}, selection.toString(), selectionArgs, null, null, "dif", null, new HashSet<String>(), GET_STRING_0); } return queryToColl(dbTableCaches, new String[] { "geocode" }, selection.toString(), selectionArgs, null, null, "geocode", null, new HashSet<String>(), GET_STRING_0); } catch (final Exception e) { Log.e("DataStore.loadBatchOfStoredGeocodes", e); return Collections.emptySet(); } } private static Set<String> loadBatchOfHistoricGeocodes(final boolean detailedOnly, final CacheType cacheType) { final StringBuilder selection = new StringBuilder("visiteddate > 0"); if (detailedOnly) { selection.append(" and detailed = 1"); } String[] selectionArgs = null; if (cacheType != CacheType.ALL) { selection.append(" and type = ?"); selectionArgs = new String[] { String.valueOf(cacheType.id) }; } try { return queryToColl(dbTableCaches, new String[]{"geocode"}, selection.toString(), selectionArgs, null, null, "visiteddate", null, new HashSet<String>(), GET_STRING_0); } catch (final Exception e) { Log.e("DataStore.loadBatchOfHistoricGeocodes", e); } return Collections.emptySet(); } /** Retrieve all stored caches from DB */ public static SearchResult loadCachedInViewport(final Viewport viewport, final CacheType cacheType) { return loadInViewport(false, viewport, cacheType); } /** Retrieve stored caches from DB with listId >= 1 */ public static SearchResult loadStoredInViewport(final Viewport viewport, final CacheType cacheType) { return loadInViewport(true, viewport, cacheType); } /** * Loads the geocodes of caches in a viewport from CacheCache and/or Database * * @param stored * True - query only stored caches, False - query cached ones as well * @param centerLat * @param centerLon * @param spanLat * @param spanLon * @param cacheType * @return Set with geocodes */ private static SearchResult loadInViewport(final boolean stored, final Viewport viewport, final CacheType cacheType) { final Set<String> geocodes = new HashSet<>(); // if not stored only, get codes from CacheCache as well if (!stored) { geocodes.addAll(cacheCache.getInViewport(viewport, cacheType)); } // viewport limitation final StringBuilder selection = buildCoordinateWhere(dbTableCaches, viewport); // cacheType limitation String[] selectionArgs = null; if (cacheType != CacheType.ALL) { selection.append(" and type = ?"); selectionArgs = new String[] { String.valueOf(cacheType.id) }; } // offline caches only if (stored) { selection.append(" and reason >= " + StoredList.STANDARD_LIST_ID); } try { return new SearchResult(queryToColl(dbTableCaches, new String[]{"geocode"}, selection.toString(), selectionArgs, null, null, null, "500", geocodes, GET_STRING_0)); } catch (final Exception e) { Log.e("DataStore.loadInViewport", e); } return new SearchResult(); } /** * Remove caches with listId = 0 * * @param more * true = all caches false = caches stored 3 days or more before */ public static void clean(final boolean more) { if (databaseCleaned) { return; } Log.d("Database clean: started"); try { Set<String> geocodes = new HashSet<>(); if (more) { queryToColl(dbTableCaches, new String[]{"geocode"}, "reason = 0", null, null, null, null, null, geocodes, GET_STRING_0); } else { final long timestamp = System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED; final String timestampString = Long.toString(timestamp); queryToColl(dbTableCaches, new String[]{"geocode"}, "reason = 0 and detailed < ? and detailedupdate < ? and visiteddate < ?", new String[]{timestampString, timestampString, timestampString}, null, null, null, null, geocodes, GET_STRING_0); } geocodes = exceptCachesWithOfflineLog(geocodes); if (!geocodes.isEmpty()) { Log.d("Database clean: removing " + geocodes.size() + " geocaches from listId=0"); removeCaches(geocodes, LoadFlags.REMOVE_ALL); } // This cleanup needs to be kept in place for about one year so that older log images records are // cleaned. TO BE REMOVED AFTER 2015-03-24. Log.d("Database clean: removing obsolete log images records"); database.delete(dbTableLogImages, "log_id NOT IN (SELECT _id FROM " + dbTableLogs + ")", null); } catch (final Exception e) { Log.w("DataStore.clean", e); } Log.d("Database clean: finished"); databaseCleaned = true; } /** * remove all geocodes from the given list of geocodes where an offline log exists * * @param geocodes * @return */ private static Set<String> exceptCachesWithOfflineLog(final Set<String> geocodes) { if (geocodes.isEmpty()) { return geocodes; } final List<String> geocodesWithOfflineLog = queryToColl(dbTableLogsOffline, new String[] { "geocode" }, null, null, null, null, null, null, new LinkedList<String>(), GET_STRING_0); geocodes.removeAll(geocodesWithOfflineLog); return geocodes; } public static void removeAllFromCache() { // clean up CacheCache cacheCache.removeAllFromCache(); } public static void removeCache(final String geocode, final EnumSet<LoadFlags.RemoveFlag> removeFlags) { removeCaches(Collections.singleton(geocode), removeFlags); } /** * Drop caches from the tables they are stored into, as well as the cache files * * @param geocodes * list of geocodes to drop from cache */ public static void removeCaches(final Set<String> geocodes, final EnumSet<LoadFlags.RemoveFlag> removeFlags) { if (CollectionUtils.isEmpty(geocodes)) { return; } init(); if (removeFlags.contains(RemoveFlag.CACHE)) { for (final String geocode : geocodes) { cacheCache.removeCacheFromCache(geocode); } } if (removeFlags.contains(RemoveFlag.DB)) { // Drop caches from the database final ArrayList<String> quotedGeocodes = new ArrayList<>(geocodes.size()); for (final String geocode : geocodes) { quotedGeocodes.add(DatabaseUtils.sqlEscapeString(geocode)); } final String geocodeList = StringUtils.join(quotedGeocodes.toArray(), ','); final String baseWhereClause = "geocode in (" + geocodeList + ")"; database.beginTransaction(); try { database.delete(dbTableCaches, baseWhereClause, null); database.delete(dbTableAttributes, baseWhereClause, null); database.delete(dbTableSpoilers, baseWhereClause, null); database.delete(dbTableLogImages, "log_id IN (SELECT _id FROM " + dbTableLogs + " WHERE " + baseWhereClause + ")", null); database.delete(dbTableLogs, baseWhereClause, null); database.delete(dbTableLogCount, baseWhereClause, null); database.delete(dbTableLogsOffline, baseWhereClause, null); String wayPointClause = baseWhereClause; if (!removeFlags.contains(RemoveFlag.OWN_WAYPOINTS_ONLY_FOR_TESTING)) { wayPointClause += " and type <> 'own'"; } database.delete(dbTableWaypoints, wayPointClause, null); database.delete(dbTableTrackables, baseWhereClause, null); database.setTransactionSuccessful(); } finally { database.endTransaction(); } // Delete cache directories for (final String geocode : geocodes) { LocalStorage.deleteDirectory(LocalStorage.getStorageDir(geocode)); } } } public static boolean saveLogOffline(final String geocode, final Date date, final LogType type, final String log) { if (StringUtils.isBlank(geocode)) { Log.e("DataStore.saveLogOffline: cannot log a blank geocode"); return false; } if (LogType.UNKNOWN == type && StringUtils.isBlank(log)) { Log.e("DataStore.saveLogOffline: cannot log an unknown log type and no message"); return false; } init(); final ContentValues values = new ContentValues(); values.put("geocode", geocode); values.put("updated", System.currentTimeMillis()); values.put("type", type.id); values.put("log", log); values.put("date", date.getTime()); if (hasLogOffline(geocode)) { final int rows = database.update(dbTableLogsOffline, values, "geocode = ?", new String[] { geocode }); return rows > 0; } final long id = database.insert(dbTableLogsOffline, null, values); return id != -1; } public static LogEntry loadLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); final Cursor cursor = database.query( dbTableLogsOffline, new String[]{"_id", "type", "log", "date"}, "geocode = ?", new String[]{geocode}, null, null, "_id desc", "1"); LogEntry log = null; if (cursor.moveToFirst()) { log = new LogEntry(cursor.getLong(3), LogType.getById(cursor.getInt(1)), cursor.getString(2)); log.id = cursor.getInt(0); } cursor.close(); return log; } public static void clearLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return; } init(); database.delete(dbTableLogsOffline, "geocode = ?", new String[]{geocode}); } public static void clearLogsOffline(final List<Geocache> caches) { if (CollectionUtils.isEmpty(caches)) { return; } init(); final Set<String> geocodes = new HashSet<>(caches.size()); for (final Geocache cache : caches) { geocodes.add(cache.getGeocode()); cache.setLogOffline(false); } database.execSQL(String.format("DELETE FROM %s where %s", dbTableLogsOffline, whereGeocodeIn(geocodes))); } public static boolean hasLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return false; } init(); try { final SQLiteStatement logCount = PreparedStatements.getLogCountOfGeocode(); synchronized (logCount) { logCount.bindString(1, geocode); return logCount.simpleQueryForLong() > 0; } } catch (final Exception e) { Log.e("DataStore.hasLogOffline", e); } return false; } private static void setVisitDate(final List<String> geocodes, final long visitedDate) { if (geocodes.isEmpty()) { return; } init(); database.beginTransaction(); try { final SQLiteStatement setVisit = PreparedStatements.getUpdateVisitDate(); for (final String geocode : geocodes) { setVisit.bindLong(1, visitedDate); setVisit.bindString(2, geocode); setVisit.execute(); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } @NonNull public static List<StoredList> getLists() { init(); final Resources res = CgeoApplication.getInstance().getResources(); final List<StoredList> lists = new ArrayList<>(); lists.add(new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatements.getCountCachesOnStandardList().simpleQueryForLong())); try { final String query = "SELECT l._id as _id, l.title as title, COUNT(c._id) as count" + " FROM " + dbTableLists + " l LEFT OUTER JOIN " + dbTableCaches + " c" + " ON l._id + " + customListIdOffset + " = c.reason" + " GROUP BY l._id" + " ORDER BY l.title COLLATE NOCASE ASC"; lists.addAll(getListsFromCursor(database.rawQuery(query, null))); } catch (final Exception e) { Log.e("DataStore.readLists", e); } return lists; } private static ArrayList<StoredList> getListsFromCursor(final Cursor cursor) { final int indexId = cursor.getColumnIndex("_id"); final int indexTitle = cursor.getColumnIndex("title"); final int indexCount = cursor.getColumnIndex("count"); return cursorToColl(cursor, new ArrayList<StoredList>(), new Func1<Cursor, StoredList>() { @Override public StoredList call(final Cursor cursor) { final int count = indexCount != -1 ? cursor.getInt(indexCount) : 0; return new StoredList(cursor.getInt(indexId) + customListIdOffset, cursor.getString(indexTitle), count); } }); } public static StoredList getList(final int id) { init(); if (id >= customListIdOffset) { final Cursor cursor = database.query( dbTableLists, new String[]{"_id", "title"}, "_id = ? ", new String[] { String.valueOf(id - customListIdOffset) }, null, null, null); final ArrayList<StoredList> lists = getListsFromCursor(cursor); if (!lists.isEmpty()) { return lists.get(0); } } final Resources res = CgeoApplication.getInstance().getResources(); if (id == PseudoList.ALL_LIST.id) { return new StoredList(PseudoList.ALL_LIST.id, res.getString(R.string.list_all_lists), getAllCachesCount()); } // fall back to standard list in case of invalid list id if (id == StoredList.STANDARD_LIST_ID || id >= customListIdOffset) { return new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatements.getCountCachesOnStandardList().simpleQueryForLong()); } return null; } public static int getAllCachesCount() { return (int) PreparedStatements.getCountAllCaches().simpleQueryForLong(); } /** * Create a new list * * @param name * Name * @return new listId */ public static int createList(final String name) { int id = -1; if (StringUtils.isBlank(name)) { return id; } init(); database.beginTransaction(); try { final ContentValues values = new ContentValues(); values.put("title", name); values.put("updated", System.currentTimeMillis()); id = (int) database.insert(dbTableLists, null, values); database.setTransactionSuccessful(); } finally { database.endTransaction(); } return id >= 0 ? id + customListIdOffset : -1; } /** * @param listId * List to change * @param name * New name of list * @return Number of lists changed */ public static int renameList(final int listId, final String name) { if (StringUtils.isBlank(name) || StoredList.STANDARD_LIST_ID == listId) { return 0; } init(); database.beginTransaction(); int count = 0; try { final ContentValues values = new ContentValues(); values.put("title", name); values.put("updated", System.currentTimeMillis()); count = database.update(dbTableLists, values, "_id = " + (listId - customListIdOffset), null); database.setTransactionSuccessful(); } finally { database.endTransaction(); } return count; } /** * Remove a list. Caches in the list are moved to the standard list. * * @param listId * @return true if the list got deleted, false else */ public static boolean removeList(final int listId) { if (listId < customListIdOffset) { return false; } init(); database.beginTransaction(); boolean status = false; try { final int cnt = database.delete(dbTableLists, "_id = " + (listId - customListIdOffset), null); if (cnt > 0) { // move caches from deleted list to standard list final SQLiteStatement moveToStandard = PreparedStatements.getMoveToStandardList(); moveToStandard.bindLong(1, listId); moveToStandard.execute(); status = true; } database.setTransactionSuccessful(); } finally { database.endTransaction(); } return status; } public static void moveToList(final Geocache cache, final int listId) { moveToList(Collections.singletonList(cache), listId); } public static void moveToList(final List<Geocache> caches, final int listId) { final AbstractList list = AbstractList.getListById(listId); if (list == null) { return; } if (!list.isConcrete()) { return; } if (caches.isEmpty()) { return; } init(); final SQLiteStatement move = PreparedStatements.getMoveToList(); database.beginTransaction(); try { for (final Geocache cache : caches) { move.bindLong(1, listId); move.bindString(2, cache.getGeocode()); move.execute(); cache.setListId(listId); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } public static boolean isInitialized() { return database != null; } public static boolean removeSearchedDestination(final Destination destination) { if (destination == null) { return false; } init(); database.beginTransaction(); try { database.delete(dbTableSearchDestionationHistory, "_id = " + destination.getId(), null); database.setTransactionSuccessful(); return true; } catch (final Exception e) { Log.e("Unable to remove searched destination", e); } finally { database.endTransaction(); } return false; } /** * Load the lazily initialized fields of a cache and return them as partial cache (all other fields unset). * * @param geocode * @return */ public static Geocache loadCacheTexts(final String geocode) { final Geocache partial = new Geocache(); // in case of database issues, we still need to return a result to avoid endless loops partial.setDescription(StringUtils.EMPTY); partial.setShortDescription(StringUtils.EMPTY); partial.setHint(StringUtils.EMPTY); partial.setLocation(StringUtils.EMPTY); init(); try { final Cursor cursor = database.query( dbTableCaches, new String[] { "description", "shortdesc", "hint", "location" }, "geocode = ?", new String[] { geocode }, null, null, null, "1"); if (cursor.moveToFirst()) { partial.setDescription(StringUtils.defaultString(cursor.getString(0))); partial.setShortDescription(StringUtils.defaultString(cursor.getString(1))); partial.setHint(StringUtils.defaultString(cursor.getString(2))); partial.setLocation(StringUtils.defaultString(cursor.getString(3))); } cursor.close(); } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (final Exception e) { Log.e("DataStore.getCacheDescription", e); } return partial; } /** * checks if this is a newly created database */ public static boolean isNewlyCreatedDatebase() { return newlyCreatedDatabase; } /** * resets flag for newly created database to avoid asking the user multiple times */ public static void resetNewlyCreatedDatabase() { newlyCreatedDatabase = false; } /** * Creates the WHERE clause for matching multiple geocodes. This automatically converts all given codes to * UPPERCASE. */ private static StringBuilder whereGeocodeIn(final Collection<String> geocodes) { final StringBuilder whereExpr = new StringBuilder("geocode in ("); final Iterator<String> iterator = geocodes.iterator(); while (true) { whereExpr.append(DatabaseUtils.sqlEscapeString(StringUtils.upperCase(iterator.next()))); if (!iterator.hasNext()) { break; } whereExpr.append(','); } return whereExpr.append(')'); } /** * Loads all Waypoints in the coordinate rectangle. * * @param excludeDisabled * @param excludeMine * @param type * @return */ public static Set<Waypoint> loadWaypoints(final Viewport viewport, final boolean excludeMine, final boolean excludeDisabled, final CacheType type) { final StringBuilder where = buildCoordinateWhere(dbTableWaypoints, viewport); if (excludeMine) { where.append(" and ").append(dbTableCaches).append(".found == 0"); } if (excludeDisabled) { where.append(" and ").append(dbTableCaches).append(".disabled == 0"); where.append(" and ").append(dbTableCaches).append(".archived == 0"); } if (type != CacheType.ALL) { where.append(" and ").append(dbTableCaches).append(".type == '").append(type.id).append('\''); } final StringBuilder query = new StringBuilder("SELECT "); for (int i = 0; i < WAYPOINT_COLUMNS.length; i++) { query.append(i > 0 ? ", " : "").append(dbTableWaypoints).append('.').append(WAYPOINT_COLUMNS[i]).append(' '); } query.append(" FROM ").append(dbTableWaypoints).append(", ").append(dbTableCaches).append(" WHERE ").append(dbTableWaypoints) .append(".geocode == ").append(dbTableCaches).append(".geocode and ").append(where) .append(" LIMIT " + (Settings.SHOW_WP_THRESHOLD_MAX * 2)); // Hardcoded limit to avoid memory overflow return cursorToColl(database.rawQuery(query.toString(), null), new HashSet<Waypoint>(), new Func1<Cursor, Waypoint>() { @Override public Waypoint call(final Cursor cursor) { return createWaypointFromDatabaseContent(cursor); } }); } public static void saveChangedCache(final Geocache cache) { DataStore.saveCache(cache, cache.getStorageLocation().contains(StorageLocation.DATABASE) ? LoadFlags.SAVE_ALL : EnumSet.of(SaveFlag.CACHE)); } private static class PreparedStatements { private static HashMap<String, SQLiteStatement> statements = new HashMap<>(); public static SQLiteStatement getMoveToStandardList() { return getStatement("MoveToStandardList", "UPDATE " + dbTableCaches + " SET reason = " + StoredList.STANDARD_LIST_ID + " WHERE reason = ?"); } public static SQLiteStatement getMoveToList() { return getStatement("MoveToList", "UPDATE " + dbTableCaches + " SET reason = ? WHERE geocode = ?"); } public static SQLiteStatement getUpdateVisitDate() { return getStatement("UpdateVisitDate", "UPDATE " + dbTableCaches + " SET visiteddate = ? WHERE geocode = ?"); } public static SQLiteStatement getInsertLogImage() { return getStatement("InsertLogImage", "INSERT INTO " + dbTableLogImages + " (log_id, title, url) VALUES (?, ?, ?)"); } public static SQLiteStatement getInsertLogCounts() { return getStatement("InsertLogCounts", "INSERT INTO " + dbTableLogCount + " (geocode, updated, type, count) VALUES (?, ?, ?, ?)"); } public static SQLiteStatement getInsertSpoiler() { return getStatement("InsertSpoiler", "INSERT INTO " + dbTableSpoilers + " (geocode, updated, url, title, description) VALUES (?, ?, ?, ?, ?)"); } public static SQLiteStatement getInsertSearchDestination(final Destination destination) { final SQLiteStatement statement = getStatement("InsertSearch", "INSERT INTO " + dbTableSearchDestionationHistory + " (date, latitude, longitude) VALUES (?, ?, ?)"); statement.bindLong(1, destination.getDate()); final Geopoint coords = destination.getCoords(); statement.bindDouble(2, coords.getLatitude()); statement.bindDouble(3, coords.getLongitude()); return statement; } private static void clearPreparedStatements() { for (final SQLiteStatement statement : statements.values()) { statement.close(); } statements.clear(); } private static synchronized SQLiteStatement getStatement(final String key, final String query) { SQLiteStatement statement = statements.get(key); if (statement == null) { init(); statement = database.compileStatement(query); statements.put(key, statement); } return statement; } public static SQLiteStatement getCountHistoryCaches() { return getStatement("HistoryCount", "select count(_id) from " + dbTableCaches + " where visiteddate > 0"); } private static SQLiteStatement getLogCountOfGeocode() { return getStatement("LogCountFromGeocode", "SELECT count(_id) FROM " + DataStore.dbTableLogsOffline + " WHERE geocode = ?"); } private static SQLiteStatement getCountCachesOnStandardList() { return getStatement("CountStandardList", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason = " + StoredList.STANDARD_LIST_ID); } private static SQLiteStatement getCountAllCaches() { return getStatement("CountAllLists", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason >= " + StoredList.STANDARD_LIST_ID); } private static SQLiteStatement getInsertLog() { return getStatement("InsertLog", "INSERT INTO " + dbTableLogs + " (geocode, updated, type, author, log, date, found, friend) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); } private static SQLiteStatement getInsertAttribute() { return getStatement("InsertAttribute", "INSERT INTO " + dbTableAttributes + " (geocode, updated, attribute) VALUES (?, ?, ?)"); } private static SQLiteStatement getListIdOfGeocode() { return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE geocode = ?"); } private static SQLiteStatement getListIdOfGuid() { return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE guid = ?"); } private static SQLiteStatement getCacheIdOfGeocode() { return getStatement("cacheIdFromGeocode", "SELECT cacheid FROM " + dbTableCaches + " WHERE geocode = ?"); } private static SQLiteStatement getGeocodeOfGuid() { return getStatement("geocodeFromGuid", "SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?"); } } public static void saveVisitDate(final String geocode) { setVisitDate(Collections.singletonList(geocode), System.currentTimeMillis()); } public static void markDropped(final List<Geocache> caches) { moveToList(caches, StoredList.TEMPORARY_LIST_ID); } public static Viewport getBounds(final String geocode) { if (geocode == null) { return null; } return DataStore.getBounds(Collections.singleton(geocode)); } public static void clearVisitDate(final String[] selected) { setVisitDate(Arrays.asList(selected), 0); } public static SearchResult getBatchOfStoredCaches(final Geopoint coords, final CacheType cacheType, final int listId) { final Set<String> geocodes = DataStore.loadBatchOfStoredGeocodes(coords, cacheType, listId); return new SearchResult(geocodes, DataStore.getAllStoredCachesCount(cacheType, listId)); } public static SearchResult getHistoryOfCaches(final boolean detailedOnly, final CacheType cacheType) { final Set<String> geocodes = DataStore.loadBatchOfHistoricGeocodes(detailedOnly, cacheType); return new SearchResult(geocodes, DataStore.getAllHistoryCachesCount()); } public static boolean saveWaypoint(final int id, final String geocode, final Waypoint waypoint) { if (DataStore.saveWaypointInternal(id, geocode, waypoint)) { DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE)); return true; } return false; } public static Set<String> getCachedMissingFromSearch(final SearchResult searchResult, final Set<Tile> tiles, final IConnector connector, final int maxZoom) { // get cached CacheListActivity final Set<String> cachedGeocodes = new HashSet<>(); for (final Tile tile : tiles) { cachedGeocodes.addAll(cacheCache.getInViewport(tile.getViewport(), CacheType.ALL)); } // remove found in search result cachedGeocodes.removeAll(searchResult.getGeocodes()); // check remaining against viewports final Set<String> missingFromSearch = new HashSet<>(); for (final String geocode : cachedGeocodes) { if (connector.canHandle(geocode)) { final Geocache geocache = cacheCache.getCacheFromCache(geocode); // TODO: parallel searches seem to have the potential to make some caches be expunged from the CacheCache (see issue #3716). if (geocache != null && geocache.getCoordZoomLevel() <= maxZoom) { for (final Tile tile : tiles) { if (tile.containsPoint(geocache)) { missingFromSearch.add(geocode); break; } } } } } return missingFromSearch; } public static Cursor findSuggestions(final String searchTerm) { // require 3 characters, otherwise there are to many results if (StringUtils.length(searchTerm) < 3) { return null; } init(); final SearchSuggestionCursor resultCursor = new SearchSuggestionCursor(); try { final String selectionArg = getSuggestionArgument(searchTerm); findCaches(resultCursor, selectionArg); findTrackables(resultCursor, selectionArg); } catch (final Exception e) { Log.e("DataStore.loadBatchOfStoredGeocodes", e); } return resultCursor; } private static void findCaches(final SearchSuggestionCursor resultCursor, final String selectionArg) { final Cursor cursor = database.query( dbTableCaches, new String[] { "geocode", "name", "type" }, "geocode IS NOT NULL AND geocode != '' AND (geocode LIKE ? OR name LIKE ? OR owner LIKE ?)", new String[] { selectionArg, selectionArg, selectionArg }, null, null, "name"); while (cursor.moveToNext()) { final String geocode = cursor.getString(0); final String cacheName = cursor.getString(1); final String type = cursor.getString(2); resultCursor.addCache(geocode, cacheName, type); } cursor.close(); } private static String getSuggestionArgument(final String input) { return "%" + StringUtils.trim(input) + "%"; } private static void findTrackables(final MatrixCursor resultCursor, final String selectionArg) { final Cursor cursor = database.query( dbTableTrackables, new String[] { "tbcode", "title" }, "tbcode IS NOT NULL AND tbcode != '' AND (tbcode LIKE ? OR title LIKE ?)", new String[] { selectionArg, selectionArg }, null, null, "title"); while (cursor.moveToNext()) { final String tbcode = cursor.getString(0); resultCursor.addRow(new String[] { String.valueOf(resultCursor.getCount()), cursor.getString(1), tbcode, Intents.ACTION_TRACKABLE, tbcode }); } cursor.close(); } public static String[] getSuggestions(final String table, final String column, final String input) { try { final Cursor cursor = database.rawQuery("SELECT DISTINCT " + column + " FROM " + table + " WHERE " + column + " LIKE ?" + " ORDER BY " + column + " COLLATE NOCASE ASC;", new String[] { getSuggestionArgument(input) }); return cursorToColl(cursor, new LinkedList<String>(), GET_STRING_0).toArray(new String[cursor.getCount()]); } catch (final RuntimeException e) { Log.e("cannot get suggestions from " + table + "->" + column + " for input '" + input + "'", e); return new String[0]; } } public static String[] getSuggestionsOwnerName(final String input) { return getSuggestions(dbTableCaches, "owner_real", input); } public static String[] getSuggestionsTrackableCode(final String input) { return getSuggestions(dbTableTrackables, "tbcode", input); } public static String[] getSuggestionsFinderName(final String input) { return getSuggestions(dbTableLogs, "author", input); } public static String[] getSuggestionsGeocode(final String input) { return getSuggestions(dbTableCaches, "geocode", input); } public static String[] getSuggestionsKeyword(final String input) { return getSuggestions(dbTableCaches, "name", input); } /** * * @return list of last caches opened in the details view, ordered by most recent first */ public static ArrayList<Geocache> getLastOpenedCaches() { final List<String> geocodes = Settings.getLastOpenedCaches(); final Set<Geocache> cachesSet = DataStore.loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB); // order result set by time again final ArrayList<Geocache> caches = new ArrayList<>(cachesSet); Collections.sort(caches, new Comparator<Geocache>() { @Override public int compare(final Geocache lhs, final Geocache rhs) { final int lhsIndex = geocodes.indexOf(lhs.getGeocode()); final int rhsIndex = geocodes.indexOf(rhs.getGeocode()); return lhsIndex < rhsIndex ? -1 : (lhsIndex == rhsIndex ? 0 : 1); } }); return caches; } }
import org.eclipse.jetty.websocket.api.Session; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static spark.Spark.*; public class Chat { static Map<Session, String> userUsernameMap = new ConcurrentHashMap<>(); static int nextUserNumber = 1; //Assign to username for next connecting user public static void main(String[] args) { staticFiles.location("/public"); //index.html is served at localhost:4567 (default port) staticFiles.expireTime(600); webSocket("/chat", ChatWebSocketHandler.class); init(); } //Sends a message from one user to all users, along with a list of current usernames public static void broadcastMessage(String sender, String message) { userUsernameMap.keySet().stream().filter(Session::isOpen).forEach(session -> { try { session.getRemote().sendString(String.valueOf(new JSONObject() .put("message", message) .put("sender", sender) .put("timestamp", getTimestampString()) .put("userList", userUsernameMap.values()) )); } catch (Exception e) { e.printStackTrace(); } }); } public static String getTimestampString(){ return new SimpleDateFormat("HH:mm:ss").format(new Date()); } }
import java.awt.*; import java.awt.image.BufferedImage; /** * A pure Java implementation of the Directional Cubic Convoluted Interpolation image scaling algorithm. */ public class Dcci { /** * Scales an image to twice its original width minus one and twice its original height minus one using Directional * Cubic Convoluted Interpolation. * * <p>Using Java built-in nearest neighbor, scale the original image to the final size of twice the original * dimensions minus one. This is a very cheap and fast way to preserve the alpha channel "good enough" and dispose * the pixels the way they need to be. * * <p>Interpolate is called in every pixel that had been over-simplistically interpolated by nearest neighbor to * interpolate it using Directional Cubic Convoluted Interpolation. * * @param original the original BufferedImage, must be at least one pixel * @return a BufferedImage whose size is twice the original dimensions minus one */ private static BufferedImage scale(BufferedImage original) { int newWidth = original.getWidth() * 2 - 1; int newHeight = original.getHeight() * 2 - 1; BufferedImage result = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = result.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); g2.drawImage(original, 0, 0, newWidth, newHeight, null); g2.dispose(); interpolateDiagonalsGaps(result); interpolateRemainingGaps(result); return result; } private static void interpolateDiagonalsGaps(BufferedImage scaledImage) { for (int y = 1; y < scaledImage.getHeight(); y += 2) { for (int x = 1; x < scaledImage.getWidth(); x += 2) { interpolateDiagonalGap(scaledImage, x, y); } } } private static void interpolateRemainingGaps(BufferedImage scaledImage) { for (int y = 0; y < scaledImage.getHeight(); y++) { for (int x = ((y % 2 == 0) ? 1 : 0); x < scaledImage.getWidth(); x += 2) { interpolateRemainingGap(scaledImage, x, y); } } } /** * Evaluates the sum of the RGB channel differences between two RGB values. * * <p>This is equal to |a.r - b.r| + |a.g - b.g| + |a.b - b.b| * * @param rgbA a RGB integer where each 8 bits represent one channel * @param rgbB an RGB integer where each 8 bits represent one channel * @return an integer in the range [0, 765] */ protected static int getRGBChannelsDifferenceSum(int rgbA, int rgbB) { int differenceSum = 0; for (short offset = 0; offset <= 16; offset += 8) { differenceSum += Math.abs(((rgbA >> offset) & 0xFF) - ((rgbB >> offset) & 0xFF)); } return differenceSum; } /** * Evaluates the up-right diagonal strength. Uses the sum of all RGB channels differences. * * @param image a BufferedImage object * @param x the x-coordinate of the point * @param y the y-coordinate of the point * @return an integer that represents the edge strength in this direction */ private static int evaluateD1(BufferedImage image, final int x, final int y) { int d1 = 0; for (int cY = y - 3; cY <= y + 1; cY += 2) { for (int cX = x - 1; cX <= x + 3; cX += 2) { d1 += getRGBChannelsDifferenceSum(image.getRGB(cX, cY), image.getRGB(cX - 2, cY + 2)); } } return d1; } /** * Evaluates the down-right diagonal strength. Uses the sum of all RGB channels differences. * * @param image a BufferedImage object * @param x the x-coordinate of the point * @param y the y-coordinate of the point * @return an integer that represents the edge strength in this direction */ private static int evaluateD2(BufferedImage image, final int x, final int y) { int d2 = 0; for (int cY = y - 3; cY <= y + 1; cY += 2) { for (int cX = x - 3; cX <= x + 1; cX += 2) { d2 += getRGBChannelsDifferenceSum(image.getRGB(cX, cY), image.getRGB(cX + 2, cY + 2)); } } return d2; } private static int getShiftForChannel(int channel) { return 16 - 8 * channel; } /** * Returns the eight bits that correspond to a given channel of the provided RGB integer. * * 0 maps to Red 1 maps to Green 2 maps to Blue */ protected static int getChannel(int rgb, int channel) { return (rgb >> getShiftForChannel(channel)) & 0xFF; } /** * Returns the provided RGB integer with the specified channel set to the provided value. */ protected static int withChannel(int rgb, int channel, int value) { // Unset the bits that will be modified rgb &= ~(0xFF << (getShiftForChannel(channel))); // Set them the provided value int shiftedValue = value << (getShiftForChannel(channel)); // JVM should be smart and reuse the first result return rgb | shiftedValue; } protected static int forceValidRange(int total, int minimum, int maximum) { if (maximum < minimum) { throw new IllegalArgumentException("maximum should not be less than minimum"); } return Math.min(Math.max(total, minimum), maximum); } private static int getInterpolatedRGB(final int[] sources) { int rgb = 0; for (int channel = 0; channel <= 2; channel++) { int total = 0; total -= getChannel(sources[0], channel); total += 9 * getChannel(sources[1], channel); total += 9 * getChannel(sources[2], channel); total -= getChannel(sources[3], channel); total /= 16; total = forceValidRange(total, 0, 255); // total may actually range from -32 to 286 rgb = withChannel(rgb, channel, total); } return rgb; } private static void effectivelyInterpolate(BufferedImage image, final int[] sources, final int x, final int y) { image.setRGB(x, y, getInterpolatedRGB(sources)); } private static int weightedRGBAverage(int rgbA, int rgbB, double aWeight, double bWeight) { int finalRgb = 0; for (int channel = 0; channel <= 2; channel++) { double weightedAverage = aWeight * getChannel(rgbA, channel) + bWeight * getChannel(rgbB, channel); int roundedWeightedAverage = (int) Math.round(weightedAverage); finalRgb = withChannel(finalRgb, channel, forceValidRange(roundedWeightedAverage, 0, 255)); } return finalRgb; } /** * The original paper does not specify how to handle colored images. The solution used here is to sum all RGB * components when calculating edge strength and interpolate over each color channel separately. */ private static void interpolateDiagonalGap(BufferedImage image, final int x, final int y) { // Diagonal edge strength int d1 = evaluateD1(image, x, y); int d2 = evaluateD2(image, x, y); if (100 * (1 + d1) > 115 * (1 + d2)) { // Up-right edge // For an up-right edge, interpolate in the down-right direction downRightInterpolate(image, x, y); } else if (100 * (1 + d2) > 115 * (1 + d1)) { // Down-right edge // For an down-right edge, interpolate in the up-right direction upRightInterpolate(image, x, y); } else { // Smooth area // In the smooth area, edge strength from Up-Right will contribute to the Down-Right sampled pixel, and edge // strength from Down-Right will contribute to the Up-Right sampled pixel. double w1 = 1 / (1 + Math.pow(d1, 5)); double w2 = 1 / (1 + Math.pow(d2, 5)); double downRightWeight = w1 / (w1 + w2); double upRightWeight = w2 / (w1 + w2); smoothDiagonalInterpolate(image, x, y, downRightWeight, upRightWeight); } } private static int[] getDownRightRGB(BufferedImage image, int x, int y) { int[] sourceRgb = new int[4]; sourceRgb[0] = image.getRGB(x - 3, y - 3); sourceRgb[1] = image.getRGB(x - 1, y - 1); sourceRgb[2] = image.getRGB(x + 1, y + 1); sourceRgb[3] = image.getRGB(x + 3, y + 3); return sourceRgb; } private static int[] getUpRightRGB(BufferedImage image, int x, int y) { int[] sourceRgb = new int[4]; sourceRgb[0] = image.getRGB(x + 3, y - 3); sourceRgb[1] = image.getRGB(x + 1, y - 1); sourceRgb[2] = image.getRGB(x - 1, y + 1); sourceRgb[3] = image.getRGB(x - 3, y + 3); return sourceRgb; } private static void downRightInterpolate(BufferedImage image, final int x, final int y) { int[] sourceRgb = getDownRightRGB(image, x, y); effectivelyInterpolate(image, sourceRgb, x, y); } private static void upRightInterpolate(BufferedImage image, int x, int y) { int[] sourceRgb = getUpRightRGB(image, x, y); effectivelyInterpolate(image, sourceRgb, x, y); } private static void smoothDiagonalInterpolate(BufferedImage image, int x, int y, double downRightWeight, double upRightWeight) { int[] upRightRGB = getUpRightRGB(image, x, y); int upRightRGBValue = getInterpolatedRGB(upRightRGB); int[] downRightRGB = getDownRightRGB(image, x, y); int downRightRGBValue = getInterpolatedRGB(downRightRGB); image.setRGB(x, y, weightedRGBAverage(downRightRGBValue, upRightRGBValue, downRightWeight, upRightWeight)); } /** * The original paper does not specify how to handle colored images. The solution used here is to sum all RGB * components when calculating edge strength and interpolate over each color channel separately. */ private static void interpolateRemainingGap(BufferedImage image, final int x, final int y) { // Diagonal edge strength int d1 = evaluateHorizontalWeight(image, x, y); int d2 = evaluateVerticalWeight(image, x, y); if (100 * (1 + d1) > 115 * (1 + d2)) { // Horizontal edge // For a horizontal edge, interpolate vertically. verticalInterpolate(image, x, y); } else if (100 * (1 + d2) > 115 * (1 + d1)) { // Vertical edge // For a vertical edge, interpolate horizontally. horizontalInterpolate(image, x, y); } else { // Smooth area // In the smooth area, edge strength from horizontal will contribute to the vertical sampled pixel, and // edge strength from vertical will contribute to the horizontal sampled pixel. double w1 = 1 / (1 + Math.pow(d1, 5)); double w2 = 1 / (1 + Math.pow(d2, 5)); double verticalWeight = w1 / (w1 + w2); double horizontalWeight = w2 / (w1 + w2); smoothRemainingInterpolate(image, x, y, verticalWeight, horizontalWeight); } } private static int[] getVerticalRGB(BufferedImage image, int x, int y) { int[] sourceRgb = new int[4]; sourceRgb[0] = image.getRGB(x, y - 3); sourceRgb[1] = image.getRGB(x, y - 1); sourceRgb[2] = image.getRGB(x, y + 1); sourceRgb[3] = image.getRGB(x, y + 3); return sourceRgb; } private static int[] getHorizontalRGB(BufferedImage image, int x, int y) { int[] sourceRgb = new int[4]; sourceRgb[0] = image.getRGB(x - 3, y); sourceRgb[1] = image.getRGB(x - 1, y); sourceRgb[2] = image.getRGB(x + 1, y); sourceRgb[3] = image.getRGB(x + 3, y); return sourceRgb; } private static void verticalInterpolate(BufferedImage image, int x, int y) { int[] source = getVerticalRGB(image, x, y); effectivelyInterpolate(image, source, x, y); } private static void horizontalInterpolate(BufferedImage image, int x, int y) { int[] source = getHorizontalRGB(image, x, y); effectivelyInterpolate(image, source, x, y); } private static void smoothRemainingInterpolate(BufferedImage image, int x, int y, double verticalWeight, double horizontalWeight) { int[] verticalRGB = getVerticalRGB(image, x, y); int interpolatedVerticalRGB = getInterpolatedRGB(verticalRGB); int[] horizontalRGB = getHorizontalRGB(image, x, y); int interpolatedHorizontalRGB = getInterpolatedRGB(horizontalRGB); int finalRGB = weightedRGBAverage(interpolatedVerticalRGB, interpolatedHorizontalRGB, verticalWeight, horizontalWeight); image.setRGB(x, y, finalRGB); } private static int evaluateVerticalWeight(BufferedImage image, int x, int y) { int weight = 0; // Could be refactored into a for loop to improve readability. However, I don't know if there is a way to do // so that wouldn't make it too cryptic. // Notice that these operations are exactly the same as the ones in evaluateHorizontalWeight but swapped x and // y modifications. weight += getRGBChannelsDifferenceSum(image.getRGB(x - 2, y + 1), image.getRGB(x - 2, y - 1)); weight += getRGBChannelsDifferenceSum(image.getRGB(x - 1, y + 2), image.getRGB(x - 1, y)); weight += getRGBChannelsDifferenceSum(image.getRGB(x - 1, y), image.getRGB(x - 1, y - 2)); weight += getRGBChannelsDifferenceSum(image.getRGB(x, y + 3), image.getRGB(x, y + 1)); weight += getRGBChannelsDifferenceSum(image.getRGB(x, y + 1), image.getRGB(x, y - 1)); weight += getRGBChannelsDifferenceSum(image.getRGB(x, y - 1), image.getRGB(x, y - 3)); weight += getRGBChannelsDifferenceSum(image.getRGB(x + 1, y + 2), image.getRGB(x + 1, y)); weight += getRGBChannelsDifferenceSum(image.getRGB(x + 1, y), image.getRGB(x + 1, y - 2)); weight += getRGBChannelsDifferenceSum(image.getRGB(x + 2, y + 1), image.getRGB(x + 2, y - 1)); return weight; } private static int evaluateHorizontalWeight(BufferedImage image, int x, int y) { int weight = 0; // Could be refactored into a for loop to improve readability. However, I don't know if there is a way to do // so that wouldn't make it too cryptic. weight += getRGBChannelsDifferenceSum(image.getRGB(x + 1, y - 2), image.getRGB(x - 1, y - 2)); weight += getRGBChannelsDifferenceSum(image.getRGB(x + 2, y - 1), image.getRGB(x, y - 1)); weight += getRGBChannelsDifferenceSum(image.getRGB(x, y - 1), image.getRGB(x - 2, y - 1)); weight += getRGBChannelsDifferenceSum(image.getRGB(x + 3, y), image.getRGB(x + 1, y)); weight += getRGBChannelsDifferenceSum(image.getRGB(x + 1, y), image.getRGB(x - 1, y)); weight += getRGBChannelsDifferenceSum(image.getRGB(x - 1, y), image.getRGB(x - 3, y)); weight += getRGBChannelsDifferenceSum(image.getRGB(x + 2, y + 1), image.getRGB(x, y + 1)); weight += getRGBChannelsDifferenceSum(image.getRGB(x, y + 1), image.getRGB(x - 2, y + 1)); weight += getRGBChannelsDifferenceSum(image.getRGB(x + 1, y + 2), image.getRGB(x - 1, y + 2)); return weight; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.gui; import erp.data.SDataConstants; import erp.data.SDataConstantsSys; import erp.data.SDataReadDescriptions; import erp.data.SDataUtilities; import erp.lib.SLibConstants; import erp.lib.SLibUtilities; import erp.lib.table.STableTabComponent; import erp.lib.table.STableTabInterface; import erp.mod.SModConsts; import erp.mtrn.data.SDataDiog; import erp.mtrn.data.SDataDiogAdjustmentType; import erp.mtrn.data.SDataStockConfig; import erp.mtrn.data.SDataStockConfigDns; import erp.mtrn.data.SDataStockConfigItem; import erp.mtrn.data.SDataStockLot; import erp.mtrn.data.STrnDiogComplement; import erp.mtrn.form.SDialogDiogSaved; import erp.mtrn.form.SDialogRepStock; import erp.mtrn.form.SDialogRepStockMoves; import erp.mtrn.form.SDialogRepStockTrackingLot; import erp.mtrn.form.SDialogUtilStockClosing; import erp.mtrn.form.SFormDiog; import erp.mtrn.form.SFormDiogAdjustmentType; import erp.mtrn.form.SFormStockConfig; import erp.mtrn.form.SFormStockConfigDns; import erp.mtrn.form.SFormStockConfigItem; import erp.mtrn.form.SFormStockLot; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; /** * * @author Sergio Flores */ public class SGuiModuleTrnInv extends erp.lib.gui.SGuiModule implements java.awt.event.ActionListener { private javax.swing.JMenu jmMenuCat; private javax.swing.JMenuItem jmiCatStockLot; private javax.swing.JMenuItem jmiCatStockConfig; private javax.swing.JMenuItem jmiCatStockAdjustmentType; private javax.swing.JMenuItem jmiCatStockConfigItem; private javax.swing.JMenuItem jmiCatStockConfigDns; private javax.swing.JMenu jmMenuDpsPurSup; private javax.swing.JMenuItem jmiDpsPurSupplyPend; private javax.swing.JMenuItem jmiDpsPurSupplyPendEty; private javax.swing.JMenuItem jmiDpsPurSupplied; private javax.swing.JMenuItem jmiDpsPurSuppliedEty; private javax.swing.JMenu jmMenuDpsPurRet; private javax.swing.JMenuItem jmiDpsPurReturnPend; private javax.swing.JMenuItem jmiDpsPurReturnPendEty; private javax.swing.JMenuItem jmiDpsPurReturned; private javax.swing.JMenuItem jmiDpsPurReturnedEty; private javax.swing.JMenu jmMenuDpsSalSup; private javax.swing.JMenuItem jmiDpsSalSupplyPend; private javax.swing.JMenuItem jmiDpsSalSupplyPendEntry; private javax.swing.JMenuItem jmiDpsSalSupplied; private javax.swing.JMenuItem jmiDpsSalSuppliedEntry; private javax.swing.JMenu jmMenuDpsSalRet; private javax.swing.JMenuItem jmiDpsSalReturnPend; private javax.swing.JMenuItem jmiDpsSalReturnPendEntry; private javax.swing.JMenuItem jmiDpsSalReturned; private javax.swing.JMenuItem jmiDpsSalReturnedEntry; private javax.swing.JMenu jmMenuMfg; private javax.swing.JMenuItem jmiMfgPanelProdOrder; private javax.swing.JMenuItem jmiMfgAssignPend; private javax.swing.JMenuItem jmiMfgAssignPendEntry; private javax.swing.JMenuItem jmiMfgAssigned; private javax.swing.JMenuItem jmiMfgAssignedEntry; private javax.swing.JMenuItem jmiMfgFinishPend; private javax.swing.JMenuItem jmiMfgFinishPendEntry; private javax.swing.JMenuItem jmiMfgFinished; private javax.swing.JMenuItem jmiMfgFinishedEntry; private javax.swing.JMenuItem jmiMfgConsumePend; private javax.swing.JMenuItem jmiMfgConsumePendEntry; private javax.swing.JMenuItem jmiMfgConsumed; private javax.swing.JMenuItem jmiMfgConsumedEntry; private javax.swing.JMenu jmMenuIog; private javax.swing.JMenuItem jmiIogStock; private javax.swing.JMenuItem jmiIogMfgRmAssign; private javax.swing.JMenuItem jmiIogMfgRmReturn; private javax.swing.JMenuItem jmiIogMfgWpAssign; private javax.swing.JMenuItem jmiIogMfgWpReturn; private javax.swing.JMenuItem jmiIogMfgFgAssign; private javax.swing.JMenuItem jmiIogMfgFgReturn; private javax.swing.JMenuItem jmiIogMfgConsumeIn; private javax.swing.JMenuItem jmiIogMfgConsumeOut; private javax.swing.JMenuItem jmiIogAuditPending; private javax.swing.JMenuItem jmiIogAudited; private javax.swing.JMenuItem jmiIogInventoryValuation; private javax.swing.JMenuItem jmiIogInventoryMfgCost; private javax.swing.JMenuItem jmiIogStockValueByWarehouse; private javax.swing.JMenuItem jmiIogStockValueByItem; private javax.swing.JMenuItem jmiIogStockValueByDiogType; private javax.swing.JMenuItem jmiIogStockClosing; private javax.swing.JMenu jmMenuStk; private javax.swing.JMenuItem jmiStkStock; private javax.swing.JMenuItem jmiStkStockLot; private javax.swing.JMenuItem jmiStkStockWarehouse; private javax.swing.JMenuItem jmiStkStockWarehouseLot; private javax.swing.JMenuItem jmiStkStockMovements; private javax.swing.JMenuItem jmiStkStockMovementsEntry; private javax.swing.JMenuItem jmiStkStockRotation; private javax.swing.JMenuItem jmiStkStockRotationLot; private javax.swing.JMenu jmMenuRep; private javax.swing.JMenuItem jmiReportStock; private javax.swing.JMenuItem jmiReportStockMoves; private javax.swing.JMenuItem jmiReportStockTrackingLot; private javax.swing.JMenu jmMenuRepStats; private javax.swing.JMenuItem jmiRepStatsMfgConsumePendMass; private javax.swing.JMenuItem jmiRepStatsMfgConsumePendEntryMass; private javax.swing.JMenuItem jmiRepStatsMfgConsumedMass; private javax.swing.JMenuItem jmiRepStatsMfgConsumedEntryMass; private erp.mtrn.form.SDialogDiogSaved moDialogDiogSaved; private erp.mtrn.form.SDialogRepStock moDialogRepStock; private erp.mtrn.form.SDialogRepStockMoves moDialogRepStockMoves; private erp.mtrn.form.SDialogRepStockTrackingLot moDialogRepStockTrackingLot; private erp.mtrn.form.SFormDiog moFormDiog; private erp.mtrn.form.SFormStockLot moFormStockLot; private erp.mtrn.form.SFormStockConfig moFormStockConfig; private erp.mtrn.form.SFormDiogAdjustmentType moFormDiogAdjustmentType; private erp.mtrn.form.SFormStockConfigItem moFormStockConfigItem; private erp.mtrn.form.SFormStockConfigDns moFormStockConfigDns; private erp.mtrn.form.SDialogUtilStockClosing moDialogUtilStockClosing; public SGuiModuleTrnInv(erp.client.SClientInterface client) { super(client, SDataConstants.MOD_INV); initComponents(); } private void initComponents() { boolean hasRightInPur = false; boolean hasRightInSal = false; boolean hasRightInAdj = false; boolean hasRightInMfg = false; boolean hasRightInOtherInt = false; boolean hasRightInOtherExt = false; boolean hasRightOutPur = false; boolean hasRightOutSal = false; boolean hasRightOutAdj = false; boolean hasRightOutMfg = false; boolean hasRightOutOtherInt = false; boolean hasRightOutOtherExt = false; boolean hasRightStock = false; boolean hasRightAudit = false; boolean hasRightReports = false; boolean hasRightMfgRmAsg = false; boolean hasRightMfgRmDev = false; boolean hasRightMfgWpAsg = false; boolean hasRightMfgWpDev = false; boolean hasRightMfgFgAsg = false; boolean hasRightMfgFgDev = false; boolean hasRightMfgCon = false; jmMenuCat = new JMenu("Catálogos"); jmiCatStockLot = new JMenuItem("Lotes"); jmiCatStockConfig = new JMenuItem("Máximos y mínimos"); jmiCatStockAdjustmentType = new JMenuItem("Tipos de ajuste de inventario"); jmiCatStockConfigItem = new JMenuItem("Configuración de ítems por almacén"); jmiCatStockConfigDns = new JMenuItem("Configuración de series docs. de ventas por almacén"); jmMenuCat.add(jmiCatStockLot); jmMenuCat.add(jmiCatStockConfig); jmMenuCat.addSeparator(); jmMenuCat.add(jmiCatStockAdjustmentType); jmMenuCat.add(jmiCatStockConfigItem); jmMenuCat.add(jmiCatStockConfigDns); jmiCatStockLot.addActionListener(this); jmiCatStockConfig.addActionListener(this); jmiCatStockAdjustmentType.addActionListener(this); jmiCatStockConfigItem.addActionListener(this); jmiCatStockConfigDns.addActionListener(this); jmMenuDpsPurSup = new JMenu("Surtidos compras"); jmiDpsPurSupplyPend = new JMenuItem("Compras por surtir"); jmiDpsPurSupplyPendEty = new JMenuItem("Compras por surtir a detalle"); jmiDpsPurSupplied = new JMenuItem("Compras surtidas"); jmiDpsPurSuppliedEty = new JMenuItem("Compras surtidas a detalle"); jmMenuDpsPurSup.add(jmiDpsPurSupplyPend); jmMenuDpsPurSup.add(jmiDpsPurSupplyPendEty); jmMenuDpsPurSup.addSeparator(); jmMenuDpsPurSup.add(jmiDpsPurSupplied); jmMenuDpsPurSup.add(jmiDpsPurSuppliedEty); jmiDpsPurSupplyPend.addActionListener(this); jmiDpsPurSupplyPendEty.addActionListener(this); jmiDpsPurSupplied.addActionListener(this); jmiDpsPurSuppliedEty.addActionListener(this); jmMenuDpsPurRet = new JMenu("Devoluciones compras"); jmiDpsPurReturnPend = new JMenuItem("Compras por devolver"); jmiDpsPurReturnPendEty = new JMenuItem("Compras por devolver a detalle"); jmiDpsPurReturned = new JMenuItem("Compras devueltas"); jmiDpsPurReturnedEty = new JMenuItem("Compras devueltas a detalle"); jmMenuDpsPurRet.add(jmiDpsPurReturnPend); jmMenuDpsPurRet.add(jmiDpsPurReturnPendEty); jmMenuDpsPurRet.addSeparator(); jmMenuDpsPurRet.add(jmiDpsPurReturned); jmMenuDpsPurRet.add(jmiDpsPurReturnedEty); jmiDpsPurReturnPend.addActionListener(this); jmiDpsPurReturnPendEty.addActionListener(this); jmiDpsPurReturned.addActionListener(this); jmiDpsPurReturnedEty.addActionListener(this); jmMenuDpsSalSup = new JMenu("Surtidos ventas"); jmiDpsSalSupplyPend = new JMenuItem("Ventas por surtir"); jmiDpsSalSupplyPendEntry = new JMenuItem("Ventas por surtir a detalle"); jmiDpsSalSupplied = new JMenuItem("Ventas surtidas"); jmiDpsSalSuppliedEntry = new JMenuItem("Ventas surtidas a detalle"); jmMenuDpsSalSup.add(jmiDpsSalSupplyPend); jmMenuDpsSalSup.add(jmiDpsSalSupplyPendEntry); jmMenuDpsSalSup.addSeparator(); jmMenuDpsSalSup.add(jmiDpsSalSupplied); jmMenuDpsSalSup.add(jmiDpsSalSuppliedEntry); jmiDpsSalSupplyPend.addActionListener(this); jmiDpsSalSupplyPendEntry.addActionListener(this); jmiDpsSalSupplied.addActionListener(this); jmiDpsSalSuppliedEntry.addActionListener(this); jmMenuDpsSalRet = new JMenu("Devoluciones ventas"); jmiDpsSalReturnPend = new JMenuItem("Ventas por devolver"); jmiDpsSalReturnPendEntry = new JMenuItem("Ventas por devolver a detalle"); jmiDpsSalReturned = new JMenuItem("Ventas devueltas"); jmiDpsSalReturnedEntry = new JMenuItem("Ventas devueltas a detalle"); jmMenuDpsSalRet.add(jmiDpsSalReturnPend); jmMenuDpsSalRet.add(jmiDpsSalReturnPendEntry); jmMenuDpsSalRet.addSeparator(); jmMenuDpsSalRet.add(jmiDpsSalReturned); jmMenuDpsSalRet.add(jmiDpsSalReturnedEntry); jmiDpsSalReturnPend.addActionListener(this); jmiDpsSalReturnPendEntry.addActionListener(this); jmiDpsSalReturned.addActionListener(this); jmiDpsSalReturnedEntry.addActionListener(this); jmMenuMfg = new JMenu("Movs. producción"); jmiMfgPanelProdOrder = new JMenuItem("Panel movs. producción"); jmiMfgAssignPend = new JMenuItem("Órdenes prod. por asignar"); jmiMfgAssignPendEntry = new JMenuItem("Órdenes prod. por asignar a detalle"); jmiMfgAssigned = new JMenuItem("Órdenes prod. asignadas"); jmiMfgAssignedEntry = new JMenuItem("Órdenes prod. asignadas a detalle"); jmiMfgFinishPend = new JMenuItem("Órdenes prod. por terminar"); jmiMfgFinishPendEntry = new JMenuItem("Órdenes prod. por terminar a detalle"); jmiMfgFinished = new JMenuItem("Órdenes prod. terminadas"); jmiMfgFinishedEntry = new JMenuItem("Órdenes prod. terminadas a detalle"); jmiMfgConsumePend = new JMenuItem("Insumos y productos por consumir"); jmiMfgConsumePendEntry = new JMenuItem("Insumos y productos por consumir a detalle"); jmiMfgConsumed = new JMenuItem("Insumos y productos consumidos"); jmiMfgConsumedEntry = new JMenuItem("Insumos y productos consumidos a detalle"); jmMenuMfg.add(jmiMfgPanelProdOrder); jmMenuMfg.addSeparator(); jmMenuMfg.add(jmiMfgAssignPend); jmMenuMfg.add(jmiMfgAssignPendEntry); jmMenuMfg.addSeparator(); jmMenuMfg.add(jmiMfgAssigned); jmMenuMfg.add(jmiMfgAssignedEntry); jmMenuMfg.addSeparator(); jmMenuMfg.add(jmiMfgFinishPend); jmMenuMfg.add(jmiMfgFinishPendEntry); jmMenuMfg.addSeparator(); jmMenuMfg.add(jmiMfgFinished); jmMenuMfg.add(jmiMfgFinishedEntry); jmMenuMfg.addSeparator(); jmMenuMfg.add(jmiMfgConsumePend); jmMenuMfg.add(jmiMfgConsumePendEntry); jmMenuMfg.addSeparator(); jmMenuMfg.add(jmiMfgConsumed); jmMenuMfg.add(jmiMfgConsumedEntry); jmiMfgPanelProdOrder.addActionListener(this); jmiMfgAssignPend.addActionListener(this); jmiMfgAssignPendEntry.addActionListener(this); jmiMfgAssigned.addActionListener(this); jmiMfgAssignedEntry.addActionListener(this); jmiMfgFinishPend.addActionListener(this); jmiMfgFinishPendEntry.addActionListener(this); jmiMfgFinished.addActionListener(this); jmiMfgFinishedEntry.addActionListener(this); jmiMfgConsumePend.addActionListener(this); jmiMfgConsumePendEntry.addActionListener(this); jmiMfgConsumed.addActionListener(this); jmiMfgConsumedEntry.addActionListener(this); jmMenuIog = new JMenu("Docs. inventarios"); jmiIogStock = new JMenuItem("Docs. inventarios"); jmiIogMfgRmAssign = new JMenuItem("Docs. entrega de materia prima (MP)"); jmiIogMfgRmReturn = new JMenuItem("Docs. devolución de materia prima (MP)"); jmiIogMfgWpAssign = new JMenuItem("Docs. entrega de producto en proceso (PP)"); jmiIogMfgWpReturn = new JMenuItem("Docs. devolución de producto en proceso (PP)"); jmiIogMfgFgAssign = new JMenuItem("Docs. entrega de producto terminado (PT)"); jmiIogMfgFgReturn = new JMenuItem("Docs. devolución de producto terminado (PT)"); jmiIogMfgConsumeIn = new JMenuItem("Docs. entrada por consumo de insumos y productos"); jmiIogMfgConsumeOut = new JMenuItem("Docs. salida por consumo de insumos y productos"); jmiIogAuditPending = new JMenuItem("Docs. inventarios por auditar"); jmiIogAudited = new JMenuItem("Docs. inventarios auditados"); jmiIogInventoryValuation = new JMenuItem("Valuación de inventarios"); jmiIogInventoryMfgCost = new JMenuItem("Costos de producción por producto"); jmiIogStockValueByWarehouse = new JMenuItem("Valor de inventarios por almacén"); jmiIogStockValueByItem = new JMenuItem("Valor de inventarios por ítem"); jmiIogStockValueByDiogType = new JMenuItem("Valor de inventarios por tipo movimiento"); jmiIogStockClosing = new JMenuItem("Generación de inventarios iniciales..."); jmMenuIog.add(jmiIogStock); jmMenuIog.addSeparator(); jmMenuIog.add(jmiIogMfgRmAssign); jmMenuIog.add(jmiIogMfgRmReturn); jmMenuIog.addSeparator(); jmMenuIog.add(jmiIogMfgWpAssign); jmMenuIog.add(jmiIogMfgWpReturn); jmMenuIog.addSeparator(); jmMenuIog.add(jmiIogMfgFgAssign); jmMenuIog.add(jmiIogMfgFgReturn); jmMenuIog.addSeparator(); jmMenuIog.add(jmiIogMfgConsumeIn); jmMenuIog.add(jmiIogMfgConsumeOut); jmMenuIog.addSeparator(); jmMenuIog.add(jmiIogAuditPending); jmMenuIog.add(jmiIogAudited); jmMenuIog.addSeparator(); jmMenuIog.add(jmiIogInventoryValuation); jmMenuIog.add(jmiIogInventoryMfgCost); jmMenuIog.add(jmiIogStockValueByWarehouse); jmMenuIog.add(jmiIogStockValueByItem); //jmMenuIog.add(jmiIogStockValueByDiogType); sflores, 2016-03-09, evaluating to remove it jmMenuIog.addSeparator(); jmMenuIog.add(jmiIogStockClosing); jmiIogStock.addActionListener(this); jmiIogMfgRmAssign.addActionListener(this); jmiIogMfgRmReturn.addActionListener(this); jmiIogMfgWpAssign.addActionListener(this); jmiIogMfgWpReturn.addActionListener(this); jmiIogMfgFgAssign.addActionListener(this); jmiIogMfgFgReturn.addActionListener(this); jmiIogMfgConsumeIn.addActionListener(this); jmiIogMfgConsumeOut.addActionListener(this); jmiIogAuditPending.addActionListener(this); jmiIogAudited.addActionListener(this); jmiIogInventoryValuation.addActionListener(this); jmiIogInventoryMfgCost.addActionListener(this); jmiIogStockValueByWarehouse.addActionListener(this); jmiIogStockValueByItem.addActionListener(this); jmiIogStockValueByDiogType.addActionListener(this); jmiIogStockClosing.addActionListener(this); jmMenuStk = new JMenu("Inventarios"); jmiStkStock = new JMenuItem("Existencias"); jmiStkStockLot = new JMenuItem("Existencias por lote"); jmiStkStockWarehouse = new JMenuItem("Existencias por almacén"); jmiStkStockWarehouseLot = new JMenuItem("Existencias por almacén por lote"); jmiStkStockMovements = new JMenuItem("Movimientos de inventarios"); jmiStkStockMovementsEntry = new JMenuItem("Movimientos de inventarios a detalle"); jmiStkStockRotation = new JMenuItem("Rotación"); jmiStkStockRotationLot = new JMenuItem("Rotación por lote"); jmMenuStk.add(jmiStkStock); jmMenuStk.add(jmiStkStockLot); jmMenuStk.addSeparator(); jmMenuStk.add(jmiStkStockWarehouse); jmMenuStk.add(jmiStkStockWarehouseLot); jmMenuStk.addSeparator(); jmMenuStk.add(jmiStkStockMovements); jmMenuStk.add(jmiStkStockMovementsEntry); jmMenuStk.addSeparator(); jmMenuStk.add(jmiStkStockRotation); jmMenuStk.add(jmiStkStockRotationLot); jmiStkStock.addActionListener(this); jmiStkStockLot.addActionListener(this); jmiStkStockWarehouse.addActionListener(this); jmiStkStockWarehouseLot.addActionListener(this); jmiStkStockMovements.addActionListener(this); jmiStkStockMovementsEntry.addActionListener(this); jmiStkStockRotation.addActionListener(this); jmiStkStockRotationLot.addActionListener(this); jmMenuRep = new JMenu("Reportes"); jmiReportStock = new JMenuItem("Reporte de existencias..."); jmiReportStockMoves = new JMenuItem("Reporte de movimientos de inventarios..."); jmiReportStockTrackingLot = new JMenuItem("Reporte de rastreo de lotes..."); jmMenuRep.add(jmiReportStock); jmMenuRep.add(jmiReportStockMoves); jmMenuRep.add(jmiReportStockTrackingLot); jmiReportStock.addActionListener(this); jmiReportStockMoves.addActionListener(this); jmiReportStockTrackingLot.addActionListener(this); jmMenuRepStats = new JMenu("Estadísticas de producción"); jmiRepStatsMfgConsumePendMass = new JMenuItem("Masa de insumos y productos por consumir"); jmiRepStatsMfgConsumePendEntryMass = new JMenuItem("Masa de insumos y productos por consumir a detalle"); jmiRepStatsMfgConsumedMass = new JMenuItem("Masa de insumos y productos consumidos"); jmiRepStatsMfgConsumedEntryMass = new JMenuItem("Masa de insumos y productos consumidos a detalle"); jmMenuRepStats.add(jmiRepStatsMfgConsumePendMass); jmMenuRepStats.add(jmiRepStatsMfgConsumePendEntryMass); jmMenuRepStats.addSeparator(); jmMenuRepStats.add(jmiRepStatsMfgConsumedMass); jmMenuRepStats.add(jmiRepStatsMfgConsumedEntryMass); jmiRepStatsMfgConsumePendMass.addActionListener(this); jmiRepStatsMfgConsumePendEntryMass.addActionListener(this); jmiRepStatsMfgConsumedMass.addActionListener(this); jmiRepStatsMfgConsumedEntryMass.addActionListener(this); jmMenuRep.addSeparator(); jmMenuRep.add(jmMenuRepStats); hasRightInPur = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_IN_PUR).HasRight; hasRightInSal = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_IN_SAL).HasRight; hasRightInAdj = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_IN_ADJ).HasRight; hasRightInMfg = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_IN_MFG).HasRight; hasRightInOtherInt = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_IN_INT).HasRight; hasRightInOtherExt = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_IN_EXT).HasRight; hasRightOutPur = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_OUT_PUR).HasRight; hasRightOutSal = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_OUT_SAL).HasRight; hasRightOutAdj = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_OUT_ADJ).HasRight; hasRightOutMfg = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_OUT_MFG).HasRight; hasRightOutOtherInt = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_OUT_INT).HasRight; hasRightOutOtherExt = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_OUT_EXT).HasRight; hasRightStock = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_STOCK).HasRight; hasRightAudit = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_AUDIT).HasRight; hasRightReports = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_REP).HasRight; hasRightMfgRmAsg = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_MFG_RM_ASG).HasRight; hasRightMfgRmDev = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_MFG_RM_DEV).HasRight; hasRightMfgWpAsg = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_MFG_WP_ASG).HasRight; hasRightMfgWpDev = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_MFG_WP_DEV).HasRight; hasRightMfgFgAsg = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_MFG_FG_ASG).HasRight; hasRightMfgFgDev = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_MFG_FG_DEV).HasRight; hasRightMfgCon = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_INV_MFG_CON).HasRight; jmMenuCat.setEnabled(hasRightInAdj || hasRightOutAdj || hasRightOutOtherInt); jmMenuDpsPurSup.setEnabled(hasRightInPur); jmMenuDpsPurRet.setEnabled(hasRightOutPur); jmMenuDpsSalSup.setEnabled(hasRightOutSal); jmMenuDpsSalRet.setEnabled(hasRightInSal); jmMenuIog.setEnabled(hasRightInAdj || hasRightOutAdj || hasRightOutOtherInt || hasRightMfgRmAsg || hasRightMfgRmDev || hasRightMfgWpAsg || hasRightMfgWpDev || hasRightMfgFgAsg || hasRightMfgFgDev); jmiIogMfgRmAssign.setEnabled(hasRightMfgRmAsg); jmiIogMfgRmReturn.setEnabled(hasRightMfgRmDev); jmiIogMfgWpAssign.setEnabled(hasRightMfgWpAsg); jmiIogMfgWpReturn.setEnabled(hasRightMfgWpDev); jmiIogMfgFgAssign.setEnabled(hasRightMfgFgAsg); jmiIogMfgFgReturn.setEnabled(hasRightMfgFgDev); jmiIogMfgConsumeIn.setEnabled(hasRightMfgCon); jmiIogMfgConsumeOut.setEnabled(hasRightMfgCon); jmiIogAuditPending.setEnabled(hasRightAudit); jmiIogAudited.setEnabled(hasRightAudit); jmiIogInventoryValuation.setEnabled(hasRightInAdj || hasRightOutAdj); jmiIogInventoryMfgCost.setEnabled(hasRightInAdj || hasRightOutAdj); jmiIogStockValueByWarehouse.setEnabled(hasRightInAdj || hasRightOutAdj); jmiIogStockValueByItem.setEnabled(hasRightInAdj || hasRightOutAdj); jmiIogStockValueByDiogType.setEnabled(hasRightInAdj || hasRightOutAdj); jmiIogStockClosing.setEnabled(hasRightInAdj || hasRightOutAdj); jmMenuMfg.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev || hasRightMfgWpAsg || hasRightMfgWpDev || hasRightMfgFgAsg || hasRightMfgFgDev); jmiMfgPanelProdOrder.setEnabled(true); jmiMfgAssignPend.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev); jmiMfgAssignPendEntry.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev); jmiMfgAssigned.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev); jmiMfgAssignedEntry.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev); jmiMfgFinishPend.setEnabled(hasRightMfgWpAsg || hasRightMfgWpDev || hasRightMfgFgAsg || hasRightMfgFgDev); jmiMfgFinishPendEntry.setEnabled(hasRightMfgWpAsg || hasRightMfgWpDev || hasRightMfgFgAsg || hasRightMfgFgDev); jmiMfgFinishPendEntry.setEnabled(false); // not implemented yet jmiMfgFinished.setEnabled(hasRightMfgWpAsg || hasRightMfgWpDev || hasRightMfgFgAsg || hasRightMfgFgDev); jmiMfgFinishedEntry.setEnabled(hasRightMfgWpAsg || hasRightMfgWpDev || hasRightMfgFgAsg || hasRightMfgFgDev); jmiMfgFinishedEntry.setEnabled(false); // not implemented yet jmiMfgConsumePend.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev); jmiMfgConsumePendEntry.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev); jmiMfgConsumed.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev); jmiMfgConsumedEntry.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev); jmMenuStk.setEnabled(hasRightStock); jmMenuRep.setEnabled(hasRightReports); jmMenuRepStats.setEnabled(hasRightMfgRmAsg || hasRightMfgRmDev); moDialogDiogSaved = new SDialogDiogSaved(miClient); moDialogUtilStockClosing = new SDialogUtilStockClosing(miClient); } private void menuRepStock() { if (moDialogRepStock == null) { moDialogRepStock = new SDialogRepStock(miClient); } moDialogRepStock.formRefreshCatalogues(); moDialogRepStock.formReset(); moDialogRepStock.setFormVisible(true); } private void menuRepStockMoves() { if (moDialogRepStockMoves == null) { moDialogRepStockMoves = new SDialogRepStockMoves(miClient); } moDialogRepStockMoves.formRefreshCatalogues(); moDialogRepStockMoves.formReset(); moDialogRepStockMoves.setFormVisible(true); } private void menuRepStockTrackingLot() { if (moDialogRepStockTrackingLot == null) { moDialogRepStockTrackingLot = new SDialogRepStockTrackingLot(miClient); } moDialogRepStockTrackingLot.formRefreshCatalogues(); moDialogRepStockTrackingLot.formReset(); moDialogRepStockTrackingLot.setFormVisible(true); } private void showPanelProdOrder(int panelType) { int index = 0; int count = 0; boolean exists = false; String title = ""; STableTabInterface tableTab = null; count = miClient.getTabbedPane().getTabCount(); for (index = 0; index < count; index++) { if (miClient.getTabbedPane().getComponentAt(index) instanceof STableTabInterface) { tableTab = (STableTabInterface) miClient.getTabbedPane().getComponentAt(index); if (tableTab.getTabType() == panelType && tableTab.getTabTypeAux01() == SLibConstants.UNDEFINED && tableTab.getTabTypeAux02() == SLibConstants.UNDEFINED) { exists = true; break; } } } if (exists) { miClient.getTabbedPane().setSelectedIndex(index); } else { switch (panelType) { case SDataConstants.TRNX_MFG_ORD: title = "Panel - Movs. prod."; tableTab = new SPanelInvProdOrder(miClient); break; default: tableTab = null; miClient.showMsgBoxWarning(SLibConstants.MSG_ERR_UTIL_UNKNOWN_VIEW); } if (tableTab != null) { miClient.getTabbedPane().addTab(title, (JComponent) tableTab); miClient.getTabbedPane().setTabComponentAt(count, new STableTabComponent(miClient.getTabbedPane(), miClient.getImageIcon(mnModuleType))); miClient.getTabbedPane().setSelectedIndex(count); } } } private int showForm(int formType, int auxType, java.lang.Object pk, boolean isCopy) { int result = SLibConstants.UNDEFINED; SDataDiog iog = null; STrnDiogComplement iogComplement = null; try { clearFormMembers(); setFrameWaitCursor(); switch (formType) { case SDataConstants.TRN_DIOG: if (moFormDiog == null) { moFormDiog = new SFormDiog(miClient); } if (pk != null) { moRegistry = new SDataDiog(); } if (moFormComplement != null) { iogComplement = (STrnDiogComplement) moFormComplement; moFormDiog.formReset(); moFormDiog.setParamIogTypeKey(iogComplement.getDiogTypeKey()); moFormDiog.setParamDpsSource(iogComplement.getDpsSource()); moFormDiog.setParamProdOrderSource(iogComplement.getProdOrderKey()); } miForm = moFormDiog; break; case SDataConstants.TRN_LOT: if (moFormStockLot == null) { moFormStockLot = new SFormStockLot(miClient); } if (pk != null) { moRegistry = new SDataStockLot(); } miForm = moFormStockLot; break; case SDataConstants.TRN_STK_CFG: if (moFormStockConfig == null) { moFormStockConfig = new SFormStockConfig(miClient); } if (pk != null) { moRegistry = new SDataStockConfig(); } miForm = moFormStockConfig; break; case SDataConstants.TRNU_TP_IOG_ADJ: if (moFormDiogAdjustmentType == null) { moFormDiogAdjustmentType = new SFormDiogAdjustmentType(miClient); } if (pk != null) { moRegistry = new SDataDiogAdjustmentType(); } miForm = moFormDiogAdjustmentType; break; case SDataConstants.TRN_STK_CFG_ITEM: if (moFormStockConfigItem == null) { moFormStockConfigItem = new SFormStockConfigItem(miClient); } if (pk != null) { moRegistry = new SDataStockConfigItem(); } miForm = moFormStockConfigItem; break; case SDataConstants.TRN_STK_CFG_DNS: if (moFormStockConfigDns == null) { moFormStockConfigDns = new SFormStockConfigDns(miClient); } if (pk != null) { moRegistry = new SDataStockConfigDns(); } miForm = moFormStockConfigDns; break; default: throw new Exception(SLibConstants.MSG_ERR_UTIL_UNKNOWN_FORM); } result = processForm(pk, isCopy); if (result == SLibConstants.DB_ACTION_SAVE_OK) { switch (formType) { case SDataConstants.TRN_DIOG: iog = (SDataDiog) SDataUtilities.readRegistry(miClient, SDataConstants.TRN_DIOG, getLastSavedPrimaryKey(), SLibConstants.EXEC_MODE_VERBOSE); if (iog.getUserNewTs().getTime() == iog.getUserEditTs().getTime()) { moDialogDiogSaved.formReset(); moDialogDiogSaved.setFormParams(iog); moDialogDiogSaved.setVisible(true); } break; default: } } clearFormComplement(); } catch (java.lang.Exception e) { SLibUtilities.renderException(this, e); } finally { restoreFrameCursor(); } return result; } @Override public void showView(int viewType) { showView(viewType, 0, 0); } @Override public void showView(int viewType, int auxType) { showView(viewType, auxType, 0); } @Override public void showView(int viewType, int auxType01, int auxType02) { String sViewTitle = ""; Class oViewClass = null; try { setFrameWaitCursor(); switch (viewType) { case SDataConstants.TRN_LOT: oViewClass = erp.mtrn.view.SViewStockLot.class; sViewTitle = "Lotes"; break; case SDataConstants.TRN_STK_CFG: oViewClass = erp.mtrn.view.SViewStockConfig.class; sViewTitle = "Máximos y mínimos"; break; case SDataConstants.TRNU_TP_IOG_ADJ: oViewClass = erp.mtrn.view.SViewDiogAdjustmentType.class; sViewTitle = "Tipos ajuste inventario"; break; case SDataConstants.TRN_STK_CFG_ITEM: oViewClass = erp.mtrn.view.SViewStockConfigItem.class; sViewTitle = "Config. ítems x almacén "; break; case SDataConstants.TRN_STK_CFG_DNS: oViewClass = erp.mtrn.view.SViewStockConfigDns.class; sViewTitle = "Config. series docs. ventas x almacén "; break; case SDataConstants.TRN_STK: oViewClass = erp.mtrn.view.SViewStock.class; switch (auxType01) { case SDataConstants.TRNX_STK_STK: sViewTitle = "Existencias"; break; case SDataConstants.TRNX_STK_STK_WH: sViewTitle = "Existencias x almacén"; break; case SDataConstants.TRNX_STK_LOT: sViewTitle = "Existencias x lote"; break; case SDataConstants.TRNX_STK_LOT_WH: sViewTitle = "Existencias x almacén x lote"; break; default: throw new Exception(SLibConstants.MSG_ERR_UTIL_UNKNOWN_VIEW); } break; case SDataConstants.TRNX_STK_MOVES: oViewClass = erp.mtrn.view.SViewStockMoves.class; sViewTitle = "Movimientos inventarios"; break; case SDataConstants.TRNX_STK_MOVES_ETY: oViewClass = erp.mtrn.view.SViewStockMovesEntry.class; sViewTitle = "Movimientos inventarios (detalle)"; break; case SDataConstants.TRNX_STK_ROTATION: oViewClass = erp.mtrn.view.SViewStockRotation.class; switch (auxType01) { case SDataConstants.TRNX_STK_STK: sViewTitle = "Rotación"; break; case SDataConstants.TRNX_STK_LOT: sViewTitle = "Rotación x lote"; break; default: throw new Exception(SLibConstants.MSG_ERR_UTIL_UNKNOWN_VIEW); } break; case SDataConstants.TRNX_STK_COMSUME: oViewClass = erp.mtrn.view.SViewDpsStockConsume.class; switch (auxType01) { case SDataConstantsSys.TRNS_CT_DPS_PUR: sViewTitle = "Consumo compras"; break; case SDataConstantsSys.TRNS_CT_DPS_SAL: sViewTitle = "Consumo ventas"; break; default: throw new Exception(SLibConstants.MSG_ERR_UTIL_UNKNOWN_VIEW); } break; case SDataConstants.TRNX_DPS_SUPPLY_PEND: oViewClass = erp.mtrn.view.SViewDpsStockSupply.class; sViewTitle = auxType01 == SDataConstantsSys.TRNS_CT_DPS_PUR ? "Compras x surtir" : "Ventas x surtir"; break; case SDataConstants.TRNX_DPS_SUPPLY_PEND_ETY: oViewClass = erp.mtrn.view.SViewDpsStockSupply.class; sViewTitle = auxType01 == SDataConstantsSys.TRNS_CT_DPS_PUR ? "Compras x surtir (detalle)" : "Ventas x surtir (detalle)"; break; case SDataConstants.TRNX_DPS_SUPPLIED: oViewClass = erp.mtrn.view.SViewDpsStockSupply.class; sViewTitle = auxType01 == SDataConstantsSys.TRNS_CT_DPS_PUR ? "Compras surtidas" : "Ventas surtidas"; break; case SDataConstants.TRNX_DPS_SUPPLIED_ETY: oViewClass = erp.mtrn.view.SViewDpsStockSupply.class; sViewTitle = auxType01 == SDataConstantsSys.TRNS_CT_DPS_PUR ? "Compras surtidas (detalle)" : "Ventas surtidas (detalle)"; break; case SDataConstants.TRNX_DPS_RETURN_PEND: oViewClass = erp.mtrn.view.SViewDpsStockReturn.class; sViewTitle = auxType01 == SDataConstantsSys.TRNS_CT_DPS_PUR ? "Compras x devolver" : "Ventas x devolver"; break; case SDataConstants.TRNX_DPS_RETURN_PEND_ETY: oViewClass = erp.mtrn.view.SViewDpsStockReturn.class; sViewTitle = auxType01 == SDataConstantsSys.TRNS_CT_DPS_PUR ? "Compras x devolver (detalle)" : "Ventas x devolver (detalle)"; break; case SDataConstants.TRNX_DPS_RETURNED: oViewClass = erp.mtrn.view.SViewDpsStockReturn.class; sViewTitle = auxType01 == SDataConstantsSys.TRNS_CT_DPS_PUR ? "Compras devueltas" : "Ventas devueltas"; break; case SDataConstants.TRNX_DPS_RETURNED_ETY: oViewClass = erp.mtrn.view.SViewDpsStockReturn.class; sViewTitle = auxType01 == SDataConstantsSys.TRNS_CT_DPS_PUR ? "Compras devueltas (detalle)" : "Ventas devueltas (detalle)"; break; case SDataConstants.TRN_DIOG: oViewClass = erp.mtrn.view.SViewDiog.class; sViewTitle = "Docs. inventarios"; if (auxType01 != SLibConstants.UNDEFINED && auxType02 != SLibConstants.UNDEFINED) { sViewTitle += " (" + SDataReadDescriptions.getCatalogueDescription(miClient, SDataConstants.TRNS_TP_IOG, new int[] { auxType01, auxType02, 1 }, SLibConstants.DESCRIPTION_CODE) + ")"; } switch (auxType01) { case SDataConstants.TRNX_DIOG_AUDIT_PEND: oViewClass = erp.mtrn.view.SViewDiogAudit.class; sViewTitle = "Docs. inventarios x auditar"; break; case SDataConstants.TRNX_DIOG_AUDITED: oViewClass = erp.mtrn.view.SViewDiogAudit.class; sViewTitle = "Docs. inventarios auditad@s"; break; } break; case SDataConstants.TRNX_DIOG_MFG: oViewClass = erp.mtrn.view.SViewDiogProdOrder.class; switch (auxType01) { case SDataConstants.TRNX_DIOG_MFG_RM: case SDataConstants.TRNX_DIOG_MFG_WP: case SDataConstants.TRNX_DIOG_MFG_FG: sViewTitle = "Docs. " + (auxType02 == SDataConstants.TRNX_DIOG_MFG_MOVE_ASG ? "entrega" : "devolución"); break; case SDataConstants.TRNX_DIOG_MFG_CON: sViewTitle = "Docs. " + (auxType02 == SDataConstants.TRNX_DIOG_MFG_MOVE_IN ? "entrada" : "salida"); break; default: throw new Exception(SLibConstants.MSG_ERR_UTIL_UNKNOWN_VIEW); } switch (auxType01) { case SDataConstants.TRNX_DIOG_MFG_RM: sViewTitle += " MP"; break; case SDataConstants.TRNX_DIOG_MFG_WP: sViewTitle += " PP"; break; case SDataConstants.TRNX_DIOG_MFG_FG: sViewTitle += " PT"; break; case SDataConstants.TRNX_DIOG_MFG_CON: sViewTitle += " x consumo"; break; default: throw new Exception(SLibConstants.MSG_ERR_UTIL_UNKNOWN_VIEW); } break; case SDataConstants.TRNX_MFG_ORD: sViewTitle = "Movs. prod. - "; switch (auxType01) { case SDataConstants.TRNX_MFG_ORD_ASSIGN_PEND: oViewClass = erp.mtrn.view.SViewProdOrderStockAssign.class; sViewTitle += "OP x asignar"; break; case SDataConstants.TRNX_MFG_ORD_ASSIGN_PEND_ETY: oViewClass = erp.mtrn.view.SViewProdOrderStockAssign.class; sViewTitle += "OP x asignar (detalle)"; break; case SDataConstants.TRNX_MFG_ORD_ASSIGNED: oViewClass = erp.mtrn.view.SViewProdOrderStockAssign.class; sViewTitle += "OP asignadas"; break; case SDataConstants.TRNX_MFG_ORD_ASSIGNED_ETY: oViewClass = erp.mtrn.view.SViewProdOrderStockAssign.class; sViewTitle += "OP asignadas (detalle)"; break; case SDataConstants.TRNX_MFG_ORD_FINISH_PEND: oViewClass = erp.mtrn.view.SViewProdOrderStockFinish.class; sViewTitle += "OP x terminar"; break; case SDataConstants.TRNX_MFG_ORD_FINISH_PEND_ETY: oViewClass = erp.mtrn.view.SViewProdOrderStockFinish.class; sViewTitle += "OP x terminar (detalle)"; break; case SDataConstants.TRNX_MFG_ORD_FINISHED: oViewClass = erp.mtrn.view.SViewProdOrderStockFinish.class; sViewTitle += "OP terminadas"; break; case SDataConstants.TRNX_MFG_ORD_FINISHED_ETY: oViewClass = erp.mtrn.view.SViewProdOrderStockFinish.class; sViewTitle += "OP terminadas (detalle)"; break; case SDataConstants.TRNX_MFG_ORD_CONSUME_PEND: oViewClass = erp.mtrn.view.SViewProdOrderStockConsume.class; sViewTitle += "MP & P x consumir"; break; case SDataConstants.TRNX_MFG_ORD_CONSUME_PEND_ETY: oViewClass = erp.mtrn.view.SViewProdOrderStockConsume.class; sViewTitle += "MP & P x consumir (detalle)"; break; case SDataConstants.TRNX_MFG_ORD_CONSUMED: oViewClass = erp.mtrn.view.SViewProdOrderStockConsume.class; sViewTitle += "MP & P consumidos"; break; case SDataConstants.TRNX_MFG_ORD_CONSUMED_ETY: oViewClass = erp.mtrn.view.SViewProdOrderStockConsume.class; sViewTitle += "MP & P consumidos (detalle)"; break; case SDataConstants.TRNX_MFG_ORD_CONSUME_PEND_MASS: oViewClass = erp.mtrn.view.SViewProdOrderStockConsume.class; sViewTitle = "Masa MP & P x consumir"; break; case SDataConstants.TRNX_MFG_ORD_CONSUME_PEND_ETY_MASS: oViewClass = erp.mtrn.view.SViewProdOrderStockConsume.class; sViewTitle = "Masa MP & P x consumir (detalle)"; break; case SDataConstants.TRNX_MFG_ORD_CONSUMED_MASS: oViewClass = erp.mtrn.view.SViewProdOrderStockConsume.class; sViewTitle = "Masa MP & P consumidos"; break; case SDataConstants.TRNX_MFG_ORD_CONSUMED_ETY_MASS: oViewClass = erp.mtrn.view.SViewProdOrderStockConsume.class; sViewTitle = "Masa MP & P consumidos (detalle)"; break; default: throw new Exception(SLibConstants.MSG_ERR_UTIL_UNKNOWN_VIEW); } break; default: throw new Exception(SLibConstants.MSG_ERR_UTIL_UNKNOWN_VIEW); } processView(oViewClass, sViewTitle, viewType, auxType01, auxType02); } catch (java.lang.Exception e) { SLibUtilities.renderException(this, e); } finally { restoreFrameCursor(); } } @Override public int showForm(int formType, java.lang.Object pk) { return showForm(formType, SDataConstants.UNDEFINED, pk, false); } @Override public int showForm(int formType, int auxType, Object pk) { return showForm(formType, auxType, pk, false); } @Override public int showFormForCopy(int formType, java.lang.Object pk) { return showForm(formType, SDataConstants.UNDEFINED, pk, true); } @Override public erp.lib.form.SFormOptionPickerInterface getOptionPicker(int optionType) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int annulRegistry(int registryType, java.lang.Object pk, sa.lib.gui.SGuiParams params) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int deleteRegistry(int registryType, java.lang.Object pk) { int result = SLibConstants.UNDEFINED; boolean isDocBeingDeleted = false; String message = ""; try { switch (registryType) { case SDataConstants.TRN_DIOG: moRegistry = (SDataDiog) SDataUtilities.readRegistry(miClient, SDataConstants.TRN_DIOG, pk, SLibConstants.EXEC_MODE_VERBOSE); if (moRegistry.canDelete(null) != SLibConstants.DB_CAN_DELETE_YES) { throw new Exception(moRegistry.getDbmsError()); } else { isDocBeingDeleted = !moRegistry.getIsDeleted(); message = ((SDataDiog) moRegistry).validateStockLots(miClient, isDocBeingDeleted); if (message.length() > 0) { throw new Exception(message); } message = ((SDataDiog) moRegistry).validateStockMoves(miClient, isDocBeingDeleted); if (message.length() > 0) { throw new Exception(message); } } break; default: throw new Exception(SLibConstants.MSG_ERR_UTIL_UNKNOWN_OPTION); } result = processActionDelete(pk, isDocBeingDeleted); } catch (Exception e) { SLibUtilities.renderException(this, e); } return result; } @Override public javax.swing.JMenu[] getMenues() { return new JMenu[] { jmMenuCat, jmMenuDpsPurSup, jmMenuDpsPurRet, jmMenuDpsSalSup, jmMenuDpsSalRet, jmMenuMfg, jmMenuIog, jmMenuStk, jmMenuRep }; } @Override public javax.swing.JMenu[] getMenuesForModule(int moduleType) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getSource() instanceof javax.swing.JMenuItem) { javax.swing.JMenuItem item = (javax.swing.JMenuItem) e.getSource(); if (item == jmiCatStockLot) { showView(SDataConstants.TRN_LOT); } else if (item == jmiCatStockConfig) { showView(SDataConstants.TRN_STK_CFG); } else if (item == jmiCatStockAdjustmentType) { showView(SDataConstants.TRNU_TP_IOG_ADJ); } else if (item == jmiCatStockConfigItem) { showView(SDataConstants.TRN_STK_CFG_ITEM); } else if (item == jmiCatStockConfigDns) { showView(SDataConstants.TRN_STK_CFG_DNS); } else if (item == jmiDpsPurSupplyPend) { showView(SDataConstants.TRNX_DPS_SUPPLY_PEND, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC[0], SDataConstantsSys.TRNS_CL_DPS_PUR_DOC[1]); } else if (item == jmiDpsPurSupplyPendEty) { showView(SDataConstants.TRNX_DPS_SUPPLY_PEND_ETY, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC[0], SDataConstantsSys.TRNS_CL_DPS_PUR_DOC[1]); } else if (item == jmiDpsPurSupplied) { showView(SDataConstants.TRNX_DPS_SUPPLIED, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC[0], SDataConstantsSys.TRNS_CL_DPS_PUR_DOC[1]); } else if (item == jmiDpsPurSuppliedEty) { showView(SDataConstants.TRNX_DPS_SUPPLIED_ETY, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC[0], SDataConstantsSys.TRNS_CL_DPS_PUR_DOC[1]); } else if (item == jmiDpsPurReturnPend) { showView(SDataConstants.TRNX_DPS_RETURN_PEND, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ[0], SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ[1]); } else if (item == jmiDpsPurReturnPendEty) { showView(SDataConstants.TRNX_DPS_RETURN_PEND_ETY, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ[0], SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ[1]); } else if (item == jmiDpsPurReturned) { showView(SDataConstants.TRNX_DPS_RETURNED, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ[0], SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ[1]); } else if (item == jmiDpsPurReturnedEty) { showView(SDataConstants.TRNX_DPS_RETURNED_ETY, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ[0], SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ[1]); } else if (item == jmiDpsSalSupplyPend) { showView(SDataConstants.TRNX_DPS_SUPPLY_PEND, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC[0], SDataConstantsSys.TRNS_CL_DPS_SAL_DOC[1]); } else if (item == jmiDpsSalSupplyPendEntry) { showView(SDataConstants.TRNX_DPS_SUPPLY_PEND_ETY, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC[0], SDataConstantsSys.TRNS_CL_DPS_SAL_DOC[1]); } else if (item == jmiDpsSalSupplied) { showView(SDataConstants.TRNX_DPS_SUPPLIED, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC[0], SDataConstantsSys.TRNS_CL_DPS_SAL_DOC[1]); } else if (item == jmiDpsSalSuppliedEntry) { showView(SDataConstants.TRNX_DPS_SUPPLIED_ETY, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC[0], SDataConstantsSys.TRNS_CL_DPS_SAL_DOC[1]); } else if (item == jmiDpsSalReturnPend) { showView(SDataConstants.TRNX_DPS_RETURN_PEND, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ[0], SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ[1]); } else if (item == jmiDpsSalReturnPendEntry) { showView(SDataConstants.TRNX_DPS_RETURN_PEND_ETY, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ[0], SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ[1]); } else if (item == jmiDpsSalReturned) { showView(SDataConstants.TRNX_DPS_RETURNED, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ[0], SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ[1]); } else if (item == jmiDpsSalReturnedEntry) { showView(SDataConstants.TRNX_DPS_RETURNED_ETY, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ[0], SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ[1]); } else if (item == jmiMfgPanelProdOrder) { showPanelProdOrder(SDataConstants.TRNX_MFG_ORD); } else if (item == jmiMfgAssignPend) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_ASSIGN_PEND); } else if (item == jmiMfgAssignPendEntry) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_ASSIGN_PEND_ETY); } else if (item == jmiMfgAssigned) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_ASSIGNED); } else if (item == jmiMfgAssignedEntry) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_ASSIGNED_ETY); } else if (item == jmiMfgFinishPend) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_FINISH_PEND); } else if (item == jmiMfgFinishPendEntry) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_FINISH_PEND_ETY); } else if (item == jmiMfgFinished) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_FINISHED); } else if (item == jmiMfgFinishedEntry) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_FINISHED_ETY); } else if (item == jmiMfgConsumePend) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_CONSUME_PEND, SDataConstantsSys.TRNX_TP_UNIT_TOT_QTY); } else if (item == jmiMfgConsumePendEntry) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_CONSUME_PEND_ETY, SDataConstantsSys.TRNX_TP_UNIT_TOT_QTY); } else if (item == jmiMfgConsumed) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_CONSUMED, SDataConstantsSys.TRNX_TP_UNIT_TOT_QTY); } else if (item == jmiMfgConsumedEntry) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_CONSUMED_ETY, SDataConstantsSys.TRNX_TP_UNIT_TOT_QTY); } else if (item == jmiRepStatsMfgConsumePendMass) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_CONSUME_PEND_MASS, SDataConstantsSys.TRNX_TP_UNIT_TOT_MASS); } else if (item == jmiRepStatsMfgConsumePendEntryMass) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_CONSUME_PEND_ETY_MASS, SDataConstantsSys.TRNX_TP_UNIT_TOT_MASS); } else if (item == jmiRepStatsMfgConsumedMass) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_CONSUMED_MASS, SDataConstantsSys.TRNX_TP_UNIT_TOT_MASS); } else if (item == jmiRepStatsMfgConsumedEntryMass) { showView(SDataConstants.TRNX_MFG_ORD, SDataConstants.TRNX_MFG_ORD_CONSUMED_ETY_MASS, SDataConstantsSys.TRNX_TP_UNIT_TOT_MASS); } else if (item == jmiIogStock) { showView(SDataConstants.TRN_DIOG); } else if (item == jmiIogMfgRmAssign) { showView(SDataConstants.TRNX_DIOG_MFG, SDataConstants.TRNX_DIOG_MFG_RM, SDataConstants.TRNX_DIOG_MFG_MOVE_ASG); } else if (item == jmiIogMfgRmReturn) { showView(SDataConstants.TRNX_DIOG_MFG, SDataConstants.TRNX_DIOG_MFG_RM, SDataConstants.TRNX_DIOG_MFG_MOVE_RET); } else if (item == jmiIogMfgWpAssign) { showView(SDataConstants.TRNX_DIOG_MFG, SDataConstants.TRNX_DIOG_MFG_WP, SDataConstants.TRNX_DIOG_MFG_MOVE_ASG); } else if (item == jmiIogMfgWpReturn) { showView(SDataConstants.TRNX_DIOG_MFG, SDataConstants.TRNX_DIOG_MFG_WP, SDataConstants.TRNX_DIOG_MFG_MOVE_RET); } else if (item == jmiIogMfgFgAssign) { showView(SDataConstants.TRNX_DIOG_MFG, SDataConstants.TRNX_DIOG_MFG_FG, SDataConstants.TRNX_DIOG_MFG_MOVE_ASG); } else if (item == jmiIogMfgFgReturn) { showView(SDataConstants.TRNX_DIOG_MFG, SDataConstants.TRNX_DIOG_MFG_FG, SDataConstants.TRNX_DIOG_MFG_MOVE_RET); } else if (item == jmiIogMfgConsumeIn) { showView(SDataConstants.TRNX_DIOG_MFG, SDataConstants.TRNX_DIOG_MFG_CON, SDataConstants.TRNX_DIOG_MFG_MOVE_IN); } else if (item == jmiIogMfgConsumeOut) { showView(SDataConstants.TRNX_DIOG_MFG, SDataConstants.TRNX_DIOG_MFG_CON, SDataConstants.TRNX_DIOG_MFG_MOVE_OUT); } else if (item == jmiIogAuditPending) { showView(SDataConstants.TRN_DIOG, SDataConstants.TRNX_DIOG_AUDIT_PEND); } else if (item == jmiIogAudited) { showView(SDataConstants.TRN_DIOG, SDataConstants.TRNX_DIOG_AUDITED); } else if (item == jmiIogInventoryValuation) { miClient.getSession().showView(SModConsts.TRN_INV_VAL, SLibConstants.UNDEFINED, null); } else if (item == jmiIogInventoryMfgCost) { miClient.getSession().showView(SModConsts.TRN_INV_MFG_CST, SLibConstants.UNDEFINED, null); } else if (item == jmiIogStockValueByWarehouse) { miClient.getSession().showView(SModConsts.TRNX_STK_COST, SModConsts.CFGU_COB_ENT, null); } else if (item == jmiIogStockValueByItem) { miClient.getSession().showView(SModConsts.TRNX_STK_COST, SModConsts.ITMU_ITEM, null); } else if (item == jmiIogStockValueByDiogType) { miClient.getSession().showView(SModConsts.TRNX_STK_DIOG_TP, SModConsts.TRNX_STK_WAH, null); } else if (item == jmiIogStockClosing) { moDialogUtilStockClosing.resetForm(); moDialogUtilStockClosing.setVisible(true); } else if (item == jmiStkStock) { showView(SDataConstants.TRN_STK, SDataConstants.TRNX_STK_STK); } else if (item == jmiStkStockLot) { showView(SDataConstants.TRN_STK, SDataConstants.TRNX_STK_LOT); } else if (item == jmiStkStockWarehouse) { showView(SDataConstants.TRN_STK, SDataConstants.TRNX_STK_STK_WH); } else if (item == jmiStkStockWarehouseLot) { showView(SDataConstants.TRN_STK, SDataConstants.TRNX_STK_LOT_WH); } else if (item == jmiStkStockMovements) { showView(SDataConstants.TRNX_STK_MOVES); } else if (item == jmiStkStockMovementsEntry) { showView(SDataConstants.TRNX_STK_MOVES_ETY); } else if (item == jmiStkStockRotation) { showView(SDataConstants.TRNX_STK_ROTATION, SDataConstants.TRNX_STK_STK); } else if (item == jmiStkStockRotationLot) { showView(SDataConstants.TRNX_STK_ROTATION, SDataConstants.TRNX_STK_LOT); } else if (item == jmiReportStock) { menuRepStock(); } else if (item == jmiReportStockMoves) { menuRepStockMoves(); } else if (item == jmiReportStockTrackingLot) { menuRepStockTrackingLot(); } } } }
import java.net.URI; import java.sql.*; import java.util.ArrayList; import com.heroku.sdk.jdbc.DatabaseUrl; public class Jobs { public static ArrayList<Job> GetJobs() { ArrayList<Job> jobs = new ArrayList<Job>(); Connection connection = null; try { connection = getDBConnection(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM salesforce.hr_job_requisition__c WHERE hr_status__c = 'Open - Approved'"); while (rs.next()) { Job job = convertResultSetToJob(rs); jobs.add(job); } } catch (Exception e) { System.out.println(e.toString()); return new ArrayList<>(); } finally { if (connection != null) try { connection.close(); } catch (SQLException e) { } return jobs; } } public static Job GetJob(String sfid) { Job job = new Job(); Connection connection = null; try { connection = getDBConnection(); PreparedStatement stmt = connection.prepareStatement("SELECT * FROM salesforce.hr_job_requisition__c WHERE sfid = ?"); stmt.setString(1, sfid); ResultSet rs = stmt.executeQuery(); if (rs.next()) { job = convertResultSetToJob(rs); } } catch (Exception e) { System.out.println(e.toString()); return job; } finally { if (connection != null) try { connection.close(); } catch (SQLException e) { } return job; } } private static Connection getDBConnection() { Connection connection = null; try { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath() + "?user=" + username + "&password=" + password + "&ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"; connection = DriverManager.getConnection(dbUrl); } catch (Exception e) { System.out.println(e.toString()); } return connection; } private static Job convertResultSetToJob(ResultSet rs) { Job job = new Job(); try { job.setSFid(rs.getString("sfid")); job.setName(rs.getString("name")); job.setLocation(rs.getString("hr_location__c")); job.setDescription(rs.getString("hr_description__c")); } catch (Exception e) { System.out.println(e.toString()); return job; } return job; } }
import java.sql.*; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import java.net.URI; import java.net.URISyntaxException; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; import com.google.gson.Gson; import spark.Request; import spark.Response; import spark.QueryParamsMap; import spark.Route; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); get("/hello", (req, res) -> "Hello World"); // get("/", (request, response) -> { // Map<String, Object> attributes = new HashMap<>(); // attributes.put("message", "Hello World!"); // return new ModelAndView(attributes, "index.ftl"); // }, new FreeMarkerEngine()); get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS guitarists (tick timestamp)"); //stmt.executeUpdate("INSERT INTO guitarists VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT * FROM guitarists"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { //output.add( "Read from DB: " + rs.getTimestamp("tick")); output.add( "Read from DB: " + rs.getString("firstname")); output.add( "Read from DB: " + rs.getString("lastname")); output.add( "Read from DB: " + rs.getString("instructiontype")); output.add( "Read from DB: " + rs.getString("zip")); output.add( "Read from DB: " + rs.getString("guitartype")); output.add( "Read from DB: " + rs.getString("genre")); output.add( "Read from DB: " + rs.getString("agerange")); output.add( "Read from DB: " + rs.getString("skill")); output.add( "Read from DB: " + rs.getString("focus")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); /* post("/api", (req, res) -> userService.createUser( String firstName = req.queryParams("firstname"); String lastname = req.queryParams("lastname"); //todo : send to database Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT firstname, lastname INTO mytable VALUES (" firstname + "," + lastname +")"); ResultSet rs = stmt.executeQuery("SELECT * FROM mytable"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } */ //String instructiontype = req.queryParams("instructiontype"); //String zip = req.queryParams("zip"); //String guitartype = req.queryParams("guitartype"); //String genre = req.queryParams("genre"); //String agerange = req.queryParams("agerange"); //String skill = req.queryParams("skill"); //String focus = req.queryParams("focus"); post("/saveuser", (Request req, Response res) -> { String firstname = req.queryParams("firstname"); String lastname = req.queryParams("lastname"); String email = req.queryParams("email"); String password = req.queryParams("password"); String instructiontype = req.queryParams("instructiontype"); String zip = req.queryParams("zip"); String guitartype = req.queryParams("guitartype"); String genre = req.queryParams("genre"); String agerange = req.queryParams("agerange"); String skill = req.queryParams("skill"); String focus = req.queryParams("focus"); System.out.println("*** firstname: " + firstname); //make new db connection, create a new hashmap to be used later for results Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try{ connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.execute("INSERT INTO guitarists (firstname) VALUES ('" +firstname+ "')"); //stmt.execute("INSERT INTO guitarists (firstname, lastname, instructiontype, zip, guitartype, genre, agerange, skill, focus) // VALUES ('Martin', 'Dale', 'Online Instruction', '40052','Acoustic', 'Folk', 'Thirties','Beginner', 'Chords')" ); //stmt.executeUpdate("CREATE TABLE IF NOT EXISTS guitarists (tick timestamp)"); //stmt.executeUpdate("INSERT INTO guitarists (firstname, lastname) VALUES('Mike','Bloomfield')"); //stmt.executeUpdate("INSERT INTO guitarists VALUES (now())"); //stmt.executeUpdate("INSERT INTO guitarists (firstname) VALUES (" +firstname+ ")"); /* PreparedStatement pstmt = connection.prepareStatement("INSERT INTO 'guitarists'" + "(firstname,lastname,email,password,focus,genre,guitartype,instructiontype,skill,zip,agerange)" + "VALUE(?,?,?,?,?,?,?,?,?,?,?)"); pstmt.setString(1, firstname); pstmt.setString(2, lastname); pstmt.setString(2, email); pstmt.setString(2, password); pstmt.setString(2, focus); pstmt.setString(2, genre); pstmt.setString(2, guitartype); pstmt.setString(2, instructiontype); pstmt.setString(2, skill); pstmt.setString(2, zip); pstmt.setString(2, agerange); */ //stmt.executeUpdate("INSERT INTO guitarists (firstname, lastname) VALUES ('" +firstname+ "','" +lastname+ "')"); //now that data has been inserted, query for all records in this table and make an arraylist of objects ResultSet rs = stmt.executeQuery("SELECT * FROM guitarists"); ArrayList<String> output = new ArrayList<>(); while (rs.next()) { output.add("Read from DB: " + rs.getTimestamp("tick")); } } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "profile.html"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } //res.redirect("db.ftl"); return attributes; }); }//end of main() }//end Main Class
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.*; import java.net.URI; import java.net.URISyntaxException; import java.sql.*; public class Main extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getRequestURI().endsWith("/db")) { showDatabase(req,resp); } else { showHome(req,resp); } } private void showHome(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().print("Welcome to YounSung's World!"); } private void showDatabase(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Connection connection = getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); String out = "Hello!\n"; while (rs.next()) { out += "Read from DB: " + rs.getTimestamp("tick") + "\n"; } resp.getWriter().print(out); } catch (Exception e) { resp.getWriter().print("There was an error: " + e.getMessage()); } } private Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } public static void main(String[] args) throws Exception{ Server server = new Server(Integer.valueOf(System.getenv("PORT"))); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context);
import java.util.ArrayList; import java.util.Calendar; public class Menu { private ArrayList<Meal> meals = new ArrayList<Meal>(); private String menuNote; private Calendar date; public Menu() { super(); } public Menu (Calendar cal) { this.date = cal; } public void add(Meal meal) { meals.add(meal); } public Meal[] getMeals() { return meals.toArray(new Meal[meals.size()]); } public String getMenuNote() { return menuNote; } public void setMenuNote(String menuNote) { this.menuNote = menuNote; } public Calendar getDate() { return date; } } class Meal { private String name; private boolean isServing; private String hours; private ArrayList<MenuItem> menuItems = new ArrayList<MenuItem>(); public void add(MenuItem menuItem) { menuItems.add(menuItem); } public void setServing(boolean serving) { isServing = serving; if (!serving) { hours = null; } } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean getIsServing() { return isServing; } public String getHours() { return hours; } public void setHours(String hours) { this.hours = hours; isServing = true; } public MenuItem[] getMenuItems() { return menuItems.toArray(new MenuItem[menuItems.size()]); } public String toString() { return name; } } class MenuItem { private String name; private boolean isVegetarian; public void setVegetarian(boolean vegetarian) { isVegetarian = vegetarian; } public boolean getIsVegetarian() { return isVegetarian; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return name; } }
package com.intellij; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.DefaultBundleService; import com.intellij.util.containers.ConcurrentFactoryMap; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.*; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.text.MessageFormat; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.function.Supplier; /** * Base class for particular scoped bundles (e.g. {@code 'vcs'} bundles, {@code 'aop'} bundles etc). * <p/> * Usage pattern: * <ol> * <li>Create class that extends this class and provides path to the target bundle to the current class constructor;</li> * <li> * Optionally create static facade method at the subclass - create single shared instance and delegate * to its {@link #getMessage(String, Object...)}; * </li> * </ol> * * @author Denis Zhdanov */ public abstract class AbstractBundle { private static final Logger LOG = Logger.getInstance(AbstractBundle.class); private Reference<ResourceBundle> myBundle; private Reference<ResourceBundle> myDefaultBundle; @NonNls private final String myPathToBundle; protected AbstractBundle(@NonNls @NotNull String pathToBundle) { myPathToBundle = pathToBundle; } @Contract(pure = true) public @NotNull @Nls String getMessage(@NotNull @NonNls String key, Object @NotNull ... params) { return message(getResourceBundle(), key, params); } /** * Performs partial application of the pattern message from the bundle leaving some parameters unassigned. * It's expected that the message contains params.length+unassignedParams placeholders. Parameters * {@code {0}..{params.length-1}} will be substituted using passed params array. The remaining parameters * will be renumbered: {@code {params.length}} will become {@code {0}} and so on, so the resulting template * could be applied once more. * * @param key resource key * @param unassignedParams number of unassigned parameters * @param params assigned parameters * @return a template suitable to pass to {@link MessageFormat#format(Object)} having the specified number of placeholders left */ @Contract(pure = true) public @NotNull @Nls String getPartialMessage(@NotNull @NonNls String key, int unassignedParams, Object @NotNull ... params) { return BundleBase.partialMessage(getResourceBundle(), key, unassignedParams, params); } public @NotNull Supplier<@Nls String> getLazyMessage(@NotNull @NonNls String key, Object @NotNull ... params) { return () -> getMessage(key, params); } public @Nullable @Nls String messageOrNull(@NotNull @NonNls String key, Object @NotNull ... params) { return messageOrNull(getResourceBundle(), key, params); } public @Nls String messageOrDefault(@NotNull @NonNls String key, @Nullable @Nls String defaultValue, Object @NotNull ... params) { return messageOrDefault(getResourceBundle(), key, defaultValue, params); } @Contract("null, _, _, _ -> param3") public static @Nls String messageOrDefault(@Nullable ResourceBundle bundle, @NotNull @NonNls String key, @Nullable @Nls String defaultValue, Object @NotNull ... params) { if (bundle == null) { return defaultValue; } else if (!bundle.containsKey(key)) { return BundleBase.postprocessValue(bundle, BundleBase.useDefaultValue(bundle, key, defaultValue), params); } return BundleBase.messageOrDefault(bundle, key, defaultValue, params); } public static @Nls @NotNull String message(@NotNull ResourceBundle bundle, @NotNull @NonNls String key, Object @NotNull ... params) { return BundleBase.message(bundle, key, params); } public static @Nullable @Nls String messageOrNull(@NotNull ResourceBundle bundle, @NotNull @NonNls String key, Object @NotNull ... params) { @SuppressWarnings("HardCodedStringLiteral") String value = messageOrDefault(bundle, key, key, params); if (key.equals(value)) return null; return value; } public boolean containsKey(@NotNull @NonNls String key) { return getResourceBundle().containsKey(key); } public ResourceBundle getResourceBundle() { return getResourceBundle(null); } @ApiStatus.Internal protected @NotNull ResourceBundle getResourceBundle(@Nullable ClassLoader classLoader) { ResourceBundle bundle; if (DefaultBundleService.isDefaultBundle()) { bundle = getBundle(classLoader, myDefaultBundle); myDefaultBundle = new SoftReference<>(bundle); } else { bundle = getBundle(classLoader, myBundle); myBundle = new SoftReference<>(bundle); } return bundle; } private ResourceBundle getBundle(@Nullable ClassLoader classLoader, @Nullable Reference<ResourceBundle> bundleReference) { ResourceBundle bundle = com.intellij.reference.SoftReference.dereference(bundleReference); if (bundle != null) { return bundle; } return getResourceBundle(myPathToBundle, classLoader == null ? getClass().getClassLoader() : classLoader); } private static final Map<ClassLoader, Map<String, ResourceBundle>> ourCache = ConcurrentFactoryMap.createWeakMap(k -> ContainerUtil.createConcurrentSoftValueMap()); private static final Map<ClassLoader, Map<String, ResourceBundle>> ourDefaultCache = ConcurrentFactoryMap.createWeakMap(k -> ContainerUtil.createConcurrentSoftValueMap()); public @NotNull ResourceBundle getResourceBundle(@NotNull @NonNls String pathToBundle, @NotNull ClassLoader loader) { return DefaultBundleService.isDefaultBundle() ? getResourceBundle(pathToBundle, loader, ourDefaultCache.get(loader)) : getResourceBundle(pathToBundle, loader, ourCache.get(loader)); } public ResourceBundle getResourceBundle(@NotNull @NonNls String pathToBundle, @NotNull ClassLoader loader, Map<String, ResourceBundle> map) { ResourceBundle result = map.get(pathToBundle); if (result == null) { try { ResourceBundle.Control control = ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_PROPERTIES); result = findBundle(pathToBundle, loader, control); } catch (MissingResourceException e) { LOG.info("Cannot load resource bundle from *.properties file, falling back to slow class loading: " + pathToBundle); ResourceBundle.clearCache(loader); result = ResourceBundle.getBundle(pathToBundle, Locale.getDefault(), loader); } map.put(pathToBundle, result); } return result; } protected ResourceBundle findBundle(@NotNull @NonNls String pathToBundle, @NotNull ClassLoader loader, @NotNull ResourceBundle.Control control) { return ResourceBundle.getBundle(pathToBundle, Locale.getDefault(), loader, control); } protected static void clearGlobalLocaleCache() { ourCache.clear(); } protected void clearLocaleCache() { if (myBundle != null) { myBundle.clear(); } } }
// Read_Image.java import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.io.OpenDialog; import ij.plugin.PlugIn; import ij.process.ImageProcessor; import java.io.IOException; import loci.formats.ChannelSeparator; import loci.formats.FormatException; import loci.formats.IFormatReader; import loci.plugins.Util; /** A very simple example of using Bio-Formats in an ImageJ plugin. */ public class Read_Image implements PlugIn { public void run(String arg) { OpenDialog od = new OpenDialog("Open Image File...", arg); String dir = od.getDirectory(); String name = od.getFileName(); String id = dir + name; IFormatReader r = new ChannelSeparator(); try { IJ.showStatus("Examining file " + name); r.setId(id); int num = r.getImageCount(); int width = r.getSizeX(); int height = r.getSizeY(); ImageStack stack = new ImageStack(width, height); for (int i=0; i<num; i++) { IJ.showStatus("Reading image plane #" + (i + 1) + "/" + num); ImageProcessor ip = Util.openProcessor(r, i); stack.addSlice("" + (i + 1), ip); } IJ.showStatus("Constructing image"); ImagePlus imp = new ImagePlus(name, stack); imp.show(); IJ.showStatus(""); } catch (FormatException exc) { IJ.error("Sorry, an error occurred: " + exc.getMessage()); } catch (IOException exc) { IJ.error("Sorry, an error occurred: " + exc.getMessage()); } } }
package gamepack.view; import gamepack.data.drawable.Grid; import gamepack.manager.GameSaver; import gamepack.manager.TileMatrixManager; import gamepack.utility.Direction; import gamepack.utility.GameState; import java.awt.Font; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.TrueTypeFont; public class WindowGame extends BasicGame { // ATTRIBUTES private GameContainer container; private final int windowSizeX; private final int windowSizeY; private GameState state; private Grid grid; private TileMatrixManager gameManager; private int gameFPS; private int numberOfFrameWithMovement; //in order to generate a new tile only if there is movement private GameSaver gSave; private Color transparentbg; private Font font; private TrueTypeFont ttf; //INTERFACE private String strWin1 = new String("Congratulation !"); private String strWin2 = new String("You won with a score of "); private String strLose1 = new String("You lost ..."); private String strLose2 = new String("But try again and beat your score of "); private Color prevColor; // METHODS public WindowGame() { //Parent Constructor super("2C0A"); //Attributes initialization windowSizeX = 800; windowSizeY = 600; state = GameState.Ongoing; gameFPS = 100; numberOfFrameWithMovement = 0; //Object initialization grid = new Grid(windowSizeX, windowSizeY); gSave = new GameSaver("save.txt", "score.txt"); transparentbg = new Color(193, 184, 176, 136); font = new Font("Times New Roman", Font.BOLD, 32); //Matrix Manager Initialization generateGameManager(); } private void generateGameManager() { //If there is no save if (!gSave.areFilesAvailable()) { gameManager = new TileMatrixManager(grid.getRectangles()); //The game starts with the generation of new tiles gameManager.generateNewTile(); gameManager.generateNewTile(); gSave.save(gameManager.getNextTileMatrix(), gameManager.getScore()); } //otherwise, we load the save else { gameManager = new TileMatrixManager(grid.getRectangles(), gSave.getSavedTileList(), gSave.getScore()); } } //Slick2D method which start when the game container start public void init(GameContainer container) throws SlickException { this.container = container; ttf = new TrueTypeFont(font, true); container.getGraphics().setBackground(new Color(193, 184, 176)); } //Size methods for the container public int getWindowSizeX() { return windowSizeX; } //Size methods for the container public int getWindowSizeY() { return windowSizeY; } //Refresh the screen public void render(GameContainer container, Graphics g) throws SlickException { //Draw the grid if (state == GameState.Win) { this.drawWin(g); } else if (state == GameState.Lose) { this.drawLose(g); } else { grid.beDrawn(g); //Draw the next tile matrix if movements have been done, otherwise draw the tile matrix if (state == GameState.Ongoing || state == GameState.DoneMoving) gameManager.getNextTileMatrix().beDrawn(g); else gameManager.getTileMatrix().beDrawn(g); //Draw the score this.drawRightPannel(g); } } //Do computation public void update(GameContainer gc, int delta) throws SlickException { //if we're not waiting for an event if (state != GameState.Ongoing) { //Once tiles have finished their movement if (state == GameState.DoneMoving) { //If there was a movement (so if each tiles are not stuck in a corner for example) //(one movement is always done to check if the tile are arrived and to reset their arrived point) if (numberOfFrameWithMovement != 0) { //We generate a new tile gameManager.generateNewTile(); gameManager.refreshBomb(); state = gameManager.isOver(); } } //if a movement has been initialized if (state == GameState.Moving) { if (!gameManager.manageMovement(gameFPS)) //if there is no movement (all tiles have their arrivedPoint equal to null) state = GameState.DoneMoving; else //if there is a movement numberOfFrameWithMovement++; //we notice that there was a movement gameManager.manageFusion(); } refreshFPS(gc.getFPS()); } } //check if the FPS is correct (the default function to manage FPS is not really good) public void refreshFPS(int fps) { if (fps == 0) fps = 60; gameFPS = fps; } //Draw the score public void drawRightPannel(Graphics g) { int commandsTopPositon = 20; int scoreTopPositon = commandsTopPositon+15*6; g.setColor(Color.white); g.drawString("Options :", grid.getRightPosition(), commandsTopPositon); g.drawString("F1 : Save game",grid.getRightPosition(), commandsTopPositon+15*1); g.drawString("F2 : load game",grid.getRightPosition(), commandsTopPositon+15*2); g.drawString("F3 : New game", grid.getRightPosition(), commandsTopPositon+15*3); g.setColor(Color.white); g.drawString("Score : " + this.gameManager.getScore(), grid.getRightPosition(), scoreTopPositon); } public void drawWin(Graphics g) { grid.beDrawn(g); gameManager.getTileMatrix().beDrawn(g); prevColor = g.getColor(); g.setColor(transparentbg); g.fillRect(0, 0, windowSizeX, windowSizeY); // Draw a rectangle to 'hide' the background ttf.drawString((float)(this.windowSizeX - ttf.getWidth(strWin1))/2, (float)(this.windowSizeY/2 - ttf.getHeight(strWin1)*1.5), strWin1, Color.black); ttf.drawString((float)(this.windowSizeX - ttf.getWidth(strWin2))/2, (float)(this.windowSizeY/2 - ttf.getHeight(strWin2)+ttf.getHeight(strWin1)), strWin2 + this.gameManager.getScore(), Color.black); g.setColor(prevColor); } public void drawLose(Graphics g) { grid.beDrawn(g); gameManager.getNextTileMatrix().beDrawn(g); prevColor = g.getColor(); g.setColor(transparentbg); g.fillRect(0, 0, windowSizeX, windowSizeY); // Draw a rectangle to 'hide' the background ttf.drawString((float)(this.windowSizeX - ttf.getWidth(strLose1))/2, (float)(this.windowSizeY/2 - ttf.getHeight(strLose1)*1.5), strLose1, Color.black); ttf.drawString((float)(this.windowSizeX - ttf.getWidth(strLose2))/2, (float)(this.windowSizeY/2 - ttf.getHeight(strLose2)+ttf.getHeight(strLose1)), strLose2 + this.gameManager.getScore()+ " !", Color.black); g.setColor(prevColor); } @Override public boolean closeRequested() { // Save the game when closing if(state != GameState.Lose && state != GameState.Win ) gSave.save(gameManager.getNextTileMatrix(), gameManager.getScore()); return true; } //when a key is pressed public void keyPressed(int key, char c) { //if we press a command if (key == Input.KEY_F1) //F1 save the game { if(state != GameState.Win && state != GameState.Lose) gSave.save(gameManager.getNextTileMatrix(), gameManager.getScore()); } else if (key == Input.KEY_F2) //F2 load the game { state = GameState.Ongoing; gameManager = new TileMatrixManager(grid.getRectangles(), gSave.getSavedTileList(), gSave.getScore()); } else if (key == Input.KEY_F3) //F3 make a new game { state = GameState.Ongoing; gSave.deleteSave(); generateGameManager(); } //If it wasn't a command else { //If we are waiting for an event or if the movement has been done if (state == GameState.Ongoing || state == GameState.DoneMoving) { //if we press a direction Direction directionPressed = Direction.None; if (key == Input.KEY_LEFT || key == Input.KEY_Q) directionPressed = Direction.Left; else if (key == Input.KEY_RIGHT || key == Input.KEY_D) directionPressed = Direction.Right; else if (key == Input.KEY_DOWN || key == Input.KEY_S) directionPressed = Direction.Down; else if (key == Input.KEY_UP || key == Input.KEY_Z) directionPressed = Direction.Up; //If we have press a key for a movement if (directionPressed != Direction.None) { state = GameState.Moving; numberOfFrameWithMovement = 0; //set the number of frame with movement at 0 gameManager.initMovement(directionPressed); //launch the movement for all tiles } } //If we press a key while there is a movement, we accelerate the movement else if(state != GameState.Win && state != GameState.Lose) gameManager.manageMovement(1); } } //Main methods, create the window public static void main(String[] args) throws SlickException { AppGameContainer appgc; WindowGame wGame = new WindowGame(); appgc = new AppGameContainer(wGame); //set our game in the container appgc.setDisplayMode(wGame.getWindowSizeX(), wGame.getWindowSizeY(), false); //the container & the game have the same dimensions appgc.setShowFPS(false); //don't show the FPS appgc.setTargetFrameRate(100); //default frame rate appgc.start(); //Launch the game } }
package games.engine.gui; import java.awt.event.*; import javax.swing.*; import java.awt.*; import java.awt.image.*; import java.net.*; import javax.swing.JComponent.*; import java.awt.geom.*; import java.io.*; class MainGUI extends JFrame implements ActionListener, MouseMotionListener, MouseListener, WindowListener { JLabel image; JTextArea msg; JPanel panel; JTextField input; JScrollPane scrollPane; int mouseX, mouseY; JMenuBar menuBar; JMenu menu; JMenuItem menuItem; JRadioButtonMenuItem rbMenuItem; Image cardspic; Image back; Image backSW; Image title; Image pointer[] = new Image[4]; Image burntPic; Graphics g; BufferedImage offscreen; ImageIcon imageI; Image offscreen2; Graphics g2; Graphics2D g2d; boolean player1 = false; boolean player2 = false; boolean myTurn = false; Message message = null; Dealer dealer = null; Player player = null; Score score; String playersName = "unknown"; Hand hand; Point pointplayer1[] = new Point[3]; Point pointplayer2[] = new Point[3]; Point pointplayer3[] = new Point[3]; Point pointplayer4[] = new Point[3]; Point centre1; Dimension screenSize; MainGUI() { MediaTracker tracker = new MediaTracker(this); Toolkit toolkit = Toolkit.getDefaultToolkit(); cardspic = toolkit.getImage(this.getClass().getResource("Images/cards.gif")); back = toolkit.getImage(this.getClass().getResource("Images/back.gif")); backSW = toolkit.getImage(this.getClass().getResource("Images/backSW.gif")); title = toolkit.getImage(this.getClass().getResource("Images/Title.jpg")); pointer[0] = toolkit.getImage(this.getClass().getResource("Images/pointer.gif")); burntPic = toolkit.getImage(this.getClass().getResource("Images/burnt.jpg")); tracker.addImage(cardspic, 1); tracker.addImage(back, 1); tracker.addImage(backSW, 1); tracker.addImage(title, 1); tracker.addImage(pointer[0], 1); tracker.addImage(burntPic, 1); try { tracker.waitForAll(); } catch (InterruptedException e) { msg.setText("Image load Error " + e); } pointer[3] = rotatePointer(pointer[0]); pointer[2] = rotatePointer(pointer[3]); pointer[1] = rotatePointer(pointer[2]); offscreen = new BufferedImage(450, 550, BufferedImage.TYPE_3BYTE_BGR); g = offscreen.getGraphics(); g.drawImage(title, -40, 120, this); g.setColor(Color.white); g.drawLine(0, 450, 450, 450); screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if(screenSize.width < 1024){ offscreen2 = new BufferedImage(338, 413, BufferedImage.TYPE_3BYTE_BGR); g2 = offscreen2.getGraphics(); g2d = (Graphics2D) g2; AffineTransform at = new AffineTransform(); at.scale(0.75, 0.75); g2d.transform(at); g2d.drawImage(offscreen, 0, 0, null); imageI = new ImageIcon(offscreen2); }else imageI = new ImageIcon(offscreen); image = new JLabel(imageI); addMouseMotionListener(this); addMouseListener(this); requestFocus(); menuBar = new JMenuBar(); //Build the first menu. menu = new JMenu("File"); menu.setMnemonic(KeyEvent.VK_F); menu.getAccessibleContext().setAccessibleDescription( "Game Options"); menuBar.add(menu); //File group of JMenuItems menuItem = new JMenuItem("2 Player", KeyEvent.VK_P); menuItem.getAccessibleContext().setAccessibleDescription( "Start Single Player Game"); menuItem.addActionListener( this ); menu.add(menuItem); menuItem = new JMenuItem("Scoreboard", KeyEvent.VK_B); menuItem.getAccessibleContext().setAccessibleDescription( "Veiw Scoreboard"); menuItem.addActionListener( this ); menu.add(menuItem); menuItem = new JMenuItem("Quit", KeyEvent.VK_Q); menuItem.getAccessibleContext().setAccessibleDescription( "Quit Game"); menuItem.addActionListener( this ); menu.add(menuItem); menu = new JMenu("Options"); menu.getAccessibleContext().setAccessibleDescription( "Game Options"); menuBar.add(menu); menuItem = new JMenuItem("Redeal", KeyEvent.VK_R); menuItem.getAccessibleContext().setAccessibleDescription( "Redeal the deck"); menuItem.addActionListener( this ); menu.add(menuItem); menuItem = new JMenuItem("Start Game", KeyEvent.VK_S); menuItem.getAccessibleContext().setAccessibleDescription( "Start game now"); menuItem.addActionListener( this ); menu.add(menuItem); menu = new JMenu("About"); menu.getAccessibleContext().setAccessibleDescription( "About the Game"); menuBar.add(menu); menuItem = new JMenuItem("Rules", KeyEvent.VK_R); menuItem.getAccessibleContext().setAccessibleDescription( "How to play"); menuItem.addActionListener( this ); menu.add(menuItem); menuItem = new JMenuItem("Home Page", KeyEvent.VK_H); menuItem.getAccessibleContext().setAccessibleDescription( "View Home Page"); menuItem.addActionListener( this ); menu.add(menuItem); menuItem = new JMenuItem("About", KeyEvent.VK_A); menuItem.getAccessibleContext().setAccessibleDescription( "About the Game"); menuItem.addActionListener( this ); menu.add(menuItem); addWindowListener(this); msg = new JTextArea("Welcome to the card game\n", 4, 20); msg.setLineWrap(true); msg.setEditable(false); msg.setDisabledTextColor(Color.black); input = new JTextField(); input.addActionListener(this); scrollPane = new JScrollPane(msg, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); panel = new JPanel(); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); panel.setLayout(gridbag); c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.BOTH; panel.setBackground(Color.white); getContentPane().add(panel); panel.add(menuBar, c); c.gridy = 1; panel.add(image, c); c.gridy = 2; panel.add(scrollPane, c); c.gridy = 3; panel.add(input, c); addMsg("Detected Screen Size: " + screenSize.width + "x" + screenSize.height); if(screenSize.width < 1024) addMsg("For optimal graphics use 1024x768 resolution"); score = new Score(this); } public void actionPerformed(ActionEvent event){ String label = event.getActionCommand(); if (label.equals("Quit")){ System.exit(0); } } public static void main(String[] args) { try { MainGUI frame = new MainGUI(); frame.setTitle("Card Game"); frame.setResizable(false); frame.pack(); frame.setVisible(true); } catch (Exception e) { System.out.println("Game Error: " + e); } } }
/** * This class is the main class of the "World of Zuul" application. * "World of Zuul" is a very simple, text based adventure game. Users * can walk around some scenery. That's all. It should really be extended * to make it more interesting! * * To play this game, create an instance of this class and call the "play" * method. * * This main class creates and initialises all the others: it creates all * rooms, creates the parser and starts the game. It also evaluates and * executes the commands that the parser returns. * * @author Michael Kolling and David J. Barnes * @version 2006.03.30 */ public class Game { private Parser parser; private Room currentRoom; private Players MrKitten; /** * Create the game and initialise its internal map. */ public Game() { createRooms(); createItems(); MrKitten = new Players("Mr.Kitten"); parser = new Parser(); } /** * Create all the rooms and link their exits together. */ private void createRooms() { //Room outside, theatre, pub, lab, office; Room kitchen,livingRoom,bedroom,street1,street2,sewer,petshop,theGreatDescent,dory,theFishPalace; Room tavernSanRicardo,starWars,theCloset,theEnd; kitchen = new Room ("are in the Kitchen of the Master's house"); livingRoom = new Room ("are in the Living room of the Master's house"); bedroom = new Room ("are in the Bedroom of the Master's house"); street1 = new Room ("are in the Street near the entrance of the house"); street2 = new Room ("are in the Street near the Petshop"); sewer = new Room ("are in the Sewer under the streets"); petshop = new Room ("are in the Petshop"); theGreatDescent = new Room ("are going deep down under water"); dory = new Room ("are with Dory the great fish"); theFishPalace = new Room ("are in the Fish Palace"); tavernSanRicardo = new Room ("are in the magnificient Tavern Of San Ricardo"); starWars = new Room ("are in a Galaxy far far away..."); theCloset = new Room ("are ready to fight with lions"); theEnd = new Room ("did it, you did it, Yeah!"); Door doorKLr = new Door(livingRoom,kitchen); kitchen.addExit("east", doorKLr); livingRoom.addExit("west",doorKLr); Door doorBLr = new Door (bedroom, livingRoom); livingRoom.addExit("east",doorBLr); bedroom.addExit("west",doorBLr); Item keyLivingStreet = new Item("home key", "this key opens the door to exit the master's house",0); LockedDoor doorS1Lr = new LockedDoor (keyLivingStreet, street1, livingRoom); livingRoom.addExit("south",doorS1Lr);street1.addExit("north",doorS1Lr); Door doorS2S1 = new Door (street2, street1);street1.addExit("east",doorS2S1); street2.addExit("west",doorS2S1); Door doorSS1 = new Door (sewer, street1);street1.addExit("down",doorSS1);sewer.addExit("up",doorSS1); Door doorPS2 = new Door (petshop, street2);street2.addExit("south",doorPS2);petshop.addExit("north",doorPS2); Door doorSS2 = new Door (sewer, street2);street2.addExit("down",doorSS2);sewer.addExit("up",doorSS2); Door doorGdP = new Door (theGreatDescent, petshop);petshop.addExit("down", doorGdP);theGreatDescent.addExit("up",doorGdP); Door doorDGd = new Door (dory, theGreatDescent);theGreatDescent.addExit("west",doorDGd); dory.addExit("east",doorDGd); Door doorFpGd = new Door (theFishPalace, theGreatDescent);theGreatDescent.addExit("down",doorFpGd);theFishPalace.addExit("up",doorFpGd); Item keyFishTavern = new Item ("blue key","This key opens the door between the fish palace and the San Ricardo tavern",0); LockedDoor doorFpTsr = new LockedDoor (keyFishTavern, theFishPalace, tavernSanRicardo);tavernSanRicardo.addExit("north", doorFpTsr); theFishPalace.addExit("south", doorFpTsr); Door doorSwTsr = new Door (starWars, tavernSanRicardo);tavernSanRicardo.addExit("up", doorSwTsr); starWars.addExit("down",doorSwTsr); Door doorCSw = new Door (theCloset,starWars);starWars.addExit("east",doorCSw);theCloset.addExit("west",doorCSw); Door doorEC = new Door (theEnd, theCloset);theCloset.addExit("south", doorEC); currentRoom = livingRoom; // start game in master's house } /* * Create all the items in the game */ private void createItems() { Item potion = new Item ("potion","It's nice and warm",1); Item jaw = new Item ("jaw","It's sharp and ready",5); Item superPiss = new Item ("superPiss","Wow it's dirty",8); } /** * Main play routine. Loops until end of play. */ public void play() { printWelcome(); // Enter the main command loop. Here we repeatedly read commands and // execute them until the game is over. boolean finished = false; while (! finished) { Command command = parser.getCommand(); finished = processCommand(command); } System.out.println("Thank you for playing. Good bye."); } /** * Print out the opening message for the player. */ private void printWelcome() { System.out.println(); System.out.println("Welcome to the World of Zuul!"); System.out.println("World of Zuul is a new, incredibly boring adventure game."); System.out.println("Type 'help' if you need help."); System.out.println(); System.out.println("You are " + currentRoom.getDescription()); currentRoom.printExits(); } /** * Given a command, process (that is: execute) the command. * @param command The command to be processed. * @return true If the command ends the game, false otherwise. */ private boolean processCommand(Command command) { boolean wantToQuit = false; if(command.isUnknown()) { System.out.println("I don't know what you mean..."); return false; } String commandWord = command.getCommandWord(); if (commandWord.equals("help")) printHelp(); else if (commandWord.equals("go")) goRoom(command); else if (commandWord.equals("quit")) wantToQuit = quit(command); else if (commandWord.equals("look")) lookRoom(command); return wantToQuit; } // implementations of user commands: /** * Print out some help information. * Here we print some stupid, cryptic message and a list of the * command words. */ private void printHelp() { System.out.println("You are lost. You are alone. You wander"); System.out.println("around at the university."); System.out.println(); System.out.println("Your command words are:"); System.out.println(" go quit help"); } /** * Try to go to one direction. If there is an exit, enter * the new room, otherwise print an error message. */ private void goRoom(Command command) { if(!command.hasSecondWord()) { // if there is no second word, we don't know where to go... System.out.println("Go where?"); return; } String direction = command.getSecondWord(); // Try to leave current room. Door nextDoor = currentRoom.getNextRoom(direction); if (nextDoor instanceof LockedDoor){ LockedDoor l = (LockedDoor)nextDoor; l.openLockedDoor(MrKitten.getInventory(),currentRoom); } else{ try{ Room nextRoom = nextDoor.getRoom(currentRoom); currentRoom = nextRoom; System.out.println("You " + currentRoom.getDescription()); currentRoom.printExits(); } catch (Exception e){ System.out.println("Wrong direction!"); System.out.println("You " + currentRoom.getDescription()); System.out.println("You can go :"); currentRoom.printExits(); } } } /** * "Quit" was entered. Check the rest of the command to see * whether we really quit the game. * @return true, if this command quits the game, false otherwise. */ private boolean quit(Command command) { if(command.hasSecondWord()) { System.out.println("Quit what?"); return false; } else { return true; // signal that we want to quit } } /* * You can look into the room to see the description of the room or to describe an item */ private void lookRoom(Command command) { if(!command.hasSecondWord()) { // if there is no second word, we describe the current room System.out.println("You " + currentRoom.getDescription()); currentRoom.printExits(); return; } else { String itemName = command.getSecondWord(); Players.getItemDescription(itemName); return; } } }
package com.intellij.idea; import com.intellij.ide.BootstrapClassLoaderUtil; import com.intellij.ide.WindowsCommandLineProcessor; import com.intellij.ide.startup.StartupActionScriptManager; import com.intellij.openapi.application.JetBrainsProtocolHandler; import com.intellij.openapi.application.PathManager; import com.intellij.util.ArrayUtilRt; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Properties; public final class Main { public static final int NO_GRAPHICS = 1; public static final int RESTART_FAILED = 2; public static final int STARTUP_EXCEPTION = 3; public static final int JDK_CHECK_FAILED = 4; public static final int DIR_CHECK_FAILED = 5; public static final int INSTANCE_CHECK_FAILED = 6; public static final int LICENSE_ERROR = 7; public static final int PLUGIN_ERROR = 8; public static final int OUT_OF_MEMORY = 9; @SuppressWarnings("unused") public static final int UNSUPPORTED_JAVA_VERSION = 10; // left for compatibility/reserved for future use public static final int PRIVACY_POLICY_REJECTION = 11; public static final int INSTALLATION_CORRUPTED = 12; public static final int ACTIVATE_WRONG_TOKEN_CODE = 13; public static final int ACTIVATE_NOT_INITIALIZED = 14; public static final int ACTIVATE_ERROR = 15; public static final int ACTIVATE_DISPOSING = 16; public static final String FORCE_PLUGIN_UPDATES = "idea.force.plugin.updates"; private static final String AWT_HEADLESS = "java.awt.headless"; private static final String PLATFORM_PREFIX_PROPERTY = "idea.platform.prefix"; private static final String[] NO_ARGS = ArrayUtilRt.EMPTY_STRING_ARRAY; private static final List<String> HEADLESS_COMMANDS = Arrays.asList( "ant", "duplocate", "traverseUI", "buildAppcodeCache", "format", "keymap", "update", "inspections", "intentions"); private static final List<String> GUI_COMMANDS = Arrays.asList("diff", "merge"); private static boolean isHeadless; private static boolean isCommandLine; private static boolean hasGraphics = true; private static boolean isLightEdit; private Main() { } public static void main(String[] args) { LinkedHashMap<String, Long> startupTimings = new LinkedHashMap<>(); startupTimings.put("startup begin", System.nanoTime()); if (args.length == 1 && "%f".equals(args[0])) { args = NO_ARGS; } if (args.length == 1 && args[0].startsWith(JetBrainsProtocolHandler.PROTOCOL)) { JetBrainsProtocolHandler.processJetBrainsLauncherParameters(args[0]); args = NO_ARGS; } setFlags(args); if (!isHeadless() && !checkGraphics()) { System.exit(NO_GRAPHICS); } try { bootstrap(args, startupTimings); } catch (Throwable t) { showMessage("Start Failed", t); System.exit(STARTUP_EXCEPTION); } } private static void bootstrap(String[] args, LinkedHashMap<String, Long> startupTimings) throws Exception { startupTimings.put("properties loading", System.nanoTime()); PathManager.loadProperties(); // this check must be performed before system directories are locked String configPath = PathManager.getConfigPath(); boolean configImportNeeded = !isHeadless() && !Files.exists(Paths.get(configPath)); if (!configImportNeeded) { installPluginUpdates(); } startupTimings.put("classloader init", System.nanoTime()); ClassLoader newClassLoader = BootstrapClassLoaderUtil.initClassLoader(); Thread.currentThread().setContextClassLoader(newClassLoader); startupTimings.put("MainRunner search", System.nanoTime()); Class<?> klass = Class.forName("com.intellij.ide.plugins.MainRunner", true, newClassLoader); WindowsCommandLineProcessor.ourMainRunnerClass = klass; Method startMethod = klass.getMethod("start", String.class, String[].class, LinkedHashMap.class); startMethod.setAccessible(true); startMethod.invoke(null, Main.class.getName() + "Impl", args, startupTimings); } private static void installPluginUpdates() { if (!isCommandLine() || Boolean.getBoolean(FORCE_PLUGIN_UPDATES)) { try { StartupActionScriptManager.executeActionScript(); } catch (IOException e) { String message = "The IDE failed to install some plugins.\n\n" + "Most probably, this happened because of a change in a serialization format.\n" + "Please try again, and if the problem persists, please report it\n" + "to http://jb.gg/ide/critical-startup-errors" + "\n\nThe cause: " + e.getMessage(); showMessage("Plugin Installation Error", message, false); } } } public static boolean isHeadless() { return isHeadless; } public static boolean isCommandLine() { return isCommandLine; } public static boolean isLightEdit() { return isLightEdit; } public static void setFlags(String @NotNull [] args) { isHeadless = isHeadless(args); isCommandLine = isHeadless || (args.length > 0 && GUI_COMMANDS.contains(args[0])); if (isHeadless) { System.setProperty(AWT_HEADLESS, Boolean.TRUE.toString()); } isLightEdit = "LightEdit".equals(System.getProperty(PLATFORM_PREFIX_PROPERTY)) || (args.length > 0 && Files.isRegularFile(Paths.get(args[0]))); } public static boolean isHeadless(String @NotNull [] args) { if (Boolean.getBoolean(AWT_HEADLESS)) { return true; } if (args.length == 0) { return false; } String firstArg = args[0]; return HEADLESS_COMMANDS.contains(firstArg) || firstArg.length() < 20 && firstArg.endsWith("inspect"); } private static boolean checkGraphics() { if (GraphicsEnvironment.isHeadless()) { showMessage("Startup Error", "Unable to detect graphics environment", true); return false; } return true; } public static void showMessage(String title, Throwable t) { StringWriter message = new StringWriter(); AWTError awtError = findGraphicsError(t); if (awtError != null) { message.append("Failed to initialize graphics environment\n\n"); hasGraphics = false; t = awtError; } else { message.append("Internal error. Please refer to "); boolean studio = "AndroidStudio".equalsIgnoreCase(System.getProperty(PLATFORM_PREFIX_PROPERTY)); message.append(studio ? "https: message.append("\n\n"); } t.printStackTrace(new PrintWriter(message)); Properties sp = System.getProperties(); String jre = sp.getProperty("java.runtime.version", sp.getProperty("java.version", "(unknown)")); String vendor = sp.getProperty("java.vendor", "(unknown vendor)"); String arch = sp.getProperty("os.arch", "(unknown arch)"); String home = sp.getProperty("java.home", "(unknown java.home)"); message.append("\n showMessage(title, message.toString(), true); } private static AWTError findGraphicsError(Throwable t) { while (t != null) { if (t instanceof AWTError) { return (AWTError)t; } t = t.getCause(); } return null; } @SuppressWarnings({"UndesirableClassUsage", "UseOfSystemOutOrSystemErr"}) public static void showMessage(String title, String message, boolean error) { PrintStream stream = error ? System.err : System.out; stream.println("\n" + title + ": " + message); boolean headless = !hasGraphics || isCommandLine() || GraphicsEnvironment.isHeadless(); if (!headless) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Throwable ignore) { } try { JTextPane textPane = new JTextPane(); textPane.setEditable(false); textPane.setText(message.replaceAll("\t", " ")); textPane.setBackground(UIManager.getColor("Panel.background")); textPane.setCaretPosition(0); JScrollPane scrollPane = new JScrollPane( textPane, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setBorder(null); int maxHeight = Toolkit.getDefaultToolkit().getScreenSize().height / 2; int maxWidth = Toolkit.getDefaultToolkit().getScreenSize().width / 2; Dimension component = scrollPane.getPreferredSize(); if (component.height > maxHeight || component.width > maxWidth) { scrollPane.setPreferredSize(new Dimension(Math.min(maxWidth, component.width), Math.min(maxHeight, component.height))); } int type = error ? JOptionPane.ERROR_MESSAGE : JOptionPane.WARNING_MESSAGE; JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), scrollPane, title, type); } catch (Throwable t) { stream.println("\nAlso, a UI exception occurred on an attempt to show the above message:"); t.printStackTrace(stream); } } } }
package inpro.apps; import inpro.apps.util.CommonCommandLineParser; import inpro.apps.util.MonitorCommandLineParser; import inpro.audio.DispatchStream; import inpro.sphinx.frontend.ConversionUtil; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import edu.cmu.sphinx.util.props.ConfigurationManager; import edu.cmu.sphinx.util.props.PropertyException; import gov.nist.jrtp.RtpErrorEvent; import gov.nist.jrtp.RtpException; import gov.nist.jrtp.RtpListener; import gov.nist.jrtp.RtpPacket; import gov.nist.jrtp.RtpPacketEvent; import gov.nist.jrtp.RtpSession; import gov.nist.jrtp.RtpStatusEvent; import gov.nist.jrtp.RtpTimeoutEvent; /** * SimpleMonitor is kind of a "mixer" application with several * input ports (microphone, OAA-goals, RTP, programmatically) and several * output ports (speakers or file). * * More or less, the software works as follows (and should probably be * refactored to be self-explanatory) * * createMicrophoneSource() * createDispatcherSource() * * * @author timo */ public class SimpleMonitor implements RtpListener { private static final Logger logger = Logger.getLogger(SimpleMonitor.class); /* make these variables global, so that they are accessible from sub functions */ final MonitorCommandLineParser clp; final ConfigurationManager cm; SourceDataLine line; FileOutputStream fileStream; SimpleMonitor(MonitorCommandLineParser clp) throws RtpException, IOException, PropertyException { this(clp, new ConfigurationManager(clp.getConfigURL())); } public SimpleMonitor(MonitorCommandLineParser clp, ConfigurationManager cm) throws RtpException, IOException, PropertyException { this.clp = clp; this.cm = cm; logger.info("Setting up output stream...\n"); if (clp.matchesOutputMode(CommonCommandLineParser.FILE_OUTPUT)) { logger.info("setting up file output to file " + clp.getAudioURL().toString()); setupFileStream(); } if (clp.matchesOutputMode(CommonCommandLineParser.SPEAKER_OUTPUT)) { logger.info("setting up speaker output"); setupSpeakers(); } switch (clp.getInputMode()) { case CommonCommandLineParser.RTP_INPUT : createRTPSource(); break; case CommonCommandLineParser.OAA_DISPATCHER_INPUT : Runnable streamDrainer = createDispatcherSource("oaaDispatchStream"); startDeamon(streamDrainer, "oaa dispatcher source"); break; case CommonCommandLineParser.DISPATCHER_OBJECT_INPUT: streamDrainer = createDispatcherSource("dispatchStream"); startDeamon(streamDrainer, "dispatcher object source"); break; case CommonCommandLineParser.DISPATCHER_OBJECT_2_INPUT: streamDrainer = createDispatcherSource("dispatchStream2"); startDeamon(streamDrainer, "dispatcher object source 2"); break; case CommonCommandLineParser.MICROPHONE_INPUT: streamDrainer = createMicrophoneSource(); startDeamon(streamDrainer, "microphone thread"); break; default: throw new RuntimeException("oups in SimpleMonitor"); } } private void startDeamon(Runnable r, String description) { Thread t = new Thread(r, description); t.setDaemon(true); t.start(); } /* setup of output streams */ /** setup output to file */ void setupFileStream() { fileStream = null; try { fileStream = new FileOutputStream(clp.getAudioURL().getFile()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** setup output to speakers */ void setupSpeakers() { AudioFormat format = getFormat(); // define the required attributes for our line, // and make sure a compatible line is supported. DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); if (!AudioSystem.isLineSupported(info)) { throw new RuntimeException("Line matching " + info + " not supported."); } // get and open the source data line for playback. try { line = (SourceDataLine) AudioSystem.getLine(info); logger.info("opening speaker with buffer size " + clp.getBufSize()); line.open(format, clp.getBufSize()); logger.info("speaker actually has buffer size " + line.getBufferSize()); } catch (LineUnavailableException ex) { throw new RuntimeException("Unable to open the line: " + ex); } // start the source data line line.start(); logger.info("output to speakers has started"); } /** defines the supported audio format */ AudioFormat getFormat() { AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED; float rate = 16000.f; int sampleSize = 16; int channels = 1; boolean bigEndian = clp.isInputMode(MonitorCommandLineParser.RTP_INPUT); return new AudioFormat(encoding, rate, sampleSize, channels, (sampleSize/8)*channels, rate, bigEndian); } /* setup of input streams */ /** * returns a runnable that will continuously read data from the microphone * and append the data read to the output stream(s) using newData() (see below) * @return a Runnable that continuously drains the microphone and pipes * its data to newData() */ Runnable createMicrophoneSource() { AudioFormat format = getFormat(); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); Runnable streamDrainer = null; if (!AudioSystem.isLineSupported(info)) { logger.error("cannot acquire line for microphone input"); } try { final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); logger.info("opening microphone with buffer size " + clp.getBufSize()); line.open(format, clp.getBufSize()); logger.info("microphone actually has buffer size " + line.getBufferSize()); streamDrainer = new Runnable() { @Override public void run() { logger.info("opened microphone, now starting."); line.start(); byte[] b = new byte[320]; // that will fit 10 ms while (true) { int bytesRead = 0; bytesRead = line.read(b, 0, b.length); if (bytesRead > 0) // no need to sleep, because the call to the microphone will already slow us down newData(b, 0, bytesRead); else // if there is no data, then we wait a little for data to become available (instead of looping like crazy) try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } } }; } catch (LineUnavailableException ex) { logger.error("cannot acquire line for microphone input"); } return streamDrainer; } /** * returns a runnable that will read data from an OAADispatchStream (which * in turn either returns silence, sine waves, or data from audio files, * depending on how it is instructed via OAA * @return a Runnable that pipes its data to newData() */ Runnable createDispatcherSource(String name) throws PropertyException { final DispatchStream ods = (DispatchStream) cm.lookup(name); ods.initialize(); Runnable streamDrainer = new Runnable() { @Override public void run() { byte[] b = new byte[320]; // that will fit 10 ms while (true) { int bytesRead = 0; try { bytesRead = ods.read(b, 0, b.length); } catch (IOException e1) { e1.printStackTrace(); } if (bytesRead > 0) // no need to sleep, because the call to the microphone will already slow us down newData(b, 0, bytesRead); else {// if there is no data, then we wait a little for data to become available (instead of looping like crazy) if (bytesRead <= 0 && ods.inShutdown()) return; try { Thread.sleep(40); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; return streamDrainer; } /** creates an RTP session that piepes incoming audio to newData() */ void createRTPSource() throws SocketException, UnknownHostException, RtpException { RtpSession rs = new RtpSession(InetAddress.getLocalHost(), clp.getLocalPort()); rs.addRtpListener(this); rs.receiveRTPPackets(); } @Override public void handleRtpPacketEvent(RtpPacketEvent arg0) { RtpPacket rp = arg0.getRtpPacket(); byte[] bytes = rp.getPayload(); int offset = (clp.isSphinxMode() ? ConversionUtil.SPHINX_RTP_HEADER_LENGTH : 0); // dirty hack, oh well newData(bytes, offset, bytes.length - offset); } @Override public void handleRtpStatusEvent(RtpStatusEvent arg0) { if (clp.verbose()) System.err.println(arg0); } @Override public void handleRtpErrorEvent(RtpErrorEvent arg0) { if (clp.verbose()) System.err.println(arg0); } @Override public void handleRtpTimeoutEvent(RtpTimeoutEvent arg0) { if (clp.verbose()) System.err.println(arg0); } @SuppressWarnings("unused") public static DispatchStream setupDispatcher(URL configURL) { ConfigurationManager cm = new ConfigurationManager(configURL); final String tmpAudio = "file:///" + System.getProperty("java.io.tmpdir") + "/" + "monitor.raw"; MonitorCommandLineParser clp = new MonitorCommandLineParser(new String[] { "-F", tmpAudio, "-S", "-M" // -M is just a placeholder here, it's immediately overridden in the next line: }); clp.setInputMode(CommonCommandLineParser.DISPATCHER_OBJECT_INPUT); try { new SimpleMonitor(clp, cm); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } return (DispatchStream) cm.lookup("dispatchStream"); } public static DispatchStream setupDispatcher() { return setupDispatcher(SimpleMonitor.class.getResource("config.xml")); } /** * handle incoming data: copy to lineout and/or filebuffer */ void newData(byte[] bytes, int offset, int length) { assert length >= 0; assert offset >= 0; assert offset + length <= bytes.length; if (clp.verbose()) { System.err.print("."); } if (clp.matchesOutputMode(CommonCommandLineParser.SPEAKER_OUTPUT)) { line.write(bytes, offset, length); } if (clp.matchesOutputMode(CommonCommandLineParser.FILE_OUTPUT)) { try { fileStream.write(bytes, offset, length); } catch (IOException e) { e.printStackTrace(); } } } @SuppressWarnings("unused") public static void main(String[] args) { MonitorCommandLineParser clp = new MonitorCommandLineParser(args); if (!clp.parsedSuccessfully()) { System.exit(1); } PropertyConfigurator.configure("log4j.properties"); try { new SimpleMonitor(clp); logger.info("up and running"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
// BUI - a user interface library for the JME 3D engine // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.jmex.bui; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.Text; import com.jme.scene.shape.Quad; import com.jme.system.DisplaySystem; import com.jmex.bui.icon.BIcon; import com.jmex.bui.text.BText; import com.jmex.bui.util.Dimension; import com.jmex.bui.util.Insets; /** * A simple component for displaying a textual label. */ public class BLabel extends BTextComponent implements BConstants { /** * Creates a label that will display the supplied text. */ public BLabel (String text) { this(text, null); } /** * Creates a label that will display the supplied text using the specified * style class. */ public BLabel (String text, String styleClass) { _label = new Label(this); _label.setText(text); if (styleClass != null) { setStyleClass(styleClass); } } /** * Creates a label that will display the supplied icon. */ public BLabel (BIcon icon) { this(icon, null); } /** * Creates a label that will display the supplied icon using the specified * style class. */ public BLabel (BIcon icon, String styleClass) { _label = new Label(this); _label.setIcon(icon); if (styleClass != null) { setStyleClass(styleClass); } } /** * Configures the label to display the specified icon. */ public void setIcon (BIcon icon) { _label.setIcon(icon); } /** * Returns the icon being displayed by this label. */ public BIcon getIcon () { return _label.getIcon(); } /** * Configures the gap between the icon and the text. */ public void setIconTextGap (int gap) { _label.setIconTextGap(gap); } /** * Returns the gap between the icon and the text. */ public int getIconTextGap () { return _label.getIconTextGap(); } /** * Sets the orientation of this label with respect to its icon. If the * horizontal (the default) the text is displayed to the right of the icon, * if vertical the text is displayed below it. */ public void setOrientation (int orient) { _label.setOrientation(orient); } // documentation inherited public void setText (String text) { _label.setText(text); } // documentation inherited public String getText () { return _label.getText(); } // documentation inherited protected String getDefaultStyleClass () { return "label"; } // documentation inherited protected void wasAdded () { super.wasAdded(); _label.wasAdded(); } // documentation inherited protected void wasRemoved () { super.wasRemoved(); _label.wasRemoved(); } // documentation inherited protected void stateDidChange () { super.stateDidChange(); _label.stateDidChange(); } // documentation inherited protected void layout () { super.layout(); _label.layout(getInsets()); } // documentation inherited protected void renderComponent (Renderer renderer) { super.renderComponent(renderer); _label.render(renderer, _alpha); } // documentation inherited protected Dimension computePreferredSize (int whint, int hhint) { return _label.computePreferredSize(whint, hhint); } protected Label _label; }
// arch-tag: 78AC4743-1110-11D9-9A79-000A957659CC package net.spy.net; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import net.spy.log.Logger; import net.spy.log.LoggerFactory; /** * A particular URL that's being watched. */ public class URLItem extends TimerTask { private static final int DEFAULT_UPDATE_FREQ = 900000; // How long a URL will be watched if nobody wants it (defaults to a // half hour). private int maxIdleTime=1800000; private int updateFrequency=DEFAULT_UPDATE_FREQ; private long lastRequest=0; private int numUpdates=0; private URL url=null; private Map<String, List<String>> lastHeaders=null; private String content=null; private long lastModified=0; private boolean isRunning=true; private IOException lastError=null; private Logger logger=null; /** * Get an instance of URLItem. * * @param u URL to watch */ public URLItem(URL u) { this(u, DEFAULT_UPDATE_FREQ); } /** * Get an instance of URLItem. * * @param u URL to watch * @param i the update frequency */ public URLItem(URL u, int i) { super(); this.updateFrequency=i; this.url=u; lastRequest=System.currentTimeMillis(); logger=LoggerFactory.getLogger(getClass()); } /** * Get a fetcher (override for testing). */ protected HTTPFetch getFetcher(Map<String, List<String>> headers) { return(new HTTPFetch(url, headers)); } private synchronized void setContent(String to, Map<String, List<String>> headers, long lastMod) { content=to; // Big chunk of debug logging. if(logger.isDebugEnabled()) { logger.debug("Setting content for %s: %s", this, content==null?"<null>":content.length() + " bytes"); } lastModified=lastMod; lastHeaders=headers; // Notify listeners that this has been updated. notifyAll(); } /** * Get the content from the last fetch. */ public synchronized String getContent() throws IOException { lastRequest=System.currentTimeMillis(); if(lastError!=null) { throw lastError; } if(logger.isDebugEnabled()) { logger.debug("Getting content for %s: %s", this, content==null?"<null>":content.length() + " bytes"); } return(content); } /** * Find out when the last request was. * * @return the timestamp of the last request. */ public long getLastRequest() { return(lastRequest); } /** * Get the URL this thing is watching. * * @return the URL */ public URL getURL() { return(url); } /** * Set the maximum number of milliseconds this URL will remain in the * container if nothing requests it. */ public void setMaxIdleTime(int to) { this.maxIdleTime=to; } /** * Get the maximum number of milliseconds this URL will remain in the * container if nothing requests it. */ public int getMaxIdleTime() { return(maxIdleTime); } /** * True if this is still running. */ public boolean isRunning() { return isRunning; } /** * Get the update frequency. */ public int getUpdateFrequency() { return updateFrequency; } public void run() { HashMap<String, List<String>> headers=new HashMap<String, List<String>>(); // make sure the stuff isn't cached ArrayList<String> tmp=new ArrayList<String>(); tmp.add("no-cache"); headers.put("Pragma", tmp); // But don't request something if we know we already have it. if(lastHeaders != null) { List<String> eTags=lastHeaders.get("ETag"); if(eTags != null) { // Put the etags in the none-match headers.put("If-None-Match", eTags); } } numUpdates++; try { logger.info("Updating %s", url); HTTPFetch hf=getFetcher(headers); hf.setIfModifiedSince(lastModified); if(hf.getStatus() == HttpURLConnection.HTTP_OK) { logger.info("Updated %s", url); setContent(hf.getData(), hf.getResponseHeaders(), hf.getLastModified()); } else { logger.info("Not saving content due to response status %s", hf.getStatus()); } } catch(IOException e) { lastError=e; } if((System.currentTimeMillis() - lastRequest) > maxIdleTime) { cancel(); isRunning=false; } } }