answer
stringlengths
17
10.2M
package com.jcwhatever.nucleus.utils.text; import com.jcwhatever.nucleus.utils.PreCon; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Replaces tags in text. * * <p>Tags consist of enclosing curly braces with tag text inside.</p> * * <p>Numbers are used to mark the index of the parameter that should be * placed where the tag is. ie {0} is parameter 1 (index 0)</p> * * <p>{@link TextColor} constant names are automatically added as tags and * replaced with the equivalent color code. ie {RED} is replaced with the * Minecraft color code for red.</p> * * <p>Tags that don't match a parameter index or other defined tag formatter * are ignored and added as is.</p> * * <p>Comments can be added to tags by inserting a colon. Useful for including * the purpose of the format tag for documentation purposes. * ie {0: This part of the tag is a comment and is ignored}</p> * */ public class TextFormatter { private static Map<String, ITagFormatter> _colors = new HashMap<>(TextColor.values().length); static { for (final TextColor color : TextColor.values()) { _colors.put(color.name(), new ITagFormatter() { @Override public String getTag() { return color.name(); } @Override public void append(StringBuilder sb, String tag) { sb.append(color.getColorCode()); } }); } } private final Map<String, ITagFormatter> _formatters = new HashMap<>(20); private final StringBuilder _textBuffer = new StringBuilder(100); private final StringBuilder _tagBuffer = new StringBuilder(25); /** * Constructor. */ public TextFormatter(){} /** * Constructor. * * @param formatters A collection of formatters to include. */ public TextFormatter(Collection<? extends ITagFormatter> formatters) { for (ITagFormatter formatter : formatters) { _formatters.put(formatter.getTag(), formatter); } } /** * Constructor. * * @param formatters The formatters to include. */ public TextFormatter(ITagFormatter... formatters) { for (ITagFormatter formatter : formatters) { _formatters.put(formatter.getTag(), formatter); } } /** * Get a default tag formatter by case sensitive tag. * * @param tag The tag text. */ public ITagFormatter getFormatter(String tag) { return _formatters.get(tag); } /** * Get all default tag formatters. */ public List<ITagFormatter> getFormatters() { return new ArrayList<>(_formatters.values()); } /** * Remove a default tag formatter. * * @param tag The tag to remove. */ public void removeFormatter(String tag) { _formatters.remove(tag); } /** * Add a default tag formatter. * * @param formatter The tag formatter to add. */ public void addFormatter(ITagFormatter formatter) { _formatters.put(formatter.getTag(), formatter); } /** * Format text. * * @param template The template text. * @param params The parameters to add. * * @return The formatted string. */ public String format(String template, Object... params) { PreCon.notNull(template); return format(_formatters, template, params); } /** * Format text using a custom set of formatters. * * @param formatters The formatter map to use. * @param template The template text. * @param params The parameters to add. * * @return The formatted string. */ public String format(Map<String, ITagFormatter> formatters, String template, Object... params) { PreCon.notNull(template); if (template.indexOf('{') == -1 && template.indexOf('\\') == -1) return template; _textBuffer.setLength(0); for (int i=0; i < template.length(); i++) { char ch = template.charAt(i); // check for tag opening if (ch == '{') { // parse tag String tag = parseTag(template, i); // update index position i += _tagBuffer.length(); // template ended before tag was closed if (tag == null) { _textBuffer.append('{'); _textBuffer.append(_tagBuffer); } // tag parsed else { i++; // add 1 for closing brace appendReplacement(_textBuffer, tag, params, formatters); } } else if (ch == '\\' && i < template.length() - 1) { char next = template.charAt(i + 1); if (next == '\\') { // append escaped back slash _textBuffer.append(ch); _textBuffer.append(next); i++; } else if (next == 'n' || next == 'r') { // append new line _textBuffer.append('\n'); i++; } else if (next == 'u') { i++; char unicode = parseUnicode(template, i); if (unicode == 0) { // append non unicode text _textBuffer.append("\\u"); } else { _textBuffer.append(unicode); i+= Math.min(4, template.length() - i); } } else { // append non unicode back slash _textBuffer.append(ch); } } else { // append next character _textBuffer.append(ch); } } return _textBuffer.toString(); } /** * Parse a unicode character from the string */ private char parseUnicode(String template, int currentIndex) { _tagBuffer.setLength(0); for (int i=currentIndex + 1, readCount=0; i < template.length(); i++, readCount++) { if (readCount == 4) { break; } else { char ch = template.charAt(i); if ("01234567890abcdefABCDEF".indexOf(ch) == -1) return 0; _tagBuffer.append(ch); } } if (_tagBuffer.length() == 4) { try { return (char) Integer.parseInt(_tagBuffer.toString(), 16); } catch (NumberFormatException ignore) { return 0; } } return 0; } /* * Parse a single tag from the template */ private String parseTag(String template, int currentIndex) { _tagBuffer.setLength(0); for (int i=currentIndex + 1; i < template.length(); i++) { char ch = template.charAt(i); if (ch == '}') { return _tagBuffer.toString(); } else { _tagBuffer.append(ch); } } return null; } /* * Append replacement text for a tag */ private void appendReplacement(StringBuilder sb, String tag, Object[] params, Map<String, ITagFormatter> formatters) { boolean isNumber = !tag.isEmpty(); _tagBuffer.setLength(0); // parse out tag from comment section for (int i=0; i < tag.length(); i++) { char ch = tag.charAt(i); // done at comment character if (ch == ':') { break; } // append next tag character else { _tagBuffer.append(ch); // check if the character is a number if (isNumber && !Character.isDigit(ch)) { isNumber = false; } } } String parsedTag = _tagBuffer.toString(); if (isNumber) { int index = Integer.parseInt(parsedTag); // make sure number is in the range of the provided parameters. if (params.length <= index) { reappendTag(sb, tag); } // replace number with parameter argument. else { String toAppend = String.valueOf(params[index]); String lastColors = null; // make sure colors from inserted text do not continue // into template text if (toAppend.indexOf(TextColor.FORMAT_CHAR) != -1) { lastColors = TextColor.getEndColor(sb); } // append parameter argument sb.append(params[index]); // append template color if (lastColors != null && !lastColors.isEmpty()) { sb.append(lastColors); } } } else { // check for custom formatter ITagFormatter formatter = formatters.get(parsedTag); if (formatter == null) { // check for color formatter formatter = _colors.get(parsedTag); } if (formatter != null) { // formatter appends replacement text to format buffer formatter.append(sb, tag); } else { // no formatter, append tag to result buffer reappendTag(sb, tag); } } } /* * Append raw tag to string builder */ private void reappendTag(StringBuilder sb, String tag) { sb.append('{'); sb.append(tag); sb.append('}'); } /** * Defines a format tag. */ public static interface ITagFormatter { /** * Get the format tag. */ String getTag(); /** * Append replacement text into the provided * string builder. The parsed tag is provided for reference. * * @param sb The string builder to append to. * @param rawTag The tag that was parsed. */ void append(StringBuilder sb, String rawTag); } }
package com.ktl.moment.android.fragment; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.ktl.moment.R; import com.ktl.moment.android.activity.AccountActivity; import com.ktl.moment.android.adapter.MomentListViewAdapter; import com.ktl.moment.android.base.BaseFragment; import com.ktl.moment.android.component.LoadingDialog; import com.ktl.moment.android.component.listview.arc.widget.SimpleFooter; import com.ktl.moment.android.component.listview.arc.widget.SimpleHeader; import com.ktl.moment.android.component.listview.arc.widget.ZrcListView; import com.ktl.moment.android.component.listview.arc.widget.ZrcListView.OnStartListener; import com.ktl.moment.common.Account; import com.ktl.moment.common.constant.C; import com.ktl.moment.entity.Moment; import com.ktl.moment.entity.User; import com.ktl.moment.infrastructure.HttpCallBack; import com.ktl.moment.utils.ToastUtil; import com.ktl.moment.utils.net.ApiManager; import com.loopj.android.http.RequestParams; public class DynamicFragment extends BaseFragment { private static final String TAG = "dynamicFragment"; private ZrcListView dynamicListView; private List<Moment> momentList; private int pageSize = 5; private int pageNum = 1; private MomentListViewAdapter dynamicListViewAdapter; private long userId; private LoadingDialog loading; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.fragment_dynamic, container, false); dynamicListView = (ZrcListView) view .findViewById(R.id.fragment_dynamic_list); // show loading dialog after fragment create User user = Account.getUserInfo(); if (user == null) { Intent intent = new Intent(getActivity(), AccountActivity.class); startActivity(intent); getActivity().finish(); } userId = user.getUserId(); initView(); if(momentList==null){ momentList = new ArrayList<Moment>(); } if(momentList.size()==0){ Log.i(TAG,"listView-->refresh"); dynamicListView.refresh(); loading = new LoadingDialog(getActivity()); loading.show(); } dynamicListViewAdapter = new MomentListViewAdapter(getActivity(),momentList, getDisplayImageOptions()); dynamicListView.setAdapter(dynamicListViewAdapter); initEvent(); return view; } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); Log.i(TAG,"OnResume"); } private void initView() { // Header SimpleHeader header = new SimpleHeader(getActivity()); header.setTextColor(0xff0066aa); header.setCircleColor(0xff33bbee); dynamicListView.setHeadable(header); SimpleFooter footer = new SimpleFooter(getActivity()); footer.setCircleColor(0xff33bbee); dynamicListView.setFootable(footer); dynamicListView.setItemAnimForTopIn(R.anim.zrc_topitem_in); dynamicListView.setItemAnimForBottomIn(R.anim.zrc_bottomitem_in); dynamicListView.stopLoadMore(); } private void initEvent() { dynamicListView.setOnRefreshStartListener(new OnStartListener() { @Override public void onStart() { getDataFromServer(); } }); dynamicListView.setOnLoadMoreStartListener(new OnStartListener() { @Override public void onStart() { loadMoreMoment(); } }); } private void getDataFromServer() { pageNum = 1; RequestParams params = new RequestParams(); params.put("pageNum", pageNum); params.put("pageSize", pageSize); params.put("userId", userId); ApiManager.getInstance().post(getActivity(), C.API.GET_HOME_FOCUS_LIST, params, new HttpCallBack() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object res) { // TODO Auto-generated method stub List<Moment> moments = (List<Moment>) res; if(momentList==null){ momentList = new ArrayList<Moment>(); } momentList.clear(); momentList.addAll(moments); new Handler().postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub loading.dismiss(); dynamicListViewAdapter.notifyDataSetChanged(); dynamicListView.setRefreshSuccess(""); dynamicListView.startLoadMore(); } }, 500); } @Override public void onFailure(Object res) { // TODO Auto-generated method stub // ToastUtil.show(getActivity(), str);// Toast.makeText(getActivity(), "!", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub dynamicListView.setRefreshSuccess(""); loading.dismiss(); } }, 1000); } }, "Moment"); } private void loadMoreMoment(){ RequestParams params = new RequestParams(); params.put("pageNum", ++pageNum); params.put("pageSize", pageSize); params.put("userId", userId); ApiManager.getInstance().post(getActivity(), C.API.GET_HOME_FOCUS_LIST, params, new HttpCallBack() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object res) { // TODO Auto-generated method stub dynamicListView.setLoadMoreSuccess(); List<Moment> moments = (List<Moment>) res; if(moments == null || moments.isEmpty()){ dynamicListView.stopLoadMore(); ToastUtil.show(getActivity(), "~"); return ; } if(momentList==null){ momentList = new ArrayList<Moment>(); } momentList.addAll(moments); dynamicListViewAdapter.notifyDataSetChanged(); } @Override public void onFailure(Object res) { // TODO Auto-generated method stub // ToastUtil.show(getActivity(), (String) res); Toast.makeText(getActivity(), "!", Toast.LENGTH_SHORT).show(); } }, "Moment"); } }
package com.momoweather.app.activity; import java.util.ArrayList; import java.util.List; import com.example.momoweather.R; import com.momoweather.app.model.City; import com.momoweather.app.model.Country; import com.momoweather.app.model.MoMoWeatherDB; import com.momoweather.app.model.Province; import com.momoweather.app.util.HttpCallbackListener; import com.momoweather.app.util.HttpUtil; import com.momoweather.app.util.Utility; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ChooseAreaActivity extends Activity{ public static final int LEVEL_PROVINCE = 0 ; public static final int LEVEL_CITY = 1 ; public static final int LEVEL_COUNTRY = 2; public static int currentLevel ; private ProgressDialog dialog ; private ListView contentList ; private TextView titleText ; private ArrayAdapter<String> adapter ; private MoMoWeatherDB momoWeatherDB ; private List<String> dataList = new ArrayList<String>(); private List<Province> provincesList ; private List<City> citiesList ; private List<Country> countriesList ; private Province selectedProvince ; private City selectedCity ; private boolean isFromWeatherActivity ; public ChooseAreaActivity() { } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ChooseAreaActivity.this); isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false); if(prefs.getBoolean("city_selected" , false) && !isFromWeatherActivity){ Intent intent = new Intent(this,WeatherActivity.class); startActivity(intent); finish(); return ; } requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.choose_area); contentList = (ListView)findViewById(R.id.content_list); titleText = (TextView)findViewById(R.id.title_text); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList); contentList.setAdapter(adapter); momoWeatherDB = MoMoWeatherDB.getInstance(this); contentList.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub if(currentLevel == LEVEL_PROVINCE){ selectedProvince = provincesList.get(position); queryCities(); }else if(currentLevel == LEVEL_CITY){ selectedCity = citiesList.get(position); queryCountries(); }else if(currentLevel == LEVEL_COUNTRY){ String countryCode = countriesList.get(position).getCountryCode(); Intent intent = new Intent(ChooseAreaActivity.this,WeatherActivity.class); intent.putExtra("country_code",countryCode); startActivity(intent); finish(); } } }); queryProvinces(); } protected void queryProvinces() { // TODO Auto-generated method stub provincesList = momoWeatherDB.loadProvinces() ; if(provincesList.size()>0){ dataList.clear(); for(Province province : provincesList){ dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); contentList.setSelection(0); titleText.setText("й"); currentLevel = LEVEL_PROVINCE ; }else{ queryFromServer(null,"province"); } } protected void queryCities() { // TODO Auto-generated method stub citiesList = momoWeatherDB.loadCities(selectedProvince.getId()) ; if(citiesList.size()>0){ dataList.clear(); for(City city : citiesList){ dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); contentList.setSelection(0); titleText.setText(selectedProvince.getProvinceName()); currentLevel = LEVEL_CITY ; }else { queryFromServer(selectedProvince.getProvinceCode(),"city"); } } protected void queryCountries() { // TODO Auto-generated method stub countriesList = momoWeatherDB.loadCounties(selectedCity.getId()) ; if(countriesList.size()>0){ dataList.clear(); for(Country country : countriesList){ dataList.add(country.getCountryName()); } adapter.notifyDataSetChanged(); contentList.setSelection(0); titleText.setText(selectedCity.getCityName()); currentLevel = LEVEL_COUNTRY ; }else { queryFromServer(selectedCity.getCityCode(),"country") ; } } public void queryFromServer(final String code, final String type) { // TODO Auto-generated method stub String address ; if(!TextUtils.isEmpty(code)){ address = "http: }else{ address = "http: } showProgressDialog(); HttpUtil.sendHttpRequest(address, new HttpCallbackListener(){ @Override public void onFinish(String response) { // TODO Auto-generated method stub boolean result = false ; if("province".equals(type)){ result = Utility.handleProvincesResponse(momoWeatherDB, response); }else if("city".equals(type)){ result = Utility.handleCitiesResponse(momoWeatherDB, response, selectedProvince.getId()); }else if("country".equals(type)){ result = Utility.handleCountriesResponse(momoWeatherDB, response, selectedCity.getId()); } if(result){ runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub closeProgressDialog(); if("province".equals(type)){ queryProvinces(); }else if("city".equals(type)){ queryCities(); }else if("country".equals(type)){ queryCountries(); } } }); } } @Override public void onError(Exception e) { // TODO Auto-generated method stub runOnUiThread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub closeProgressDialog(); Toast.makeText(getApplicationContext(), "ʧ", Toast.LENGTH_SHORT).show(); } }); } }); } private void showProgressDialog() { // TODO Auto-generated method stub if(dialog == null){ dialog = new ProgressDialog(this); dialog.setMessage("ڼء"); dialog.setCanceledOnTouchOutside(false); } dialog.show(); } private void closeProgressDialog() { // TODO Auto-generated method stub if(dialog != null){ dialog.dismiss(); } } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); if(currentLevel == LEVEL_COUNTRY){ queryCities(); }else if(currentLevel == LEVEL_CITY){ queryProvinces(); }else{ if(isFromWeatherActivity){ Intent intent = new Intent(this,WeatherActivity.class); startActivity(intent); } finish(); } } }
package com.swabunga.spell.engine; import java.io.*; import java.io.File; import java.io.IOException; import java.security.InvalidParameterException; import java.util.*; public abstract class SpellDictionaryASpell implements SpellDictionary { /** The reference to a Transformator, used to transform a word into it's phonetic code. */ protected Transformator tf; public SpellDictionaryASpell(File phonetic) throws IOException { if (phonetic == null) tf = new DoubleMeta(); else tf = new GenericTransformator(phonetic); } public SpellDictionaryASpell(Reader phonetic) throws IOException { if (phonetic == null) tf = new DoubleMeta(); else tf = new GenericTransformator(phonetic); } /** * Returns a list of Word objects that are the suggestions to an * incorrect word. * <p> * @param word Suggestions for given mispelt word * @param threshold The lower boundary of similarity to mispelt word * @return Vector a List of suggestions */ public List getSuggestions(String word, int threshold) { Hashtable nearmisscodes = new Hashtable(); String code = getCode(word); // add all words that have the same phonetics nearmisscodes.put(code, code); Vector phoneticList = getWordsFromCode(word, nearmisscodes); // do some tranformations to pick up more results //interchange nearmisscodes = new Hashtable(); char[] charArray = word.toCharArray(); for (int i = 0; i < word.length() - 1; i++) { char a = charArray[i]; char b = charArray[i + 1]; charArray[i] = b; charArray[i + 1] = a; String s = getCode(new String(charArray)); nearmisscodes.put(s, s); charArray[i] = a; charArray[i + 1] = b; } char[] replacelist = tf.getReplaceList(); //change charArray = word.toCharArray(); for (int i = 0; i < word.length(); i++) { char original = charArray[i]; for (int j = 0; j < replacelist.length; j++) { charArray[i] = replacelist[j]; String s = getCode(new String(charArray)); nearmisscodes.put(s, s); } charArray[i] = original; } //add charArray = (word += " ").toCharArray(); int iy = charArray.length - 1; while (true) { for (int j = 0; j < replacelist.length; j++) { charArray[iy] = replacelist[j]; String s = getCode(new String(charArray)); nearmisscodes.put(s, s); } if (iy == 0) break; charArray[iy] = charArray[iy - 1]; --iy; } //delete word = word.trim(); charArray = word.toCharArray(); char[] charArray2 = new char[charArray.length - 1]; for (int ix = 0; ix < charArray2.length; ix++) { charArray2[ix] = charArray[ix]; } char a, b; a = charArray[charArray.length - 1]; int ii = charArray2.length; while (true) { String s = getCode(new String(charArray)); nearmisscodes.put(s, s); if (ii == 0) break; b = a; a = charArray2[ii - 1]; charArray2[ii - 1] = b; --ii; } nearmisscodes.remove(code); //already accounted for in phoneticList Vector wordlist = getWordsFromCode(word, nearmisscodes); if (wordlist.size() == 0 && phoneticList.size() == 0) addBestGuess(word,phoneticList); // We sort a Vector at the end instead of maintaining a // continously sorted TreeSet because everytime you add a collection // to a treeset it has to be resorted. It's better to do this operation // once at the end. Collections.sort( phoneticList, new Word()); //always sort phonetic matches along the top Collections.sort( wordlist, new Word()); //the non-phonetic matches can be listed below phoneticList.addAll(wordlist); return phoneticList; } /** * When we don't come up with any suggestions (probably because the threshold was too strict), * then pick the best guesses from the those words that have the same phonetic code. * @param word - the word we are trying spell correct * @param wordList - the linked list that will get the best guess */ private void addBestGuess(String word, Vector wordList) { if (wordList.size() != 0) throw new InvalidParameterException("the wordList vector must be empty"); int bestScore = Integer.MAX_VALUE; String code = getCode(word); List simwordlist = getWords(code); LinkedList candidates = new LinkedList(); for (Iterator j = simwordlist.iterator(); j.hasNext();) { String similar = (String) j.next(); int distance = EditDistance.getDistance(word, similar); if (distance <= bestScore) { bestScore = distance; Word goodGuess = new Word(similar, distance); candidates.add(goodGuess); } } //now, only pull out the guesses that had the best score for (Iterator iter = candidates.iterator(); iter.hasNext();) { Word candidate = (Word) iter.next(); if (candidate.getCost() == bestScore) wordList.add(candidate); } } private Vector getWordsFromCode(String word, Hashtable codes) { Configuration config = Configuration.getConfiguration(); Vector result = new Vector(); final int configDistance = config.getInteger(Configuration.SPELL_THRESHOLD); for (Enumeration i = codes.keys();i.hasMoreElements();) { String code = (String) i.nextElement(); List simwordlist = getWords(code); for (Iterator iter = simwordlist.iterator(); iter.hasNext();) { String similar = (String) iter.next(); int distance = EditDistance.getDistance(word, similar); if (distance < configDistance) { Word w = new Word(similar, distance); result.addElement(w); } } } return result; } /** * Returns the phonetic code representing the word. */ public String getCode(String word) { return tf.transform(word); } /** * Returns a list of words that have the same phonetic code. */ protected abstract List getWords(String phoneticCode); /** * Returns true if the word is correctly spelled against the current word list. */ public boolean isCorrect(String word) { List possible = getWords(getCode(word)); if (possible.contains(word)) return true; //JMH should we always try the lowercase version. If I dont then capitalised //words are always returned as incorrect. else if (possible.contains(word.toLowerCase())) return true; return false; } }
package de.fun2code.android.piratebox.widget; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; import de.fun2code.android.piratebox.Constants; import de.fun2code.android.piratebox.R; public class InfoWidget extends AppWidgetProvider { private static String TAG = "PirateBoxInfoWidget"; private final String WIDGET_INTENT_CLICKED = "de.fun2code.android.piratebox.infowidget.intent.clicked"; private static boolean serverStatus = false; private static int uploads = 0; private static int shouts = 0; private static int connections = 0; @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); AppWidgetManager manager = AppWidgetManager.getInstance(context); int[] widgetIds = manager.getAppWidgetIds(new ComponentName(context, InfoWidget.class)); //Toast.makeText(context, intent.getAction(), Toast.LENGTH_SHORT).show(); if(intent.getAction() .equals(Constants.BROADCAST_INTENT_SERVER)) { serverStatus = intent.getBooleanExtra(Constants.INTENT_SERVER_EXTRA_STATE, false); } else if(intent.getAction() .equals(Constants.BROADCAST_INTENT_STATUS_RESULT)) { serverStatus = intent.getBooleanExtra(Constants.INTENT_SERVER_EXTRA_STATE, false); uploads = intent.getIntExtra(Constants.INTENT_UPLOAD_EXTRA_NUMBER, 0); shouts = intent.getIntExtra(Constants.INTENT_SHOUT_EXTRA_NUMBER, 0); connections = intent.getIntExtra(Constants.INTENT_CONNECTION_EXTRA_NUMBER, 0); } else if(intent.getAction() .equals(Constants.BROADCAST_INTENT_UPLOAD)) { uploads++; } else if(intent.getAction() .equals(Constants.BROADCAST_INTENT_SHOUT)) { shouts++; } else if(intent.getAction() .equals(Constants.BROADCAST_INTENT_CONNECTION)) { connections++; } else if(intent.getAction() .equals(WIDGET_INTENT_CLICKED) || intent.getAction() .equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) { // Send broadcast to request info context.sendBroadcast(new Intent(Constants.BROADCAST_INTENT_STATUS_REQUEST)); } showWidget(context, manager, widgetIds); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] ints) { context.sendBroadcast(new Intent(Constants.BROADCAST_INTENT_STATUS_REQUEST)); showWidget(context, appWidgetManager, ints); } private void showWidget(Context context, AppWidgetManager manager, int[] widgetIds) { RemoteViews views = createRemoteViews(context); manager.updateAppWidget(widgetIds, views); } private RemoteViews createRemoteViews(Context context) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_info_layout); //views.setTextViewText(R.id.textStatus, serverStatus ? "up" : "down"); views.setTextViewText(R.id.textUploads, String.valueOf(uploads)); views.setTextViewText(R.id.textShouts, String.valueOf(shouts)); views.setTextViewText(R.id.textConnections, String.valueOf(connections)); Intent msg = new Intent(WIDGET_INTENT_CLICKED); PendingIntent intent = PendingIntent.getBroadcast(context, -1 /*not used*/, msg, PendingIntent.FLAG_UPDATE_CURRENT); views.setOnClickPendingIntent(R.id.main, intent); return views; } @Override public void onDisabled(Context context) { super.onDisabled(context); } @Override public void onEnabled(Context context) { super.onEnabled(context); context.sendBroadcast(new Intent(Constants.BROADCAST_INTENT_STATUS_REQUEST)); } }
package dk.netarkivet.harvester.scheduler; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import dk.netarkivet.common.distribute.JMSConnection; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.IOFailure; import dk.netarkivet.common.utils.ExceptionUtils; import dk.netarkivet.harvester.datamodel.HarvestDefinitionDAO; import dk.netarkivet.harvester.datamodel.Job; import dk.netarkivet.harvester.datamodel.JobDAO; import dk.netarkivet.harvester.datamodel.JobPriority; import dk.netarkivet.harvester.datamodel.JobStatus; import dk.netarkivet.harvester.datamodel.SparseFullHarvest; import dk.netarkivet.harvester.datamodel.SparsePartialHarvest; import dk.netarkivet.harvester.harvesting.HeritrixLauncher; import dk.netarkivet.harvester.harvesting.distribute.DoOneCrawlMessage; import dk.netarkivet.harvester.harvesting.distribute.JobChannelUtil; import dk.netarkivet.harvester.harvesting.distribute.MetadataEntry; import dk.netarkivet.harvester.harvesting.distribute.PersistentJobData.HarvestDefinitionInfo; /** * This class handles dispatching of Harvest jobs to the Harvesters. */ public class JobDispatcher { /** The logger to use. */ private final Log log = LogFactory.getLog(getClass()); /** Connection to JMS provider. */ private JMSConnection jmsConnection; /** For jobDB access. */ private JobDAO jobDao; /** * @param jmsConnection The JMS connection to use. */ public JobDispatcher(JMSConnection jmsConnection, JobDAO dao) { log.info("Creating JobDispatcher"); ArgumentNotValid.checkNotNull(jmsConnection, "jmsConnection"); this.jmsConnection = jmsConnection; } /** * Submit the next new job (the one with the lowest ID) with the given * priority, and updates the internal counter as needed. If no jobs are * ready for the given priority, nothing is done * @param priority the job priority */ protected void submitNextNewJob(JobPriority priority) { final JobDAO dao = JobDAO.getInstance(); Job jobToSubmit = prepareNextJobForSubmission(priority); if (jobToSubmit == null) { if (log.isTraceEnabled()) { log.trace("No " + priority + " jobs to be run at this time"); } } else { if (log.isDebugEnabled()) { log.debug("Submitting new " + priority + " job"); } try { List<MetadataEntry> metadata = createMetadata(jobToSubmit); // Extract documentary information about the harvest HarvestDefinitionDAO hDao = HarvestDefinitionDAO.getInstance(); String hName = hDao.getHarvestName( jobToSubmit.getOrigHarvestDefinitionID()); String schedule = ""; String hdComments = ""; SparseFullHarvest fh = hDao.getSparseFullHarvest(hName); if (fh != null) { hdComments = fh.getComments(); } else { SparsePartialHarvest ph = hDao.getSparsePartialHarvest(hName); if (ph == null) { throw new ArgumentNotValid("No harvest definition " + "found for id '" + jobToSubmit.getOrigHarvestDefinitionID() + "', named '" + hName + "'"); } // The schedule name can only be documented for // selective crawls. schedule = ph.getScheduleName(); hdComments = ph.getComments(); } doOneCrawl(jobToSubmit, hName, hdComments, schedule, metadata); log.info("Submitting job: " + jobToSubmit); } catch (Throwable e) { String message = "Error while dispatching job " + jobToSubmit.getJobID() + ". Job status changed to FAILED"; log.warn(message, e); if (jobToSubmit != null) { jobToSubmit.setStatus(JobStatus.FAILED); jobToSubmit.appendHarvestErrors(message); jobToSubmit.appendHarvestErrorDetails( ExceptionUtils.getStackTrace(e)); dao.update(jobToSubmit); } } } } /** * Will read the next job ready to run from the db and set the job to * submitted. If no job are ready, null will be returned. * * Note the operation is synchronized, so only one thread may start the * submission of a job. * @param priority the job priority. * @return The job prepared for submission. */ private synchronized Job prepareNextJobForSubmission(JobPriority priority) { final JobDAO dao = JobDAO.getInstance(); Iterator<Long> jobsToSubmit = dao.getAllJobIds(JobStatus.NEW, priority); if (!jobsToSubmit.hasNext()) { return null; } else { if (log.isDebugEnabled()) { log.debug("Submitting new " + priority + " job"); } final long jobID = jobsToSubmit.next(); Job jobToSubmit = null; jobToSubmit = dao.read(jobID); jobToSubmit.setStatus(JobStatus.SUBMITTED); jobToSubmit.setSubmittedDate(new Date()); dao.update(jobToSubmit); return jobToSubmit; } } /** * Creates the metadata for the indicated job. This includes: <ol> * <li> Alias metadata. * <li>DuplicationReduction MetadataEntry, if Deduplication * //is enabled. * @param job The job to create meta data for. */ private List<MetadataEntry> createMetadata(Job job) { final JobDAO dao = JobDAO.getInstance(); List<MetadataEntry> metadata = new ArrayList<MetadataEntry>(); MetadataEntry aliasMetadataEntry = MetadataEntry.makeAliasMetadataEntry( job.getJobAliasInfo(), job.getOrigHarvestDefinitionID(), job.getHarvestNum(), job.getJobID()); if (aliasMetadataEntry != null) { metadata.add(aliasMetadataEntry); } if (HeritrixLauncher.isDeduplicationEnabledInTemplate( job.getOrderXMLdoc())) { MetadataEntry duplicateReductionMetadataEntry = MetadataEntry.makeDuplicateReductionMetadataEntry( dao.getJobIDsForDuplicateReduction(job.getJobID()), job.getOrigHarvestDefinitionID(), job.getHarvestNum(), job.getJobID() ); if (duplicateReductionMetadataEntry != null) { metadata.add(duplicateReductionMetadataEntry); } } return metadata; } /** * Submit an doOneCrawl request to a HarvestControllerServer. * @param job the specific job to send * @param origHarvestName the harvest definition's name * @param origHarvestDesc the harvest definition's description * @param origHarvestSchedule the harvest definition schedule name * @param metadata pre-harvest metadata to store in arcfile. * @throws ArgumentNotValid one of the parameters are null * @throws IOFailure if unable to send the doOneCrawl request to a * harvestControllerServer */ public void doOneCrawl( Job job, String origHarvestName, String origHarvestDesc, String origHarvestSchedule, List<MetadataEntry> metadata) throws ArgumentNotValid, IOFailure { ArgumentNotValid.checkNotNull(job, "job"); ArgumentNotValid.checkNotNull(metadata, "metadata"); DoOneCrawlMessage nMsg = new DoOneCrawlMessage( job, JobChannelUtil.getChannel(job.getPriority()), new HarvestDefinitionInfo( origHarvestName, origHarvestDesc, origHarvestSchedule), metadata); if (log.isDebugEnabled()) { log.debug("Send crawl request: " + nMsg); } jmsConnection.send(nMsg); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.ghouse.drivesystem.MultiCANJaguar; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.can.CANTimeoutException; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class GHouse2014Robot extends SimpleRobot { /*** Constants ***/ private final int PRESSURE_SWITCH_CH = 1; //Digital IO private final int COMPRESSOR_RELAY_CH = 2; //Digital IO //Speed change solenoid channels private final int LEFT_SPEED_CHANGE_CH = 1; //Pneumatics Slot private final int RIGHT_SPEED_CHANGE_CH = 2; //Pneumatics Slot //Feed arm solenoid channels private final int FEED_LEFT_ARM_CH = 3; //Pneumatics Slot private final int FEED_RIGHT_ARM_CH = 4; //Pneumatics Slot private final int FEED_MOTOR_CH = 1; //PWM Port //Scissor Lift private final int SCISSOR_LEFT_PISTON_CH = 5; //Pneumatics Slot private final int SCISSOR_RIGHT_PISTON_CH = 6; //Pneumatics Slot /*** General Components ***/ private Compressor compressor = new Compressor(PRESSURE_SWITCH_CH, COMPRESSOR_RELAY_CH); /*** Drivetrain Components ***/ private final int leftControllerChannels[] = {11, 12, 13}; private final int rightControllerChannels[] = {14, 15, 16}; private MultiCANJaguar leftController, rightController; private RobotDrive chassis; private Solenoid leftSpeedChangeSolenoid = new Solenoid(LEFT_SPEED_CHANGE_CH); private Solenoid rightSpeedChangeSolenoid = new Solenoid(RIGHT_SPEED_CHANGE_CH); /*** Feed Mechanism ***/ private Solenoid leftFeedArmSolenoid = new Solenoid(FEED_LEFT_ARM_CH); private Solenoid rightFeedArmSolenoid = new Solenoid(FEED_RIGHT_ARM_CH); private Victor feedMotor = new Victor(FEED_MOTOR_CH); /*** Scissor Lift Mechanism ***/ private Solenoid leftScissorPiston = new Solenoid(SCISSOR_LEFT_PISTON_CH); private Solenoid rightScissorPiston = new Solenoid(SCISSOR_RIGHT_PISTON_CH); public GHouse2014Robot() { try { leftController = new MultiCANJaguar(leftControllerChannels); rightController = new MultiCANJaguar(rightControllerChannels); chassis = new RobotDrive(leftController, rightController); //Setup routines //Start the compressor compressor.start(); } catch (CANTimeoutException e) { System.out.println("WARNING: CANTimeoutException: " + e.getMessage()); } } /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { while (isEnabled() && isAutonomous()) { } } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { //TODO Do any initial resetting here //Default loop while (isEnabled() && isOperatorControl()) { //1) Sense //TODO: Take in any sensor data that we need //2) Act } } /** * This function is called once each time the robot enters test mode. */ public void test() { } }
package net.fortuna.ical4j.model.component; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.Calendar; import java.util.Iterator; import junit.framework.TestSuite; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Dur; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.PeriodList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.Recur; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.WeekDay; import net.fortuna.ical4j.model.parameter.TzId; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.ExDate; import net.fortuna.ical4j.model.property.Method; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.util.Calendars; import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.UidGenerator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * $Id: VEventTest.java [28/09/2004] * * A test case for VEvents. * @author Ben Fortuna */ public class VEventTest extends CalendarComponentTest { private static Log log = LogFactory.getLog(VEventTest.class); private VEvent event; private Period period; private Date date; private TzId tzParam; /** * @param testMethod */ public VEventTest(String testMethod) { super(testMethod, null); } /** * @param testMethod * @param component */ public VEventTest(String testMethod, VEvent event) { super(testMethod, event); this.event = event; } /** * @param testMethod * @param component * @param period */ public VEventTest(String testMethod, VEvent component, Period period) { this(testMethod, component); this.period = period; } /** * @param testMethod * @param component * @param date */ public VEventTest(String testMethod, VEvent component, Date date) { this(testMethod, component); this.date = date; } /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ public void setUp() throws Exception { super.setUp(); // relax validation to avoid UID requirement.. CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); // create timezone property.. VTimeZone tz = registry.getTimeZone("Australia/Melbourne").getVTimeZone(); // create tzid parameter.. tzParam = new TzId(tz.getProperty(Property.TZID).getValue()); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { // relax validation to avoid UID requirement.. CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_VALIDATION, false); super.tearDown(); } /** * @return */ private static Calendar getCalendarInstance() { return Calendar.getInstance(); //java.util.TimeZone.getTimeZone(TimeZones.GMT_ID)); } /** * @param filename * @return */ private net.fortuna.ical4j.model.Calendar loadCalendar(String filename) throws IOException, ParserException, ValidationException { net.fortuna.ical4j.model.Calendar calendar = Calendars.load( filename); calendar.validate(); log.info("File: " + filename); if (log.isDebugEnabled()) { log.debug("Calendar:\n=========\n" + calendar.toString()); } return calendar; } public final void testChristmas() { // create event start date.. java.util.Calendar calendar = getCalendarInstance(); calendar.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); calendar.set(java.util.Calendar.DAY_OF_MONTH, 25); DtStart start = new DtStart(new Date(calendar.getTime())); start.getParameters().add(tzParam); start.getParameters().add(Value.DATE); Summary summary = new Summary("Christmas Day; \n this is a, test\\"); VEvent christmas = new VEvent(); christmas.getProperties().add(start); christmas.getProperties().add(summary); log.info(christmas); } /** * Test creating an event with an associated timezone. */ public final void testMelbourneCup() { TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); TimeZone timezone = registry.getTimeZone("Australia/Melbourne"); java.util.Calendar cal = java.util.Calendar.getInstance(timezone); cal.set(java.util.Calendar.YEAR, 2005); cal.set(java.util.Calendar.MONTH, java.util.Calendar.NOVEMBER); cal.set(java.util.Calendar.DAY_OF_MONTH, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 15); cal.clear(java.util.Calendar.MINUTE); cal.clear(java.util.Calendar.SECOND); DateTime dt = new DateTime(cal.getTime()); dt.setTimeZone(timezone); VEvent melbourneCup = new VEvent(dt, "Melbourne Cup"); log.info(melbourneCup); } public final void test2() { java.util.Calendar cal = getCalendarInstance(); cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); cal.set(java.util.Calendar.DAY_OF_MONTH, 25); VEvent christmas = new VEvent(new Date(cal.getTime()), "Christmas Day"); // initialise as an all-day event.. christmas.getProperty(Property.DTSTART).getParameters().add(Value.DATE); // add timezone information.. christmas.getProperty(Property.DTSTART).getParameters().add(tzParam); log.info(christmas); } public final void test3() { java.util.Calendar cal = getCalendarInstance(); // tomorrow.. cal.add(java.util.Calendar.DAY_OF_MONTH, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 9); cal.set(java.util.Calendar.MINUTE, 30); VEvent meeting = new VEvent(new DateTime(cal.getTime().getTime()), new Dur(0, 1, 0, 0), "Progress Meeting"); // add timezone information.. meeting.getProperty(Property.DTSTART).getParameters().add(tzParam); log.info(meeting); } /** * Test Null Dates * Test Start today, End One month from now. * * @throws Exception */ public final void testGetConsumedTime() throws Exception { // Test Null Dates try { event.getConsumedTime(null, null); fail("Should've thrown an exception."); } catch (RuntimeException re) { log.info("Expecting an exception here."); } // Test Start 04/01/2005, End One month later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0); queryStartDate.set(Calendar.MILLISECOND, 0); DateTime queryStart = new DateTime(queryStartDate.getTime().getTime()); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.MAY, 1, 07, 15, 0); queryEndDate.set(Calendar.MILLISECOND, 0); DateTime queryEnd = new DateTime(queryEndDate.getTime().getTime()); Calendar week1EndDate = getCalendarInstance(); week1EndDate.set(2005, Calendar.APRIL, 8, 11, 15, 0); week1EndDate.set(Calendar.MILLISECOND, 0); Calendar week4StartDate = getCalendarInstance(); week4StartDate.set(2005, Calendar.APRIL, 24, 14, 47, 0); week4StartDate.set(Calendar.MILLISECOND, 0); // DateTime week4Start = new DateTime(week4StartDate.getTime().getTime()); // This range is monday to friday every three weeks, starting from // March 7th 2005, which means for our query dates we need // April 18th through to the 22nd. PeriodList weeklyPeriods = event.getConsumedTime(queryStart, queryEnd); // PeriodList dailyPeriods = dailyWeekdayEvents.getConsumedTime(queryStart, queryEnd); // week1EndDate.getTime()); // dailyPeriods.addAll(dailyWeekdayEvents.getConsumedTime(week4Start, queryEnd)); Calendar expectedCal = Calendar.getInstance(); //TimeZone.getTimeZone(TimeZones.GMT_ID)); expectedCal.set(2005, Calendar.APRIL, 1, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime().getTime()); expectedCal.set(2005, Calendar.APRIL, 1, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime().getTime()); assertNotNull(weeklyPeriods); assertTrue(weeklyPeriods.size() > 0); Period firstPeriod = (Period) weeklyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); // assertEquals(dailyPeriods, weeklyPeriods); } public final void testGetConsumedTimeDaily() throws Exception { // Test Starts 04/03/2005, Ends One week later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0); queryStartDate.set(Calendar.MILLISECOND, 0); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.APRIL, 10, 21, 55, 0); queryEndDate.set(Calendar.MILLISECOND, 0); // This range is Monday to Friday every day (which has a filtering // effect), starting from March 7th 2005. Our query dates are // April 3rd through to the 10th. // PeriodList weeklyPeriods = // event.getConsumedTime(new DateTime(queryStartDate.getTime()), // new DateTime(queryEndDate.getTime())); PeriodList dailyPeriods = event.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); Calendar expectedCal = getCalendarInstance(); expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime()); expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime()); assertNotNull(dailyPeriods); assertTrue(dailyPeriods.size() > 0); Period firstPeriod = (Period) dailyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); // assertEquals(weeklyPeriods, dailyPeriods); } /** * Test whether you can select weekdays using a monthly frequency. * <p> * This test really belongs in RecurTest, but the weekly range test * in this VEventTest matches so perfectly with the daily range test * that should produce the same results for some weeks that it was * felt leveraging the existing test code was more important. * <p> * Section 4.3.10 of the iCalendar specification RFC 2445 reads: * <pre> * If an integer modifier is not present, it means all days of * this type within the specified frequency. * </pre> * This test ensures compliance. */ public final void testGetConsumedTimeMonthly() throws Exception { // Test Starts 04/03/2005, Ends two weeks later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0); queryStartDate.set(Calendar.MILLISECOND, 0); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.APRIL, 17, 21, 55, 0); queryEndDate.set(Calendar.MILLISECOND, 0); // This range is Monday to Friday every month (which has a multiplying // effect), starting from March 7th 2005. Our query dates are // April 3rd through to the 17th. PeriodList monthlyPeriods = event.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); // PeriodList dailyPeriods = // dailyWeekdayEvents.getConsumedTime(new DateTime(queryStartDate.getTime()), // new DateTime(queryEndDate.getTime())); Calendar expectedCal = getCalendarInstance(); expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime()); expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime()); assertNotNull(monthlyPeriods); assertTrue(monthlyPeriods.size() > 0); Period firstPeriod = (Period) monthlyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); // assertEquals(dailyPeriods, monthlyPeriods); } public final void testGetConsumedTime2() throws Exception { String filename = "etc/samples/valid/derryn.ics"; net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename); Date start = new Date(); Calendar endCal = getCalendarInstance(); endCal.setTime(start); endCal.add(Calendar.WEEK_OF_YEAR, 4); // Date end = new Date(start.getTime() + (1000 * 60 * 60 * 24 * 7 * 4)); for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) { Component c = (Component) i.next(); if (c instanceof VEvent) { PeriodList consumed = ((VEvent) c).getConsumedTime(start, new Date(endCal.getTime().getTime())); log.debug("Event [" + c + "]"); log.debug("Consumed time [" + consumed + "]"); } } } public final void testGetConsumedTime3() throws Exception { String filename = "etc/samples/valid/calconnect10.ics"; net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename); VEvent vev = (VEvent) calendar.getComponent(Component.VEVENT); Date start = vev.getStartDate().getDate(); Calendar cal = getCalendarInstance(); cal.add(Calendar.YEAR, 1); Date latest = new Date(cal.getTime()); PeriodList pl = vev.getConsumedTime(start, latest); assertTrue(!pl.isEmpty()); } /** * Test COUNT rules. */ public void testGetConsumedTimeByCount() { Recur recur = new Recur(Recur.WEEKLY, 3); recur.setInterval(1); recur.getDayList().add(WeekDay.SU); log.info(recur); Calendar cal = getCalendarInstance(); cal.set(Calendar.DAY_OF_MONTH, 8); Date start = new DateTime(cal.getTime()); // cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 10); cal.add(Calendar.HOUR_OF_DAY, 1); Date end = new DateTime(cal.getTime()); // log.info(recur.getDates(start, end, Value.DATE_TIME)); RRule rrule = new RRule(recur); VEvent event = new VEvent(start, end, "Test recurrence COUNT"); event.getProperties().add(rrule); log.info(event); Calendar rangeCal = getCalendarInstance(); Date rangeStart = new DateTime(rangeCal.getTime()); rangeCal.add(Calendar.WEEK_OF_YEAR, 4); Date rangeEnd = new DateTime(rangeCal.getTime()); log.info(event.getConsumedTime(rangeStart, rangeEnd)); } /** * A test to confirm that the end date is calculated correctly * from a given start date and duration. */ public final void testEventEndDate() { Calendar cal = getCalendarInstance(); Date startDate = new Date(cal.getTime()); log.info("Start date: " + startDate); VEvent event = new VEvent(startDate, new Dur(3, 0, 0, 0), "3 day event"); Date endDate = event.getEndDate().getDate(); log.info("End date: " + endDate); cal.add(Calendar.DAY_OF_YEAR, 3); assertEquals(new Date(cal.getTime()), endDate); } /** * Test to ensure that EXDATE properties are correctly applied. * @throws ParseException */ public void testGetConsumedTimeWithExDate() throws ParseException { VEvent event1 = new VEvent(new DateTime("20050103T080000"), new Dur(0, 0, 15, 0), "Event 1"); Recur rRuleRecur = new Recur("FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR"); RRule rRule = new RRule(rRuleRecur); event1.getProperties().add(rRule); ParameterList parameterList = new ParameterList(); parameterList.add(Value.DATE); ExDate exDate = new ExDate(parameterList, "20050106"); event1.getProperties().add(exDate); Date start = new Date("20050106"); Date end = new Date("20050107"); PeriodList list = event1.getConsumedTime(start, end); assertTrue(list.isEmpty()); } /** * Test to ensure that EXDATE properties are correctly applied. * @throws ParseException */ public void testGetConsumedTimeWithExDate2() throws IOException, ParserException { FileInputStream fin = new FileInputStream("etc/samples/valid/friday13.ics"); net.fortuna.ical4j.model.Calendar calendar = new CalendarBuilder().build(fin); VEvent event = (VEvent) calendar.getComponent(Component.VEVENT); Calendar cal = Calendar.getInstance(); cal.set(1997, 8, 2); Date start = new Date(cal.getTime()); cal.set(1997, 8, 4); Date end = new Date(cal.getTime()); PeriodList periods = event.getConsumedTime(start, end); assertTrue(periods.isEmpty()); } /** * Test equality of events with different alarm sub-components. */ public void testEquals() { Date date = new Date(); String summary = "test event"; PropertyList props = new PropertyList(); props.add(new DtStart(date)); props.add(new Summary(summary)); VEvent e1 = new VEvent(props); VEvent e2 = new VEvent(props); assertTrue(e1.equals(e2)); e2.getAlarms().add(new VAlarm()); assertFalse(e1.equals(e2)); } public void testCalculateRecurrenceSetNotEmpty() { PeriodList recurrenceSet = event.calculateRecurrenceSet(period); assertTrue(!recurrenceSet.isEmpty()); } /** * Unit tests for {@link VEvent#getOccurrence(Date)}. */ public void testGetOccurrence() throws IOException, ParseException, URISyntaxException { VEvent occurrence = event.getOccurrence(date); assertNotNull(occurrence); assertEquals(event.getUid(), occurrence.getUid()); } /** * @return * @throws ValidationException * @throws ParseException * @throws URISyntaxException * @throws IOException * @throws ParserException */ public static TestSuite suite() throws ValidationException, ParseException, IOException, URISyntaxException, ParserException { UidGenerator uidGenerator = new UidGenerator("1"); Calendar weekday9AM = getCalendarInstance(); weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0); weekday9AM.set(Calendar.MILLISECOND, 0); Calendar weekday5PM = getCalendarInstance(); weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0); weekday5PM.set(Calendar.MILLISECOND, 0); // Do the recurrence until December 31st. Calendar untilCal = getCalendarInstance(); untilCal.set(2005, Calendar.DECEMBER, 31); untilCal.set(Calendar.MILLISECOND, 0); Date until = new Date(untilCal.getTime().getTime()); // 9:00AM to 5:00PM Rule using weekly Recur recurWeekly = new Recur(Recur.WEEKLY, until); recurWeekly.getDayList().add(WeekDay.MO); recurWeekly.getDayList().add(WeekDay.TU); recurWeekly.getDayList().add(WeekDay.WE); recurWeekly.getDayList().add(WeekDay.TH); recurWeekly.getDayList().add(WeekDay.FR); recurWeekly.setInterval(1); recurWeekly.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleWeekly = new RRule(recurWeekly); // 9:00AM to 5:00PM Rule using daily frequency Recur recurDaily = new Recur(Recur.DAILY, until); recurDaily.getDayList().add(WeekDay.MO); recurDaily.getDayList().add(WeekDay.TU); recurDaily.getDayList().add(WeekDay.WE); recurDaily.getDayList().add(WeekDay.TH); recurDaily.getDayList().add(WeekDay.FR); recurDaily.setInterval(1); recurDaily.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleDaily = new RRule(recurDaily); // 9:00AM to 5:00PM Rule using monthly frequency Recur recurMonthly = new Recur(Recur.MONTHLY, until); recurMonthly.getDayList().add(WeekDay.MO); recurMonthly.getDayList().add(WeekDay.TU); recurMonthly.getDayList().add(WeekDay.WE); recurMonthly.getDayList().add(WeekDay.TH); recurMonthly.getDayList().add(WeekDay.FR); recurMonthly.setInterval(1); recurMonthly.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleMonthly = new RRule(recurMonthly); Summary summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED WEEKLY"); VEvent weekdayNineToFiveEvents = new VEvent(); weekdayNineToFiveEvents.getProperties().add(rruleWeekly); weekdayNineToFiveEvents.getProperties().add(summary); DtStart dtStart = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart.getParameters().add(Value.DATE); weekdayNineToFiveEvents.getProperties().add(dtStart); DtEnd dtEnd = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd.getParameters().add(Value.DATE); weekdayNineToFiveEvents.getProperties().add(dtEnd); weekdayNineToFiveEvents.getProperties().add(uidGenerator.generateUid()); // ensure event is valid.. weekdayNineToFiveEvents.validate(); summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED DAILY"); VEvent dailyWeekdayEvents = new VEvent(); dailyWeekdayEvents.getProperties().add(rruleDaily); dailyWeekdayEvents.getProperties().add(summary); DtStart dtStart2 = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart2.getParameters().add(Value.DATE); dailyWeekdayEvents.getProperties().add(dtStart2); DtEnd dtEnd2 = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd2.getParameters().add(Value.DATE); dailyWeekdayEvents.getProperties().add(dtEnd2); dailyWeekdayEvents.getProperties().add(uidGenerator.generateUid()); // ensure event is valid.. dailyWeekdayEvents.validate(); summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED MONTHLY"); VEvent monthlyWeekdayEvents = new VEvent(); monthlyWeekdayEvents.getProperties().add(rruleMonthly); monthlyWeekdayEvents.getProperties().add(summary); DtStart dtStart3 = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart3.getParameters().add(Value.DATE); monthlyWeekdayEvents.getProperties().add(dtStart3); DtEnd dtEnd3 = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd3.getParameters().add(Value.DATE); monthlyWeekdayEvents.getProperties().add(dtEnd3); monthlyWeekdayEvents.getProperties().add(uidGenerator.generateUid()); // ensure event is valid.. monthlyWeekdayEvents.validate(); // enable relaxed parsing to allow copying of invalid events.. CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); TestSuite suite = new TestSuite(); //testCalculateRecurrenceSet.. DateTime periodStart = new DateTime("20050101T000000"); DateTime periodEnd = new DateTime("20051231T235959"); Period period = new Period(periodStart, periodEnd); suite.addTest(new VEventTest("testCalculateRecurrenceSetNotEmpty", weekdayNineToFiveEvents, period)); //testGetOccurrence.. suite.addTest(new VEventTest("testGetOccurrence", weekdayNineToFiveEvents, weekdayNineToFiveEvents.getStartDate().getDate())); //testGetConsumedTime.. suite.addTest(new VEventTest("testGetConsumedTime", weekdayNineToFiveEvents)); suite.addTest(new VEventTest("testGetConsumedTimeDaily", dailyWeekdayEvents)); suite.addTest(new VEventTest("testGetConsumedTimeMonthly", monthlyWeekdayEvents)); //test event validation.. UidGenerator ug = new UidGenerator("1"); Uid uid = ug.generateUid(); DtStart start = new DtStart(new Date()); DtEnd end = new DtEnd(new Date()); VEvent event = new VEvent(); event.getProperties().add(uid); event.getProperties().add(start); event.getProperties().add(end); suite.addTest(new VEventTest("testValidation", event)); event = (VEvent) event.copy(); // start = (DtStart) event.getProperty(Property.DTSTART); start = new DtStart(new DateTime()); start.getParameters().replace(Value.DATE_TIME); event.getProperties().remove(event.getProperty(Property.DTSTART)); event.getProperties().add(start); suite.addTest(new VEventTest("testValidationException", event)); // test 1.. event = (VEvent) event.copy(); start = (DtStart) event.getProperty(Property.DTSTART); start.getParameters().replace(Value.DATE); suite.addTest(new VEventTest("testValidationException", event)); // event = (VEvent) event.copy(); // start = (DtStart) event.getProperty(Property.DTSTART); // start.getParameters().remove(Value.DATE_TIME); // end = (DtEnd) event.getProperty(Property.DTEND); // end.getParameters().replace(Value.DATE_TIME); // suite.addTest(new VEventTest("testValidation", event)); // test 2.. event = (VEvent) event.copy(); start = (DtStart) event.getProperty(Property.DTSTART); start.getParameters().replace(Value.DATE_TIME); end = (DtEnd) event.getProperty(Property.DTEND); end.getParameters().replace(Value.DATE); suite.addTest(new VEventTest("testValidationException", event)); // test 3.. // event = (VEvent) event.copy(); // start = (DtStart) event.getProperty(Property.DTSTART); // start.getParameters().remove(Value.DATE); // end = (DtEnd) event.getProperty(Property.DTEND); // end.getParameters().replace(Value.DATE); // suite.addTest(new VEventTest("testValidationException", event)); // disable relaxed parsing after copying invalid events.. CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, false); suite.addTest(new VEventTest("testChristmas")); suite.addTest(new VEventTest("testMelbourneCup")); suite.addTest(new VEventTest("testGetConsumedTime2")); suite.addTest(new VEventTest("testGetConsumedTime3")); suite.addTest(new VEventTest("testGetConsumedTimeByCount")); suite.addTest(new VEventTest("testEventEndDate")); suite.addTest(new VEventTest("testGetConsumedTimeWithExDate")); suite.addTest(new VEventTest("testGetConsumedTimeWithExDate2")); suite.addTest(new VEventTest("testIsCalendarComponent", event)); suite.addTest(new VEventTest("testEquals")); // suite.addTest(new VEventTest("testValidation")); // use relaxed unfolding for samples.. CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_NOTES_COMPATIBILITY, true); // test iTIP validation.. // File[] testFiles = new File("etc/samples/valid").listFiles((FileFilter) new NotFileFilter(DirectoryFileFilter.INSTANCE)); File[] testFiles = new File[] {new File("etc/samples/valid/calconnect.ics"), new File("etc/samples/valid/calconnect10.ics")}; for (int i = 0; i < testFiles.length; i++) { log.info("Sample [" + testFiles[i] + "]"); net.fortuna.ical4j.model.Calendar calendar = Calendars.load(testFiles[i].getPath()); if (Method.PUBLISH.equals(calendar.getProperty(Property.METHOD))) { for (Iterator it = calendar.getComponents(Component.VEVENT).iterator(); it.hasNext();) { VEvent event1 = (VEvent) it.next(); suite.addTest(new VEventTest("testPublishValidation", event1)); } } else if (Method.REQUEST.equals(calendar.getProperty(Property.METHOD))) { for (Iterator it = calendar.getComponents(Component.VEVENT).iterator(); it.hasNext();) { VEvent event1 = (VEvent) it.next(); suite.addTest(new VEventTest("testRequestValidation", event1)); } } } CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, false); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_NOTES_COMPATIBILITY, false); return suite; } }
package com.google.refine.importing; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.io.FileUtils; import org.json.JSONException; import org.json.JSONWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.refine.RefineServlet; import edu.mit.simile.butterfly.ButterflyModule; public class ImportingManager { static public class Format { final public String id; final public String label; final public boolean download; final public String uiClass; final public ImportingParser parser; private Format( String id, String label, boolean download, String uiClass, ImportingParser parser ) { this.id = id; this.label = label; this.download = download; this.uiClass = uiClass; this.parser = parser; } } final static Logger logger = LoggerFactory.getLogger("importing"); static private RefineServlet servlet; static private File importDir; final static private Map<Long, ImportingJob> jobs = Collections.synchronizedMap(new HashMap<Long, ImportingJob>()); // Mapping from format to label, e.g., "text" to "Text files", "text/xml" to "XML files" final static public Map<String, Format> formatToRecord = new HashMap<String, Format>(); // Mapping from format to guessers final static public Map<String, List<FormatGuesser>> formatToGuessers = new HashMap<String, List<FormatGuesser>>(); // Mapping from file extension to format, e.g., ".xml" to "text/xml" final static public Map<String, String> extensionToFormat = new HashMap<String, String>(); // Mapping from mime type to format, e.g., "application/json" to "text/json" final static public Map<String, String> mimeTypeToFormat = new HashMap<String, String>(); // URL rewriters final static public Set<UrlRewriter> urlRewriters = new HashSet<UrlRewriter>(); // Mapping from controller name to controller final static public Map<String, ImportingController> controllers = new HashMap<String, ImportingController>(); // timer for periodically deleting stale importing jobs static private Timer _timer; final static private long s_timerPeriod = 1000 * 60 * 10; // 10 minutes final static private long s_stalePeriod = 1000 * 60 * 60; // 60 minutes static private class CleaningTimerTask extends TimerTask { @Override public void run() { try { cleanUpStaleJobs(); } finally { _timer.schedule(new CleaningTimerTask(), s_timerPeriod); // we don't use scheduleAtFixedRate because that might result in // bunched up events when the computer is put in sleep mode } } } static public void initialize(RefineServlet servlet) { ImportingManager.servlet = servlet; _timer = new Timer("autosave"); _timer.schedule(new CleaningTimerTask(), s_timerPeriod); } static public void registerFormat(String format, String label) { registerFormat(format, label, null, null); } static public void registerFormat(String format, String label, String uiClass, ImportingParser parser) { formatToRecord.put(format, new Format(format, label, true, uiClass, parser)); } static public void registerFormat( String format, String label, boolean download, String uiClass, ImportingParser parser) { formatToRecord.put(format, new Format(format, label, download, uiClass, parser)); } static public void registerFormatGuesser(String format, FormatGuesser guesser) { List<FormatGuesser> guessers = formatToGuessers.get(format); if (guessers == null) { guessers = new LinkedList<FormatGuesser>(); formatToGuessers.put(format, guessers); } guessers.add(0, guesser); // prepend so that newer guessers take priority } static public void registerExtension(String extension, String format) { extensionToFormat.put(extension.startsWith(".") ? extension : ("." + extension), format); } static public void registerMimeType(String mimeType, String format) { mimeTypeToFormat.put(mimeType, format); } static public void registerUrlRewriter(UrlRewriter urlRewriter) { urlRewriters.add(urlRewriter); } static public void registerController(ButterflyModule module, String name, ImportingController controller) { String key = module.getName() + "/" + name; controllers.put(key, controller); controller.init(servlet); } static synchronized public File getImportDir() { if (importDir == null) { File tempDir = servlet.getTempDir(); importDir = tempDir == null ? new File(".import-temp") : new File(tempDir, "import"); if (importDir.exists()) { try { // start fresh FileUtils.deleteDirectory(importDir); } catch (IOException e) { } } importDir.mkdirs(); } return importDir; } static public ImportingJob createJob() { long id = System.currentTimeMillis() + (long) (Math.random() * 1000000); File jobDir = new File(getImportDir(), Long.toString(id)); ImportingJob job = new ImportingJob(id, jobDir); jobs.put(id, job); return job; } static public ImportingJob getJob(long id) { return jobs.get(id); } static public void disposeJob(long id) { ImportingJob job = getJob(id); if (job != null) { job.dispose(); jobs.remove(id); } } static public void writeConfiguration(JSONWriter writer, Properties options) throws JSONException { writer.object(); writer.key("formats"); writer.object(); for (String format : formatToRecord.keySet()) { Format record = formatToRecord.get(format); writer.key(format); writer.object(); writer.key("id"); writer.value(record.id); writer.key("label"); writer.value(record.label); writer.key("download"); writer.value(record.download); writer.key("uiClass"); writer.value(record.uiClass); writer.endObject(); } writer.endObject(); writer.key("mimeTypeToFormat"); writer.object(); for (String mimeType : mimeTypeToFormat.keySet()) { writer.key(mimeType); writer.value(mimeTypeToFormat.get(mimeType)); } writer.endObject(); writer.key("extensionToFormat"); writer.object(); for (String extension : extensionToFormat.keySet()) { writer.key(extension); writer.value(extensionToFormat.get(extension)); } writer.endObject(); writer.endObject(); } static public String getFormatFromFileName(String fileName) { int start = 0; while (true) { int dot = fileName.indexOf('.', start); if (dot < 0) { break; } String extension = fileName.substring(dot); String format = extensionToFormat.get(extension); if (format != null) { return format; } else { start = dot + 1; } } return null; } static public String getFormatFromMimeType(String mimeType) { return mimeTypeToFormat.get(mimeType); } static public String getFormat(String fileName, String mimeType) { String fileNameFormat = getFormatFromFileName(fileName); if (mimeType != null) { mimeType = mimeType.split(";")[0]; } String mimeTypeFormat = mimeType == null ? null : getFormatFromMimeType(mimeType); if (mimeTypeFormat == null) { return fileNameFormat; } else if (fileNameFormat == null) { return mimeTypeFormat; } else if (mimeTypeFormat.startsWith(fileNameFormat)) { // mime type-base format is more specific return mimeTypeFormat; } else { return fileNameFormat; } } static private void cleanUpStaleJobs() { long now = System.currentTimeMillis(); HashSet<Long> keys; synchronized(jobs) { keys = new HashSet<Long>(jobs.keySet()); } for (Long id : keys) { ImportingJob job = jobs.get(id); if (job != null && !job.updating && now - job.lastTouched > s_stalePeriod) { job.dispose(); jobs.remove(id); logger.info("Disposed " + id); } } } }
package net.fortuna.ical4j.model.property; import java.text.ParseException; import java.util.Calendar; import junit.framework.TestCase; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import net.fortuna.ical4j.model.parameter.TzId; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.util.Strings; public class DtStartTest extends TestCase { private TimeZone timezone; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); TimeZoneRegistry tzReg = TimeZoneRegistryFactory.getInstance().createRegistry(); timezone = tzReg.getTimeZone("Australia/Melbourne"); } /* * Test method for 'net.fortuna.ical4j.model.property.DtStart.DtStart(String)' */ public void testDtStartString() throws ParseException { ParameterList params = new ParameterList(); params.add(Value.DATE); DtStart dtStart = new DtStart(params, "20060811"); Calendar calendar = Calendar.getInstance(); //TimeZone.getTimeZone(TimeZones.GMT_ID)); calendar.clear(); calendar.set(2006, 7, 11); calendar.clear(Calendar.HOUR_OF_DAY); calendar.clear(Calendar.MINUTE); calendar.clear(Calendar.SECOND); calendar.clear(Calendar.MILLISECOND); assertEquals(dtStart.getDate(), calendar.getTime()); } /** * Unit tests for timezone constructor. */ public void testDtStartTimezone() throws ParseException { DtStart dtStart = new DtStart(timezone); dtStart.setValue(new DateTime().toString()); assertEquals(timezone, dtStart.timezone); // initialising with DATE value should reset timezone.. dtStart.setDate(new Date()); assertNull(dtStart.timezone); } /** * Unit tests for value/timezone constructor. */ public void testDtStartStringTimezone() throws ParseException { String value = new DateTime().toString(); DtStart dtStart = new DtStart(value, timezone); assertEquals(timezone, dtStart.timezone); assertEquals(value, dtStart.getValue()); } /** * Test non-utc timezone works. */ public void testNonUtcTimezone() throws ParseException { DtStart start = new DtStart(); start.getParameters().add(Value.DATE_TIME); start.getParameters().add(new TzId("GMT")); start.setValue("20070101T080000"); assertEquals("DTSTART;VALUE=DATE-TIME;TZID=GMT:20070101T080000" + Strings.LINE_SEPARATOR, start.toString()); } }
package com.miloshpetrov.sol2.soundtest; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.math.Vector2; import com.miloshpetrov.sol2.Const; import com.miloshpetrov.sol2.ui.UiDrawer; class SoundTestCmp { private static final float SPD = .5f; private final UiDrawer myUiDrawer; private final Vector2 myPos = new Vector2(.5f, .5f); private Color c = new Color(myPos.x, myPos.y, 0, 1f); private boolean start = false; private float play_time = 1f; private float radius = .05f; private boolean isMousePressed = false; private float myAccum; SoundTestCmp() { myUiDrawer = new UiDrawer(); } // this method is called externally as often as possible public void render() { myAccum += Gdx.graphics.getDeltaTime(); // we want to call the update() method 60 times per second or so, therefore these checks are needed while (myAccum > Const.REAL_TIME_STEP) { // in this method we update the game state update(); myAccum -= Const.REAL_TIME_STEP; } // in this method we draw, this method is called as often as possible draw(); } private void draw() { // clearing the screen from the previous frame Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); myUiDrawer.begin(); myUiDrawer.drawCircle(myPos, radius, c); myUiDrawer.end(); } private void update() { updatePos(); updateSound(); change_color(); if (!(this.isMousePressed) && play_time < 1f) //full animation lasts 1 second { change_radius(Const.REAL_TIME_STEP); } if (!(this.isMousePressed) && Gdx.input.isButtonPressed(Input.Buttons.LEFT)) //if pressed mouse button - init circle auto-morphing { play_time = 0f; radius = .05f; this.isMousePressed = true; } else this.isMousePressed = false; } private void updatePos() { float spd = 0; if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) { spd = -SPD; } else if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) { spd = SPD; } spd *= Const.REAL_TIME_STEP; myPos.x += spd; } private void change_color() { c.set(myPos.x, myPos.y, 0, 1f); } private void change_radius(float d_time) { if (play_time <= .5f) //incrementing within half a second { radius += d_time * 0.1f; //amount of change in passed time } else //decrementing after { radius -= d_time * 0.1f; } play_time += d_time; } private void updateSound() { } }
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; public class Tk103ProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { Tk103ProtocolDecoder decoder = new Tk103ProtocolDecoder(new Tk103Protocol()); verifyPosition(decoder, text( "(325031693849BR00170228A5750.8012N02700.7476E000.2154529000.0000000200L00000000,170228,194530)")); verifyPosition(decoder, text( "(087073803649BR00170221A6142.0334N02712.2197E000.3203149000.00,00000000L00000000)")); verifyPosition(decoder, text( "(864768010869060,DW30,050117,A,5135.82713N,00001.17918E,0.089,154745,000.0,43.40,12)")); verifyNotNull(decoder, text( "(087073104337BZ00,740,000,3bf7,0425,3bf7,0bf5,3bf7,09e7,3bf7,cbad,3bf7,0dcf,3bf7,c7b2,01000000)")); verifyNothing(decoder, text( "(087073005534BP00HSO")); verifyNothing(decoder, text( "(027028258309BQ86,0,05550c21b10d1d0f431008bd114c0ea5078400010007a100423932,161117005322,01000001)")); verifyNothing(decoder, text( "(027028258309BQ86,0,05470c0eb20d040f4410022911360e92077e00010007a1004237c7,161117005232,01000001)")); verifyPosition(decoder, text( "(01602009983BR00160830V1855.7022S4817.8731W000.0002729000.0010000000L00000000)")); verifyPosition(decoder, text( "(088046338039BR00160727A3354.7768N03540.7258E000.0140832068.4700000000L00BEB0D4+017.7)")); verifyPosition(decoder, text( "(088046338039BP05000088046338039160727A3354.7768N03540.7258E000.0140309065.1000000000L00BEB0D4+017.3)")); verifyAttributes(decoder, text( "(013632651491,ZC20,180716,144222,6,392,65535,255")); verifyAttributes(decoder, text( "(087072009461BR00000007V0000.0000N00000.0000E000.00014039900000000L00000000")); verifyPosition(decoder, text( "(013612345678BO012061830A2934.0133N10627.2544E040.0080331309.6200000000L000770AD")); verifyNotNull(decoder, text( "(088047194605BZ00,510,010,36e6,932c,43,36e6,766b,36,36e6,7668,32")); verifyAttributes(decoder, text( "(013632651491,ZC20,040613,040137,6,421,112,0")); verifyAttributes(decoder, text( "(864768010159785,ZC20,291015,030413,3,362,65535,255")); verifyPosition(decoder, text( "(088047365460BR00151024A2555.3531S02855.3329E004.7055148276.1701000000L00009AA3)"), position("2015-10-24 05:51:48.000", true, -25.92255, 28.92222)); verifyPosition(decoder, text( "(088047365460BP05354188047365460150929A3258.1754S02755.4323E009.4193927301.9000000000L00000000)")); verifyPosition(decoder, text( "(088048003342BP05354188048003342150917A1352.9801N10030.9050E000.0103115265.5600010000L000003F9)")); verifyPosition(decoder, text( "(088048003342BR00150917A1352.9801N10030.9050E000.0103224000.0000010000L000003F9)")); verifyPosition(decoder, text( "(088048003342BR00150807A1352.9871N10030.9084E000.0110718000.0001010000L00000000)")); verifyNothing(decoder, text( "(090411121854BP0000001234567890HSO")); verifyPosition(decoder, text( "(01029131573BR00150428A3801.6382N02351.0159E000.0080729278.7800000000LEF9ECB9C)")); verifyPosition(decoder, text( "(035988863964BP05000035988863964110524A4241.7977N02318.7561E000.0123536356.5100000000L000946BB")); verifyPosition(decoder, text( "(013632782450BP05000013632782450120803V0000.0000N00000.0000E000.0174654000.0000000000L00000000")); verifyPosition(decoder, text( "(013666666666BP05000013666666666110925A1234.5678N01234.5678W000.002033490.00000000000L000024DE")); verifyPosition(decoder, text( "(013666666666BO012110925A1234.5678N01234.5678W000.0025948118.7200000000L000024DE")); verifyPosition(decoder, text( "\n\n\n(088045133878BR00130228A5124.5526N00117.7152W000.0233614352.2200000000L01B0CF1C")); verifyPosition(decoder, text( "(008600410203BP05000008600410203130721A4152.5790N01239.2770E000.0145238173.870100000AL0000000")); verifyPosition(decoder, text( "(013012345678BR00130515A4843.9703N01907.6211E000.019232800000000000000L00009239")); verifyPosition(decoder, text( "(012345678901BP05000012345678901130520A3439.9629S05826.3504W000.1175622323.8700000000L000450AC")); verifyPosition(decoder, text( "(012345678901BR00130520A3439.9629S05826.3504W000.1175622323.8700000000L000450AC")); verifyPosition(decoder, text( "(352606090042050,BP05,240414,V,0000.0000N,00000.0000E,000.0,193133,000.0")); verifyPosition(decoder, text( "(352606090042050,BP05,240414,A,4527.3513N,00909.9758E,4.80,112825,155.49"), position("2014-04-24 11:28:25.000", true, 45.45586, 9.16626)); verifyPosition(decoder, text( "(013632782450,BP05,101201,A,2234.0297N,11405.9101E,000.0,040137,178.48,00000000,L00000000")); verifyPosition(decoder, text( "(864768010009188,BP05,271114,V,4012.19376N,00824.05638E,000.0,154436,000.0")); verifyPosition(decoder, text( "(013632651491,BP05,040613,A,2234.0297N,11405.9101E,000.0,040137,178.48)")); verifyPosition(decoder, text( "(013632651491,ZC07,040613,A,2234.0297N,11405.9101E,000.0,040137,178.48)")); verifyPosition(decoder, text( "(013632651491,ZC11,040613,A,2234.0297N,11405.9101E,000.0,040137,178.48)")); verifyPosition(decoder, text( "(013632651491,ZC12,040613,A,2234.0297N,11405.9101E,000.0,040137,178.48)")); verifyPosition(decoder, text( "(013632651491,ZC13,040613,A,2234.0297N,11405.9101E,000.0,040137,178.48)")); verifyPosition(decoder, text( "(013632651491,ZC17,040613,A,2234.0297N,11405.9101E,000.0,040137,178.48)")); verifyNothing(decoder, text( "(013632651491,ZC20,040613,040137,6,42,112,0)")); verifyPosition(decoder, text( "(094050000111BP05000094050000111150808A3804.2418N04616.7468E000.0201447133.3501000011L0028019DT000)")); } }
package controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import model.machine.IdleMachine; import service.MachineService; import service.QRCodeService; import utils.HttpDeal; import utils.ResponseCode; import utils.ResultData; @CrossOrigin @RestController @RequestMapping("/machine") public class MachineController { private Logger logger = LoggerFactory.getLogger(MachineController.class); @Autowired private MachineService machineService; @Autowired private QRCodeService qRCodeService; @RequestMapping(method = RequestMethod.POST, value = "/device/delete/{deviceId}") public ResultData delete(@PathVariable String deviceId) { ResultData resultData = machineService.deleteDevice(deviceId); logger.info("delete device using deviceId: " + deviceId); return resultData; } @RequestMapping(method = RequestMethod.GET, value = "/idle") public ResultData idle() { ResultData result = new ResultData(); String listUrl = "http://commander.gmair.net/AirCleanerOperation/device/all"; try { String response = HttpDeal.getResponse(listUrl); JSONObject json = JSONObject.parseObject(response); if (!StringUtils.isEmpty(json.get("contents")) && !StringUtils.isEmpty(json.getJSONObject("contents").get("devices"))) { JSONArray uids = json.getJSONObject("contents").getJSONArray("devices"); for (int i = 0; i < uids.size(); i++) { String session = uids.getString(i); String uid = session.replaceAll("session.", ""); ResultData rs = qRCodeService.fetchPreBindByUid(uid); if (rs.getResponseCode() == ResponseCode.RESPONSE_OK) { continue; } if (rs.getResponseCode() == ResponseCode.RESPONSE_NULL) { IdleMachine im = new IdleMachine(uid); rs = machineService.createIdleMachine(im); if (rs.getResponseCode() == ResponseCode.RESPONSE_OK) { logger.debug(":" + uid + "idle"); } else { logger.debug(":" + uid + ""); } } } } } catch (Exception e) { logger.error(e.getMessage()); } Map<String, Object> condition = new HashMap<>(); condition.put("blockFlag", false); ResultData response = machineService.fetchIdleMachine(condition); if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(""); return result; } if (response.getResponseCode() == ResponseCode.RESPONSE_OK) { result.setResponseCode(ResponseCode.RESPONSE_OK); result.setData(response.getData()); return result; } return result; } @RequestMapping(method = RequestMethod.POST, value = "/idle/update") public ResultData idleUpdate(@RequestParam String imId) { ResultData result = new ResultData(); Map<String, Object> condition = new HashMap<>(); condition.put("blockFlag", false); condition.put("im_id", imId); ResultData response = machineService.updateIdleMachine(condition); if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(""); return result; } if (response.getResponseCode() == ResponseCode.RESPONSE_OK) { result.setResponseCode(ResponseCode.RESPONSE_OK); result.setData(response.getData()); return result; } return result; } @RequestMapping(method = RequestMethod.GET, value = "{uid}/detail") public ResultData detail(@PathVariable("uid") String uid) { ResultData result = new ResultData(); String url = new StringBuffer("http://commander.gmair.net/AirCleanerOperation/device/status/device?token=") .append(uid).toString(); try { String response = HttpDeal.getResponse(url); JSONObject json = JSONObject.parseObject(response); JSONObject info = new JSONObject(); if (!StringUtils.isEmpty(json.get("contents")) && !StringUtils.isEmpty(json.getJSONObject("contents").get("status"))) { info.put("ip", json.getJSONObject("contents").getJSONObject("status").get("ip")); info.put("time", json.getJSONObject("contents").getJSONObject("status").get("time")); } result.setData(info); } catch (Exception e) { logger.error(e.getMessage()); result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(e.getMessage()); } return result; } @CrossOrigin @RequestMapping(method = RequestMethod.GET, value = "/device/status") public ResultData status() { ResultData result = new ResultData(); Map<String, Object> condition = new HashMap<>(); ResultData response = machineService.queryMachineStatus(condition); if (response.getResponseCode() == ResponseCode.RESPONSE_NULL) { result.setResponseCode(ResponseCode.RESPONSE_NULL); } else if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(""); } else { result.setData(response.getData()); } return result; } }
package org.jgroups.blocks; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jgroups.Address; import org.jgroups.stack.IpAddress; import org.jgroups.util.Util; import java.net.InetAddress; import java.net.UnknownHostException; import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; import java.lang.management.ThreadInfo; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * Tests ConnectionTable * @author Bela Ban * @version $Id: ConnectionTableTest.java,v 1.5 2007/06/08 16:11:46 belaban Exp $ */ public class ConnectionTableTest extends TestCase { private BasicConnectionTable ct1, ct2; static InetAddress loopback_addr=null; static byte[] data=new byte[]{'b', 'e', 'l', 'a'}; Address addr1, addr2; int active_threads=0; static { try { loopback_addr=InetAddress.getByName("127.0.0.1"); } catch(UnknownHostException e) { e.printStackTrace(); } } public ConnectionTableTest(String testName) { super(testName); } protected void setUp() throws Exception { super.setUp(); active_threads=Thread.activeCount(); System.out.println("active threads before (" + active_threads + "):\n" + Util.activeThreads()); addr1=new IpAddress(loopback_addr, 7500); addr2=new IpAddress(loopback_addr, 8000); } protected void tearDown() throws Exception { if(ct2 != null) { ct2.stop(); ct2=null; } if(ct1 != null) { ct1.stop(); ct1=null; } super.tearDown(); } public void testBlockingQueue() { final BlockingQueue queue=new LinkedBlockingQueue(); Thread taker=new Thread() { public void run() { try { System.out.println("taking an element from the queue"); Object obj=queue.take(); System.out.println("clear"); } catch(InterruptedException e) { e.printStackTrace(); } } }; taker.start(); Util.sleep(500); queue.clear(); // does this release the taker thread ? Util.sleep(200); assertFalse("taker: " + taker, taker.isAlive()); } public void testStopConnectionTableNoSendQueues() throws Exception { ct1=new ConnectionTable(new DummyReceiver(), loopback_addr, null, 7500, 7500, 60000, 120000); ct1.setUseSendQueues(false); ct2=new ConnectionTable(new DummyReceiver(), loopback_addr, null, 8000, 8000, 60000, 120000); ct2.setUseSendQueues(false); _testStop(ct1, ct2); } public void testStopConnectionTableWithSendQueues() throws Exception { ct1=new ConnectionTable(new DummyReceiver(), loopback_addr, null, 7500, 7500, 60000, 120000); ct2=new ConnectionTable(new DummyReceiver(), loopback_addr, null, 8000, 8000, 60000, 120000); _testStop(ct1, ct2); } public void testStopConnectionTableNIONoSendQueues() throws Exception { ct1=new ConnectionTableNIO(new DummyReceiver(), loopback_addr, null, 7500, 7500, 60000, 120000, false); ct1.setUseSendQueues(false); ct2=new ConnectionTableNIO(new DummyReceiver(), loopback_addr, null, 8000, 8000, 60000, 120000, false); ct2.setUseSendQueues(false); ct1.start(); ct2.start(); _testStop(ct1, ct2); } public void testStopConnectionTableNIOWithSendQueues() throws Exception { ct1=new ConnectionTableNIO(new DummyReceiver(), loopback_addr, null, 7500, 7500, 60000, 120000, false); ct2=new ConnectionTableNIO(new DummyReceiver(), loopback_addr, null, 8000, 8000, 60000, 120000, false); ct1.start(); ct2.start(); _testStop(ct1, ct2); } private void _testStop(BasicConnectionTable table1, BasicConnectionTable table2) throws Exception { table1.send(addr1, data, 0, data.length); // send to self table1.send(addr2, data, 0, data.length); // send to other table2.send(addr2, data, 0, data.length); // send to self table2.send(addr1, data, 0, data.length); // send to other System.out.println("table1:\n" + table1 + "\ntable2:\n" + table2); assertEquals(1, table1.getNumConnections()); assertEquals(1, table2.getNumConnections()); table2.stop(); table1.stop(); assertEquals(0, table1.getNumConnections()); assertEquals(0, table2.getNumConnections()); int current_active_threads=Thread.activeCount(); System.out.println("active threads after (" + current_active_threads + "):\n" + Util.activeThreads()); assertEquals("threads:\n" + dumpThreads(), active_threads, current_active_threads); } private String dumpThreads() { StringBuilder sb=new StringBuilder(); ThreadMXBean bean=ManagementFactory.getThreadMXBean(); long[] ids=bean.getAllThreadIds(); ThreadInfo[] threads=bean.getThreadInfo(ids, 20); for(int i=0; i < threads.length; i++) { ThreadInfo info=threads[i]; if(info == null) continue; sb.append(info.getThreadName()).append(":\n"); StackTraceElement[] stack_trace=info.getStackTrace(); for(int j=0; j < stack_trace.length; j++) { StackTraceElement el=stack_trace[j]; sb.append("at ").append(el.getClassName()).append(".").append(el.getMethodName()); sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")"); sb.append("\n"); } sb.append("\n\n"); } return sb.toString(); } public static Test suite() { return new TestSuite(ConnectionTableTest.class); } public static void main(String[] args) { junit.textui.TestRunner.run(ConnectionTableTest.suite()); } static class DummyReceiver implements ConnectionTable.Receiver { public void receive(Address sender, byte[] data, int offset, int length) { System.out.println("-- received " + length + " bytes from " + sender); } } static class DummyReceiverNIO implements ConnectionTableNIO.Receiver { public void receive(Address sender, byte[] data, int offset, int length) { System.out.println("-- received " + length + " bytes from " + sender); } } }
package org.openhds.domain.model; import java.io.Serializable; import java.util.Calendar; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.openhds.domain.annotations.Description; import org.openhds.domain.constraint.CheckDeathDateGreaterThanBirthDate; import org.openhds.domain.constraint.CheckFieldNotBlank; import org.openhds.domain.constraint.CheckIndividualNotUnknown; import org.openhds.domain.constraint.Searchable; import org.openhds.domain.util.CalendarAdapter; @Description(description="A Death represents the final event than an Individual can " + "have within the system. It consists of the Individual who has passed on, the " + "Visit associated with the Death, as well as descriptive information about the " + "occurrence, cause, and date of the death. If the Individual had any Residencies, " + "Relationships, or Memberships then they will become closed.") @CheckDeathDateGreaterThanBirthDate @Entity @Table(name="death") @XmlRootElement(name = "death") public class Death extends AuditableCollectedEntity implements Serializable { private static final long serialVersionUID = -6644256636909420061L; @Searchable @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST}) @CheckIndividualNotUnknown @Description(description="Individual who has died, identified by the external id.") Individual individual; @CheckFieldNotBlank @Searchable @Description(description="Place where the death occurred.") String deathPlace; @CheckFieldNotBlank @Searchable @Description(description="Cause of the death.") String deathCause; @NotNull @Past(message = "Start date should be in the past") @Temporal(javax.persistence.TemporalType.DATE) @Description(description="Date of the death.") Calendar deathDate; @Searchable @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST}) @Description(description="Visit associated with the death, identified by external id.") Visit visitDeath; @Description(description="Age of death in number of days.") Long ageAtDeath; public Individual getIndividual() { return individual; } public void setIndividual(Individual individual) { this.individual = individual; } public String getDeathPlace() { return deathPlace; } public void setDeathPlace(String deathPlace) { this.deathPlace = deathPlace; } public String getDeathCause() { return deathCause; } public void setDeathCause(String deathCause) { this.deathCause = deathCause; } @XmlJavaTypeAdapter(value=CalendarAdapter.class) public Calendar getDeathDate() { return deathDate; } public void setDeathDate(Calendar deathDate) { this.deathDate = deathDate; } public Visit getVisitDeath() { return visitDeath; } public void setVisitDeath(Visit visitDeath) { this.visitDeath = visitDeath; } public Long getAgeAtDeath() { return ageAtDeath; } public void setAgeAtDeath(Long ageAtDeath) { this.ageAtDeath = ageAtDeath; } @Override public String toString() { return "Death [deathCause=" + deathCause + ", deathDate=" + deathDate + ", deathPlace=" + deathPlace + ", individual=" + individual + "]"; } }
package owltools.sim2; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.semanticweb.elk.owlapi.ElkReasonerFactory; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.reasoner.Node; import org.semanticweb.owlapi.reasoner.NodeSet; import org.semanticweb.owlapi.reasoner.OWLReasoner; import org.semanticweb.owlapi.reasoner.impl.DefaultNode; import org.semanticweb.owlapi.reasoner.impl.OWLClassNode; import owltools.sim.io.SimResultRenderer.AttributesSimScores; import owltools.sim2.OwlSim.ScoreAttributeSetPair; import owltools.sim2.SimpleOwlSim.Direction; import owltools.sim2.SimpleOwlSim.Metric; import owltools.sim2.SimpleOwlSim.ScoreAttributePair; import owltools.sim2.scores.AttributePairScores; import owltools.sim2.scores.ElementPairScores; import owltools.sim2.scores.ScoreMatrix; import owltools.util.ClassExpressionPair; import com.googlecode.javaewah.EWAHCompressedBitmap; import com.googlecode.javaewah.IntIterator; /** * Faster implementation of OwlSim * * Makes use of integers to index classes, and bitmaps to represent class sets * * @author cjm * */ public class FastOwlSim extends AbstractOwlSim implements OwlSim { private Logger LOG = Logger.getLogger(FastOwlSim.class); private Map<OWLNamedIndividual, Set<OWLClass>> elementToDirectAttributesMap; private Map<OWLNamedIndividual, Set<Node<OWLClass>>> elementToInferredAttributesMap; // REDUNDANT WITH typesMap private Map<OWLClass,Set<Node<OWLClass>>> superclassMap; private Map<OWLNamedIndividual,Set<Node<OWLClass>>> inferredTypesMap; // cache of Type(i)->Cs private Map<OWLClass,Set<Integer>> superclassIntMap; private Map<OWLNamedIndividual,Set<Integer>> inferredTypesIntMap; private EWAHCompressedBitmap[] superclassBitmapIndex; private Map<OWLClass,EWAHCompressedBitmap> superclassBitmapMap; private Map<OWLNamedIndividual, EWAHCompressedBitmap> inferredTypesBitmapMap; // cache of Type(i)->BM Map<OWLClass,EWAHCompressedBitmap> properSuperclassBitmapMap; // TODO - implement Map<Node<OWLClass>, OWLClass> representativeClassMap; Map<OWLClass, OWLClass> classTorepresentativeClassMap; private Map<OWLClass,Integer> classIndex; private OWLClass[] classArray; private Set<OWLClass> allTypes = null; // all Types used in Type(e) for all e in E private Map<OWLClass, Double> icCache = new HashMap<OWLClass,Double>(); private Double[] icClassArray = null; // private Map<ClassIntPair, Set<Integer>> classPairLCSMap; // private Map<ClassIntPair, ScoreAttributeSetPair> classPairICLCSMap; final int scaleFactor = 1000; //short[][] ciPairScaledScore; ScoreAttributeSetPair[][] testCache = null; boolean[][] ciPairIsCached = null; int[][] ciPairLCS = null; @Override public void dispose() { showTimings(); } // represents a pair of classes using their indices // NOTE; replaced by arrays @Deprecated private class ClassIntPair { int c; int d; public ClassIntPair(int c, int d) { super(); this.c = c; this.d = d; } @Override public int hashCode() { final int prime = 991; int result = 1; result = prime * result + c; result = prime * result + d; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ClassIntPair other = (ClassIntPair) obj; return c == other.c && d == other.d; } } /** * @param sourceOntology */ public FastOwlSim(OWLOntology sourceOntology) { reasoner = new ElkReasonerFactory().createReasoner(sourceOntology); } /** * @param reasoner */ public FastOwlSim(OWLReasoner reasoner) { this.reasoner = reasoner; } @Override public Set<OWLClass> getAllAttributeClasses() { return allTypes; // note - only attributes used directly or indirectly } private int getClassIndex(OWLClass c) throws UnknownOWLClassException { Integer ix = classIndex.get(c); if (ix == null) { throw new UnknownOWLClassException(c); } return ix; } private int getClassIndex(Node<OWLClass> n) throws UnknownOWLClassException { OWLClass c = n.getRepresentativeElement(); return getClassIndex(c); } // not yet implemented: guaranteed to yield and indexed class private OWLClass getIndexedClass(Node<OWLClass> n) throws UnknownOWLClassException { if (representativeClassMap == null) representativeClassMap = new HashMap<Node<OWLClass>, OWLClass>(); else if (representativeClassMap.containsKey(n)) return representativeClassMap.get(n); for (OWLClass c : n.getEntities()) { if (classIndex.containsKey(c)) { representativeClassMap.put(n,c); return c; } } throw new UnknownOWLClassException(n.getRepresentativeElement()); } @Override public void createElementAttributeMapFromOntology() throws UnknownOWLClassException { getReasoner().flush(); Set<OWLClass> cset = getSourceOntology().getClassesInSignature(); Set<OWLNamedIndividual> inds = getSourceOntology().getIndividualsInSignature(true); LOG.info("|C|="+cset.size()); LOG.info("|I|="+inds.size()); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (OWLClass c : cset) { nodes.add(getReasoner().getEquivalentClasses(c)); } LOG.info("|N|="+nodes.size()); // TODO - use this representativeClassMap = new HashMap<Node<OWLClass>, OWLClass>(); classTorepresentativeClassMap = new HashMap<OWLClass, OWLClass>(); for (Node<OWLClass> n : nodes) { OWLClass c = n.getRepresentativeElement(); representativeClassMap.put(n, c); for (OWLClass c2 : n.getEntities()) { classTorepresentativeClassMap.put(c2, c); } } // Create a bidirectional index, class by number int n=0; classArray = (OWLClass[]) Array.newInstance(OWLClass.class, cset.size()+1); classIndex = new HashMap<OWLClass,Integer>(); // 0th element is always owlThing (root) classArray[n] = owlThing(); classIndex.put(owlThing(), n); n++; // TODO - investigate if ordering elements makes a difference; // e.g. if more frequent classes recieve lower bit indices this // may speed certain BitMap operations? for (OWLClass c : cset) { if (c.equals(owlThing())) continue; classArray[n] = c; classIndex.put(c, n); n++; } for (OWLClass c : cset) { ancsCachedModifiable(c); ancsIntsCachedModifiable(c); ancsBitmapCachedModifiable(c); } // cache E -> Type(E) elementToDirectAttributesMap = new HashMap<OWLNamedIndividual,Set<OWLClass>>(); elementToInferredAttributesMap = new HashMap<OWLNamedIndividual,Set<Node<OWLClass>>>(); allTypes = new HashSet<OWLClass>(); for (OWLNamedIndividual e : inds) { // The attribute classes for an individual are the direct inferred // named types. We assume that grouping classes have already been // generated. NodeSet<OWLClass> nodesetDirect = getReasoner().getTypes(e, true); NodeSet<OWLClass> nodesetInferred = getReasoner().getTypes(e, false); allTypes.addAll(nodesetDirect.getFlattened()); elementToInferredAttributesMap.put(e, nodesetInferred.getNodes()); elementToDirectAttributesMap.put(e, nodesetDirect.getFlattened()); // TODO - remove deprecated classes elementToDirectAttributesMap.get(e).remove(owlThing()); elementToInferredAttributesMap.get(e).remove(owlThing()); // force cacheing ancsBitmapCachedModifiable(e); } // cache for (OWLClass c : cset) { getInformationContentForAttribute(c); getInformationContentForAttribute(classIndex.get(c)); } } // TODO - change set to be (ordered) List, to avoid sorting each time private EWAHCompressedBitmap convertIntsToBitmap(Set<Integer> bits) { EWAHCompressedBitmap bm = new EWAHCompressedBitmap(); ArrayList<Integer> bitlist = new ArrayList<Integer>(bits); // necessary for EWAH API, otherwise silently fails Collections.sort(bitlist); for (Integer i : bitlist) { bm.set(i.intValue()); } return bm; } // cached proper superclasses (i.e. excludes equivalent classes) as BitMap public EWAHCompressedBitmap ancsProperBitmapCachedModifiable(OWLClass c) { if (properSuperclassBitmapMap != null && properSuperclassBitmapMap.containsKey(c)) { return properSuperclassBitmapMap.get(c); } Set<Integer> ancsInts = new HashSet<Integer>(); for (Node<OWLClass> anc : reasoner.getSuperClasses(c, false)) { // TODO - verify robust for non-Rep elements OWLClass ac = anc.getRepresentativeElement(); if (ac.equals(thing)) continue; ancsInts.add(classIndex.get(ac)); } EWAHCompressedBitmap bm = convertIntsToBitmap(ancsInts); if (properSuperclassBitmapMap == null) properSuperclassBitmapMap = new HashMap<OWLClass,EWAHCompressedBitmap>(); properSuperclassBitmapMap.put(c, bm); return bm; } private EWAHCompressedBitmap ancsBitmapCachedModifiable(OWLClass c) throws UnknownOWLClassException { if (superclassBitmapMap != null && superclassBitmapMap.containsKey(c)) { return superclassBitmapMap.get(c); } Set<Integer> caints = ancsIntsCachedModifiable(c); EWAHCompressedBitmap bm = convertIntsToBitmap(caints); if (superclassBitmapMap == null) superclassBitmapMap = new HashMap<OWLClass,EWAHCompressedBitmap>(); superclassBitmapMap.put(c, bm); return bm; } private EWAHCompressedBitmap ancsBitmapCachedModifiable(int cix) throws UnknownOWLClassException { if (superclassBitmapIndex != null && superclassBitmapIndex[cix] != null) { return superclassBitmapIndex[cix]; } Set<Integer> caints = ancsIntsCachedModifiable(classArray[cix]); EWAHCompressedBitmap bm = convertIntsToBitmap(caints); if (superclassBitmapIndex == null) superclassBitmapIndex = new EWAHCompressedBitmap[classArray.length]; superclassBitmapIndex[cix] = bm; return bm; } private EWAHCompressedBitmap ancsBitmapCachedModifiable(OWLNamedIndividual i) throws UnknownOWLClassException { if (inferredTypesBitmapMap != null && inferredTypesBitmapMap.containsKey(i)) { return inferredTypesBitmapMap.get(i); } Set<Integer> caints = ancsIntsCachedModifiable(i); EWAHCompressedBitmap bm = convertIntsToBitmap(caints); if (inferredTypesBitmapMap == null) inferredTypesBitmapMap = new HashMap<OWLNamedIndividual,EWAHCompressedBitmap>(); inferredTypesBitmapMap.put(i, bm); return bm; } private Set<Integer> ancsIntsCachedModifiable(OWLClass c) throws UnknownOWLClassException { if (superclassIntMap != null && superclassIntMap.containsKey(c)) { return superclassIntMap.get(c); } Set<Integer> a = ancsInts(c); if (superclassIntMap == null) superclassIntMap = new HashMap<OWLClass,Set<Integer>>(); superclassIntMap.put(c, a); return a; } // TODO - make this an ordered list, for faster bitmaps private Set<Integer> ancsIntsCachedModifiable(OWLNamedIndividual i) throws UnknownOWLClassException { if (inferredTypesIntMap != null && inferredTypesIntMap.containsKey(i)) { return inferredTypesIntMap.get(i); } Set<Integer> a = ancsInts(i); if (inferredTypesIntMap == null) inferredTypesIntMap = new HashMap<OWLNamedIndividual,Set<Integer>>(); inferredTypesIntMap.put(i, a); return a; } // all ancestors as IntSet // note that for equivalence sets, the representative element is returned private Set<Integer> ancsInts(OWLClass c) throws UnknownOWLClassException { Set<Node<OWLClass>> ancs = ancsCachedModifiable(c); Set<Integer> ancsInts = new HashSet<Integer>(); OWLClass thing = owlThing(); for (Node<OWLClass> anc : ancs) { // TODO - verify robust for non-Rep elements OWLClass ac = anc.getRepresentativeElement(); if (ac.equals(thing)) continue; Integer ix = classIndex.get(ac); if (ix == null) { throw new UnknownOWLClassException(ac); } ancsInts.add(ix.intValue()); } return ancsInts; } private Set<Integer> ancsInts(OWLNamedIndividual i) throws UnknownOWLClassException { Set<Node<OWLClass>> ancs = ancsCachedModifiable(i); Set<Integer> ancsInts = new HashSet<Integer>(); OWLClass thing = owlThing(); for (Node<OWLClass> anc : ancs) { // TODO - verify robust for non-Rep elements OWLClass ac = anc.getRepresentativeElement(); if (ac.equals(thing)) continue; Integer ix = classIndex.get(ac); if (ix == null) { throw new UnknownOWLClassException(ac); } ancsInts.add(ix.intValue()); } return ancsInts; } @Deprecated private Set<Node<OWLClass>> ancsCached(OWLClass c) { return new HashSet<Node<OWLClass>>(ancsCachedModifiable(c)); } private Set<Node<OWLClass>> ancsCachedModifiable(OWLClass c) { if (superclassMap != null && superclassMap.containsKey(c)) { return superclassMap.get(c); } Set<Node<OWLClass>> a = ancs(c); if (superclassMap == null) superclassMap = new HashMap<OWLClass,Set<Node<OWLClass>>>(); superclassMap.put(c, a); return a; } private Set<Node<OWLClass>> ancsCachedModifiable(OWLNamedIndividual i) { if (inferredTypesMap != null && inferredTypesMap.containsKey(i)) { return inferredTypesMap.get(i); } Set<Node<OWLClass>> a = ancs(i); if (inferredTypesMap == null) inferredTypesMap = new HashMap<OWLNamedIndividual,Set<Node<OWLClass>>>(); inferredTypesMap.put(i, a); return a; } private Set<Node<OWLClass>> ancs(OWLClass c) { NodeSet<OWLClass> ancs = getReasoner().getSuperClasses(c, false); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(ancs.getNodes()); nodes.add(getReasoner().getEquivalentClasses(c)); nodes.remove(owlThingNode()); return nodes; } private Set<Node<OWLClass>> ancs(OWLNamedIndividual i) { Set<Node<OWLClass>> nodes = getReasoner().getTypes(i, false).getNodes(); nodes.remove(owlThingNode()); return nodes; } @Override public Set<OWLClass> getAttributesForElement(OWLNamedIndividual e) throws UnknownOWLClassException { if (elementToDirectAttributesMap == null) createElementAttributeMapFromOntology(); return new HashSet<OWLClass>(elementToDirectAttributesMap.get(e)); } @Override public Set<OWLNamedIndividual> getElementsForAttribute(OWLClass c) { return getReasoner().getInstances(c, false).getFlattened(); } @Override public int getNumElementsForAttribute(OWLClass c) { return getElementsForAttribute(c).size(); } @Override public Set<OWLNamedIndividual> getAllElements() { // Note: will only return elements that have >=1 attributes return elementToDirectAttributesMap.keySet(); } @Override public Double getInformationContentForAttribute(OWLClass c) throws UnknownOWLClassException { if (icCache.containsKey(c)) return icCache.get(c); int freq = getNumElementsForAttribute(c); Double ic = null; if (freq > 0) { ic = -Math.log(((double) (freq) / getCorpusSize())) / Math.log(2); // experimental: use depth in graph as tie-breaker int numAncs = ancsBitmapCachedModifiable(c).cardinality(); ic += numAncs / (double) scaleFactor; } icCache.put(c, ic); return ic; } private Double getInformationContentForAttribute(int cix) throws UnknownOWLClassException { if (icClassArray != null && icClassArray[cix] != null) { return icClassArray[cix]; } OWLClass c = classArray[cix]; Double ic = getInformationContentForAttribute(c); if (icClassArray == null) { icClassArray = new Double[classArray.length]; } icClassArray[cix] = ic; return ic; } @Override public Set<Node<OWLClass>> getInferredAttributes(OWLNamedIndividual a) { return new HashSet<Node<OWLClass>>(elementToInferredAttributesMap.get(a)); } @Override public Set<Node<OWLClass>> getNamedReflexiveSubsumers(OWLClass a) { return ancs(a); } @Override public Set<Node<OWLClass>> getNamedCommonSubsumers(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); EWAHCompressedBitmap cad = bmc.and(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } private Set<Node<OWLClass>> getNamedCommonSubsumers(int cix, int dix) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(cix); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(dix); EWAHCompressedBitmap cad = bmc.and(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } private EWAHCompressedBitmap getNamedCommonSubsumersAsBitmap(int cix, int dix) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(cix); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(dix); EWAHCompressedBitmap cad = bmc.and(bmd); return cad; } //@Override public Set<Node<OWLClass>> getNamedUnionSubsumers(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); EWAHCompressedBitmap cud = bmc.or(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cud.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } @Override public int getNamedCommonSubsumersCount(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); return bmc.andCardinality(bmd); } @Override public Set<Node<OWLClass>> getNamedCommonSubsumers(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); EWAHCompressedBitmap cad = bmc.and(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } private Set<Node<OWLClass>> getNamedUnionSubsumers(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); EWAHCompressedBitmap cad = bmc.or(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } @Override public Set<Node<OWLClass>> getNamedLowestCommonSubsumers(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap cad = getNamedLowestCommonSubsumersAsBitmap(c, d); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); // TODO - optimize this & ensure all elements of an equivalence set are included for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } private Set<Node<OWLClass>> getNamedLowestCommonSubsumers(int cix, int dix) throws UnknownOWLClassException { EWAHCompressedBitmap cad = getNamedLowestCommonSubsumersAsBitmap(cix, dix); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); // TODO - optimize this & ensure all elements of an equivalence set are included for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } // fast bitmap implementation of LCS private EWAHCompressedBitmap getNamedLowestCommonSubsumersAsBitmap(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); EWAHCompressedBitmap cad = bmc.and(bmd); int[] csInts = cad.toArray(); for (int ix : csInts) { cad = cad.andNot(ancsProperBitmapCachedModifiable(classArray[ix])); } return cad; } private EWAHCompressedBitmap getNamedLowestCommonSubsumersAsBitmap(int cix, int dix) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(cix); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(dix); EWAHCompressedBitmap cad = bmc.and(bmd); int[] csInts = cad.toArray(); for (int ix : csInts) { cad = cad.andNot(ancsProperBitmapCachedModifiable(classArray[ix])); } return cad; } @Deprecated private Set<Node<OWLClass>> getNamedLowestCommonSubsumersNaive(OWLClass a, OWLClass b) throws UnknownOWLClassException { // currently no need to cache this, as only called from // getLowestCommonSubsumerIC, which does its own caching Set<Node<OWLClass>> commonSubsumerNodes = getNamedCommonSubsumers(a, b); Set<Node<OWLClass>> rNodes = new HashSet<Node<OWLClass>>(); // remove redundant for (Node<OWLClass> node : commonSubsumerNodes) { rNodes.addAll(getReasoner().getSuperClasses( node.getRepresentativeElement(), false).getNodes()); } commonSubsumerNodes.removeAll(rNodes); return commonSubsumerNodes; } @Override public double getAttributeSimilarity(OWLClass c, OWLClass d, Metric metric) throws UnknownOWLClassException { if (metric.equals(Metric.JACCARD)) { return getAttributeJaccardSimilarity(c, d); } else if (metric.equals(Metric.OVERLAP)) { return getNamedCommonSubsumers(c, d).size(); } else if (metric.equals(Metric.NORMALIZED_OVERLAP)) { return getNamedCommonSubsumers(c, d).size() / Math.min(getNamedReflexiveSubsumers(c).size(), getNamedReflexiveSubsumers(d).size()); } else if (metric.equals(Metric.DICE)) { // TODO return -1; } else { return 0; } } @Override public AttributePairScores getPairwiseSimilarity(OWLClass c, OWLClass d) throws UnknownOWLClassException { AttributePairScores s = new AttributePairScores(c,d); EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); s.simjScore = bmc.andCardinality(bmd) / (double) bmc.orCardinality(bmd); s.asymmetricSimjScore = bmc.andCardinality(bmd) / (double) bmd.cardinality(); s.inverseAsymmetricSimjScore = bmc.andCardinality(bmd) / (double) bmc.cardinality(); ScoreAttributeSetPair sap = getLowestCommonSubsumerWithIC(c, d); s.lcsIC = sap.score; s.lcsSet = sap.attributeClassSet; return s; } @Override public double getAttributeJaccardSimilarity(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); return bmc.andCardinality(bmd) / (double) bmc.orCardinality(bmd); } @Override public double getElementJaccardSimilarity(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); return bmc.andCardinality(bmd) / (double) bmc.orCardinality(bmd); } @Override public double getAsymmerticAttributeJaccardSimilarity(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); return bmc.andCardinality(bmd) / (double) bmd.cardinality(); } //@Override public double getAsymmetricElementJaccardSimilarity(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); return bmc.andCardinality(bmd) / (double) bmd.cardinality(); } // SimGIC // TODO - optimize @Override public double getElementGraphInformationContentSimilarity( OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { // TODO - optimize long t = System.currentTimeMillis(); EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); EWAHCompressedBitmap cad = bmc.and(bmd); EWAHCompressedBitmap cud = bmc.or(bmd); //Set<Node<OWLClass>> ci = getNamedCommonSubsumers(i, j); //Set<Node<OWLClass>> cu = getNamedUnionSubsumers(i, j); double sumICboth = 0; double sumICunion = 0; // faster than translating to integer list IntIterator it = cud.intIterator(); while (it.hasNext()) { int x = it.next(); double ic = getInformationContentForAttribute(x); // TODO - we can avoid doing this twice by using xor in the bitmap sumICunion += ic; if (cad.get(x)) { sumICboth += ic; } } totalTimeGIC += tdelta(t); this.totalCallsGIC++; return sumICboth / sumICunion; } // TODO - optimize @Override public double getAttributeGraphInformationContentSimilarity( OWLClass c, OWLClass d) throws UnknownOWLClassException { return getAttributeGraphInformationContentSimilarity(classIndex.get(c), classIndex.get(d)); } public double getAttributeGraphInformationContentSimilarity( int cix, int dix) throws UnknownOWLClassException { long t = System.currentTimeMillis(); EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(cix); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(dix); EWAHCompressedBitmap cad = bmc.and(bmd); EWAHCompressedBitmap cud = bmc.or(bmd); double sumICboth = 0; double sumICunion = 0; // faster than translating to integer list IntIterator it = cud.intIterator(); while (it.hasNext()) { int x = it.next(); double ic = getInformationContentForAttribute(x); // TODO - we can avoid doing this twice by using xor in the bitmap sumICunion += ic; if (cad.get(x)) { sumICboth += ic; } } totalTimeGIC += tdelta(t); this.totalCallsGIC++; return sumICboth / sumICunion; } //@Override public double getAsymmetricElementGraphInformationContentSimilarity( OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { // TODO - optimize Set<Node<OWLClass>> ci = getNamedCommonSubsumers(i, j); Set<Node<OWLClass>> cu = this.getInferredAttributes(j); double sumICboth = 0; double sumICunion = 0; for (Node<OWLClass> c : cu) { // TODO - we can avoid doing this twice by using xor in the bitmap sumICunion += getInformationContentForAttribute(c .getRepresentativeElement()); if (ci.contains(c)) { sumICboth += getInformationContentForAttribute(c .getRepresentativeElement()); } } return sumICboth / sumICunion; } // NOTE: current implementation will also return redundant classes if // they rank the same - use groupwise if true maxIC required @Override public ScoreAttributeSetPair getSimilarityMaxIC(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { Set<Node<OWLClass>> atts = getNamedCommonSubsumers(i,j); ScoreAttributeSetPair best = new ScoreAttributeSetPair(0.0); for (Node<OWLClass> n : atts) { OWLClass c = n.getRepresentativeElement(); Double ic = getInformationContentForAttribute(c); if (Math.abs(ic - best.score) < 0.000001) { // tie for best attribute best.addAttributeClass(c); } if (ic > best.score) { best = new ScoreAttributeSetPair(ic, c); } } return best; } @Override public ScoreAttributeSetPair getSimilarityBestMatchAverageAsym( OWLNamedIndividual i, OWLNamedIndividual j) { // TODO Auto-generated method stub return null; } @Override public ScoreAttributeSetPair getSimilarityBestMatchAverageAsym( OWLNamedIndividual i, OWLNamedIndividual j, Metric metric) { // TODO Auto-generated method stub return null; } @Override public ScoreAttributeSetPair getSimilarityBestMatchAverage( OWLNamedIndividual i, OWLNamedIndividual j, Metric metric, Direction dir) { // TODO Auto-generated method stub return null; } @Override public ElementPairScores getGroupwiseSimilarity(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { ElementPairScores s = new ElementPairScores(i,j); populateSimilarityMatrix(i, j, s); s.simGIC = getElementGraphInformationContentSimilarity(i, j); return s; } public void populateSimilarityMatrix( OWLNamedIndividual i, OWLNamedIndividual j, ElementPairScores ijscores) throws UnknownOWLClassException { /* EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); EWAHCompressedBitmap cad = bmc.and(bmd); EWAHCompressedBitmap cud = bmc.or(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } */ /* ijscores.simGIC = getElementGraphInformationContentSimilarity(i, j); ijscores.asymmetricSimGIC = getAsymmetricElementGraphInformationContentSimilarity(i, j); ijscores.inverseAsymmetricSimGIC = getAsymmetricElementGraphInformationContentSimilarity(j, i); */ ijscores.simjScore = getElementJaccardSimilarity(i, j); ijscores.asymmetricSimjScore = getAsymmetricElementJaccardSimilarity(i, j); ijscores.inverseAsymmetricSimjScore = getAsymmetricElementJaccardSimilarity(j, i); Vector<OWLClass> cs = new Vector<OWLClass>(getAttributesForElement(i)); Vector<OWLClass> ds = new Vector<OWLClass>(getAttributesForElement(j)); populateSimilarityMatrix(cs, ds, ijscores); } public void populateSimilarityMatrix(Vector<OWLClass> cs, Vector<OWLClass> ds, ElementPairScores ijscores) throws UnknownOWLClassException { ScoreAttributeSetPair bestsap = null; int csize = cs.size(); int dsize = ds.size(); ijscores.cs = cs; ijscores.ds = ds; double total = 0.0; double[][] scoreMatrix = new double[csize][dsize]; ScoreAttributeSetPair[][] sapMatrix = new ScoreAttributeSetPair[csize][dsize]; ScoreAttributeSetPair[] bestSapForC = new ScoreAttributeSetPair[csize]; ScoreAttributeSetPair[] bestSapForD = new ScoreAttributeSetPair[dsize]; double bestMatchCTotal = 0; double bestMatchDTotal = 0; // populate matrix for (int cx=0; cx<csize; cx++) { OWLClass c = cs.elementAt(cx); int cix = classIndex.get(c); ScoreAttributeSetPair bestcsap = null; for (int dx=0; dx<dsize; dx++) { OWLClass d = ds.elementAt(dx); int dix = classIndex.get(d); ScoreAttributeSetPair sap = getLowestCommonSubsumerWithIC(cix,dix); sapMatrix[cx][dx] = sap; double score = sap.score; total += score; if (bestsap == null || score >= bestsap.score) { bestsap = sap; } if (bestcsap == null || score >= bestcsap.score) { bestcsap = sap; } } bestSapForC[cx] = bestcsap; bestMatchCTotal += bestcsap.score; } // retrieve best values for each D for (int dx=0; dx<dsize; dx++) { ScoreAttributeSetPair bestdsap = null; for (int cx=0; cx<csize; cx++) { ScoreAttributeSetPair sap = sapMatrix[cx][dx]; if (bestdsap == null || sap.score >= bestdsap.score) { bestdsap = sap; } } bestSapForD[dx] = bestdsap; bestMatchDTotal += bestdsap.score; } // TODO - use these ijscores.avgIC = total / (csize * dsize); ijscores.bmaAsymIC = bestMatchCTotal / (double)csize; ijscores.bmaInverseAsymIC = bestMatchDTotal / (double)dsize; ijscores.bmaSymIC = (bestMatchCTotal + bestMatchDTotal) / (double)(csize+dsize); ijscores.iclcsMatrix = new ScoreMatrix<ScoreAttributeSetPair>(); ijscores.iclcsMatrix.matrix = sapMatrix; ijscores.iclcsMatrix.bestForC = bestSapForC; ijscores.iclcsMatrix.bestForD = bestSapForD; ijscores.maxIC = bestsap.score; ijscores.maxICwitness = bestsap.attributeClassSet; } // uses integer 2D array cache private ScoreAttributeSetPair getLowestCommonSubsumerWithIC(int cix, int dix) throws UnknownOWLClassException { return getLowestCommonSubsumerWithIC(cix, dix, null); } private ScoreAttributeSetPair getLowestCommonSubsumerWithIC(int cix, int dix, Double thresh) throws UnknownOWLClassException { if (isDisableLCSCache) { return getLowestCommonSubsumerWithICNoCache(cix, dix); } // set up cache if (ciPairIsCached == null) { // Estimates: 350mb for MP // 5.4Gb for 30k classes //int size = this.getAllAttributeClasses().size(); int size = classArray.length; LOG.info("Creating 2D cache of "+size+" * "+size); ciPairIsCached = new boolean[size][size]; ciPairLCS = new int[size][size]; LOG.info("Created LCS cache"+size+" * "+size); //ciPairScaledScore = new short[size][size]; //LOG.info("Created score cache cache"+size+" * "+size); } if (!isNoLookupForLCSCache && ciPairIsCached[cix][dix]) { // TODO null vs 0 // TODO - consider getting IC directly from main IC cache - single lookup // rather than 2D lookup int lcsix = ciPairLCS[cix][dix]; return new ScoreAttributeSetPair(icClassArray[lcsix], classArray[lcsix]); //return new ScoreAttributeSetPair(ciPairScaledScore[cix][dix] / (float)scaleFactor, // classArray[ciPairLCS[cix][dix]]); } if (!isNoLookupForLCSCache && isLCSCacheFullyPopulated) { // true if a pre-generated cache has been loaded and there is no entry for this pair; // a cache excludes certain pairs if they are below threshold return null; } ScoreAttributeSetPair sap = getLowestCommonSubsumerWithICNoCache(cix, dix); if (thresh != null && sap.score < thresh) { return null; } //testCache[cix][dix] = sap; ciPairIsCached[cix][dix] = true; OWLClass lcsCls = null; if (sap.attributeClassSet != null && !sap.attributeClassSet.isEmpty()) { lcsCls = sap.attributeClassSet.iterator().next(); // note: others are discarded Integer lcsix = classIndex.get(lcsCls); ciPairLCS[cix][dix] = lcsix; icClassArray[lcsix] = sap.score; } else { //TODO - remove obsoletes //LOG.warn("uh oh"+classArray[cix] + " "+ // classArray[dix]+" "+sap.attributeClassSet); } //ciPairScaledScore[cix][dix] = (short)(sap.score * scaleFactor); return sap; } @Override public ScoreAttributeSetPair getLowestCommonSubsumerWithIC(OWLClass c, OWLClass d) throws UnknownOWLClassException { return getLowestCommonSubsumerWithIC(classIndex.get(c), classIndex.get(d)); } public ScoreAttributeSetPair getLowestCommonSubsumerWithIC(OWLClass c, OWLClass d, Double thresh) throws UnknownOWLClassException { return getLowestCommonSubsumerWithIC(classIndex.get(c), classIndex.get(d), thresh); } private ScoreAttributeSetPair getLowestCommonSubsumerWithICNoCache(int cix, int dix) throws UnknownOWLClassException { long t = System.currentTimeMillis(); EWAHCompressedBitmap cad = getNamedLowestCommonSubsumersAsBitmap(cix, dix); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } Set<OWLClass> lcsClasses = new HashSet<OWLClass>(); double maxScore = 0.0; for (int ix : cad.toArray()) { double score = getInformationContentForAttribute(ix); if (score >= maxScore) { lcsClasses.add(classArray[ix]); maxScore = score; } } if (lcsClasses.size() == 0) { // TODO - remove obsoletes //LOG.warn("Hmmmm "+c+" "+d+" "+lcs); } totalTimeLCSIC += tdelta(t); this.totalCallsLCSIC++; return new ScoreAttributeSetPair(maxScore, lcsClasses); } /** * * @param c * @param ds * @return * @throws UnknownOWLClassException */ // TODO - rewrite @Override public List<AttributesSimScores> compareAllAttributes(OWLClass c, Set<OWLClass> ds) throws UnknownOWLClassException { List<AttributesSimScores> scoresets = new ArrayList<AttributesSimScores>(); EWAHCompressedBitmap bmc = this.ancsBitmapCachedModifiable(c); int cSize = bmc.cardinality(); Set<AttributesSimScores> best = new HashSet<AttributesSimScores>(); Double bestScore = null; for (OWLClass d : ds) { EWAHCompressedBitmap bmd = this.ancsBitmapCachedModifiable(d); int dSize = bmd.cardinality(); int cadSize = bmc.andCardinality(bmd); int cudSize = bmc.orCardinality(bmd); AttributesSimScores s = new AttributesSimScores(c,d); s.simJScore = cadSize / (double)cudSize; s.AsymSimJScore = cadSize / (double) dSize; //ClassExpressionPair pair = new ClassExpressionPair(c, d); //ScoreAttributePair lcs = getLowestCommonSubsumerIC(pair, cad, null); //s.lcsScore = lcs; scoresets.add(s); if (bestScore == null) { best.add(s); bestScore = s.simJScore; } else if (bestScore == s.simJScore) { best.add(s); } else if (s.simJScore > bestScore) { bestScore = s.simJScore; best = new HashSet<AttributesSimScores>(Collections.singleton(s)); } } for (AttributesSimScores s : best) { s.isBestMatch = true; } return scoresets; } // UTIL OWLClass thing = null; Node<OWLClass> thingNode = null; public OWLClass owlThing() { if (thing == null) thing = getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLThing(); return thing; } public Node<OWLClass> owlThingNode() { if (thingNode == null) thingNode = getReasoner().getTopClassNode(); return thingNode; } @Override public void saveLCSCache(String fileName, Double thresholdIC) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); for ( int cix = 0; cix< ciPairIsCached.length; cix++) { boolean[] arr = ciPairIsCached[cix]; OWLClass c = classArray[cix]; for ( int dix = 0; dix< arr.length; dix++) { if (arr[dix]) { //double s = ciPairScaledScore[cix][dix] / (double) scaleFactor; int lcsix = ciPairLCS[cix][dix]; double s = icClassArray[lcsix]; if (thresholdIC == null || s >= thresholdIC) { OWLClass d = classArray[dix]; OWLClass lcs = classArray[lcsix]; IOUtils.write(getShortId((OWLClass) c) +"\t" + getShortId((OWLClass) d) + "\t" + s + "\t" + getShortId(lcs) + "\n", fos); } } } } fos.close(); } /** * @param fileName * @throws IOException */ @Override public void loadLCSCache(String fileName) throws IOException { try { clearLCSCache(); } catch (UnknownOWLClassException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new IOException("Cannot clear cache"); } FileInputStream s = new FileInputStream(fileName); List<String> lines = IOUtils.readLines(s); for (String line : lines) { String[] vals = line.split("\t"); OWLClass c1 = getOWLClassFromShortId(vals[0]); OWLClass c2 = getOWLClassFromShortId(vals[1]); OWLClass a = getOWLClassFromShortId(vals[3]); int cix = classIndex.get(c1); int dix = classIndex.get(c2); ciPairIsCached[cix][dix] = true; //ciPairScaledScore[cix][dix] = (short)(Double.valueOf(vals[2]) * scaleFactor); // TODO - set all IC caches ciPairLCS[cix][dix] = classIndex.get(a); } isLCSCacheFullyPopulated = true; } @Override protected void setInformtionContectForAttribute(OWLClass c, Double v) { icCache.put(c, v); if (icClassArray == null) icClassArray = new Double[classArray.length]; icClassArray[classIndex.get(c)] = v; } @Override protected void clearInformationContentCache() { testCache = null; icCache = new HashMap<OWLClass,Double>(); icClassArray = null; } protected void clearLCSCache() throws UnknownOWLClassException { if (classArray == null) { createElementAttributeMapFromOntology(); } ciPairLCS = new int[classArray.length][classArray.length]; //ciPairScaledScore = new short[classArray.length][classArray.length]; ciPairIsCached = new boolean[classArray.length][classArray.length]; } }
package dk.aau.sw402F15.ScopeChecker; import dk.aau.sw402F15.TypeChecker.Exceptions.SymbolNotFoundException; import dk.aau.sw402F15.TypeChecker.Symboltable.*; import dk.aau.sw402F15.parser.analysis.DepthFirstAdapter; import dk.aau.sw402F15.parser.node.*; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class ScopeChecker extends DepthFirstAdapter { private Scope rootScope = new Scope(null, null); private Scope currentScope; public ScopeChecker() { currentScope = rootScope; } // When a functions is entered this makes sure that the scope is changed as well @Override public void caseAFunctionRootDeclaration(AFunctionRootDeclaration node) { inAFunctionRootDeclaration(node); if (node.getReturnType() != null) { node.getReturnType().apply(this); } if (node.getName() != null) { node.getName().apply(this); } // Open subscope before visiting the inner statements currentScope = currentScope.addSubScope(node); // Import parameters so that they are accessible from within the function. List<PDeclaration> params = new ArrayList<PDeclaration>(node.getParams()); for (PDeclaration parameter : params) { parameter.apply(this); } // Visit the inner statements List<PStatement> statements = new ArrayList<PStatement>(node.getStatements()); for (PStatement statement : statements) { statement.apply(this); } // Leave the subscope currentScope = currentScope.getParentScope(); outAFunctionRootDeclaration(node); } // Runs a small preprocessor which makes sure that global variables, structs, enum and functions are declared // before continuing on with the compiling of the program @Override public void caseAProgram(AProgram node){ List<AEnumRootDeclaration> enums = new ArrayList<AEnumRootDeclaration>(); List<AFunctionRootDeclaration> functions = new ArrayList<AFunctionRootDeclaration>(); List<AStructRootDeclaration> structs = new ArrayList<AStructRootDeclaration>(); List<ADeclarationRootDeclaration> variables = new ArrayList<ADeclarationRootDeclaration>(); // Separate the different root decelerations into different lists. for(PRootDeclaration d : node.getRootDeclaration()){ if(d.getClass() == AEnumRootDeclaration.class){ enums.add((AEnumRootDeclaration)d); } else if(d.getClass() == AFunctionRootDeclaration.class){ functions.add((AFunctionRootDeclaration)d); } else if(d.getClass() == AStructRootDeclaration.class){ structs.add((AStructRootDeclaration)d); } else if(d.getClass() == ADeclarationRootDeclaration.class){ variables.add((ADeclarationRootDeclaration) d); } } // Declare the different elements in the order in which they are likely to need each other for (AEnumRootDeclaration e : enums){ DeclareEnum(e); } for (AStructRootDeclaration s : structs){ StructBuilder builder = new StructBuilder(rootScope); s.apply(builder); } for (ADeclarationRootDeclaration v : variables){ DeclareVariable(v.getDeclaration()); } for (AFunctionRootDeclaration f : functions){ DeclareFunction(f); } // Runs the normal processor super.caseAProgram(node); } private void DeclareVariable(PDeclaration node){ boolean isArray = false; boolean isConst = false; String name = null; SymbolType type = null; if(node.getClass() == ADeclaration.class){ ADeclaration n = (ADeclaration)node; isArray = n.getArray() != null; isConst = n.getQuailifer() != null; name = n.getName().getText(); type = getSymbolType(n.getType()); } else if (node.getClass() == AAssignmentDeclaration.class){ AAssignmentDeclaration n = (AAssignmentDeclaration)node; isArray = n.getArray() != null; isConst = n.getQuailifer() != null; name = n.getName().getText(); type = getSymbolType(n.getType()); } if(isArray) DeclareArray(name, type, node); else DeclareVariable(name, type, node, isConst); } private void DeclareVariable(String name, SymbolType type, Node node, boolean isConst){ currentScope.addSymbol(new SymbolVariable(type, name, node, currentScope, isConst)); } private void DeclareArray(String name, SymbolType type, Node node){ currentScope.addSymbol(new SymbolArray(type, name, node, currentScope)); } private void DeclareEnum(AEnumRootDeclaration node){ currentScope = currentScope.addSubScope(node); List<PEnumFlag> list = node.getProgram(); for(PEnumFlag flag : list){ flag.apply(this); } List<Symbol> symbols = currentScope.toList(); currentScope = currentScope.getParentScope(); List<PEnumFlag> flags = new ArrayList<PEnumFlag>(symbols.size()); for (Symbol symbol : symbols){ if(symbol.getNode().getClass() == PEnumFlag.class){ PEnumFlag flag = (PEnumFlag)symbol.getNode(); flags.add(flag); } } currentScope.addSymbol(new SymbolEnum(node.getName().getText(), flags, node, currentScope)); } private void DeclareFunction(AFunctionRootDeclaration node){ LinkedList<PDeclaration> params = node.getParams(); List<SymbolType> paramTypes = new ArrayList<SymbolType>(params.size()); for(PDeclaration p : params){ ADeclaration param = (ADeclaration) p; paramTypes.add(getSymbolType(param.getType())); } currentScope.addSymbol(new SymbolFunction(getSymbolType(node.getReturnType()), paramTypes, node.getName().getText(), node, currentScope)); } @Override public void inAScopeStatement(AScopeStatement node) { currentScope = currentScope.addSubScope(node); } @Override public void outAScopeStatement(AScopeStatement node){ //TODO We dont call super here ? is that correct? currentScope = currentScope.getParentScope(); } @Override public void inAAssignmentDeclaration(AAssignmentDeclaration node){ DeclareVariable(node); } @Override public void inADeclaration(ADeclaration node){ DeclareVariable(node); } // Override normal visiting behaviour as root declarations already have been visited in the caseAProgram(...) // method. @Override public void caseAStructRootDeclaration(AStructRootDeclaration node){ inAStructRootDeclaration(node); // Make sure that the struct is in the symbol table currentScope.getSubScopeByNodeOrThrow(node); // Already visited in struct builder so there is no need to visit again outAStructRootDeclaration(node); } // Override normal visiting behaviour as root declarations already have been visited in the caseAProgram(...) // method. @Override public void caseADeclarationRootDeclaration(ADeclarationRootDeclaration node){ inADeclarationRootDeclaration(node); // Do nothing the variable is already declared outADeclarationRootDeclaration(node); } @Override public void inAIdentifierExpr(AIdentifierExpr node) { super.inAIdentifierExpr(node); currentScope.getSymbolOrThrow(node.getName().getText()); } @Override public void inAMemberExpr(AMemberExpr node) { super.inAMemberExpr(node); if (node.getLeft().getClass() == AIdentifierExpr.class){ //cast left node AIdentifierExpr expr = (AIdentifierExpr)node.getLeft(); // check if symbol is in table Symbol symbol = currentScope.getSymbolOrThrow(expr.getName().getText()); //check if returned symbol is a struct if ( symbol.getClass() == SymbolStruct.class){ List<Symbol> symbolList = ((SymbolStruct) symbol).getSymbolList(); // check list for field // check right node for type. Declaration or func if (node.getRight().getClass() == AIdentifierExpr.class){ // TODO Check if struct's scope contains right node AIdentifierExpr var = (AIdentifierExpr)node.getRight(); boolean okBit = false; for(Symbol sym : symbolList) if (sym.getName().equals(var.getName().getText())) okBit = true; if (okBit == false) throw new SymbolNotFoundException(); }else if (node.getRight().getClass() == AFunctionCallExpr.class){ AFunctionCallExpr var = (AFunctionCallExpr)node.getRight(); currentScope.getSymbolOrThrow(var.getName().getText()); } else { // right node is neigther var or func!!! throw new IllegalArgumentException(); } } else { throw new IllegalArgumentException(); } } else if ((node.getLeft().getClass() == AFunctionCallExpr.class)) { //cast left node AFunctionCallExpr expr = (AFunctionCallExpr) node.getLeft(); // check if symbol is in table Object symbol = currentScope.getSymbolOrThrow(expr.getName().getText()); // check if it returns a struct that have right node as field //check if returned symbol is a function if (symbol instanceof SymbolFunction) { SymbolFunction symbolFunction = (SymbolFunction)symbol; // check right node for type. Declaration or func if (node.getRight().getClass() == AIdentifierExpr.class) { AIdentifierExpr var = (AIdentifierExpr) node.getRight(); currentScope.getSymbolOrThrow(var.getName().getText()); } else if (node.getRight().getClass() == AFunctionCallExpr.class) { AFunctionCallExpr var = (AFunctionCallExpr) node.getRight(); currentScope.getSymbolOrThrow(var.getName().getText()); } else { // right node is neigther var or func!!! throw new IllegalArgumentException(); } } else { throw new IllegalArgumentException(); } } } private void checkRightNode(Object symbol){ } // Returns the outermost scope as the symbol table. public Scope getSymbolTable() { return rootScope; } private SymbolType getSymbolType(PTypeSpecifier type){ //Check for errors if(type == null){ throw new NullPointerException(); } //Find the symbol type SymbolType sType = null; if(type instanceof ABoolTypeSpecifier) { sType = SymbolType.Boolean; } else if(type instanceof ACharTypeSpecifier) { sType = SymbolType.Char; } else if(type instanceof ADoubleTypeSpecifier || type instanceof AFloatTypeSpecifier) { sType = SymbolType.Decimal; } else if(type instanceof AIntTypeSpecifier || type instanceof ALongTypeSpecifier) { sType = SymbolType.Int; } else if(type instanceof APortTypeSpecifier) { sType = SymbolType.Port; } else if(type instanceof ATimerTypeSpecifier) { sType = SymbolType.Timer; } else if(type instanceof AStructTypeSpecifier){ sType = SymbolType.Struct; } else if (type instanceof AEnumTypeSpecifier){ sType = SymbolType.Enum; } return sType; } }
package org.languagetool; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import javax.xml.parsers.ParserConfigurationException; import org.languagetool.commandline.CommandLineOptions; import org.languagetool.commandline.CommandLineParser; import org.xml.sax.SAXException; import org.apache.tika.language.*; import org.languagetool.bitext.TabBitextReader; import org.languagetool.rules.Rule; import org.languagetool.rules.bitext.BitextRule; import org.languagetool.tools.StringTools; import org.languagetool.tools.Tools; /** * The command line tool to check plain text files. * * @author Daniel Naber */ class Main { /* maximum file size to read in a single read */ private static final int MAX_FILE_SIZE = 64000; private final boolean verbose; private final boolean apiFormat; private final boolean taggerOnly; private final boolean applySuggestions; private final boolean autoDetect; private final boolean singleLineBreakMarksParagraph; private final String[] enabledRules; private final String[] disabledRules; private final Language motherTongue; private JLanguageTool lt; private boolean profileRules; private boolean bitextMode; private JLanguageTool srcLt; private List<BitextRule> bRules; private Rule currentRule; Main(final boolean verbose, final boolean taggerOnly, final Language language, final Language motherTongue, final String[] disabledRules, final String[] enabledRules, final boolean apiFormat, boolean applySuggestions, boolean autoDetect, boolean singleLineBreakMarksParagraph) throws IOException, SAXException, ParserConfigurationException { this.verbose = verbose; this.apiFormat = apiFormat; this.taggerOnly = taggerOnly; this.applySuggestions = applySuggestions; this.autoDetect = autoDetect; this.enabledRules = enabledRules; this.disabledRules = disabledRules; this.motherTongue = motherTongue; this.singleLineBreakMarksParagraph = singleLineBreakMarksParagraph; profileRules = false; bitextMode = false; srcLt = null; bRules = null; lt = new JLanguageTool(language, motherTongue); lt.activateDefaultPatternRules(); lt.activateDefaultFalseFriendRules(); Tools.selectRules(lt, disabledRules, enabledRules); } JLanguageTool getJLanguageTool() { return lt; } private void setListUnknownWords(final boolean listUnknownWords) { lt.setListUnknownWords(listUnknownWords); } private void cleanUp() { JLanguageTool.removeTemporaryFiles(); } private void setProfilingMode() { profileRules = true; } private void setBitextMode(final Language sourceLang, final String[] disabledRules, final String[] enabledRules) throws IOException, ParserConfigurationException, SAXException { bitextMode = true; final Language target = lt.getLanguage(); lt = new JLanguageTool(target, null); srcLt = new JLanguageTool(sourceLang); lt.activateDefaultPatternRules(); Tools.selectRules(lt, disabledRules, enabledRules); Tools.selectRules(srcLt, disabledRules, enabledRules); bRules = Tools.getBitextRules(sourceLang, lt.getLanguage()); List<BitextRule> bRuleList = new ArrayList<BitextRule>(bRules); for (final BitextRule bitextRule : bRules) { for (final String disabledRule : disabledRules) { if (bitextRule.getId().equals(disabledRule)) { bRuleList.remove(bitextRule); } } } bRules = bRuleList; if (enabledRules.length > 0) { bRuleList = new ArrayList<BitextRule>(); for (final String enabledRule : enabledRules) { for (final BitextRule bitextRule : bRules) { if (bitextRule.getId().equals(enabledRule)) { bRuleList.add(bitextRule); } } } bRules = bRuleList; } } private void runOnFile(final String filename, final String encoding, final boolean listUnknownWords) throws IOException { boolean oneTime = false; if (!"-".equals(filename)) { if (autoDetect) { Language language = detectLanguageOfFile(filename, encoding); if (language == null) { System.err.println("Could not detect language well enough, using English"); language = Language.ENGLISH; } changeLanguage(language, motherTongue, disabledRules, enabledRules); System.out.println("Using " + language.getName() + " for file " + filename); } final File file = new File(filename); // run once on file if the file size < MAX_FILE_SIZE or // when we use the bitext mode (we use a bitext reader // instead of a direct file access) oneTime = file.length() < MAX_FILE_SIZE || bitextMode; } if (oneTime) { runOnFileInOneGo(filename, encoding, listUnknownWords); } else { runOnFileLineByLine(filename, encoding, listUnknownWords); } } private void runOnFileInOneGo(String filename, String encoding, boolean listUnknownWords) throws IOException { if (bitextMode) { //TODO: add parameter to set different readers final TabBitextReader reader = new TabBitextReader(filename, encoding); if (applySuggestions) { Tools.correctBitext(reader, srcLt, lt, bRules); } else { Tools.checkBitext(reader, srcLt, lt, bRules, apiFormat); } } else { final String text = getFilteredText(filename, encoding); if (applySuggestions) { System.out.print(Tools.correctText(text, lt)); } else if (profileRules) { Tools.profileRulesOnText(text, lt); } else if (!taggerOnly) { Tools.checkText(text, lt, apiFormat, 0); } else { Tools.tagText(text, lt); } if (listUnknownWords) { System.out.println("Unknown words: " + lt.getUnknownWords()); } } } private void runOnFileLineByLine(String filename, String encoding, boolean listUnknownWords) throws IOException { if (verbose) { lt.setOutput(System.err); } if (!apiFormat && !applySuggestions) { if ("-".equals(filename)) { System.out.println("Working on STDIN..."); } else { System.out.println("Working on " + filename + "..."); } } int runCount = 1; final List<Rule> rules = lt.getAllActiveRules(); if (profileRules) { System.out.printf("Testing %d rules\n", rules.size()); System.out.println("Rule ID\tTime\tSentences\tMatches\tSentences per sec."); runCount = rules.size(); } InputStreamReader isr = null; BufferedReader br = null; int lineOffset = 0; int tmpLineOffset = 0; final List<String> unknownWords = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); for (int ruleIndex = 0; !rules.isEmpty() && ruleIndex < runCount; ruleIndex++) { currentRule = rules.get(ruleIndex); int matches = 0; long sentences = 0; final long startTime = System.currentTimeMillis(); try { isr = getInputStreamReader(filename, encoding, isr); br = new BufferedReader(isr); String line; int lineCount = 0; while ((line = br.readLine()) != null) { sb.append(line); lineCount++; // to detect language from the first input line if (lineCount == 1 && autoDetect) { Language language = detectLanguageOfString(line); if (language == null) { System.err.println("Could not detect language well enough, using English"); language = Language.ENGLISH; } System.out.println("Language used is: " + language.getName()); language.getSentenceTokenizer().setSingleLineBreaksMarksParagraph( singleLineBreakMarksParagraph); changeLanguage(language, motherTongue, disabledRules, enabledRules); } sb.append('\n'); tmpLineOffset++; if (lt.getLanguage().getSentenceTokenizer().singleLineBreaksMarksPara()) { matches = handleLine(matches, lineOffset, sb); sentences += lt.getSentenceCount(); if (profileRules) { sentences += lt.sentenceTokenize(sb.toString()).size(); } if (listUnknownWords && !taggerOnly) { for (String word : lt.getUnknownWords()) if (!unknownWords.contains(word)) { unknownWords.add(word); } } sb = new StringBuilder(); lineOffset = tmpLineOffset; } else { if ("".equals(line) || sb.length() >= MAX_FILE_SIZE) { matches = handleLine(matches, lineOffset, sb); sentences += lt.getSentenceCount(); if (profileRules) { sentences += lt.sentenceTokenize(sb.toString()).size(); } if (listUnknownWords && !taggerOnly) { for (String word : lt.getUnknownWords()) if (!unknownWords.contains(word)) { unknownWords.add(word); } } sb = new StringBuilder(); lineOffset = tmpLineOffset; } } } } finally { if (sb.length() > 0) { matches = handleLine(matches, tmpLineOffset - 1, sb); sentences += lt.getSentenceCount(); if (profileRules) { sentences += lt.sentenceTokenize(sb.toString()).size(); } if (listUnknownWords && !taggerOnly) { for (String word : lt.getUnknownWords()) { if (!unknownWords.contains(word)) { unknownWords.add(word); } } } } printTimingInformation(listUnknownWords, rules, unknownWords, ruleIndex, matches, sentences, startTime); if (br != null) { br.close(); } if (isr != null) { isr.close(); } } } } private InputStreamReader getInputStreamReader(String filename, String encoding, InputStreamReader isr) throws UnsupportedEncodingException, FileNotFoundException { if (!"-".equals(filename)) { final File file = new File(filename); if (encoding != null) { isr = new InputStreamReader(new BufferedInputStream( new FileInputStream(file.getAbsolutePath())), encoding); } else { isr = new InputStreamReader(new BufferedInputStream( new FileInputStream(file.getAbsolutePath()))); } } else { if (encoding != null) { isr = new InputStreamReader(new BufferedInputStream(System.in), encoding); } else { isr = new InputStreamReader(new BufferedInputStream(System.in)); } } return isr; } private void printTimingInformation(final boolean listUnknownWords, final List<Rule> rules, final List<String> unknownWords, final int ruleIndex, final int matches, final long sentences, final long startTime) { if (!applySuggestions) { final long endTime = System.currentTimeMillis(); final long time = endTime - startTime; final float timeInSeconds = time / 1000.0f; final float sentencesPerSecond = sentences / timeInSeconds; if (apiFormat) { System.out.println("<! } if (profileRules) { //TODO: run 10 times, line in runOnce mode, and use median System.out.printf(Locale.ENGLISH, "%s\t%d\t%d\t%d\t%.1f", rules.get(ruleIndex).getId(), time, sentences, matches, sentencesPerSecond); System.out.println(); } else { System.out.printf(Locale.ENGLISH, "Time: %dms for %d sentences (%.1f sentences/sec)", time, sentences, sentencesPerSecond); System.out.println(); } if (listUnknownWords) { Collections.sort(unknownWords); System.out.println("Unknown words: " + unknownWords); } if (apiFormat) { System.out.println(" } } } private int handleLine(final int matchNo, final int lineOffset, final StringBuilder sb) throws IOException { int matches = matchNo; if (applySuggestions) { System.out.print(Tools.correctText(StringTools.filterXML(sb.toString()), lt)); } else if (profileRules) { matches += Tools.profileRulesOnLine(StringTools.filterXML(sb.toString()), lt, currentRule); } else if (!taggerOnly) { if (matches == 0) { matches += Tools.checkText(StringTools.filterXML(sb.toString()), lt, apiFormat, -1, lineOffset, matches, StringTools.XmlPrintMode.START_XML); } else { matches += Tools.checkText(StringTools.filterXML(sb.toString()), lt, apiFormat, -1, lineOffset, matches, StringTools.XmlPrintMode.CONTINUE_XML); } } else { Tools.tagText(StringTools.filterXML(sb.toString()), lt); } return matches; } private void runRecursive(final String filename, final String encoding, final boolean listUnknown) throws IOException, ParserConfigurationException, SAXException { final File dir = new File(filename); if (!dir.isDirectory()) { throw new IllegalArgumentException(dir.getAbsolutePath() + " is not a directory, cannot use recursion"); } final File[] files = dir.listFiles(); for (final File file : files) { if (file.isDirectory()) { runRecursive(file.getAbsolutePath(), encoding, listUnknown); } else { runOnFile(file.getAbsolutePath(), encoding, listUnknown); } } } /** * Loads filename and filters out XML. Note that the XML * filtering can lead to incorrect positions in the list of matching rules. */ private String getFilteredText(final String filename, final String encoding) throws IOException { if (verbose) { lt.setOutput(System.err); } if (!apiFormat && !applySuggestions) { System.out.println("Working on " + filename + "..."); } final String fileContents = StringTools.readFile(new FileInputStream( filename), encoding); return StringTools.filterXML(fileContents); } private void changeLanguage(Language language, Language motherTongue, String[] disabledRules, String[] enabledRules) { try { lt = new JLanguageTool(language, motherTongue); lt.activateDefaultPatternRules(); lt.activateDefaultFalseFriendRules(); Tools.selectRules(lt, disabledRules, enabledRules); if (verbose) { lt.setOutput(System.err); } } catch (Exception e) { throw new RuntimeException("Could not create LanguageTool instance for language " + language, e); } } /** * Command line tool to check plain text files. */ public static void main(final String[] args) throws IOException, ParserConfigurationException, SAXException { final CommandLineParser commandLineParser = new CommandLineParser(); CommandLineOptions options = null; try { options = commandLineParser.parseOptions(args); } catch (IllegalArgumentException e) { if (e.getMessage() != null) { System.err.println(e.getMessage()); } commandLineParser.printUsage(); System.exit(1); } if (options.getFilename() == null) { options.setFilename("-"); } if (options.getLanguage() == null) { if (!options.isApiFormat() && !options.isAutoDetect()) { System.err.println("No language specified, using English"); } options.setLanguage(Language.ENGLISH); } else if (!options.isApiFormat() && !options.isApplySuggestions()) { System.out.println("Expected text language: " + options.getLanguage().getName()); } options.getLanguage().getSentenceTokenizer().setSingleLineBreaksMarksParagraph( options.isSingleLineBreakMarksParagraph()); final Main prg = new Main(options.isVerbose(), options.isTaggerOnly(), options.getLanguage(), options.getMotherTongue(), options.getDisabledRules(), options.getEnabledRules(), options.isApiFormat(), options.isApplySuggestions(), options.isAutoDetect(), options.isSingleLineBreakMarksParagraph()); prg.setListUnknownWords(options.isListUnknown()); if (options.isProfile()) { prg.setProfilingMode(); } if (options.isBitext()) { if (options.getMotherTongue() == null) { throw new IllegalArgumentException("You have to set the source language (as mother tongue) in bitext mode."); } prg.setBitextMode(options.getMotherTongue(), options.getDisabledRules(), options.getEnabledRules()); } if (options.isRecursive()) { prg.runRecursive(options.getFilename(), options.getEncoding(), options.isListUnknown()); } else { prg.runOnFile(options.getFilename(), options.getEncoding(), options.isListUnknown()); } prg.cleanUp(); } // for language auto detect // TODO: alter tika's language profiles so they are in line with LT's supported languages private static Language detectLanguageOfFile(final String filename, final String encoding) throws IOException { final String text = StringTools.readFile(new FileInputStream(filename), encoding); return detectLanguageOfString(text); } private static Language detectLanguageOfString(final String text) { final LanguageIdentifier identifier = new LanguageIdentifier(text); final Language lang = Language.getLanguageForShortName(identifier.getLanguage()); return lang; } }
// Tapestry Web Application Framework // Howard Lewis Ship // mailto:hship@users.sf.net // This library is free software. // You may redistribute it and/or modify it under the terms of the GNU // included with this distribution, you may find a copy at the FSF web // Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU package net.sf.tapestry; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Category; import org.apache.log4j.Priority; import net.sf.tapestry.parse.SpecificationParser; import net.sf.tapestry.spec.ApplicationSpecification; import net.sf.tapestry.util.StringSplitter; import net.sf.tapestry.util.exception.ExceptionAnalyzer; import net.sf.tapestry.util.pool.Pool; import net.sf.tapestry.util.xml.DocumentParseException; abstract public class ApplicationServlet extends HttpServlet { private static final Category CAT = Category.getInstance(ApplicationServlet.class); /** * Name of the cookie written to the client web browser to * identify the locale. * **/ private static final String LOCALE_COOKIE_NAME = "net.sf.tapestry.locale"; /** * A {@link Pool} used to store {@link IEngine engine}s that are not currently * in use. The key is on {@link Locale}. * **/ private Pool enginePool = new Pool(); /** * The application specification, which is read once and kept in memory * thereafter. * **/ private ApplicationSpecification specification; /** * The name under which the {@link IEngine engine} is stored within the * {@link HttpSession}. * **/ private String attributeName; /** * Gets the class loader for the servlet. Generally, this class (ApplicationServlet) * is loaded by the system class loader, but the servlet and other classes in the * application are loaded by a child class loader. Only the child has the full view * of all classes and package resources. * **/ private ClassLoader classLoader = getClass().getClassLoader(); /** * If true, then the engine is stored as an attribute of the {@link HttpSession} * after every request. * * @since 0.2.12 * **/ private static boolean storeEngine = Boolean.getBoolean("net.sf.tapestry.store-engine"); /** * Invokes {@link #doService(HttpServletRequest, HttpServletResponse)}. * * @since 1.0.6 * **/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doService(request, response); } /** * Handles the GET and POST requests. Performs the following: * <ul> * <li>Construct a {@link RequestContext} * <li>Invoke {@link #getEngine(RequestContext)} to get or create the {@link IEngine} * <li>Invoke {@link IEngine#service(RequestContext)} on the application * </ul> **/ protected void doService( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { RequestContext context = null; IEngine engine; try { // Create a context from the various bits and pieces. context = new RequestContext(this, request, response); // The subclass provides the engine. engine = getEngine(context); if (engine == null) throw new ServletException( Tapestry.getString("ApplicationServlet.could-not-locate-engine")); boolean dirty = engine.service(context); HttpSession session = context.getSession(); // When there's an active session, we *may* store it into // the HttpSession and we *will not* store the engine // back into the engine pool. if (session != null) { // If the service may have changed the engine and the // special storeEngine flag is on, then re-save the engine // into the session. Otherwise, we only save the engine // into the session when the session is first created (is new). try { boolean forceStore = engine.isStateful() && (session.getAttribute(attributeName) == null); if (forceStore || (dirty && storeEngine)) { if (CAT.isDebugEnabled()) CAT.debug("Storing " + engine + " into session as " + attributeName); session.setAttribute(attributeName, engine); } } catch (IllegalStateException ex) { // Ignore because the session been's invalidated. // Allow the engine (which has state particular to the client) // to be reclaimed by the garbage collector. if (CAT.isDebugEnabled()) CAT.debug("Session invalidated."); } return; } if (engine.isStateful()) { CAT.error( "Engine " + engine + " is stateful even though there is no session. Discarding the engine."); return; } // No session; the engine contains no state particular to // the client (except for locale). Don't throw it away, // instead save it in a pool for later reuse (by this, or another // client in the same locale). if (CAT.isDebugEnabled()) CAT.debug("Returning " + engine + " to pool."); enginePool.store(engine.getLocale(), engine); } catch (ServletException ex) { log("ServletException", ex); show(ex); // Rethrow it. throw ex; } catch (IOException ex) { log("IOException", ex); show(ex); // Rethrow it. throw ex; } finally { if (context != null) context.cleanup(); } } protected void show(Exception ex) { System.err.println( "\n\n**********************************************************\n\n"); new ExceptionAnalyzer().reportException(ex, System.err); System.err.println( "\n**********************************************************\n"); } /** * Invokes {@link #doService(HttpServletRequest, HttpServletResponse)}. * * **/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doService(request, response); } /** * Returns the application specification, which is read * by the {@link #init(ServletConfig)} method. * **/ public ApplicationSpecification getApplicationSpecification() { return specification; } /** * Retrieves the {@link IEngine engine} that will process this * request. This comes from one of the following places: * <ul> * <li>The {@link HttpSession}, if the there is one. * <li>From the pool of available engines * <li>Freshly created * </ul> * **/ protected IEngine getEngine(RequestContext context) throws ServletException { IEngine engine = null; HttpSession session = context.getSession(); // If there's a session, then find the engine within it. if (session != null) { engine = (IEngine) session.getAttribute(attributeName); if (engine != null) { if (CAT.isDebugEnabled()) CAT.debug("Retrieved " + engine + " from session " + session.getId() + "."); return engine; } if (CAT.isDebugEnabled()) CAT.debug("Session exists, but doesn't contain an engine."); } Locale locale = getLocaleFromRequest(context); engine = (IEngine) enginePool.retrieve(locale); if (engine == null) { engine = createEngine(context); engine.setLocale(locale); } else { if (CAT.isDebugEnabled()) CAT.debug("Using pooled engine " + engine + " (from locale " + locale + ")."); } return engine; } /** * Determines the {@link Locale} for the incoming request. * This is determined from the locale cookie or, if not set, * from the request itself. This may return null * if no locale is determined. * **/ protected Locale getLocaleFromRequest(RequestContext context) throws ServletException { Cookie cookie = context.getCookie(LOCALE_COOKIE_NAME); if (cookie != null) return Tapestry.getLocale(cookie.getValue()); return context.getRequest().getLocale(); } /** * Reads the application specification when the servlet is * first initialized. All {@link IEngine engine instances} * will have access to the specification via the servlet. * **/ public void init(ServletConfig config) throws ServletException { String path; ServletContext servletContext; String resource; InputStream stream; SpecificationParser parser; super.init(config); setupLogging(); path = getApplicationSpecificationPath(); // Make sure we locate the specification using our // own class loader. stream = getClass().getResourceAsStream(path); if (stream == null) throw new ServletException( Tapestry.getString("ApplicationServlet.could-not-load-spec", path)); parser = new SpecificationParser(); try { if (CAT.isDebugEnabled()) CAT.debug("Loading application specification from " + path); specification = parser.parseApplicationSpecification(stream, path); } catch (DocumentParseException ex) { show(ex); throw new ServletException( Tapestry.getString("ApplicationServlet.could-not-parse-spec", path), ex); } attributeName = "net.sf.tapestry.engine." + specification.getName(); } /** * Invoked from {@link #init(ServletConfig)} before the specification is loaded to * setup log4j logging. This implemention is sufficient for testing, but should * be overiden in production applications. * * <p>Gets the JVM system property <code>net.sf.tapestry.root-logging-priority</code>, * and (if non-null), converts it to a {@link Priority} and assigns it to the root * {@link Category}. * * <p>For each priority, a check is made for a JVM system property * <code>net.sf.tapestry.log4j.<em>priority</em></code> (i.e. <code>...log4j.DEBUG</code>). * The value is a list of categories seperated by semicolons. Each of these * categories will be assigned that priority. * * <p>Prior to Tapestry release 2.0.3, this method would also set the pattern * for root category appender. That is better done using a <code>log4j.properties</code> * file. This method exists to make it easy to augment or override that * configuration using command line options. * * @since 0.2.9 **/ protected void setupLogging() throws ServletException { Priority priority = Priority.ERROR; String value = System.getProperty("net.sf.tapestry.root-logging-priority"); if (value != null) { priority = Priority.toPriority(value, Priority.ERROR); Category root = Category.getRoot(); root.setPriority(priority); } Priority[] priorities = Priority.getAllPossiblePriorities(); StringSplitter splitter = new StringSplitter(';'); for (int i = 0; i < priorities.length; i++) { priority = priorities[i]; String key = "net.sf.tapestry.log4j." + priority.toString(); String categoryList = System.getProperty(key); if (categoryList != null) { String[] categories = splitter.splitToArray(categoryList); for (int j = 0; j < categories.length; j++) { Category cat = Category.getInstance(categories[j]); cat.setPriority(priority); } } } } /** * Implemented in subclasses to identify the resource path * of the application specification. * **/ abstract protected String getApplicationSpecificationPath(); /** * Invoked by {@link #getEngine(RequestContext)} to create * the {@link IEngine} instance specific to the * application, if not already in the * {@link HttpSession}. * * <p>The {@link IEngine} instance returned is stored into the * {@link HttpSession}. * * <p>This implementation instantiates a new engine as specified * by {@link ApplicationSpecification#getEngineClassName()}. * **/ protected IEngine createEngine(RequestContext context) throws ServletException { try { String className = specification.getEngineClassName(); if (className == null) throw new ServletException( Tapestry.getString("ApplicationServlet.no-engine-class")); if (CAT.isDebugEnabled()) CAT.debug("Creating engine from class " + className); Class engineClass = Class.forName(className, true, classLoader); IEngine result = (IEngine) engineClass.newInstance(); if (CAT.isDebugEnabled()) CAT.debug("Created engine " + result); return result; } catch (Exception ex) { throw new ServletException(ex); } } /** * Invoked from the {@link IEngine engine}, just prior to starting to * render a response, when the locale has changed. The servlet writes a * {@link Cookie} so that, on subsequent request cycles, an engine localized * to the selected locale is chosen. * * <p>At this time, the cookie is <em>not</em> persistent. That may * change in subsequent releases. * * @since 1.0.1 **/ public void writeLocaleCookie( Locale locale, IEngine engine, RequestContext cycle) { if (CAT.isDebugEnabled()) CAT.debug("Writing locale cookie " + locale); Cookie cookie = new Cookie(LOCALE_COOKIE_NAME, locale.toString()); cookie.setPath(engine.getServletPath()); cycle.addCookie(cookie); } }
package polyglot.ext.pao.types; import polyglot.types.*; import polyglot.ext.jl.types.TypeSystem_c; import polyglot.util.*; import java.util.*; /** * PAO type system. */ public class PaoTypeSystem_c extends TypeSystem_c implements PaoTypeSystem { public PrimitiveType createPrimitive(PrimitiveType.Kind kind) { return new PaoPrimitiveType_c(this, kind); } public ParsedClassType createClassType(LazyClassInitializer init) { return new PaoParsedClassType_c(this, init); } private static final String WRAPPER_PACKAGE = "polyglot.ext.pao.runtime"; public MethodInstance primitiveEquals() { String name = WRAPPER_PACKAGE + ".Primitive"; try { Type ct = (Type) systemResolver().find(name); List args = new LinkedList(); args.add(Object()); args.add(Object()); for (Iterator i = ct.toClass().methods("equals", args).iterator(); i.hasNext(); ) { MethodInstance mi = (MethodInstance) i.next(); return mi; } } catch (SemanticException e) { throw new InternalCompilerError(e.getMessage()); } throw new InternalCompilerError("Could not find equals method."); } public MethodInstance getter(PrimitiveType t) { String methodName = t.toString() + "Value"; ConstructorInstance ci = wrapper(t); for (Iterator i = ci.container().methods().iterator(); i.hasNext(); ) { MethodInstance mi = (MethodInstance) i.next(); if (mi.name().equals(methodName) && mi.formalTypes().isEmpty()) { return mi; } } throw new InternalCompilerError("Could not find getter for " + t); } public Type boxedType(PrimitiveType t) { return wrapper(t).container(); } public ConstructorInstance wrapper(PrimitiveType t) { String name = WRAPPER_PACKAGE + "." + wrapperTypeString(t).substring("java.lang.".length()); try { ClassType ct = ((Type) systemResolver().find(name)).toClass(); for (Iterator i = ct.constructors().iterator(); i.hasNext(); ) { ConstructorInstance ci = (ConstructorInstance) i.next(); if (ci.formalTypes().size() == 1) { Type argType = (Type) ci.formalTypes().get(0); if (equals(argType, t)) { return ci; } } } } catch (SemanticException e) { throw new InternalCompilerError(e.getMessage()); } throw new InternalCompilerError("Could not find constructor for " + t); } }
package Php; public class StringFunctions extends FileFunctions { public static char[] strtochar(String s[]) { int l=s.length; char op[]=new char[l]; for (int i = 0; i < l; i++) { op[i]=s[i].charAt(0); } return op; } public static String[] chartostr(char s[]) { int l=s.length; String op[]=new String[l]; for (int i = 0; i < l; i++) { op[i]=s[i]+""; } return op; } public static String str_replace(String search,String replace,String subject){ return subject.replaceAll(search, replace); } //For Replacing Multiple Values with one private static String str_replace(String search[],String replace,String subject,boolean isCaseSensitive) { int min=0,start=0,toReplace=0,pos; //Finding the first value to replace while(start<subject.length()){ min=subject.length(); for (int i = 0; i < search.length; i++) { //Getting the position of first occurance of the replacing value starting from index start. pos=isCaseSensitive?strpos(substr(subject, start), search[i]):stripos(substr(subject, start), search[i]); if(pos!=-1&&pos<min){ min=pos; toReplace=i; } } if(min==subject.length()) return subject; else{ subject=subject.replaceFirst((isCaseSensitive?"":"(?i)")+search[toReplace], replace); } start=min+search[toReplace].length(); } return subject; } public static String str_replace(String search[],String replace,String subject){ return str_replace(search, replace, subject, true); } public static String str_ireplace(String search,String replace,String subject){ return subject.replaceAll("(?i)"+search, replace); } public static String str_ireplace(String search[],String replace,String subject){ return str_replace(search, replace, subject, false); } public static int strlen(String string){ return string.length(); } public static String str_repeat(String string,int iterations) { if (iterations<1) { return ""; }else { return iterations==1?string:(str_repeat(string+string, (int)iterations/2)+(iterations%2==0?"":string)); } } // public static String str_repeat(String string,int iterations) { // /* // String t=""; // while(n-->0){ // t+=s; // } // return t; // */ // if(iterations<=1) // return iterations==1?string:""; // String tem="",main_temp=string; // if(iterations%2!=0){ // iterations--; // tem=string; // while(iterations>1){ // if(iterations%2==0){ // iterations/=2; // main_temp+=main_temp; // }else{ // iterations--; // tem+=main_temp; // return main_temp+tem; /* public static String str_repeat(String s,int n){ String tem,main; tem=""; main=n>0?s:""; if(n%2==0)n--; while(n>0){ if(n%2!=0){ n-=1; tem+=s; } if(n==0)break; main+=main; n/=2; } return main+tem; } */ public static String htmlspecialchars(String string) { return str_ireplace("\"", "&quot;", str_ireplace("'", "&#039;", str_ireplace("<", "&lt;", str_ireplace(">", "&gt;", str_ireplace("&", "&amp;", string))))); } public static String htmlentities(String string) { return htmlspecialchars(string); } public static String strtolower(String string) { return string.toLowerCase(); } public static String strtoupper(String string) { return string.toUpperCase(); } public static String trim(String string) { return string.trim(); } public static int strpos(String string,String find, int start) { return string.indexOf(find,start); } public static int strpos(String string,String find) { return string.indexOf(find,0); } //Something Extra public static int stripos(String string,String find, int start) { string=string.toLowerCase(); return string.indexOf(find.toLowerCase(),start); } public static int stripos(String string,String find) { string=string.toLowerCase(); return string.indexOf(find.toLowerCase(),0); } public static String substr(String string,int start,int length) { return string.substring(start, length); } public static String substr(String string,int start) { return string.substring(start); } public static String str_shuffle(String string) { int len=string.length(),tem; String st[]=string.split(""),swap; for (int i = 1; i <= len; i++) { tem=rand(1, len); swap=st[i]; st[i]=st[tem]; st[tem]=swap; } return emplode(st); } /* * Regex Methods * The pattern syntax must be in Java format and not in PHP format. * PS:I have noticed normal regex syntax works preety well. */ public static boolean preg_match(String pattern,String string) { try { return string.matches(pattern); } catch (Exception e) { return false; } } public static String preg_replace(String pattern,String replace,String string) { try { return string.replaceAll(pattern, replace); } catch (Exception e) { return ""; } } public static String[] preg_split(String pattern,String string){ try { return string.split(pattern); } catch (Exception e) { return null; } } public static char[] str_split(String string){ return string.toCharArray(); } public static String ucfirst(String string) { return Character.toUpperCase(string.charAt(0)) + string.substring(1); } public static String ucwords(String string) { String s[]=string.split(" "); StringBuffer sb=new StringBuffer(); for (String string2 : s) { sb.append(" "+ucfirst(string2)); } sb.deleteCharAt(0); return sb.toString(); } public static String strrev(String string) { return strrev(new StringBuffer(string)); } public static String strrev(StringBuffer string) { return string.reverse().toString(); } //Reverse a number. public static int strrev(int n) { int op=0; while (n>0) { op=op*10+(n%10); n/=10; } return op; } public static char chr(int ascii) { return (char)ascii; } public static int ord(char character) { return (int)character; } public static int ord(String character) { return ord(character.charAt(0)); } }
package com.almasb.fxgl.ecs; import com.almasb.fxgl.annotation.Spawns; import com.almasb.fxgl.app.FXGL; import com.almasb.fxgl.core.collection.Array; import com.almasb.fxgl.core.collection.ObjectMap; import com.almasb.fxgl.core.logging.FXGLLogger; import com.almasb.fxgl.core.logging.Logger; import com.almasb.fxgl.core.reflect.ReflectionUtils; import com.almasb.fxgl.entity.*; import com.almasb.fxgl.entity.component.*; import com.almasb.fxgl.event.EventTrigger; import com.almasb.fxgl.gameplay.Level; import com.almasb.fxgl.parser.tiled.TiledMap; import com.google.inject.Inject; import com.google.inject.Singleton; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.geometry.Point2D; import javafx.geometry.Rectangle2D; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Represents pure logical state of the game. * Manages all entities and allows queries. * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ @Singleton public class GameWorld { private static Logger log = FXGLLogger.get("FXGL.GameWorld"); private Array<EventTrigger<?> > eventTriggers = new Array<>(false, 32); private Array<Entity> updateList; /** * List of entities added to the update list in the next tick. */ private Array<Entity> waitingList; /** * List of entities in the world. */ protected List<Entity> entities; private GameWorldQuery query; /** * Constructs the world with initial entity capacity = 32. */ @Inject protected GameWorld() { this(32); } /** * @param initialCapacity initial entity capacity */ public GameWorld(int initialCapacity) { updateList = new Array<>(true, initialCapacity); waitingList = new Array<>(false, initialCapacity); entities = new ArrayList<>(initialCapacity); query = new GameWorldQuery(entities); log.debug("Game world initialized"); } /** * The entity will be added to update list in the next tick. * * @param entity the entity to add to world */ public void addEntity(Entity entity) { if (entity.isActive()) throw new IllegalArgumentException("Entity is already attached to world"); waitingList.add(entity); entities.add(entity); entity.init(this); notifyEntityAdded(entity); } public void addEntities(Entity... entitiesToAdd) { for (Entity e : entitiesToAdd) { addEntity(e); } } public void removeEntity(Entity entity) { if (entity.getWorld() != this) throw new IllegalArgumentException("Attempted to remove entity not attached to this world"); entities.remove(entity); notifyEntityRemoved(entity); entity.clean(); } public void removeEntities(Entity... entitiesToRemove) { for (Entity e : entitiesToRemove) { removeEntity(e); } } /** * Performs a single world update tick. * * @param tpf time per frame */ private void update(double tpf) { updateList.addAll(waitingList); waitingList.clear(); for (Iterator<Entity> it = updateList.iterator(); it.hasNext(); ) { Entity e = it.next(); if (e.isActive()) { e.update(tpf); } else { it.remove(); } } notifyWorldUpdated(tpf); } /** * Resets the world to its initial state. * Does NOT clear state listeners. */ public void reset() { log.debug("Resetting game world"); for (Entity e : updateList) { if (e.isActive()) { notifyEntityRemoved(e); e.clean(); } } for (Entity e : waitingList) { notifyEntityRemoved(e); e.clean(); } waitingList.clear(); updateList.clear(); entities.clear(); notifyWorldReset(); } private Array<EntityWorldListener> worldListeners = new Array<>(true, 16); public void addWorldListener(EntityWorldListener listener) { worldListeners.add(listener); } public void removeWorldListener(EntityWorldListener listener) { worldListeners.removeValueByIdentity(listener); } private void notifyEntityAdded(Entity e) { for (int i = 0; i < worldListeners.size(); i++) { worldListeners.get(i).onEntityAdded(e); } } private void notifyEntityRemoved(Entity e) { for (int i = 0; i < worldListeners.size(); i++) { worldListeners.get(i).onEntityRemoved(e); } } private void notifyWorldUpdated(double tpf) { for (int i = 0; i < worldListeners.size(); i++) { worldListeners.get(i).onWorldUpdate(tpf); } } private void notifyWorldReset() { for (int i = 0; i < worldListeners.size(); i++) { worldListeners.get(i).onWorldReset(); } } /** * @return direct list of entities in the world (do NOT modify) */ public List<Entity> getEntities() { return entities; } /** * @return shallow copy of the entities list (new list) */ public List<Entity> getEntitiesCopy() { return new ArrayList<>(entities); } public void onUpdate(double tpf) { update(tpf); updateTriggers(tpf); } private void updateTriggers(double tpf) { for (Iterator<EventTrigger<?> > it = eventTriggers.iterator(); it.hasNext(); ) { EventTrigger trigger = it.next(); trigger.onUpdate(tpf); if (trigger.reachedLimit()) { it.remove(); } } } public void addEventTrigger(EventTrigger<?> trigger) { eventTriggers.add(trigger); } public void removeEventTrigger(EventTrigger<?> trigger) { eventTriggers.removeValueByIdentity(trigger); } private ObjectProperty<Entity> selectedEntity = new SimpleObjectProperty<>(); /** * @return last selected (clicked on by mouse) entity */ public Optional<Entity> getSelectedEntity() { return Optional.ofNullable(selectedEntity.get()); } /** * @return selected entity property */ public ObjectProperty<Entity> selectedEntityProperty() { return selectedEntity; } /** * Set level to given. * Resets the world. * Adds all level entities to the world. * * @param level the level */ public void setLevel(Level level) { reset(); log.debug("Setting level: " + level); level.getEntities().forEach(this::addEntity); } /** * @param mapFileName name of the .json file */ public void setLevelFromMap(String mapFileName) { setLevelFromMap(FXGL.getAssetLoader().loadJSON(mapFileName, TiledMap.class)); } public void setLevelFromMap(TiledMap map) { reset(); log.debug("Setting level from map"); map.getLayers() .stream() .filter(l -> l.getType().equals("tilelayer")) .forEach(l -> Entities.builder() .viewFromTiles(map, l.getName(), RenderLayer.BACKGROUND) .buildAndAttach(this)); map.getLayers() .stream() .filter(l -> l.getType().equals("objectgroup")) .flatMap(l -> l.getObjects().stream()) .forEach(obj -> spawn(obj.getType(), new SpawnData(obj))); } private EntityFactory entityFactory = null; private ObjectMap<String, EntitySpawner> entitySpawners = new ObjectMap<>(); /** * @return entity factory or null if not set */ @SuppressWarnings("unchecked") public <T extends EntityFactory> T getEntityFactory() { return (T) entityFactory; } /** * Set main entity factory to be used via {@link GameWorld#spawn(String, SpawnData)}. * * @param entityFactory factory for creating entities */ public void setEntityFactory(EntityFactory entityFactory) { this.entityFactory = entityFactory; entitySpawners.clear(); ReflectionUtils.findMethodsMapToFunctions(entityFactory, Spawns.class, EntitySpawner.class) .forEach((annotation, entitySpawner) -> entitySpawners.put(annotation.value(), entitySpawner)); } public Entity spawn(String entityName) { return spawn(entityName, 0, 0); } /** * Creates an entity with given name at x, y using specified entity factory. * Adds created entity to this game world. * * @param entityName name of entity as specified by {@link Spawns} * @param position spawn location * @return spawned entity */ public Entity spawn(String entityName, Point2D position) { return spawn(entityName, position.getX(), position.getY()); } /** * Creates an entity with given name at x, y using specified entity factory. * Adds created entity to this game world. * * @param entityName name of entity as specified by {@link Spawns} * @param x x position * @param y y position * @return spawned entity */ public Entity spawn(String entityName, double x, double y) { return spawn(entityName, new SpawnData(x, y)); } /** * Creates an entity with given name and data using specified entity factory. * Adds created entity to this game world. * * @param entityName name of entity as specified by {@link Spawns} * @param data spawn data, such as x, y and any extra info * @return spawned entity */ public Entity spawn(String entityName, SpawnData data) { if (entityFactory == null) throw new IllegalStateException("EntityFactory was not set!"); EntitySpawner spawner = entitySpawners.get(entityName); if (spawner == null) throw new IllegalArgumentException("EntityFactory does not have a method annotated @Spawns(" + entityName + ")"); Entity entity = spawner.spawn(data); addEntity(entity); return entity; } /* QUERIES */ /** * Useful for singleton type entities, e.g. Player. * * @return first occurrence matching given type */ public Entity getSingleton(Enum<?> type) { return getSingleton(e -> e.hasComponent(TypeComponent.class) && e.getComponent(TypeComponent.class).isType(type) ); } /** * @return first occurrence matching given predicate */ public Entity getSingleton(Predicate<Entity> predicate) { for (int i = 0; i < entities.size(); i++) { Entity e = entities.get(i); if (predicate.test(e)) { return e; } } throw new IllegalArgumentException("No entity exists matching predicate"); } /** * @param type component type * @return array of entities that have given component (do NOT modify) */ public List<Entity> getEntitiesByComponent(Class<? extends Component> type) { return entities.stream() .filter(e -> e.hasComponent(type)) .collect(Collectors.toList()); } /** * Returns a list of entities which are filtered by * given predicate. * Warning: object allocation. * * @param predicate filter * @return new list containing entities that satisfy query filters */ public List<Entity> getEntitiesFiltered(Predicate<Entity> predicate) { return query.getEntitiesFiltered(predicate); } /** * GC-friendly version of {@link #getEntitiesFiltered(Predicate)}. * * @param result the array to collect entities * @param predicate filter */ public void getEntitiesFiltered(Array<Entity> result, Predicate<Entity> predicate) { for (int i = 0; i < entities.size(); i++) { Entity e = entities.get(i); if (predicate.test(e)) { result.add(e); } } } /** * This query only works on entities with TypeComponent. * If called with no arguments, all entities are returned. * Warning: object allocation. * * @param types entity types * @return new list containing entities that satisfy query filters */ public List<Entity> getEntitiesByType(Enum<?>... types) { return query.getEntitiesByType(types); } /** * GC-friendly version of {@link #getEntitiesByType(Enum[])}. * * @param result the array to collect entities * @param types entity types */ public void getEntitiesByType(Array<Entity> result, Enum<?>... types) { if (types.length == 0) { for (int i = 0; i < entities.size(); i++) { Entity e = entities.get(i); result.add(e); } return; } for (int i = 0; i < entities.size(); i++) { Entity e = entities.get(i); if (isOfType(e, types)) { result.add(e); } } } private boolean isOfType(Entity e, Enum<?>... types) { TypeComponent entityType = Entities.getType(e); if (entityType != null) { for (Enum<?> type : types) { if (entityType.isType(type)) { return true; } } } return false; } /** * Returns a list of entities * which are partially or entirely * in the specified rectangular selection. * This query only works on entities with BoundingBoxComponent. * Warning: object allocation. * * @param selection Rectangle2D that describes the selection box * @return new list containing entities that satisfy query filters */ public List<Entity> getEntitiesInRange(Rectangle2D selection) { return query.getEntitiesInRange(selection); } /** * GC-friendly version of {@link #getEntitiesInRange(Rectangle2D)}. * * @param result the array to collect entities * @param minX min x * @param minY min y * @param maxX max x * @param maxY max y */ public void getEntitiesInRange(Array<Entity> result, double minX, double minY, double maxX, double maxY) { for (int i = 0; i < entities.size(); i++) { Entity e = entities.get(i); BoundingBoxComponent bbox = Entities.getBBox(e); if (bbox != null && bbox.isWithin(minX, minY, maxX, maxY)) { result.add(e); } } } /** * Returns a list of entities * which colliding with given entity. * * Note: CollidableComponent is not considered. * This query only works on entities with BoundingBoxComponent. * * @param entity the entity * @return new list containing entities that satisfy query filters */ public List<Entity> getCollidingEntities(Entity entity) { return query.getCollidingEntities(entity); } /** * GC-friendly version of {@link #getCollidingEntities(Entity)}. * * @param result the array to collect entities * @param entity the entity */ public void getCollidingEntities(Array<Entity> result, Entity entity) { BoundingBoxComponent entityBBox = Entities.getBBox(entity); for (int i = 0; i < entities.size(); i++) { Entity e = entities.get(i); BoundingBoxComponent bbox = Entities.getBBox(e); if (bbox != null && bbox.isCollidingWith(entityBBox) && e != entity) { result.add(e); } } } /** * Returns a list of entities which have the given render layer index. * This query only works on entities with ViewComponent. * * @param layer render layer * @return new list containing entities that satisfy query filters */ public List<Entity> getEntitiesByLayer(RenderLayer layer) { return query.getEntitiesByLayer(layer); } /** * GC-friendly version of {@link #getEntitiesByLayer(RenderLayer)}. * * @param result the array to collect entities * @param layer render layer */ public void getEntitiesByLayer(Array<Entity> result, RenderLayer layer) { for (int i = 0; i < entities.size(); i++) { Entity e = entities.get(i); ViewComponent view = Entities.getView(e); if (view != null && view.getRenderLayer().index() == layer.index()) { result.add(e); } } } /** * Returns a list of entities at given position. * The position x and y must equal to entity's position x and y. * This query only works on entities with PositionComponent. * * @param position point in the world * @return entities at given point */ public List<Entity> getEntitiesAt(Point2D position) { return query.getEntitiesAt(position); } /** * GC-friendly version of {@link #getEntitiesAt(Point2D)}. * * @param result the array to collect entities * @param position point in the world */ public void getEntitiesAt(Array<Entity> result, Point2D position) { for (int i = 0; i < entities.size(); i++) { Entity e = entities.get(i); PositionComponent p = Entities.getPosition(e); if (p != null && p.getValue().equals(position)) { result.add(e); } } } /** * Returns the closest entity to the given entity with given * filter. The given * entity itself is never returned. * <p> * If there no entities satisfying the requirement, {@link Optional#empty()} * is returned. * Warning: object allocation. * * @param entity selected entity * @param filter requirements * @return closest entity to selected entity with type */ public Optional<Entity> getClosestEntity(Entity entity, Predicate<Entity> filter) { Array<Entity> array = new Array<>(false, 64); for (Entity e : getEntitiesByComponent(PositionComponent.class)) { if (filter.test(e) && e != entity) { array.add(e); } } if (array.size() == 0) return Optional.empty(); array.sort((e1, e2) -> (int) (Entities.getPosition(e1).distance(Entities.getPosition(entity)) - Entities.getPosition(e2).distance(Entities.getPosition(entity)))); return Optional.of(array.get(0)); } /** * Returns an entity whose IDComponent matches given name and id. * <p> * Returns {@link Optional#empty()} if no entity was found with such combination. * This query only works on entities with IDComponent. * * @param name entity name * @param id entity id * @return entity that matches the query or {@link Optional#empty()} */ public Optional<Entity> getEntityByID(String name, int id) { for (Entity e : getEntitiesByComponent(IDComponent.class)) { IDComponent idComponent = e.getComponent(IDComponent.class); if (idComponent.getName().equals(name) && idComponent.getID() == id) { return Optional.of(e); } } return Optional.empty(); } }
package edu.umd.cs.findbugs.cloud; import java.awt.GraphicsEnvironment; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.URL; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.annotation.CheckForNull; import javax.swing.JOptionPane; import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugDesignation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.SourceFile; import edu.umd.cs.findbugs.gui2.MainFrame; /** * @author pwilliam */ public class DBCloud extends AbstractCloud { final static long minimumTimestamp = 1000000000000L; Mode mode = Mode.VOTING; public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; } class BugData { final String instanceHash; public BugData(String instanceHash) { this.instanceHash = instanceHash; } int id; boolean inDatabase; long firstSeen; SortedSet<BugDesignation> designations = new TreeSet<BugDesignation>(); Collection<BugInstance> bugs = new LinkedHashSet<BugInstance>(); @CheckForNull BugDesignation getPrimaryDesignation() { BugDesignation primaryDesignation = mode.getPrimaryDesignation(findbugsUser, designations); return primaryDesignation; } @CheckForNull BugDesignation getUserDesignation() { for(BugDesignation d : designations) if (d.getUser().equals(findbugsUser)) return new BugDesignation(d); return null; } BugDesignation getNonnullUserDesignation() { BugDesignation d = getUserDesignation(); if (d != null) return d; d = new BugDesignation(UserDesignation.UNCLASSIFIED.name(), System.currentTimeMillis(), "", findbugsUser); return d; } /** * @return */ public boolean canSeeCommentsByOthers() { switch(mode) { case SECRET: return false; case COMMUNAL : return true; case VOTING : return hasVoted(); } throw new IllegalStateException(); } public boolean hasVoted() { for(BugDesignation bd : designations) if (bd.getUser().equals(findbugsUser)) return true; return false; } } Map<String, BugData> instanceMap = new HashMap<String, BugData>(); Map<Integer, BugData> idMap = new HashMap<Integer, BugData>(); IdentityHashMap<BugDesignation, Integer> bugDesignationId = new IdentityHashMap<BugDesignation, Integer>(); BugData getBugData(String instanceHash) { BugData bd = instanceMap.get(instanceHash); if (bd == null) { bd = new BugData(instanceHash); instanceMap.put(instanceHash, bd); } return bd; } BugData getBugData(BugInstance bug) { BugData bugData = getBugData(bug.getInstanceHash()); bugData.bugs.add(bug); return bugData; } void loadDatabaseInfo(String hash, int id, long firstSeen) { BugData bd = instanceMap.get(hash); if (bd == null) return; if (idMap.containsKey(id)) { assert bd == idMap.get(id); assert bd.id == id; assert bd.firstSeen == firstSeen; } else { bd.id = id; bd.firstSeen = firstSeen; bd.inDatabase = true; idMap.put(id, bd); } } DBCloud(BugCollection bugs) { super(bugs); } public void bugsPopulated() { for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) getBugData(b.getInstanceHash()).bugs.add(b); try { Connection c = getConnection(); PreparedStatement ps = c.prepareStatement("SELECT id, hash, firstSeen FROM findbugs_issue"); ResultSet rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); String hash = rs.getString(col++); Timestamp firstSeen = rs.getTimestamp(col++); loadDatabaseInfo(hash, id, firstSeen.getTime()); } rs.close(); ps.close(); ps = c.prepareStatement("SELECT id, issueId, who, designation, comment, time FROM findbugs_evaluation"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); int issueId = rs.getInt(col++); String who = rs.getString(col++); String designation = rs.getString(col++); String comment = rs.getString(col++); Timestamp when = rs.getTimestamp(col++); BugData data = idMap.get(issueId); if (data != null) { BugDesignation bd = new BugDesignation(designation, when.getTime(), comment, who); bugDesignationId.put(bd, id); data.designations.add(bd); } } rs.close(); ps.close(); c.close(); for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { BugData bd = getBugData(b.getInstanceHash()); if (!bd.inDatabase) { storeNewBug(b); } else { long firstVersion = b.getFirstVersion(); long firstSeen = bugCollection.getAppVersionFromSequenceNumber(firstVersion).getTimestamp(); if (firstSeen < minimumTimestamp) { displayMessage("Got timestamp of " + firstSeen + " which is equal to " + new Date(firstSeen)); } else if (firstSeen < bd.firstSeen) { bd.firstSeen = firstSeen; storeFirstSeen(bd); } long lastVersion = b.getLastVersion(); if (lastVersion != -1) { long lastSeen = bugCollection.getAppVersionFromSequenceNumber(firstVersion).getTimestamp(); } BugDesignation designation = bd.getPrimaryDesignation(); if (designation != null) b.setUserDesignation(new BugDesignation(designation)); } } } catch (Exception e) { e.printStackTrace(); displayMessage("problem bulk loading database", e); } } private String getProperty(String propertyName) { return SystemProperties.getProperty("findbugs.jdbc." + propertyName); } String url, dbUser, dbPassword, findbugsUser, dbName; private Connection getConnection() throws SQLException { return DriverManager.getConnection(url, dbUser, dbPassword); } public boolean initialize() { if (!bugCollection.getProject().isGuiAvaliable()) return false; String sqlDriver = getProperty("dbDriver"); url = getProperty("dbUrl"); dbName = getProperty("dbName"); dbUser = getProperty("dbUser"); dbPassword = getProperty("dbPassword"); findbugsUser = getProperty("findbugsUser"); if (sqlDriver == null || dbUser == null || url == null || dbPassword == null) return false; if (findbugsUser == null) { findbugsUser = System.getProperty("user.name", ""); if (false) try { findbugsUser += "@" + InetAddress.getLocalHost().getHostName(); } catch (Exception e) {} } try { Class.forName(sqlDriver); Connection c = getConnection(); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) from findbugs_issue"); boolean result = false; if (rs.next()) { int count = rs.getInt(1); if (!GraphicsEnvironment.isHeadless() && bugCollection.getProject().isGuiAvaliable()) { if (false) { findbugsUser = JOptionPane.showInputDialog("Identification for survey", findbugsUser); result = true; } else { findbugsUser = (String) JOptionPane.showInputDialog(MainFrame.getInstance(), "Connect to database with the specified username?", "Connect to database", JOptionPane.QUESTION_MESSAGE, null, null, findbugsUser); result = findbugsUser != null; } } else result = true; } rs.close(); stmt.close(); c.close(); if (result) { runnerThread.setDaemon(true); runnerThread.start(); } return result; } catch (Exception e) { displayMessage("Unable to connect to database", e); return false; } } final LinkedBlockingQueue<Update> queue = new LinkedBlockingQueue<Update>(); volatile boolean shutdown = false; final DatabaseSyncTask runner = new DatabaseSyncTask(); final Thread runnerThread = new Thread(runner, "Database synchronization thread"); public void shutdown() { shutdown = true; runnerThread.interrupt(); } public void storeNewBug(BugInstance bug) { queue.add(new StoreNewBug(bug)); updatedStatus(); } public void storeFirstSeen(final BugData bd) { queue.add(new Update(){ public void execute(DatabaseSyncTask t) throws SQLException { t.storeFirstSeen(bd); }}); updatedStatus(); } public void storeUserAnnotation(BugData data, BugDesignation bd) { queue.add(new StoreUserAnnotation(data, bd)); updatedStatus(); } private boolean skipBug(BugInstance bug) { return bug.getBugPattern().getCategory().equals("NOISE") || bug.isDead(); } private static HashMap<String, Integer> issueId = new HashMap<String, Integer>(); class DatabaseSyncTask implements Runnable { int handled; Connection c; public void establishConnection() throws SQLException { if (c != null) return; c = getConnection(); } public void closeConnection() throws SQLException { if (c == null) return; c.close(); c = null; } public void run() { try { while (!shutdown) { Update u = queue.poll(10, TimeUnit.SECONDS); if (u == null) { closeConnection(); continue; } establishConnection(); u.execute(this); if ((handled++) % 100 == 0 || queue.isEmpty()) { updatedStatus(); } } } catch (RuntimeException e) { displayMessage("Runtime exception; database connection shutdown", e); } catch (SQLException e) { displayMessage("SQL exception; database connection shutdown", e); } catch (InterruptedException e) { assert true; } try { closeConnection(); } catch (SQLException e) { } } public void newEvaluation(BugData data, BugDesignation bd) { if (!data.inDatabase) return; try { data.designations.add(bd); if (bd.getUser() == null) bd.setUser(findbugsUser); if (bd.getAnnotationText() == null) bd.setAnnotationText(""); PreparedStatement insertEvaluation = c.prepareStatement("INSERT INTO findbugs_evaluation (issueId, who, designation, comment, time) VALUES (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(bd.getTimestamp()); int col = 1; insertEvaluation.setInt(col++, data.id); insertEvaluation.setString(col++, bd.getUser()); insertEvaluation.setString(col++, bd.getDesignationKey()); insertEvaluation.setString(col++, bd.getAnnotationText()); insertEvaluation.setTimestamp(col++, date); insertEvaluation.executeUpdate(); ResultSet rs = insertEvaluation.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); bugDesignationId.put(bd, id); } rs.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void newBug(BugInstance b, long timestamp) { try { BugData bug = getBugData(b.getInstanceHash()); if (bug.inDatabase) return; PreparedStatement insertBugData = c.prepareStatement("INSERT INTO findbugs_issue (firstSeen, lastSeen, hash, bugPattern, priority, primaryClass, bugDatabaseKey) VALUES (?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(timestamp); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setTimestamp(col++, date); insertBugData.setString(col++, bug.instanceHash); insertBugData.setString(col++, b.getBugPattern().getType()); insertBugData.setInt(col++, b.getPriority()); insertBugData.setString(col++, b.getPrimaryClass().getClassName()); insertBugData.setString(col++, "none"); insertBugData.executeUpdate(); ResultSet rs = insertBugData.getGeneratedKeys(); if (rs.next()) { bug.id = rs.getInt(1); bug.inDatabase = true; } rs.close(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeFirstSeen(BugData bug) { try { if (!bug.inDatabase) return; PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET firstSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(bug.firstSeen); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } } static interface Update { void execute(DatabaseSyncTask t) throws SQLException; } class StoreNewBug implements Update { public StoreNewBug(BugInstance bug) { this.bug = bug; } BugInstance bug; public void execute(DatabaseSyncTask t) throws SQLException { BugData data = getBugData(bug.getInstanceHash()); if (data.inDatabase) return; long timestamp = bugCollection.getAppVersionFromSequenceNumber(bug.getFirstVersion()).getTimestamp(); t.newBug(bug, timestamp); data.inDatabase = true; } } class StoreUserAnnotation implements Update { public StoreUserAnnotation(BugData data, BugDesignation designation) { super(); this.data = data; this.designation = designation; } public void execute(DatabaseSyncTask t) throws SQLException { t.newEvaluation(data, new BugDesignation(designation)); } final BugData data; final BugDesignation designation; } private void displayMessage(String msg, Exception e) { AnalysisContext.logError(msg, e); if (!GraphicsEnvironment.isHeadless() && bugCollection.getProject().isGuiAvaliable()) { bugCollection.getProject().getGuiCallback().showMessageDialog(msg + e.getMessage()); } else { System.err.println(msg); e.printStackTrace(System.err); } } private void displayMessage(String msg) { if (!GraphicsEnvironment.isHeadless() && bugCollection.getProject().isGuiAvaliable()) { bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } else { System.err.println(msg); } } public String getUser() { return findbugsUser; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getFirstSeen(edu.umd.cs.findbugs.BugInstance) */ public long getFirstSeen(BugInstance b) { return getBugData(b).firstSeen; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUser() */ public UserDesignation getUserDesignation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return UserDesignation.UNCLASSIFIED; return UserDesignation.valueOf(bd.getDesignationKey()); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserEvaluation(edu.umd.cs.findbugs.BugInstance) */ public String getUserEvaluation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return ""; return bd.getAnnotationText(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserTimestamp(edu.umd.cs.findbugs.BugInstance) */ public long getUserTimestamp(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return Long.MAX_VALUE; return bd.getTimestamp(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserDesignation(edu.umd.cs.findbugs.BugInstance, edu.umd.cs.findbugs.cloud.UserDesignation, long) */ public void setUserDesignation(BugInstance b, UserDesignation u, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (u == UserDesignation.UNCLASSIFIED) return; bd = data.getNonnullUserDesignation(); } bd.setDesignationKey(u.name()); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserEvaluation(edu.umd.cs.findbugs.BugInstance, java.lang.String, long) */ public void setUserEvaluation(BugInstance b, String e, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (e.length() == 0) return; bd = data.getNonnullUserDesignation(); } bd.setAnnotationText(e); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserTimestamp(edu.umd.cs.findbugs.BugInstance, long) */ public void setUserTimestamp(BugInstance b, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getNonnullUserDesignation(); bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } String getBugReport(BugInstance b) { StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); out.println("Bug report generated from FindBugs"); out.println(b.getMessageWithoutPrefix()); out.println(); ClassAnnotation primaryClass = b.getPrimaryClass(); int firstLine = Integer.MAX_VALUE; int lastLine = Integer.MIN_VALUE; for(BugAnnotation a : b.getAnnotations()) { out.println(a); if (a instanceof SourceLineAnnotation) { SourceLineAnnotation s = (SourceLineAnnotation) a; if (s.getClassName().equals(primaryClass.getClassName()) && s.getStartLine() > 0) { firstLine = Math.min(firstLine, s.getStartLine()); lastLine = Math.max(lastLine, s.getEndLine()); } } } out.println(); SourceLineAnnotation primarySource = primaryClass.getSourceLines(); if (primarySource.isSourceFileKnown() && firstLine <= lastLine && MainFrame.isAvailable()) { try { SourceFile sourceFile = MainFrame.getInstance().getSourceFinder().findSourceFile(primarySource); BufferedReader in = new BufferedReader(new InputStreamReader(sourceFile.getInputStream())); int lineNumber = 1; out.println("\nRelevant source code:"); while (lineNumber <= lastLine+5) { String txt = in.readLine(); if (txt == null) break; if (lineNumber >= firstLine-5) { if (lineNumber > lastLine && txt.trim().length() == 0) break; out.printf("%4d: %s\n", lineNumber, txt); } lineNumber++; } in.close(); out.println(); } catch (IOException e) { assert true; } } out.println("FindBugs issue identifier: " + b.getInstanceHash()); out.close(); return stringWriter.toString(); } static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { assert false; return "No utf-8 encoding"; } } @Override @CheckForNull public URL getBugLink(BugInstance b) { String bugLinkPattern = SystemProperties.getProperty("findbugs.buglink"); if (bugLinkPattern == null) return null; try { String report = getBugReport(b); String summary = b.getMessageWithoutPrefix() + " in " + b.getPrimaryClass().getSourceFileName(); String u = String.format(bugLinkPattern, urlEncode(report), urlEncode(summary)); return new URL(u); } catch (Exception e) { e.printStackTrace(); return null; } } @Override public boolean supportsCloudReports() { return true; } @Override public String getCloudReport(BugInstance b) { SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd"); StringBuilder builder = new StringBuilder(); BugData bd = getBugData(b); long firstSeen = bd.firstSeen; if (firstSeen < Long.MAX_VALUE) { builder.append(String.format("First seen %s\n", format.format(new Timestamp(firstSeen)))); } BugDesignation primaryDesignation = bd.getPrimaryDesignation(); boolean canSeeCommentsByOthers = bd.canSeeCommentsByOthers(); for(BugDesignation d : bd.designations) if (d != primaryDesignation && (canSeeCommentsByOthers || d.getUser().equals(findbugsUser))) { builder.append(String.format("%s @ %s: %s\n", d.getUser(), format.format(new Timestamp(d.getTimestamp())), d.getDesignationKey())); if (d.getAnnotationText().length() > 0) { builder.append(d.getAnnotationText()); builder.append("\n\n"); } } return builder.toString(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#storeUserAnnotation(edu.umd.cs.findbugs.BugInstance) */ public void storeUserAnnotation(BugInstance bugInstance) { storeUserAnnotation(getBugData(bugInstance), bugInstance.getNonnullUserDesignation()); } }
package com.simperium.util; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import name.fraser.neil.plaintext.diff_match_patch; import name.fraser.neil.plaintext.diff_match_patch.Diff; import name.fraser.neil.plaintext.diff_match_patch.Patch; public class JSONDiff { static public boolean enableArrayDiff = false; static public final String TAG = "JSONDiff"; public static final String DIFF_VALUE_KEY = "v"; public static final String DIFF_OPERATION_KEY = "o"; public static final String OPERATION_OBJECT = "O"; public static final String OPERATION_LIST = "L"; public static final String OPERATION_INSERT = "+"; public static final String OPERATION_REMOVE = "-"; public static final String OPERATION_REPLACE = "r"; public static final String OPERATION_DIFF = "d"; private static diff_match_patch dmp = new diff_match_patch(); public static JSONObject diff(JSONArray a, JSONArray b) throws JSONException { JSONObject list_diff = new JSONObject(); if (equals(a, b)) { return list_diff; } if (!enableArrayDiff){ list_diff.put(DIFF_OPERATION_KEY, OPERATION_REPLACE); list_diff.put(DIFF_VALUE_KEY, b); return list_diff; } list_diff.put(DIFF_OPERATION_KEY, OPERATION_LIST); JSONObject diffs = new JSONObject(); list_diff.put(DIFF_VALUE_KEY, diffs); int size_a = a.length(); int size_b = b.length(); int prefix_length = commonPrefix(a, b); // remove the prefixes a = sliceJSONArray(a, prefix_length, size_a); b = sliceJSONArray(b, prefix_length, size_b); // recalculate the sizes size_a -= prefix_length; size_b -= prefix_length; int suffix_length = commonSuffix(a, b); size_a -= suffix_length; size_b -= suffix_length; a = sliceJSONArray(a, 0, size_a); b = sliceJSONArray(b, 0, size_b); int max = Math.max(size_a, size_b); for (int i=0; i<max; i++) { String index = new Integer(i+prefix_length).toString(); if(i<size_a && i<size_b){ // both lists have index // if values aren't equal add to diff if (!equals(a.get(i), b.get(i))) { diffs.put(index, diff(a.get(i), b.get(i))); } } else if(i<size_a){ // b doesn't have it remove from a JSONObject diff = new JSONObject(); diff.put(DIFF_OPERATION_KEY, OPERATION_REMOVE); diffs.put(index, diff); } else if(i<size_b){ // a doesn't have, b does so add it JSONObject diff = new JSONObject(); diff.put(DIFF_OPERATION_KEY, OPERATION_INSERT); diff.put(DIFF_VALUE_KEY, b.get(i)); diffs.put(index, diff); } } return list_diff; } public static JSONObject diff(JSONObject a, JSONObject b) throws JSONException { JSONObject diffs = new JSONObject(); if (a == null || b == null) { return diffs; } if (equals(a, b)) { return diffs; } Iterator<String> keys = a.keys(); while (keys.hasNext()) { String key = keys.next(); if (b.has(key)) { if (!equals(a.get(key), b.get(key))) { diffs.put(key, diff(a.get(key), b.get(key))); } } else { JSONObject remove = new JSONObject(); remove.put(DIFF_OPERATION_KEY, OPERATION_REMOVE); diffs.put(key, remove); } } keys = b.keys(); while (keys.hasNext()) { String key = keys.next().toString(); if (!a.has(key)) { JSONObject add = new JSONObject(); add.put(DIFF_OPERATION_KEY, OPERATION_INSERT); add.put(DIFF_VALUE_KEY, b.get(key)); diffs.put(key, add); } } JSONObject diff = new JSONObject(); if (diffs.length() > 0) { diff.put(DIFF_OPERATION_KEY, OPERATION_OBJECT); diff.put(DIFF_VALUE_KEY, diffs); } return diff; } public static JSONObject diff(Object a, Object b) throws JSONException { JSONObject m = new JSONObject(); if (a==null || b==null) { return m; } if (equals(a, b)) { return m; } Class a_class = a.getClass(); Class b_class = b.getClass(); if ( !a_class.isAssignableFrom(b_class) ) { m.put(DIFF_OPERATION_KEY, OPERATION_REPLACE); m.put(DIFF_VALUE_KEY, b); return m; } // a and b are the same type if (String.class.isInstance(a)) { // diff match patch return diff((String)a, (String)b); } else if(JSONObject.class.isInstance(a)){ return diff((JSONObject) a, (JSONObject) b); } else if (JSONArray.class.isInstance(a)) { return diff((JSONArray) a, (JSONArray) b); } else { m.put(DIFF_OPERATION_KEY, OPERATION_REPLACE); m.put(DIFF_VALUE_KEY, b); } return m; } public static JSONObject diff(String origin, String target) throws JSONException { JSONObject m = new JSONObject(); LinkedList diffs = dmp.diff_main(origin, target); if(diffs.size() > 2){ dmp.diff_cleanupEfficiency(diffs); } if(diffs.size() > 0){ m.put(DIFF_OPERATION_KEY, OPERATION_DIFF); m.put(DIFF_VALUE_KEY, dmp.diff_toDelta(diffs)); } return m; } /** * For testing equality of two objects. */ public static boolean equals(Object a, Object b) { // objects are not equal types if (!a.getClass().isAssignableFrom(b.getClass())) { return false; } if (JSONObject.class.isInstance(a)) { return equals((JSONObject) a, (JSONObject) b); } else if (JSONArray.class.isInstance(a)){ return equals((JSONArray) a, (JSONArray) b); } else { return a.equals(b); } } public static boolean equals(JSONObject a, JSONObject b) { if (a == null || b == null) { return false; } try { // before iterating through keys make sure we have the same length if (a.length() != b.length()) { return false; } // make sure each key in a is the same as b Iterator<String> keys = a.keys(); while (keys.hasNext()) { String key = keys.next(); // b is missing the key, so they're not equal if (!b.has(key)) { return false; } // a[key] does not equal b[key] so a and b are not equal if (!equals(a.get(key), b.get(key))) { return false; } } } catch (JSONException e) { return false; } // since a and b have the same number of keys, and each value each key // in a is equal to that key in b, a and b are equal return true; } public static boolean equals(JSONArray a, JSONArray b) { if (a == null || b == null) { return false; } if (a.length() != b.length()) { return false; } try { for (int i=0; i<a.length(); i++) { if (!equals(a.get(i), b.get(i))) { return false; } } } catch (JSONException e) { return false; } return true; } public static Object apply(Object origin, JSONObject patch) throws JSONException { String method = (String)patch.get(DIFF_OPERATION_KEY); if (method.equals(OPERATION_LIST)) { return apply((JSONArray) origin, patch.getJSONObject(DIFF_VALUE_KEY)); } else if(method.equals(OPERATION_OBJECT)){ return apply((JSONObject) origin, patch.getJSONObject(DIFF_VALUE_KEY)); } else if(method.equals(OPERATION_DIFF)){ return apply((String)origin, patch.getString(DIFF_VALUE_KEY)); } return null; } public static JSONObject apply(JSONObject origin, JSONObject patch) throws JSONException { JSONObject transformed = deepCopy(origin); Iterator<String> keys = patch.keys(); while (keys.hasNext()) { String key = keys.next(); JSONObject operation = patch.getJSONObject(key); String method = operation.getString(DIFF_OPERATION_KEY); if (method.equals(OPERATION_INSERT) || method.equals(OPERATION_REPLACE)) { transformed.put(key, operation.get(DIFF_VALUE_KEY)); } else if(method.equals(OPERATION_REMOVE)){ // NOTE: setting the value to null actually removes the entry transformed.put(key, null); } else if(method.equals(OPERATION_OBJECT)){ JSONObject child = transformed.getJSONObject(key); transformed.put(key, apply(child, operation.getJSONObject(DIFF_VALUE_KEY))); } else if(method.equals(OPERATION_LIST)) { JSONArray child = transformed.getJSONArray(key); transformed.put(key, apply(child, operation.getJSONObject(DIFF_VALUE_KEY))); } else if(method.equals(OPERATION_DIFF)){ String child = transformed.getString(key); transformed.put(key, apply(child, operation.getString(DIFF_VALUE_KEY))); } } return transformed; } public static String apply(String origin, String patch){ LinkedList<Diff> diffs = dmp.diff_fromDelta(origin, patch); LinkedList<Patch> patches = dmp.patch_make(origin, diffs); Object[] result = dmp.patch_apply(patches, origin); return (String)result[0]; } public static JSONArray apply(JSONArray origin, JSONObject patch) throws JSONException { // copy JSON array to a List so we can List<Object> transformed = convertJSONArrayToList(origin); List<Integer> indexes = new ArrayList<Integer>(); List<Integer> deleted = new ArrayList<Integer>(); // iterate the keys on the patch Iterator<String> keys = patch.keys(); while (keys.hasNext()){ String key = keys.next(); indexes.add(Integer.parseInt(key)); } Collections.sort(indexes); for(Integer index : indexes){ JSONObject operation = patch.getJSONObject(index.toString()); String method = operation.getString(DIFF_OPERATION_KEY); int shift = 0; for(Integer x : deleted){ if(x.intValue()<=index.intValue()) shift++; } int shifted_index = index.intValue() - shift; if (method.equals(OPERATION_INSERT)){ transformed.add(shifted_index, operation.get(DIFF_VALUE_KEY)); } else if(method.equals(OPERATION_REMOVE)){ transformed.remove(shifted_index); deleted.add(index); } else if (method.equals(OPERATION_REPLACE)){ transformed.set(shifted_index, operation.get(DIFF_VALUE_KEY)); } else if(method.equals(OPERATION_LIST)){ JSONArray list = (JSONArray) transformed.get(shifted_index); transformed.set(shifted_index, apply(list, operation.getJSONObject(DIFF_VALUE_KEY))); } else if(method.equals(OPERATION_OBJECT)){ JSONObject obj = (JSONObject) transformed.get(shifted_index); transformed.set(shifted_index, apply(obj, operation.getJSONObject(DIFF_VALUE_KEY))); } else if(method.equals(OPERATION_DIFF)){ String str = (String)transformed.get(shifted_index); transformed.set(shifted_index, apply(str, operation.getString(DIFF_VALUE_KEY))); } } return new JSONArray(transformed); } public static int commonPrefix(JSONArray a, JSONArray b) { int a_length = a.length(); int b_length = b.length(); int min_length = Math.min(a_length, b_length); int size = 0; for (int i=0; i<min_length; i++) { try { if (!equals(a.get(i), b.get(i))) break; } catch (JSONException e) { return i; } size ++; } return size; } public static int commonSuffix(JSONArray a, JSONArray b) { int a_length = a.length(); int b_length = b.length(); int min_length = Math.min(a_length, b_length); if (min_length ==0) return 0; for (int i=0; i<min_length; i++) { try { if (!equals(a.get(a_length-i-1), b.get(b_length-i-1))) return i; } catch (JSONException e) { return i; } } return min_length; } public static JSONArray sliceJSONArray(JSONArray a, int start, int end) throws JSONException { int length = a.length(); if (end > length || start < 0) throw new java.lang.IndexOutOfBoundsException( String.format("indexes %d and %d not valid for array of length %d", start, end, length)); JSONArray dest = new JSONArray(); for (int i=start; i<end; i++) { dest.put(a.get(i)); } return dest; } /** * Copy a hash */ public static Map<String, Object> deepCopy(Map<String, Object> map){ if (map == null) { return null; }; Map<String,Object> copy = new HashMap<String,Object>(map.size()); Iterator<String> keys = map.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); Object val = map.get(key); if (val instanceof Map) { copy.put(key, deepCopy((Map<String,Object>) val)); } else if (val instanceof List) { copy.put(key, deepCopy((List<Object>) val)); } else { copy.put(key, val); } } return copy; } /** * Copy a list */ public static List<Object>deepCopy(List<Object> list){ if (list == null) { return null; }; List<Object> copy = new ArrayList<Object>(list.size()); for (int i=0; i<list.size(); i++) { Object val = list.get(i); if (val instanceof Map) { copy.add(deepCopy((Map<String,Object>) val)); } else if (val instanceof List) { copy.add(deepCopy((List<Object>) val)); } else { copy.add(val); } } return copy; } /** * Naive JSONObject copying */ public static JSONObject deepCopy(JSONObject object){ try { return new JSONObject(object.toString()); } catch (JSONException e) { return new JSONObject(); } } /** * Copy an object if it is a list or map */ public static Object deepCopy(Object object){ if (object instanceof Map) { return deepCopy((Map<String,Object>)object); } else if (object instanceof List){ return deepCopy((List<Object>)object); } else if (object instanceof JSONObject) { return deepCopy((JSONObject) object); } else { return object; } } /** * Transform a JSONArray to a List<Object> */ public static List<Object> convertJSONArrayToList(JSONArray json){ List<Object> list = new ArrayList<Object>(json.length()); for (int i=0; i<json.length(); i++) { try { list.add(json.get(i)); } catch (JSONException e) { android.util.Log.e(TAG, String.format("Failed to convert JSON: %s", e.getMessage()), e); } } return list; } }
package util.propnet.architecture; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * The root class of the Component hierarchy, which is designed to represent * nodes in a PropNet. The general contract of derived classes is to override * all methods. */ public abstract class Component implements Serializable { private static final long serialVersionUID = 352524175700224447L; /** The inputs to the component. */ private final Set<Component> inputs; /** The outputs of the component. */ private final Set<Component> outputs; /** * Creates a new Component with no inputs or outputs. */ public Component() { this.inputs = new HashSet<Component>(); this.outputs = new HashSet<Component>(); } /** * Adds a new input. * * @param input * A new input. */ public void addInput(Component input) { inputs.add(input); } public void removeInput(Component input) { inputs.remove(input); } public void removeOutput(Component output) { outputs.remove(output); } /** * Adds a new output. * * @param output * A new output. */ public void addOutput(Component output) { outputs.add(output); } /** * Getter method. * * @return The inputs to the component. */ public Set<Component> getInputs() { return inputs; } /** * A convenience method, to get a single input. * To be used only when the component is known to have * exactly one input. * * @return The single input to the component. */ public Component getSingleInput() { assert inputs.size() == 1; return inputs.iterator().next(); } /** * Getter method. * * @return The outputs of the component. */ public Set<Component> getOutputs() { return outputs; } /** * A convenience method, to get a single output. * To be used only when the component is known to have * exactly one output. * * @return The single output to the component. */ public Component getSingleOutput() { assert outputs.size() == 1; return outputs.iterator().next(); } /** * Returns the value of the Component. * * @return The value of the Component. */ public abstract boolean getValue(); /** * Returns a representation of the Component in .dot format. * * @see java.lang.Object#toString() */ @Override public abstract String toString(); /** * Returns a configurable representation of the Component in .dot format. * * @param shape * The value to use as the <tt>shape</tt> attribute. * @param fillcolor * The value to use as the <tt>fillcolor</tt> attribute. * @param label * The value to use as the <tt>label</tt> attribute. * @return A representation of the Component in .dot format. */ protected String toDot(String shape, String fillcolor, String label) { StringBuilder sb = new StringBuilder(); sb.append("\"@" + Integer.toHexString(hashCode()) + "\"[shape=" + shape + ", style= filled, fillcolor=" + fillcolor + ", label=\"" + label + "\"]; "); for ( Component component : getOutputs() ) { sb.append("\"@" + Integer.toHexString(hashCode()) + "\"->" + "\"@" + Integer.toHexString(component.hashCode()) + "\"; "); } return sb.toString(); } }
package nz.cwong.spark; import static de.robv.android.xposed.XposedHelpers.*; import java.lang.reflect.Field; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import android.support.v4.app.FragmentActivity; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XC_MethodHook.MethodHookParam; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; public class ProgressBar implements IXposedHookLoadPackage { @Override public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals("nz.co.telecom.smartphone.android")){ return; } XposedBridge.log("In the Spark app"); findAndHookConstructor("nz.co.telecom.smartphone.adapter.AdapterMyUsage", lpparam.classLoader, FragmentActivity.class, findClass("nz.co.telecom.smartphone.dto.lineextended.LineExtendedDTO", lpparam.classLoader), new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { List usageMeters = (List) getObjectField( ((List) getObjectField(param.thisObject, "mAllUsageMeters")).get(0), "usageMeters"); Object monthUsageMeter = newInstance(findClass("nz.co.telecom.smartphone.dto.lineextended.LineExtendedUsageMetersDTO", lpparam.classLoader)); usageMeters.add(0, monthUsageMeter); int lastDayOfMonth = Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH); int currentDayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); Date d = new Date(); d.setDate(lastDayOfMonth); setObjectField(usageMeters.get(0), "amountUsed", currentDayOfMonth); setObjectField(usageMeters.get(0), "cap", lastDayOfMonth); setObjectField(usageMeters.get(0), "lineAmountUsed", 0.0f); setObjectField(usageMeters.get(0), "periodEnd", d); setObjectField(usageMeters.get(0), "periodEndLabel", "Last Day:"); setObjectField(usageMeters.get(0), "productInstanceId", "instanceId"); setObjectField(usageMeters.get(0), "remainingLabel", lastDayOfMonth - currentDayOfMonth + " days left"); setObjectField(usageMeters.get(0), "secondCap", 100.0f); setObjectField(usageMeters.get(0), "title", "Monthly Progress"); setObjectField(usageMeters.get(0), "usageLabel", currentDayOfMonth + " days gone"); setObjectField(usageMeters.get(0), "usageType", "usageType"); } }); /* findAndHookMethod("nz.co.telecom.smartphone.widget.UsageMeterView", lpparam.classLoader, "setTitle", String.class, new XC_MethodReplacement(){ @Override protected Object replaceHookedMethod(MethodHookParam param) throws Throwable { // setObjectField(param.thisObject, "title", "Hello!"); return null; } });*/ } }
package org.usfirst.frc.team340.robot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.JoystickButton; import org.usfirst.frc.team340.robot.OI.*; import org.usfirst.frc.team340.robot.commands.*; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ @SuppressWarnings("unused") public class OI { public OI() { //A1.whenPressed(new Score()); A1.whenPressed(new DriveForward(5, 1)); LB1.whenPressed(new CollectingMode()); } //// CREATING BUTTONS // One type of button is a joystick button which is any button on a joystick. // You create one by telling it which joystick it's on and which button // number it is. // Joystick stick = new Joystick(port); // Button button = new JoystickButton(stick, buttonNumber); // There are a few additional built in buttons you can use. Additionally, // by subclassing Button you can create custom triggers and bind those to // commands the same as any other Button. //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); //Init & Construct driver controller Joystick xBoxDriver = new Joystick(0); //Init & Construct driver controller buttons Button A1 = new JoystickButton(xBoxDriver, 1); Button B1 = new JoystickButton(xBoxDriver, 2); Button X1 = new JoystickButton(xBoxDriver, 3); Button Y1 = new JoystickButton(xBoxDriver, 4); Button LB1 = new JoystickButton(xBoxDriver, 5); Button RB1 = new JoystickButton(xBoxDriver, 6); Button Back1 = new JoystickButton(xBoxDriver, 7); Button Start1 = new JoystickButton(xBoxDriver, 8); Button LeftStick1 = new JoystickButton(xBoxDriver, 9); //Turn driver triggers to buttons public class RightTrig1 extends Button { public boolean get() { return xBoxDriver.getRawAxis(3) > .5; } } RightTrig1 rightTrig1 = new RightTrig1(); public class LeftTrig1 extends Button { public boolean get() { return xBoxDriver.getRawAxis(2) > .5; } } LeftTrig1 leftTrig1 = new LeftTrig1(); //Init & construct co-driver controller Joystick xBoxCoDriver = new Joystick(1); //Init and construct co-driver controller buttons Button A2 = new JoystickButton(xBoxCoDriver, 1); Button B2 = new JoystickButton(xBoxCoDriver, 2); Button X2 = new JoystickButton(xBoxCoDriver, 3); Button Y2 = new JoystickButton(xBoxCoDriver, 4); Button LB2 = new JoystickButton(xBoxCoDriver, 5); Button RB2 = new JoystickButton(xBoxCoDriver, 6); Button Back2 = new JoystickButton(xBoxCoDriver, 7); Button Start2 = new JoystickButton(xBoxCoDriver, 8); Button LeftStick2 = new JoystickButton(xBoxCoDriver, 9); //Turn co-driver triggers to buttons public class RightTrig2 extends Button { public boolean get() { return xBoxCoDriver.getRawAxis(3) > .5; } } RightTrig2 rightTrig2 = new RightTrig2(); public class LeftTrig2 extends Button { public boolean get() { return xBoxCoDriver.getRawAxis(2) > .5; } } LeftTrig2 leftTrig2 = new LeftTrig2(); public double getArcadeDriveMove() { return xBoxDriver.getRawAxis(0); } /** * Get throttle for GTA (trigger-based) drive * @return double throttle */ public double getGTADriveMove() { //only return for the right trigger if it above 0.05 (dead zone) if(xBoxDriver.getRawAxis(3) > 0.05) { return xBoxDriver.getRawAxis(3); //even though the right trigger isn't above 0.05, make sure the left is to avoid running the //motors really slowly } else if(xBoxDriver.getRawAxis(2) > 0.05) { return xBoxDriver.getRawAxis(2); } //in case neither trigger is held down return 0; //todo: add a dead zone variable perhaps in robotmap } public double getDriveRotate() { return xBoxDriver.getRawAxis(1); } }
package io.tetrapod.core; import static io.tetrapod.protocol.core.Core.DEFAULT_DIRECT_PORT; import static io.tetrapod.protocol.core.CoreContract.ERROR_UNKNOWN; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.utils.Util; import io.tetrapod.protocol.core.*; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.net.ssl.SSLContext; import org.slf4j.*; /** * Allows a service to spawn direct connections with one another for faster RPC */ public class ServiceConnector implements DirectConnectionRequest.Handler, ValidateConnectionRequest.Handler { private static final Logger logger = LoggerFactory.getLogger(ServiceConnector.class); /** * The number of requests sent to a specific service that triggers us to start a direct session */ private static final int REQUEST_THRESHOLD = 100; private Map<Integer, DirectServiceInfo> services = new ConcurrentHashMap<>(); private final DefaultService service; private final SSLContext sslContext; private Server server; public ServiceConnector(DefaultService service, SSLContext sslContext) { this.service = service; this.sslContext = sslContext; int port = Util.getProperty("tetrapod.direct.port", DEFAULT_DIRECT_PORT); server = new Server(port, new DirectSessionFactory(Core.TYPE_ANONYMOUS, null), service.getDispatcher(), sslContext, false); int n = 0; while (true) { try { server.start(port).sync(); return; } catch (Exception e) { port++; logger.info(e.getMessage()); if (n++ >= 100) { throw new RuntimeException(e); } } } } public void shutdown() { server.stop(); for (DirectServiceInfo service : services.values()) { service.close(); } } private class DirectSessionFactory extends WireSessionFactory { private DirectSessionFactory(byte type, Session.Listener listener) { super(service, type, listener); } } /** * This is a wrapper class for managing a single direct connection */ private class DirectServiceInfo implements Session.Listener { public final int entityId; public final String token = String.format("%016x%016x", Util.random.nextLong(), Util.random.nextLong()); public int requests; public int failures; public boolean pending; public boolean valid; public String theirToken; public Session ses; public long restUntil; public DirectServiceInfo(int entityId) { this.entityId = entityId; } public synchronized void close() { pending = false; valid = false; if (ses != null) { ses.close(); ses = null; } } /** * Fail our attempt to establish the connection. We won't try again for a while */ private synchronized void failure() { failures++; restUntil = System.currentTimeMillis() + 1000 * failures; close(); } @Override public void onSessionStop(Session ses) { failure(); } @Override public void onSessionStart(Session ses) {} /** * Attempt to initiate handshake for a direct connection */ protected synchronized void handshake() { if (System.currentTimeMillis() > restUntil) { pending = true; valid = false; service.clusterClient.getSession().sendRequest(new DirectConnectionRequest(token), entityId, (byte) 30).handle(res -> { if (res.isError()) { failure(); } else { connect((DirectConnectionResponse) res); } }); } } private synchronized void connect(final DirectConnectionResponse res) { DirectConnectionResponse r = (DirectConnectionResponse) res; Client c = new Client(new DirectSessionFactory(Core.TYPE_SERVICE, this)); try { if (sslContext != null) { c.enableTLS(sslContext); } c.connect(r.address.host, r.address.port, service.getDispatcher()).sync(); // FIXME: not good to be calling this while holding synchronized block ses = c.getSession(); ses.setMyEntityId(service.getEntityId()); validate(r.token); } catch (Exception e) { logger.error(e.getMessage(), e); failure(); } } private synchronized void validate(String theirToken) { ses.sendRequest(new ValidateConnectionRequest(service.getEntityId(), theirToken), Core.DIRECT).handle(res -> { if (res.isError()) { failure(); } else { finish(((ValidateConnectionResponse) res).token); } }); } private synchronized void finish(String token) { if (token.equals(this.token)) { ses.setTheirEntityId(entityId); ses.setTheirEntityType(Core.TYPE_SERVICE); pending = false; valid = true; failures = 0; logger.info("Direct Connection Established with {}", ses); } else { failure(); } } } public DirectServiceInfo getDirectServiceInfo(int entityId) { synchronized (services) { DirectServiceInfo e = services.get(entityId); if (e == null) { e = new DirectServiceInfo(entityId); services.put(entityId, e); } return e; } } private Session getSession(Request req, int entityId, boolean isPending) { if (entityId != Core.DIRECT) { if (entityId != Core.UNADDRESSED) { if (entityId == service.getEntityId()) { if (!isPending) { logger.warn("For some reason we're sending {} to ourselves", req); } } else { final DirectServiceInfo s = getDirectServiceInfo(entityId); synchronized (s) { s.requests++; if (s.ses != null) { if (s.valid && s.ses.isConnected()) { logger.trace("Sending {} direct to {}", req, s.ses); return s.ses; } } else { if (s.requests > REQUEST_THRESHOLD && !s.pending) { service.dispatcher.dispatch(() -> s.handshake()); } } } } } } return service.clusterClient.getSession(); } public Response sendPendingRequest(final Request req, int toEntityId, final PendingResponseHandler handler) { if (toEntityId == Core.UNADDRESSED) { Entity e = service.services.getRandomAvailableService(req.getContractId()); if (e != null) { toEntityId = e.entityId; } } final Session ses = handler.session != null ? getSession(req, toEntityId, true) : service.clusterClient.getSession(); if (ses != service.clusterClient.getSession()) { logger.debug("Dispatching pending {} to {} returning on {}", req, ses, handler.session); final Async async = ses.sendRequest(req, toEntityId, (byte) 30); async.handle(res -> { Response pendingRes = null; try { pendingRes = handler.onResponse(res); } catch (Throwable e) { logger.error(e.getMessage(), e); } finally { if (pendingRes != Response.PENDING) { // finally return the pending response we were waiting on if (pendingRes == null) { pendingRes = new Error(ERROR_UNKNOWN); } if (!handler.sendResponse(pendingRes)) { logger.error("I literally can't even ({})", pendingRes); } } else { logger.debug("Pending response returned from pending handler for {} @ {}", req, async.header.toId); } } }); return Response.PENDING; } else { // send via tetrapod routing return ses.sendPendingRequest(req, toEntityId, (byte) 30, handler); } } public Async sendRequest(Request req, int toEntityId) { if (toEntityId == Core.UNADDRESSED) { Entity e = service.services.getRandomAvailableService(req.getContractId()); if (e != null) { toEntityId = e.entityId; } } if (toEntityId == service.getEntityId()) { logger.trace("Self-dispatching {}", req); final RequestHeader header = new RequestHeader(); header.contractId = req.getContractId(); header.structId = req.getStructId(); header.toId = toEntityId; header.fromId = service.getEntityId(); header.fromType = service.getEntityType(); header.timeout = 30; return service.dispatchRequest(header, req, null); } final Session ses = getSession(req, toEntityId, false); return ses.sendRequest(req, toEntityId, (byte) 30); } @Override public Response genericRequest(Request r, RequestContext ctx) { return null; } @Override public Response requestValidateConnection(ValidateConnectionRequest r, RequestContext ctx) { final DirectServiceInfo s = getDirectServiceInfo(r.entityId); synchronized (s) { if (s.token.equals(r.token)) { s.ses = ((SessionRequestContext) ctx).session; s.ses.setMyEntityId(service.getEntityId()); s.ses.setTheirEntityId(r.entityId); s.ses.setTheirEntityType(Core.TYPE_SERVICE); s.valid = true; return new ValidateConnectionResponse(s.theirToken); } else { return new Error(CoreContract.ERROR_INVALID_TOKEN); } } } @Override public Response requestDirectConnection(DirectConnectionRequest r, RequestContext ctx) { final DirectServiceInfo s = getDirectServiceInfo(ctx.header.fromId); synchronized (s) { s.theirToken = r.token; return new DirectConnectionResponse(new ServerAddress(Util.getHostName(), server.getPort()), s.token); } } }
package group5.trackerexpress; import java.util.UUID; import android.content.Context; /** * Holds all the static data members of the app. * * @author Peter Crinklaw, Randy Hu, Parash Rahman, Jesse Emery, Sean Baergen, Rishi Barnwal * @version Part 4 */ public class Controller { /** The claims. */ private static ClaimList claimList; private static TagMap tagMap; private static User user; /** * Gets the static claim list, newing it if necessary * * @return the claim list */ public static ClaimList getClaimList(Context context){ if (claimList == null) claimList = new ClaimList(context); return claimList; } /** * Gets the static tag map, newing it if necessary * * @param context * @return */ public static TagMap getTagMap(Context context){ if (tagMap == null) tagMap = new TagMap(context); return tagMap; } /** * Gets the User data object. Right now there is but one user per phone * * @param context * @return */ public static User getUser(Context context){ if (user == null) user = new User(context); return user; } public static Claim getClaim(Context context, UUID claimID){ return getClaimList(context).getClaim(claimID); } public static Expense getExpense(Context context, UUID claimID, UUID expenseId){ try { return getClaimList(context).getClaim(claimID).getExpenseList().getExpense(expenseId); } catch (ExpenseNotFoundException e) { throw new RuntimeException("Expense not found"); } } }
package com.messagebird; import com.messagebird.exceptions.GeneralException; import com.messagebird.exceptions.NotFoundException; import com.messagebird.exceptions.UnauthorizedException; import com.messagebird.objects.*; import com.messagebird.objects.conversations.*; import com.messagebird.objects.voicecalls.*; import com.messagebird.objects.voicecalls.VoiceCallLeg; import com.messagebird.objects.voicecalls.VoiceCallLegResponse; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.*; import java.net.URLEncoder; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class MessageBirdClient { /** * The Conversations API has a different URL scheme from the other * APIs/endpoints. By default, the service prefixes paths with that URL. We * can, however, override this behaviour by providing absolute URLs * ourselves. */ private static final String CONVERSATIONS_BASE_URL = "https://conversations.messagebird.com/v1"; static final String VOICE_CALLS_BASE_URL = "https://voice.messagebird.com"; private static String[] supportedLanguages = {"de-DE", "en-AU", "en-UK", "en-US", "es-ES", "es-LA", "fr-FR", "it-IT", "nl-NL", "pt-BR"}; private static final String BALANCEPATH = "/balance"; private static final String CONTACTPATH = "/contacts"; private static final String GROUPPATH = "/groups"; private static final String HLRPATH = "/hlr"; private static final String LOOKUPHLRPATH = "/lookup/%s/hlr"; private static final String LOOKUPPATH = "/lookup"; private static final String MESSAGESPATH = "/messages"; private static final String VERIFYPATH = "/verify"; private static final String VOICEMESSAGESPATH = "/voicemessages"; private static final String CONVERSATION_PATH = "/conversations"; private static final String CONVERSATION_MESSAGE_PATH = "/messages"; private static final String CONVERSATION_WEBHOOK_PATH = "/webhooks"; static final String VOICECALLSPATH = "/calls"; static final String LEGSPATH = "/legs"; static final String RECORDINGPATH = "/recordings"; static final String TRANSCRIPTIONPATH = "/transcriptions"; static final String WEBHOOKS = "/webhooks"; private static final String VOICELEGS_SUFFIX_PATH = "/legs"; private MessageBirdService messageBirdService; public MessageBirdClient(final MessageBirdService messageBirdService) { this.messageBirdService = messageBirdService; } /** Balance and HRL methods **/ /** * MessageBird provides an API to get the balance information of your account. * * @return Balance object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Balance getBalance() throws GeneralException, UnauthorizedException, NotFoundException { return messageBirdService.requestByID(BALANCEPATH, "", Balance.class); } /** * MessageBird provides an API to send Network Queries to any mobile number across the world. * An HLR allows you to view which mobile number (MSISDN) belongs to what operator in real time and see whether the number is active. * * @param msisdn The telephone number. * @param reference A client reference * @return Hlr Object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Hlr getRequestHlr(final BigInteger msisdn, final String reference) throws GeneralException, UnauthorizedException { if (msisdn == null) { throw new IllegalArgumentException("msisdn must be specified."); } if (reference == null) { throw new IllegalArgumentException("Reference must be specified."); } final Map<String, Object> payload = new LinkedHashMap<String, Object>(); payload.put("msisdn", msisdn); payload.put("reference", reference); return messageBirdService.sendPayLoad(HLRPATH, payload, Hlr.class); } /** * Retrieves the information of an existing HLR. You only need to supply the unique message id that was returned upon creation or receiving. * * @param hlrId ID as returned by getRequestHlr in the id variable * @return Hlr Object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Hlr getViewHlr(final String hlrId) throws GeneralException, UnauthorizedException, NotFoundException { if (hlrId == null) { throw new IllegalArgumentException("Hrl ID must be specified."); } return messageBirdService.requestByID(HLRPATH, hlrId, Hlr.class); } /** Messaging **/ /** * Send a message through the messagebird platform * * @param message Message object to be send * @return Message Response * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendMessage(final Message message) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class); } /** * Convenient function to send a simple message to a list of recipients * * @param originator Originator of the message, this will get truncated to 11 chars * @param body Body of the message * @param recipients List of recipients * @return MessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(MESSAGESPATH, new Message(originator, body, recipients), MessageResponse.class); } /** * Convenient function to send a simple message to a list of recipients * * @param originator Originator of the message, this will get truncated to 11 chars * @param body Body of the message * @param recipients List of recipients * @param reference your reference * @return MessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException { final Message message = new Message(originator, body, recipients); message.setReference(reference); return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class); } /** * Convenient function to send a simple flash message to a list of recipients * * @param originator Originator of the message, this will get truncated to 11 chars * @param body Body of the message * @param recipients List of recipients * @return MessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException { final Message message = new Message(originator, body, recipients); message.setType(MsgType.flash); return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class); } /** * Convenient function to send a simple flash message to a list of recipients * * @param originator Originator of the message, this will get truncated to 11 chars * @param body Body of the message * @param recipients List of recipients * @param reference your reference * @return MessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException { final Message message = new Message(originator, body, recipients); message.setType(MsgType.flash); message.setReference(reference); return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class); } public MessageList listMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException { if (offset != null && offset < 0) { throw new IllegalArgumentException("Offset must be > 0"); } if (limit != null && limit < 0) { throw new IllegalArgumentException("Limit must be > 0"); } return messageBirdService.requestList(MESSAGESPATH, offset, limit, MessageList.class); } public void deleteMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException { if (id == null) { throw new IllegalArgumentException("Message ID must be specified."); } messageBirdService.deleteByID(MESSAGESPATH, id); } public MessageResponse viewMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException { if (id == null) { throw new IllegalArgumentException("Message ID must be specified."); } return messageBirdService.requestByID(MESSAGESPATH, id, MessageResponse.class); } /** Voice Messaging **/ /** * Convenient function to send a simple message to a list of recipients * * @param voiceMessage Voice message object * @return VoiceMessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceMessageResponse sendVoiceMessage(final VoiceMessage voiceMessage) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, voiceMessage, VoiceMessageResponse.class); } /** * Convenient function to send a simple message to a list of recipients * * @param body Body of the message * @param recipients List of recipients * @return VoiceMessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException { final VoiceMessage message = new VoiceMessage(body, recipients); return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class); } /** * Convenient function to send a simple message to a list of recipients * * @param body Body of the message * @param recipients List of recipients * @param reference your reference * @return VoiceMessageResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException { final VoiceMessage message = new VoiceMessage(body, recipients); message.setReference(reference); return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class); } public void deleteVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException { if (id == null) { throw new IllegalArgumentException("Message ID must be specified."); } messageBirdService.deleteByID(VOICEMESSAGESPATH, id); } public VoiceMessageResponse viewVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException { if (id == null) { throw new IllegalArgumentException("Voice Message ID must be specified."); } return messageBirdService.requestByID(VOICEMESSAGESPATH, id, VoiceMessageResponse.class); } /** * List voice messages * * @param offset offset for result list * @param limit limit for result list * @return VoiceMessageList * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceMessageList listVoiceMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException { if (offset != null && offset < 0) { throw new IllegalArgumentException("Offset must be > 0"); } if (limit != null && limit < 0) { throw new IllegalArgumentException("Limit must be > 0"); } return messageBirdService.requestList(VOICEMESSAGESPATH, offset, limit, VoiceMessageList.class); } /** * @param verifyRequest includes recipient, originator, reference, type, datacoding, template, timeout, tokenLenght, voice, language * @return Verify object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Verify sendVerifyToken(VerifyRequest verifyRequest) throws UnauthorizedException, GeneralException { if (verifyRequest == null) { throw new IllegalArgumentException("Verify request cannot be null"); } else if (verifyRequest.getRecipient() == null || verifyRequest.getRecipient().isEmpty()) { throw new IllegalArgumentException("Recipient cannot be empty for verify"); } return messageBirdService.sendPayLoad(VERIFYPATH, verifyRequest, Verify.class); } /** * @param recipient The telephone number that you want to verify. * @return Verify object * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Verify sendVerifyToken(String recipient) throws UnauthorizedException, GeneralException { if (recipient == null || recipient.isEmpty()) { throw new IllegalArgumentException("Recipient cannot be empty for verify"); } VerifyRequest verifyRequest = new VerifyRequest(recipient); return this.sendVerifyToken(verifyRequest); } public Verify verifyToken(String id, String token) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null || id.isEmpty()) { throw new IllegalArgumentException("ID cannot be empty for verify"); } else if (token == null || token.isEmpty()) { throw new IllegalArgumentException("ID cannot be empty for verify"); } final Map<String, Object> params = new LinkedHashMap<String, Object>(); params.put("token", token); return messageBirdService.requestByID(VERIFYPATH, id, params, Verify.class); } /** * @param id id is for getting verify object * @return Verify object * @throws NotFoundException if id is not found * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ Verify getVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null || id.isEmpty()) { throw new IllegalArgumentException("ID cannot be empty for verify"); } return messageBirdService.requestByID(VERIFYPATH, id, Verify.class); } /** * @param id id for deleting verify object * @throws NotFoundException if id is not found * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public void deleteVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null || id.isEmpty()) { throw new IllegalArgumentException("ID cannot be empty for verify"); } messageBirdService.deleteByID(VERIFYPATH, id); } /** * Send a Lookup request * * @param lookup including with country code, country prefix, phone number, type, formats, country code * @return Lookup * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception * @throws NotFoundException if lookup not found */ public Lookup viewLookup(final Lookup lookup) throws UnauthorizedException, GeneralException, NotFoundException { if (lookup.getPhoneNumber() == null) { throw new IllegalArgumentException("PhoneNumber must be specified."); } final Map<String, Object> params = new LinkedHashMap<String, Object>(); if (lookup.getCountryCode() != null) { params.put("countryCode", lookup.getCountryCode()); } return messageBirdService.requestByID(LOOKUPPATH, String.valueOf(lookup.getPhoneNumber()), params, Lookup.class); } /** * Send a Lookup request * * @param phoneNumber phone number is for viewing lookup * @return Lookup * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public Lookup viewLookup(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException { if (phoneNumber == null) { throw new IllegalArgumentException("PhoneNumber must be specified."); } final Lookup lookup = new Lookup(phoneNumber); return this.viewLookup(lookup); } /** * Request a Lookup HLR (lookup) * * @param lookupHlr country code for request lookup hlr * @return lookupHlr * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public LookupHlr requestLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException { if (lookupHlr.getPhoneNumber() == null) { throw new IllegalArgumentException("PhoneNumber must be specified."); } if (lookupHlr.getReference() == null) { throw new IllegalArgumentException("Reference must be specified."); } final Map<String, Object> payload = new LinkedHashMap<String, Object>(); payload.put("phoneNumber", lookupHlr.getPhoneNumber()); payload.put("reference", lookupHlr.getReference()); if (lookupHlr.getCountryCode() != null) { payload.put("countryCode", lookupHlr.getCountryCode()); } return messageBirdService.sendPayLoad(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), payload, LookupHlr.class); } /** * Request a Lookup HLR (lookup) * * @param phoneNumber phone number is for request hlr * @param reference reference for request hlr * @return lookupHlr * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public LookupHlr requestLookupHlr(final BigInteger phoneNumber, final String reference) throws UnauthorizedException, GeneralException { if (phoneNumber == null) { throw new IllegalArgumentException("Phonenumber must be specified."); } if (reference == null) { throw new IllegalArgumentException("Reference must be specified."); } final LookupHlr lookupHlr = new LookupHlr(); lookupHlr.setPhoneNumber(phoneNumber); lookupHlr.setReference(reference); return this.requestLookupHlr(lookupHlr); } /** * View a Lookup HLR (lookup) * * @param lookupHlr search with country code * @return LookupHlr * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception * @throws NotFoundException if there is no lookup hlr with given country code */ public LookupHlr viewLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException, NotFoundException { if (lookupHlr.getPhoneNumber() == null) { throw new IllegalArgumentException("Phonenumber must be specified"); } final Map<String, Object> params = new LinkedHashMap<String, Object>(); if (lookupHlr.getCountryCode() != null) { params.put("countryCode", lookupHlr.getCountryCode()); } return messageBirdService.requestByID(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), "", params, LookupHlr.class); } /** * View a Lookup HLR (lookup) * * @param phoneNumber phone number for searching on hlr * @return LookupHlr * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception * @throws NotFoundException phone number not found on hlr */ public LookupHlr viewLookupHlr(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException { if (phoneNumber == null) { throw new IllegalArgumentException("phoneNumber must be specified"); } final LookupHlr lookupHlr = new LookupHlr(); lookupHlr.setPhoneNumber(phoneNumber); return this.viewLookupHlr(lookupHlr); } /** * Deletes an existing contact. You only need to supply the unique id that * was returned upon creation. */ void deleteContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Contact ID must be specified."); } messageBirdService.deleteByID(CONTACTPATH, id); } /** * Gets a contact listing with specified pagination options. * * @return Listing of Contact objects. */ public ContactList listContacts(int offset, int limit) throws UnauthorizedException, GeneralException { return messageBirdService.requestList(CONTACTPATH, offset, limit, ContactList.class); } /** * Gets a contact listing with default pagination options. */ public ContactList listContacts() throws UnauthorizedException, GeneralException { final int limit = 20; final int offset = 0; return listContacts(offset, limit); } /** * Creates a new contact object. MessageBird returns the created contact * object with each request. */ public Contact sendContact(final ContactRequest contactRequest) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(CONTACTPATH, contactRequest, Contact.class); } /** * Updates an existing contact. You only need to supply the unique id that * was returned upon creation. */ public Contact updateContact(final String id, ContactRequest contactRequest) throws UnauthorizedException, GeneralException { if (id == null) { throw new IllegalArgumentException("Contact ID must be specified."); } String request = CONTACTPATH + "/" + id; return messageBirdService.sendPayLoad("PATCH", request, contactRequest, Contact.class); } /** * Retrieves the information of an existing contact. You only need to supply * the unique contact ID that was returned upon creation or receiving. */ public Contact viewContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Contact ID must be specified."); } return messageBirdService.requestByID(CONTACTPATH, id, Contact.class); } /** * Deletes an existing group. You only need to supply the unique id that * was returned upon creation. */ public void deleteGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Group ID must be specified."); } messageBirdService.deleteByID(GROUPPATH, id); } /** * Removes a contact from group. You need to supply the IDs of the group * and contact. Does not delete the contact. */ public void deleteGroupContact(final String groupId, final String contactId) throws NotFoundException, GeneralException, UnauthorizedException { if (groupId == null) { throw new IllegalArgumentException("Group ID must be specified."); } if (contactId == null) { throw new IllegalArgumentException("Contact ID must be specified."); } String id = String.format("%s%s/%s", groupId, CONTACTPATH, contactId); messageBirdService.deleteByID(GROUPPATH, id); } /** * Gets a contact listing with specified pagination options. */ public GroupList listGroups(final int offset, final int limit) throws UnauthorizedException, GeneralException { return messageBirdService.requestList(GROUPPATH, offset, limit, GroupList.class); } /** * Gets a contact listing with default pagination options. */ public GroupList listGroups() throws UnauthorizedException, GeneralException { final int offset = 0; final int limit = 20; return listGroups(offset, limit); } /** * Creates a new group object. MessageBird returns the created group object * with each request. */ public Group sendGroup(final GroupRequest groupRequest) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(GROUPPATH, groupRequest, Group.class); } /** * Adds contact to group. You need to supply the IDs of the group and * contact. */ public void sendGroupContact(final String groupId, final String[] contactIds) throws NotFoundException, GeneralException, UnauthorizedException { // reuestByID appends the "ID" to the base path, so this workaround // lets us add a query string. String path = String.format("%s%s?%s", groupId, CONTACTPATH, getQueryString(contactIds)); messageBirdService.requestByID(GROUPPATH, path, null); } private String getQueryString(final String[] contactIds) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("_method=PUT"); for (String groupId : contactIds) { stringBuilder.append("&ids[]=").append(groupId); } return stringBuilder.toString(); } /** * Updates an existing group. You only need to supply the unique ID that * was returned upon creation. */ public Group updateGroup(final String id, final GroupRequest groupRequest) throws UnauthorizedException, GeneralException { if (id == null) { throw new IllegalArgumentException("Group ID must be specified."); } String path = String.format("%s/%s", GROUPPATH, id); return messageBirdService.sendPayLoad("PATCH", path, groupRequest, Group.class); } /** * Retrieves the information of an existing group. You only need to supply * the unique group ID that was returned upon creation or receiving. */ public Group viewGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Group ID must be specified."); } return messageBirdService.requestByID(GROUPPATH, id, Group.class); } /** * Gets a single conversation. * * @param id Conversation to retrieved. * @return The retrieved conversation. */ public Conversation viewConversation(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Id must be specified"); } String url = CONVERSATIONS_BASE_URL + CONVERSATION_PATH; return messageBirdService.requestByID(url, id, Conversation.class); } /** * Updates a conversation. * * @param id Conversation to update. * @param status New status for the conversation. * @return The updated Conversation. */ public Conversation updateConversation(final String id, final ConversationStatus status) throws UnauthorizedException, GeneralException { if (id == null) { throw new IllegalArgumentException("Id must be specified."); } String url = String.format("%s%s/%s", CONVERSATIONS_BASE_URL, CONVERSATION_PATH, id); return messageBirdService.sendPayLoad("PATCH", url, status, Conversation.class); } /** * Gets a Conversation listing with specified pagination options. * * @param offset Number of objects to skip. * @param limit Number of objects to take. * @return List of conversations. */ public ConversationList listConversations(final int offset, final int limit) throws UnauthorizedException, GeneralException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_PATH; return messageBirdService.requestList(url, offset, limit, ConversationList.class); } /** * Gets a contact listing with default pagination options. * * @return List of conversations. */ public ConversationList listConversations() throws UnauthorizedException, GeneralException { final int offset = 0; final int limit = 10; return listConversations(offset, limit); } /** * Starts a conversation by sending an initial message. * * @param request Data for this request. * @return The created Conversation. */ public Conversation startConversation(ConversationStartRequest request) throws UnauthorizedException, GeneralException { String url = String.format("%s%s/start", CONVERSATIONS_BASE_URL, CONVERSATION_PATH); return messageBirdService.sendPayLoad(url, request, Conversation.class); } /** * Gets a ConversationMessage listing with specified pagination options. * * @param conversationId Conversation to get messages for. * @param offset Number of objects to skip. * @param limit Number of objects to take. * @return List of messages. */ public ConversationMessageList listConversationMessages( final String conversationId, final int offset, final int limit ) throws UnauthorizedException, GeneralException { String url = String.format( "%s%s/%s%s", CONVERSATIONS_BASE_URL, CONVERSATION_PATH, conversationId, CONVERSATION_MESSAGE_PATH ); return messageBirdService.requestList(url, offset, limit, ConversationMessageList.class); } /** * Gets a ConversationMessage listing with default pagination options. * * @param conversationId Conversation to get messages for. * @return List of messages. */ public ConversationMessageList listConversationMessages( final String conversationId ) throws UnauthorizedException, GeneralException { final int offset = 0; final int limit = 10; return listConversationMessages(conversationId, offset, limit); } /** * Gets a single message. * * @param messageId Message to retrieve. * @return The retrieved message. */ public ConversationMessage viewConversationMessage(final String messageId) throws NotFoundException, GeneralException, UnauthorizedException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_MESSAGE_PATH; return messageBirdService.requestByID(url, messageId, ConversationMessage.class); } /** * Sends a message to an existing Conversation. * * @param conversationId Conversation to send message to. * @param request Message to send. * @return The newly created message. */ public ConversationMessage sendConversationMessage( final String conversationId, final ConversationMessageRequest request ) throws UnauthorizedException, GeneralException { String url = String.format( "%s%s/%s%s", CONVERSATIONS_BASE_URL, CONVERSATION_PATH, conversationId, CONVERSATION_MESSAGE_PATH ); return messageBirdService.sendPayLoad(url, request, ConversationMessage.class); } /** * Deletes a webhook. * * @param webhookId Webhook to delete. */ public void deleteConversationWebhook(final String webhookId) throws NotFoundException, GeneralException, UnauthorizedException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_WEBHOOK_PATH; messageBirdService.deleteByID(url, webhookId); } /** * Creates a new webhook. * * @param request Webhook to create. * @return Newly created webhook. */ public ConversationWebhook sendConversationWebhook(final ConversationWebhookRequest request) throws UnauthorizedException, GeneralException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_WEBHOOK_PATH; return messageBirdService.sendPayLoad(url, request, ConversationWebhook.class); } /** * Gets a single webhook. * * @param webhookId Webhook to retrieve. * @return The retrieved webhook. */ public ConversationWebhook viewConversationWebhook(final String webhookId) throws NotFoundException, GeneralException, UnauthorizedException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_WEBHOOK_PATH; return messageBirdService.requestByID(url, webhookId, ConversationWebhook.class); } /** * Gets a ConversationWebhook listing with the specified pagination options. * * @param offset Number of objects to skip. * @param limit Number of objects to skip. * @return List of webhooks. */ ConversationWebhookList listConversationWebhooks(final int offset, final int limit) throws UnauthorizedException, GeneralException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_WEBHOOK_PATH; return messageBirdService.requestList(url, offset, limit, ConversationWebhookList.class); } /** * Gets a ConversationWebhook listing with default pagination options. * * @return List of webhooks. */ public ConversationWebhookList listConversationWebHooks() throws UnauthorizedException, GeneralException { final int offset = 0; final int limit = 10; return listConversationWebhooks(offset, limit); } /** * Function for voice call to a number * * @param voiceCall Voice call object * @return VoiceCallResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallResponse sendVoiceCall(final VoiceCall voiceCall) throws UnauthorizedException, GeneralException { if (voiceCall.getSource() == null) { throw new IllegalArgumentException("Source of voice call must be specified."); } if (voiceCall.getDestination() == null) { throw new IllegalArgumentException("Destination of voice call must be specified."); } if (voiceCall.getCallFlow() == null) { throw new IllegalArgumentException("Call flow of voice call must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); return messageBirdService.sendPayLoad(url, voiceCall, VoiceCallResponse.class); } /** * Function to list all voice calls * * @return VoiceCallResponseList * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallResponseList listAllVoiceCalls(Integer page, Integer pageSize) throws GeneralException, UnauthorizedException { String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallResponseList.class); } /** * Function to view voice call by id * * @param id Voice call ID * @return VoiceCallResponse * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallResponse viewVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Voice Message ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); return messageBirdService.requestByID(url, id, VoiceCallResponse.class); } /** * Function to delete voice call by id * * @param id Voice call ID * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public void deleteVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Voice Message ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); messageBirdService.deleteByID(url, id); } /** * Retrieves a listing of all legs. * * @param callId Voice call ID * @param page page to fetch (can be null - will return first page), number of first page is 1 * @param pageSize page size * @return VoiceCallLegResponse * @throws UnsupportedEncodingException no UTF8 supported url * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallLegResponse viewCallLegsByCallId(String callId, Integer page, Integer pageSize) throws UnsupportedEncodingException, UnauthorizedException, GeneralException { if (callId == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } String url = String.format( "%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, urlEncode(callId), VOICELEGS_SUFFIX_PATH); return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallLegResponse.class); } /** * Retrieves a leg resource. * The parameters are the unique ID of the call and of the leg that were returned upon their respective creation. * * @param callId Voice call ID * @param legId ID of leg of specified call {callId} * @return VoiceCallLeg * @throws UnsupportedEncodingException no UTF8 supported url * @throws NotFoundException not found with callId and legId * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public VoiceCallLeg viewCallLegByCallIdAndLegId(final String callId, String legId) throws UnsupportedEncodingException, NotFoundException, GeneralException, UnauthorizedException { if (callId == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } String url = String.format( "%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, urlEncode(callId), VOICELEGS_SUFFIX_PATH); VoiceCallLegResponse response = messageBirdService.requestByID(url, legId, VoiceCallLegResponse.class); if (response.getData().size() == 1) { return response.getData().get(0); } else { throw new NotFoundException("No such leg", new LinkedList<ErrorReport>()); } } private String urlEncode(String s) throws UnsupportedEncodingException { return URLEncoder.encode(s, String.valueOf(StandardCharsets.UTF_8)); } /** * Function to view recording by call id , leg id and recording id * * @param callID Voice call ID * @param legId Leg ID * @param recordingId Recording ID * @return Recording * @throws NotFoundException not found with callId and legId * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public RecordingResponse viewRecording(String callID, String legId, String recordingId) throws NotFoundException, GeneralException, UnauthorizedException { if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } if (recordingId == null) { throw new IllegalArgumentException("Recording ID must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH); Map<String, Object> params = new LinkedHashMap<>(); params.put("legs", legId); params.put("recordings", recordingId); return messageBirdService.requestByID(url, callID, params, RecordingResponse.class); } /** * Function to view recording by call id , leg id and recording id * * @param callID Voice call ID * @param legId Leg ID * @param recordingId Recording ID * @param language Language * @return TranscriptionResponseList * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public TranscriptionResponse createTranscription(String callID, String legId, String recordingId, String language) throws UnauthorizedException, GeneralException { if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } if (recordingId == null) { throw new IllegalArgumentException("Recording ID must be specified."); } if (language == null) { throw new IllegalArgumentException("Language must be specified."); } if (!Arrays.asList(supportedLanguages).contains(language)) { throw new IllegalArgumentException("Your language is not allowed."); } String url = String.format( "%s%s/%s%s/%s%s/%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, callID, LEGSPATH, legId, RECORDINGPATH, recordingId, TRANSCRIPTIONPATH); return messageBirdService.sendPayLoad(url, language, TranscriptionResponse.class); } /** * Function to view recording by call id , leg id and recording id * * @param callID Voice call ID * @param legId Leg ID * @param recordingId Recording ID * @return TranscriptionResponseList * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public TranscriptionResponse viewTranscription(String callID, String legId, String recordingId, Integer page, Integer pageSize) throws UnauthorizedException, GeneralException { if (callID == null) { throw new IllegalArgumentException("Voice call ID must be specified."); } if (legId == null) { throw new IllegalArgumentException("Leg ID must be specified."); } if (recordingId == null) { throw new IllegalArgumentException("Recording ID must be specified."); } String url = String.format( "%s%s/%s%s/%s%s/%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH, callID, LEGSPATH, legId, RECORDINGPATH, recordingId); return messageBirdService.requestList(url, new PagedPaging(page, pageSize), TranscriptionResponse.class); } /** * Function to create web hook * * @param webhook title, url and token of webHook * @return WebHookResponseData * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public WebhookResponseData createWebHook(Webhook webhook) throws UnauthorizedException, GeneralException { if (webhook.getTitle() == null) { throw new IllegalArgumentException("Title of webhook must be specified."); } if (webhook.getUrl() == null) { throw new IllegalArgumentException("URL of webhook must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS); return messageBirdService.sendPayLoad(url, webhook, WebhookResponseData.class); } /** * Function to view webhook * * @param id webHook id * @return WebHookResponseData * @throws UnauthorizedException if client is unauthorized * @throws GeneralException general exception */ public WebhookResponseData viewWebHook(String id) throws NotFoundException, GeneralException, UnauthorizedException { if (id == null) { throw new IllegalArgumentException("Id of webHook must be specified."); } String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS); return messageBirdService.requestByID(url, id, WebhookResponseData.class); } }
package org.openmrs.api; import org.openmrs.User; import org.openmrs.util.OpenmrsUtil; /** * Represents common exceptions that happen when validating a {@link User}'s password. * <p> * Preferred use of this class and its subclass are the {@link #PasswordException()} or the * {@link #PasswordException(String)}. The empty constructor will create an exception object using * without an exception message. * <p> * For details on what is checked, see {@link OpenmrsUtil#validatePassword(String, String, String)}. * * @since 1.5 */ public class PasswordException extends APIException { private static final long serialVersionUID = 31620091001L; public PasswordException() { super(); } public PasswordException(String message, Throwable cause) { super(message, (Object[]) null, cause); } public PasswordException(String message) { super(message, (Object[]) null); } public PasswordException(Throwable cause) { super(cause); } }
// $Id: Collections.java,v 1.4 2002/11/07 18:40:40 ray Exp $ package com.samskivert.util; import java.util.*; /** * Provides functionality for the samskivert collections that the * <code>java.util</code> class of the same name provides for the standard * Java collections. Collections-related functionality that is different * from the standard support provided for the Java collections should go * into {@link CollectionUtil}. */ public class Collections { /** * Returns an Iterator that iterates over all the elements contained * within the Collections within the specified Collection. * * @param metaCollection a collection of either other Collections and/or * of Iterators. */ public static Iterator getMetaIterator (Collection metaCollection) { return new MetaIterator(metaCollection); } /** * Get an Iterator over the supplied Collection that returns the * elements in their natural order. */ public static Iterator getSortedIterator (Collection coll) { return getSortedIterator(coll.iterator(), Comparators.COMPARABLE); } /** * Get an Iterator over the supplied Collection that returns the * elements in the order dictated by the supplied Comparator. */ public static Iterator getSortedIterator (Collection coll, Comparator comparator) { return getSortedIterator(coll.iterator(), comparator); } /** * Get an Iterator that returns the same elements returned by * the supplied Iterator, but in their natural order. */ public static Iterator getSortedIterator (Iterator itr) { return getSortedIterator(itr, Comparators.COMPARABLE); } /** * Get an Iterator that returns the same elements returned by * the supplied Iterator, but in the order dictated by the supplied * Comparator. */ public static Iterator getSortedIterator (Iterator itr, Comparator comparator) { SortableArrayList list = new SortableArrayList(); while (itr.hasNext()) { list.insertSorted(itr.next(), comparator); } return getUnmodifiableIterator(list); } /** * Get an Iterator over the supplied Collection that returns * the elements in a completely random order. Normally Iterators * return elements in an undefined order, but it is usually the same * between different invocations as long as the underlying Collection * has not changed. This method mixes things up. */ public static Iterator getRandomIterator (Collection c) { return getRandomIterator(c.iterator()); } /** * Get an Iterator that returns the same elements returned by * the supplied Iterator, but in a completely random order. */ public static Iterator getRandomIterator (Iterator itr) { ArrayList list = new ArrayList(); CollectionUtil.addAll(list, itr); java.util.Collections.shuffle(list); return getUnmodifiableIterator(list); } /** * Get an Iterator that returns the elements in the supplied * Collection but blocks removal. */ public static Iterator getUnmodifiableIterator (Collection c) { return getUnmodifiableIterator(c.iterator()); } /** * Get an iterator that returns the same elements as the supplied * iterator but blocks removal. */ public static Iterator getUnmodifiableIterator (final Iterator itr) { return new Iterator() { public boolean hasNext () { return itr.hasNext(); } public Object next () { return itr.next(); } public void remove () { throw new UnsupportedOperationException( "Cannot remove from an UnmodifiableIterator!"); } }; } /** * Returns a synchronized (thread-safe) int map backed by the * specified int map. In order to guarantee serial access, it is * critical that <strong>all</strong> access to the backing int map is * accomplished through the returned int map. * * <p> It is imperative that the user manually synchronize on the * returned int map when iterating over any of its collection views: * * <pre> * IntMap m = Collections.synchronizedIntMap(new HashIntMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized(m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * * Failure to follow this advice may result in non-deterministic * behavior. * * <p> The returned map will be serializable if the specified map is * serializable. * * @param m the int map to be "wrapped" in a synchronized int map. * * @return a synchronized view of the specified int map. */ public static IntMap synchronizedIntMap(IntMap m) { return new SynchronizedIntMap(m); } /** * Horked from the Java util class and extended for <code>IntMap</code>. */ protected static class SynchronizedIntMap implements IntMap { private IntMap m; // Backing Map private Object mutex; // Object on which to synchronize SynchronizedIntMap(IntMap m) { if (m == null) { throw new NullPointerException(); } this.m = m; mutex = this; } SynchronizedIntMap(IntMap m, Object mutex) { if (m == null) { throw new NullPointerException(); } this.m = m; this.mutex = mutex; } public int size() { synchronized(mutex) {return m.size();} } public boolean isEmpty(){ synchronized(mutex) {return m.isEmpty();} } public boolean containsKey(int key) { synchronized(mutex) {return m.containsKey(key);} } public boolean containsKey(Object key) { synchronized(mutex) {return m.containsKey(key);} } public boolean containsValue(Object value){ synchronized(mutex) {return m.containsValue(value);} } public Object get(int key) { synchronized(mutex) {return m.get(key);} } public Object get(Object key) { synchronized(mutex) {return m.get(key);} } public Object put(int key, Object value) { synchronized(mutex) {return m.put(key, value);} } public Object put(Object key, Object value) { synchronized(mutex) {return m.put(key, value);} } public Object remove(int key) { synchronized(mutex) {return m.remove(key);} } public Object remove(Object key) { synchronized(mutex) {return m.remove(key);} } public void putAll(Map map) { synchronized(mutex) {m.putAll(map);} } public void clear() { synchronized(mutex) {m.clear();} } private transient Set keySet = null; private transient Set entrySet = null; private transient Collection values = null; public Set keySet() { synchronized(mutex) { if (keySet==null) keySet = new SynchronizedSet(m.keySet(), mutex); return keySet; } } public Set entrySet() { synchronized(mutex) { if (entrySet==null) entrySet = new SynchronizedSet(m.entrySet(), mutex); return entrySet; } } public Collection values() { synchronized(mutex) { if (values==null) values = new SynchronizedCollection(m.values(), mutex); return values; } } public boolean equals(Object o) { synchronized(mutex) {return m.equals(o);} } public int hashCode() { synchronized(mutex) {return m.hashCode();} } public String toString() { synchronized(mutex) {return m.toString();} } } /** * I wish I could use this from the <code>java.util.Collections</code> * class, but those crazy kids at Sun are always using private and * default access and pointlessly preventing people from properly * reusing their code. Yay! */ protected static class SynchronizedSet extends SynchronizedCollection implements Set { SynchronizedSet(Set s) { super(s); } SynchronizedSet(Set s, Object mutex) { super(s, mutex); } public boolean equals(Object o) { synchronized(mutex) {return c.equals(o);} } public int hashCode() { synchronized(mutex) {return c.hashCode();} } } /** * I wish I could use this from the <code>java.util.Collections</code> * class, but those crazy kids at Sun are always using private and * default access and pointlessly preventing people from properly * reusing their code. Yay! */ protected static class SynchronizedCollection implements Collection { Collection c; // Backing Collection Object mutex; // Object on which to synchronize SynchronizedCollection(Collection c) { if (c==null) throw new NullPointerException(); this.c = c; mutex = this; } SynchronizedCollection(Collection c, Object mutex) { this.c = c; this.mutex = mutex; } public int size() { synchronized(mutex) {return c.size();} } public boolean isEmpty() { synchronized(mutex) {return c.isEmpty();} } public boolean contains(Object o) { synchronized(mutex) {return c.contains(o);} } public Object[] toArray() { synchronized(mutex) {return c.toArray();} } public Object[] toArray(Object[] a) { synchronized(mutex) {return c.toArray(a);} } public Iterator iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add(Object o) { synchronized(mutex) {return c.add(o);} } public boolean remove(Object o) { synchronized(mutex) {return c.remove(o);} } public boolean containsAll(Collection coll) { synchronized(mutex) {return c.containsAll(coll);} } public boolean addAll(Collection coll) { synchronized(mutex) {return c.addAll(coll);} } public boolean removeAll(Collection coll) { synchronized(mutex) {return c.removeAll(coll);} } public boolean retainAll(Collection coll) { synchronized(mutex) {return c.retainAll(coll);} } public void clear() { synchronized(mutex) {c.clear();} } public String toString() { synchronized(mutex) {return c.toString();} } } /** * An iterator that iterates over the union of the iterators provided by a * collection of collections. */ protected static class MetaIterator implements Iterator { /** * @param collections a Collection containing more Collections * whose elements we are to iterate over. */ public MetaIterator (Collection collections) { _meta = collections.iterator(); } // documentation inherited from interface Iterator public boolean hasNext () { while ((_current == null) || (!_current.hasNext())) { if (_meta.hasNext()) { Object o = _meta.next(); if (o instanceof Iterator) { _current = (Iterator) o; // TODO: jdk1.5, // (obsoletes the Collection case, below) //} else if (o instanceof Iterable) { // _current = ((Iterable) o).iterator(); } else if (o instanceof Collection) { _current = ((Collection) o).iterator(); } else { throw new IllegalArgumentException( "MetaIterator must be constructed with a " + "collection of Iterators or other collections."); } } else { return false; } } return true; } // documentation inherited from interface Iterator public Object next () { if (hasNext()) { return _current.next(); } else { throw new NoSuchElementException(); } } // documentation inherited from interface Iterator public void remove () { if (_current != null) { _current.remove(); } else { throw new IllegalStateException(); } } /** The iterator through the collection we were constructed with. */ protected Iterator _meta; /** The current sub-collection's iterator. */ protected Iterator _current; } }
package org.protempa; import org.protempa.backend.UnrecoverableBackendErrorEvent; import org.protempa.backend.BackendUpdatedEvent; import org.protempa.backend.Backend; import java.util.ArrayList; import java.util.List; public abstract class AbstractSource<E extends SourceUpdatedEvent, T extends BackendUpdatedEvent> implements Source<T> { private final List<SourceListener<E>> listenerList; private Backend[] backends; private boolean closed; /** * Makes this {@link Source} a listener to events fired by the provided * {@link Backend}s. * * @param backends a {@link Backend[]}. */ AbstractSource(Backend[] backends) { this.listenerList = new ArrayList<SourceListener<E>>(); if (backends != null) { this.backends = backends; for (Backend backend : this.backends) { backend.addBackendListener(this); } } else { this.backends = null; } } /** * Adds a listener that gets called whenever something changes. * * @param listener * a {@link DataSourceListener}. */ public void addSourceListener(SourceListener<E> listener) { if (listener != null) { this.listenerList.add(listener); } } /** * Removes a listener so that changes to the source are no longer sent. * * @param listener * a {@link DataSourceListener}. */ public void removeSourceListener(SourceListener<E> listener) { this.listenerList.remove(listener); } /** * Notifies registered listeners that the source has been updated. * * @param e a {@link SourceUpdatedEvent} representing an update. * * @see SourceListener */ protected void fireSourceUpdated(E e) { for (int i = 0, n = this.listenerList.size(); i < n; i++) { this.listenerList.get(i).sourceUpdated(e); } } protected void fireClosedUnexpectedly(SourceClosedUnexpectedlyEvent<T> e) { for (int i = 0, n = this.listenerList.size(); i < n; i++) { this.listenerList.get(i).closedUnexpectedly(e); } } /** * Removes this {@link Source} as a listener to the {@link Backend}s * provided to the constructor. * * Must be called by subclasses, or proper cleanup will not occur. */ @Override public void close() { if (this.backends != null) { for (Backend backend : this.backends) { backend.removeBackendListener(this); } } this.backends = null; this.closed = true; } protected boolean isClosed() { return this.closed; } @Override public void unrecoverableErrorOccurred(UnrecoverableBackendErrorEvent e) { close(); this.fireClosedUnexpectedly(new SourceClosedUnexpectedlyEvent<T>(this)); } }
package com.psddev.dari.db; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.WeakHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.StringUtils; import com.psddev.dari.util.UuidUtils; /** Enforces mutual exclusion across multiple VMs using a {@link Database}. */ public class DistributedLock implements Lock { private static final Logger LOGGER = LoggerFactory.getLogger(DistributedLock.class); private static final long TIMEOUT = 10000; private static final long TRY_INTERVAL = 50L; private final String lockId = UUID.randomUUID().toString(); private final Database database; private final String keyString; private final UUID keyId; private final AtomicReference<Thread> holderRef = new AtomicReference<Thread>(); protected DistributedLock(Database database, String key) { this.database = database; this.keyString = key; this.keyId = UuidUtils.fromBytes(StringUtils.md5(key)); } /** * {@inheritDoc} * * @throws ReentrantException If this lock is already held by the * current thread. */ @Override public void lock() { if (!tryLock()) { LOGGER.debug("Waiting to acquire [{}]", this); do { try { Thread.sleep(TRY_INTERVAL); } catch (InterruptedException ex) { } } while (!tryLock()); } } /** * {@inheritDoc} * * @throws ReentrantException If this lock is already held by the * current thread. */ @Override public void lockInterruptibly() throws InterruptedException { if (!tryLock()) { LOGGER.debug("Waiting to acquire [{}] interruptibly", this); do { Thread.sleep(TRY_INTERVAL); } while (!tryLock()); } } @Override public Condition newCondition() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * * @throws ReentrantException If this lock is already held by the * current thread. */ @Override public boolean tryLock() { if (Thread.currentThread().equals(holderRef.get())) { throw new ReentrantException(); } synchronized (holderRef) { boolean oldIgnore = Database.Static.isIgnoreReadConnection(); State key; try { Database.Static.setIgnoreReadConnection(true); key = State.getInstance(Query. from(Object.class). where("_id = ?", keyId). using(database). noCache(). first()); } finally { Database.Static.setIgnoreReadConnection(oldIgnore); } if (key == null) { key = new State(); key.setDatabase(database); key.setId(keyId); key.put("keyString", keyString); } else { if (ObjectUtils.to(long.class, key.get("lastPing")) + TIMEOUT < System.currentTimeMillis()) { LOGGER.debug("Timeout exceeded: [{}]", this); } else { return false; } } try { key.replaceAtomically("lockId", lockId); key.replaceAtomically("lastPing", System.currentTimeMillis()); key.saveImmediately(); } catch (DatabaseException ex) { Throwable cause = ex.getCause(); if (cause instanceof AtomicOperation.ReplacementException) { LOGGER.debug("Stolen by a different VM: [{}]", this); return false; } else { throw ex; } } holderRef.set(Thread.currentThread()); LOGGER.debug("Acquired [{}]", this); return true; } } /** * {@inheritDoc} * * @throws ReentrantException If this lock is already held by the * current thread. */ @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { long end = System.currentTimeMillis() + unit.toMillis(time); do { if (tryLock()) { return true; } else { Thread.sleep(TRY_INTERVAL); } } while (System.currentTimeMillis() < end); return false; } @Override public void unlock() { Thread holder = holderRef.get(); if (holder == null) { throw new IllegalStateException("Not locked yet!"); } else if (!Thread.currentThread().equals(holder)) { throw new IllegalMonitorStateException("Not the lock owner!"); } synchronized (holderRef) { try { LOGGER.debug("Releasing [{}]", this); boolean oldIgnore = Database.Static.isIgnoreReadConnection(); State key; try { Database.Static.setIgnoreReadConnection(true); key = State.getInstance(Query. from(Object.class). where("_id = ?", keyId). using(database). noCache(). first()); if (key != null && lockId.equals(key.get("lockId"))) { key.deleteImmediately(); } } finally { Database.Static.setIgnoreReadConnection(oldIgnore); } } finally { holderRef.set(null); } } } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof DistributedLock) { DistributedLock otherLock = (DistributedLock) other; return database.equals(otherLock.database) && keyId.equals(otherLock.keyId); } else { return false; } } @Override public int hashCode() { return ObjectUtils.hashCode(database, keyId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{lockId=").append(lockId); sb.append(", database=").append(database); sb.append(", keyId=").append(keyId); sb.append("}"); return sb.toString(); } /** Thrown when the thread tries to reacquire the same lock. */ @SuppressWarnings("serial") public static class ReentrantException extends IllegalStateException { public ReentrantException() { super(); } } /** {@link DistributedLock} utility methods. */ public static final class Static { private Static() { } private static final Map<Database, Map<String, WeakReference<DistributedLock>>> INSTANCES = new WeakHashMap<Database, Map<String, WeakReference<DistributedLock>>>(); /** * Returns an instance that locks around the given {@code key} * within the given {@code database}. */ public static DistributedLock getInstance(Database database, String key) { if (database == null) { throw new IllegalArgumentException("Database can't be null!"); } if (key == null) { throw new IllegalArgumentException("Key can't be null!"); } synchronized (Static.class) { Map<String, WeakReference<DistributedLock>> byKey = INSTANCES.get(database); if (byKey == null) { byKey = new HashMap<String, WeakReference<DistributedLock>>(); INSTANCES.put(database, byKey); } WeakReference<DistributedLock> lockRef = byKey.get(key); if (lockRef != null) { DistributedLock lock = lockRef.get(); if (lock != null) { return lock; } } DistributedLock lock = new DistributedLock(database, key); byKey.put(key, new WeakReference<DistributedLock>(lock)); return lock; } } } }
package etomica.freeenergy.npath; import etomica.action.BoxInflate; import etomica.action.activity.ActivityIntegrate; import etomica.api.*; import etomica.atom.DiameterHash; import etomica.atom.DiameterHashByType; import etomica.box.Box; import etomica.box.BoxAgentManager; import etomica.chem.elements.Iron; import etomica.config.ConfigurationLattice; import etomica.data.*; import etomica.data.meter.MeterKineticEnergy; import etomica.data.meter.MeterPotentialEnergy; import etomica.data.meter.MeterStructureFactor; import etomica.graphics.ColorScheme; import etomica.graphics.DisplayPlot; import etomica.graphics.SimulationGraphic; import etomica.integrator.IntegratorMC; import etomica.integrator.IntegratorMD; import etomica.lattice.LatticeCubicBcc; import etomica.lattice.LatticeCubicFcc; import etomica.lattice.LatticeHcp; import etomica.lattice.crystal.Primitive; import etomica.lattice.crystal.PrimitiveHexagonal; import etomica.meam.P2EAM; import etomica.meam.PotentialCalculationEnergySumEAM; import etomica.nbr.cell.NeighborCellManager; import etomica.nbr.cell.PotentialMasterCell; import etomica.nbr.list.BoxAgentSourceCellManagerList; import etomica.nbr.list.NeighborListManagerSlanty; import etomica.nbr.list.PotentialMasterList; import etomica.potential.PotentialCalculationForceSum; import etomica.simulation.Simulation; import etomica.space.BoundaryDeformableLattice; import etomica.space3d.Space3D; import etomica.species.SpeciesSpheresMono; import etomica.units.*; import etomica.util.HistoryCollapsingAverage; import etomica.util.ParameterBase; import etomica.util.ParseArgs; import java.awt.*; import java.util.Arrays; import static etomica.freeenergy.npath.SimFe.Crystal.HCP; /** * Simple Lennard-Jones molecular dynamics simulation in 3D */ public class SimFe extends Simulation { public final PotentialMasterList potentialMaster; public final ActivityIntegrate ai; public IntegratorImageHarmonicMD integrator; public SpeciesSpheresMono species; public IBox box; public P2EAM potential; public P1ImageHarmonic p1ImageHarmonic; public MCMoveAtomSwap mcMoveSwap; public SimFe(Crystal crystal, int numAtoms, double temperature, double density, double w, int offsetDim, int numInnerSteps) { super(Space3D.getInstance()); species = new SpeciesSpheresMono(space, Iron.INSTANCE); species.setIsDynamic(true); addSpecies(species); box = new Box(space); addBox(box); box.setNMolecules(species, numAtoms); IVectorMutable l = space.makeVector(); l.E(10); for (int i=0; i<=offsetDim; i++) { l.setX(i,20); } box.getBoundary().setBoxSize(l); if (crystal != HCP) { BoxInflate inflater = new BoxInflate(box, space); inflater.setTargetDensity(density); inflater.actionPerformed(); } double n = 8.7932; double m = 8.14475; double eps = ElectronVolt.UNIT.toSim(0.0220225); double a = 3.48501; double C = 28.8474; double rc = 6; potential = new P2EAM(space, n, m, eps, a, C, rc, rc); if (crystal == HCP) { int nc = (int)Math.round(Math.pow(numAtoms/8, 1.0/3.0)); if (8*nc*nc*nc != numAtoms) { throw new RuntimeException("Not compatible with HCP"); } // V = nc // v = 2/density = (2^.5/rho)sqrt(8/3)*f // = 4f/(rho sqrt(3)) // f = sqrt(3)/2 // v = sqrt(3)/2 a^3 coa // a = (2 v / (sqrt(3) coa))^(1/3) // = (4 / (sqrt(3) rho coa))^(1/3) double coa = Math.sqrt(8.0/3.0); double ac = Math.pow(4/(Math.sqrt(3)*density*coa), 1.0/3.0); double cc = coa*ac; IVector[] boxDim = new IVector[3]; boxDim[0] = space.makeVector(new double[]{2*nc*ac, 0, 0}); boxDim[1] = space.makeVector(new double[]{-2*nc*ac*Math.cos(Degree.UNIT.toSim(60)), 2*nc*ac*Math.sin(Degree.UNIT.toSim(60)), 0}); boxDim[2] = space.makeVector(new double[]{0, 0, nc*cc}); System.out.println("a: "+ac+" c: "+cc+" nc: "+nc); Primitive primitive = new PrimitiveHexagonal(space, ac, cc); int[] nCells = new int[]{2*nc,2*nc,nc}; BoundaryDeformableLattice boundary = new BoundaryDeformableLattice(primitive, nCells); boundary.setTruncationRadius(rc); System.out.println(Arrays.toString(nCells)); IVector edge0 = boundary.getEdgeVector(0); System.out.println(Math.sqrt(edge0.squared())+" "+edge0); IVector edge1 = boundary.getEdgeVector(1); System.out.println(Math.sqrt(edge0.squared())+" "+edge1); IVector edge2 = boundary.getEdgeVector(2); System.out.println(Math.sqrt(edge2.squared())+" "+edge2); box.setBoundary(boundary); ConfigurationLattice config = new ConfigurationLattice(new LatticeHcp(space, ac),space); config.setBoundaryPadding(0); config.initializeCoordinates(box); } if (crystal == HCP) { BoxAgentSourceCellManagerList boxAgentSource = new BoxAgentSourceCellManagerList(this, null, space); BoxAgentManager<NeighborCellManager> boxAgentManager = new BoxAgentManager<NeighborCellManager>(boxAgentSource, NeighborCellManager.class); potentialMaster = new PotentialMasterList(this, 1.2 * rc, boxAgentSource, boxAgentManager, new NeighborListManagerSlanty.NeighborListSlantyAgentSource(rc, space), space); } else { potentialMaster = new PotentialMasterList(this, 1.2*rc, space); } potentialMaster.setCellRange(2); double sigma = 1.0; if (numInnerSteps==0) { // integrator = new IntegratorImageHarmonicMD0(potentialMaster, random, 0.001, temperature, space); } else { integrator = new IntegratorImageHarmonicMD(potentialMaster, random, 0.001, temperature, space); } MeterPotentialEnergy meterPE = new MeterPotentialEnergy(potentialMaster); meterPE.setPotentialCalculation(new PotentialCalculationEnergySumEAM(potential)); integrator.setMeterPotentialEnergy(meterPE); integrator.setIsothermal(true); integrator.setThermostat(IntegratorMD.ThermostatType.HYBRID_MC); integrator.setThermostatInterval(10); integrator.setTemperature(temperature); integrator.getEventManager().addListener(potential.makeIntegratorListener(potentialMaster, box)); integrator.setForceSum(new PotentialCalculationForceSum()); ai = new ActivityIntegrate(integrator); getController().addAction(ai); IAtomType leafType = species.getLeafType(); potentialMaster.addPotential(potential,new IAtomType[]{leafType,leafType}); IVectorMutable offset = space.makeVector(); offset.setX(offsetDim, box.getBoundary().getBoxSize().getX(offsetDim)*0.5); p1ImageHarmonic = new P1ImageHarmonic(space, offset, w, true); potentialMaster.addPotential(p1ImageHarmonic, new IAtomType[]{leafType}); integrator.setBox(box); if (numInnerSteps>0) { ((IntegratorImageHarmonicMD)integrator).setP1Harmonic(p1ImageHarmonic); ((IntegratorImageHarmonicMD)integrator).setNumInnerSteps(numInnerSteps); } else { // ((IntegratorImageHarmonicMD0) integrator).setP1Harmonic(p1ImageHarmonic); } p1ImageHarmonic.setZeroForce(false); ConfigurationLattice config = null; if (crystal == Crystal.FCC) { config = new ConfigurationLattice(new LatticeCubicFcc(space), space); } else if (crystal == Crystal.BCC) { config = new ConfigurationLattice(new LatticeCubicBcc(space), space); } else if (crystal == HCP) { // do nothing -- already done } else { throw new RuntimeException("Don't know how to do "+crystal); } if (config != null) config.initializeCoordinates(box); p1ImageHarmonic.findNOffset(box); integrator.getEventManager().addListener(potentialMaster.getNeighborManager(box)); potentialMaster.getNeighborManager(box).reset(); IVector boxLength = box.getBoundary().getBoxSize(); double lMin = boxLength.getX(0); if (boxLength.getX(1) < lMin) lMin = boxLength.getX(1); if (boxLength.getX(2) < lMin) lMin = boxLength.getX(2); double ww = w / lMin; double swapDistance = 1.5*Math.sqrt(1.5*temperature/ww); if (swapDistance > lMin/4) swapDistance = lMin/4; if (swapDistance > rc) swapDistance = rc; if (swapDistance < 2) swapDistance = 2; PotentialMasterCell potentialMasterCell = new PotentialMasterCell(this, swapDistance, space); potentialMasterCell.setCellRange(2); potentialMasterCell.getNbrCellManager(box).assignCellAll(); mcMoveSwap = new MCMoveAtomSwap(random, potentialMasterCell, space, p1ImageHarmonic); mcMoveSwap.setNbrDistance(swapDistance); IntegratorMC integratorMC = new IntegratorMC(potentialMaster, random, temperature); integrator.setIntegratorMC(integratorMC, 10*numAtoms); integrator.getIntegratorMC().getMoveManager().addMCMove(mcMoveSwap); integrator.getIntegratorMC().getMoveEventManager().addListener(potentialMasterCell.getNbrCellManager(box).makeMCMoveListener()); integrator.setNeighborCellManager(potentialMasterCell.getNbrCellManager(box)); } public static void main(String[] args) { LjMC3DParams params = new LjMC3DParams(); ParseArgs.doParseArgs(params, args); if (args.length==0) { params.graphics = true; params.numAtoms = 1024; params.steps = 1000; params.density = 0.15; params.T = 6000; params.w = 1000; params.crystal = Crystal.BCC; params.offsetDim = 2; params.numInnerSteps = 100; } final int numAtoms = params.numAtoms; final double temperatureK = params.T; final double temperature = Kelvin.UNIT.toSim(temperatureK); final double density = params.density; long steps = params.steps; boolean graphics = params.graphics; double w = params.w; int offsetDim = params.offsetDim; Crystal crystal = params.crystal; int numInnerSteps = params.numInnerSteps; if (!graphics) { System.out.println("Running Iron MC with N="+numAtoms+" at rho="+density+" T="+temperatureK); System.out.println(steps+" steps"); System.out.println("w: "+w); System.out.println(numInnerSteps+" inner steps"); } double L = Math.pow(numAtoms/density, 1.0/3.0); final SimFe sim = new SimFe(crystal, numAtoms, temperature, density, w, offsetDim, numInnerSteps); System.out.println(Arrays.toString(sim.getRandomSeeds())); DataSourceEnergies dsEnergies = new DataSourceEnergies(sim.potentialMaster); dsEnergies.setPotentialCalculation(new DataSourceEnergies.PotentialCalculationEnergiesEAM(sim.potential)); dsEnergies.setBox(sim.box); IData u = dsEnergies.getData(); if (!graphics) System.out.println("Fe lattice energy (eV/atom): "+ElectronVolt.UNIT.fromSim(u.getValue(1)/numAtoms)); MeterStructureFactor meterSfac = new MeterStructureFactor(sim.space, sim.box, 8); if (graphics) { final String APP_NAME = "SimFe"; final SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, APP_NAME, 3, sim.getSpace(), sim.getController()); ColorScheme colorScheme = new ColorScheme() { @Override public Color getAtomColor(IAtom a) { return a.getLeafIndex() < numAtoms/2 ? Color.RED : Color.BLUE; } }; simGraphic.getDisplayBox(sim.box).setColorScheme(colorScheme); DiameterHash diameter = simGraphic.getDisplayBox(sim.box).getDiameterHash(); ((DiameterHashByType)diameter).setDiameter(sim.species.getLeafType(),2); simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box)); DataSourceCountTime tSource = new DataSourceCountTime(sim.integrator); AccumulatorHistory energyHist = new AccumulatorHistory(new HistoryCollapsingAverage()); energyHist.setTimeDataSource(tSource); AccumulatorHistory springHist = new AccumulatorHistory(new HistoryCollapsingAverage()); springHist.setTimeDataSource(tSource); DataSplitter splitter = new DataSplitter(); DataPumpListener energyPump = new DataPumpListener(dsEnergies, splitter, 10); sim.integrator.getEventManager().addListener(energyPump); splitter.setDataSink(0, springHist); splitter.setDataSink(1, energyHist); DisplayPlot energyPlot = new DisplayPlot(); energyPlot.setLabel("Fe"); energyPlot.setUnit(new CompoundUnit(new Unit[]{new SimpleUnit(Null.DIMENSION,1.0/numAtoms,"why do you want a name. just use it.","per atom", false)},new double[]{-1})); // energyPlot.setUnit(new CompoundUnit(new Unit[]{ElectronVolt.UNIT, new SimpleUnit(Null.DIMENSION,1.0/numAtoms,"why do you want a name. just use it.","per atom", false)},new double[]{1,-1})); // energyPlot.setUnit(ElectronVolt.UNIT); energyHist.addDataSink(energyPlot.getDataSet().makeDataSink()); simGraphic.add(energyPlot); DisplayPlot springPlot = new DisplayPlot(); springPlot.setLabel("spring"); springPlot.setUnit(new CompoundUnit(new Unit[]{new SimpleUnit(Null.DIMENSION,1.0/numAtoms,"why do you want a name. just use it.","per atom", false)},new double[]{-1})); springHist.addDataSink(springPlot.getDataSet().makeDataSink()); simGraphic.add(springPlot); MeterKineticEnergy meterKE = new MeterKineticEnergy(); meterKE.setBox(sim.box); AccumulatorHistory keHist = new AccumulatorHistory(); DataPumpListener kePump = new DataPumpListener(meterKE, keHist, 1); // sim.integrator.getEventManager().addListener(kePump); // keHist.addDataSink(energyPlot.getDataSet().makeDataSink()); energyPlot.setLegend(new DataTag[]{energyHist.getTag()}, "u"); // energyPlot.setLegend(new DataTag[]{keHist.getTag()}, "ke"); AccumulatorHistory dudwHist = new AccumulatorHistory(new HistoryCollapsingAverage()); splitter.setDataSink(2, dudwHist); dudwHist.setTimeDataSource(tSource); DisplayPlot dudwPlot = new DisplayPlot(); dudwHist.addDataSink(dudwPlot.getDataSet().makeDataSink()); dudwPlot.setLabel("dudw"); dudwPlot.setUnit(new CompoundUnit(new Unit[]{new SimpleUnit(Null.DIMENSION,1.0/numAtoms,"why do you want a name. just use it.","per atom", false)},new double[]{-1})); simGraphic.add(dudwPlot); AccumulatorAverageFixed avgSfac = new AccumulatorAverageFixed(1); avgSfac.setPushInterval(1); DataPumpListener pumpSfac = new DataPumpListener(meterSfac, avgSfac, 500); sim.integrator.getEventManager().addListener(pumpSfac); DisplayPlot plotSfac = new DisplayPlot(); avgSfac.addDataSink(plotSfac.getDataSet().makeDataSink(), new AccumulatorAverage.StatType[]{avgSfac.AVERAGE}); plotSfac.setLabel("Structure Factor"); plotSfac.setDoDrawLines(new DataTag[]{meterSfac.getTag()},false); plotSfac.getPlot().setYLog(true); simGraphic.add(plotSfac); sim.integrator.setTimeStep(0.0001); sim.integrator.getEventManager().addListener(new IIntegratorListener() { @Override public void integratorInitialized(IIntegratorEvent e) {} @Override public void integratorStepStarted(IIntegratorEvent e) {} @Override public void integratorStepFinished(IIntegratorEvent e) { if (sim.integrator.getStepCount() > 400) { sim.integrator.setTimeStep(0.001); } } }); simGraphic.makeAndDisplayFrame(APP_NAME); return; } // initial conservation of energy is often poor. use a smaller timestep // for a few steps to get off lattice sites sim.ai.setMaxSteps(steps/20); sim.integrator.setTimeStep(0.0001); sim.getController().actionPerformed(); sim.getController().reset(); if (sim.integrator.getHybridAcceptance() < 0.5) { throw new RuntimeException("hybrid acceptance "+sim.integrator.getHybridAcceptance()); } sim.integrator.resetStepCount(); sim.ai.setMaxSteps(steps/20); sim.integrator.setTimeStep(0.0002); sim.getController().actionPerformed(); sim.getController().reset(); if (sim.integrator.getHybridAcceptance() < 0.5) { throw new RuntimeException("hybrid acceptance "+sim.integrator.getHybridAcceptance()); } sim.integrator.resetStepCount(); sim.ai.setMaxSteps(steps/10); sim.integrator.setTimeStep(0.001); sim.getController().actionPerformed(); sim.getController().reset(); if (sim.integrator.getHybridAcceptance() < 0.5) { throw new RuntimeException("hybrid acceptance "+sim.integrator.getHybridAcceptance()); } sim.integrator.resetStepCount(); sim.ai.setMaxSteps(steps); System.out.println("equilibration finished ("+steps/20+"+"+steps/20+"+"+steps/10+" steps)"); long t1 = System.currentTimeMillis(); int interval = 10; long blockSize = steps/100/interval; if (blockSize==0) blockSize = 1; AccumulatorAverageCovariance accEnergies = new AccumulatorAverageCovariance(blockSize); DataPumpListener pumpEnergies = new DataPumpListener(dsEnergies, accEnergies, interval); sim.integrator.getEventManager().addListener(pumpEnergies); sim.getController().actionPerformed(); System.out.println("swap acceptance: "+sim.mcMoveSwap.getTracker().acceptanceProbability()); System.out.println("Hybrid MD/MC acceptance: "+sim.integrator.getHybridAcceptance()); IData avgEnergies = accEnergies.getData(accEnergies.AVERAGE); IData errEnergies = accEnergies.getData(accEnergies.ERROR); IData corEnergies = accEnergies.getData(accEnergies.BLOCK_CORRELATION); IData covEnergies = accEnergies.getData(accEnergies.BLOCK_COVARIANCE); System.out.println("spring energy: "+avgEnergies.getValue(0)/numAtoms+" error: "+errEnergies.getValue(0)/numAtoms+" cor: "+corEnergies.getValue(0)); System.out.println("Fe energy: "+avgEnergies.getValue(1)/numAtoms+" error: "+errEnergies.getValue(1)/numAtoms+" cor: "+corEnergies.getValue(1)); System.out.println("du/dw: "+avgEnergies.getValue(2)/numAtoms+" error: "+errEnergies.getValue(2)/numAtoms+" cor: "+corEnergies.getValue(2)); double cor01 = covEnergies.getValue(0*3+1)/Math.sqrt(covEnergies.getValue(0*3+0)*covEnergies.getValue(1*3+1)); double cor02 = covEnergies.getValue(0*3+2)/Math.sqrt(covEnergies.getValue(0*3+0)*covEnergies.getValue(2*3+2)); System.out.println("spring correlation: 1 "+cor01+" "+cor02); double cor10 = covEnergies.getValue(1*3+0)/Math.sqrt(covEnergies.getValue(1*3+1)*covEnergies.getValue(0*3+0)); double cor12 = covEnergies.getValue(1*3+2)/Math.sqrt(covEnergies.getValue(1*3+1)*covEnergies.getValue(2*3+2)); System.out.println("Fe correlation: "+cor10+" 1 "+cor12); double cor20 = covEnergies.getValue(2*3+0)/Math.sqrt(covEnergies.getValue(2*3+2)*covEnergies.getValue(0*3+0)); double cor21 = covEnergies.getValue(2*3+1)/Math.sqrt(covEnergies.getValue(2*3+2)*covEnergies.getValue(1*3+1)); System.out.println("du/dw correlation: "+cor20+" "+cor21+" 1"); long t2 = System.currentTimeMillis(); System.out.println("time: "+(t2-t1)/1000.0+" seconds"); } enum Crystal {FCC, BCC, HCP} public static class LjMC3DParams extends ParameterBase { public int numAtoms = 500; public double T = 2.0; public double density = 0.3; public long steps = 100000; public double rc = 2.5; public boolean graphics = false; public double w = 1; public int offsetDim = 0; public int numInnerSteps = 10; public Crystal crystal = Crystal.FCC; } }
package raptor.connector.ics.dialog; import org.apache.commons.lang.StringUtils; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Monitor; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import raptor.Raptor; import raptor.international.L10n; import raptor.pref.PreferenceKeys; import raptor.pref.RaptorPreferenceStore; import raptor.util.RaptorLogger; /** * The ics login dialog. */ public class IcsLoginDialog extends Dialog implements PreferenceKeys { private static final RaptorLogger LOG = RaptorLogger.getLog(IcsLoginDialog.class); private static String[] PROFILES = {"Primary", "Secondary", "Tertiary"}; protected Button autoLoginCheckBox; protected Button guestLoginCheckBox; protected Text handleField; protected Label handleLabel; protected String lastSelection; protected Button loginButton; protected Text passwordField; protected Label passwordLabel; protected Text portField; protected Label portLabel; protected Combo profile; protected Label profileLabel; protected String profilePrefix; protected Text serverField; protected Label serverLabel; protected Button simulBugButton; protected Composite content; protected Button timesealEnabledCheckBox; protected String title; protected boolean wasLoginPressed; protected boolean isShowingSimulBug; protected boolean isSimulBugLogin; protected boolean isShowingAutoLogin = true; protected static L10n local = L10n.getInstance(); public IcsLoginDialog(String profilePrefix, String title) { super(Raptor.getInstance().getWindow().getShell()); this.profilePrefix = profilePrefix; this.title = title; } @Override public Composite createContents(Composite parent) { getShell().setText(title); content = new Composite(parent, SWT.NONE); content.setLayout(new GridLayout(2, false)); profileLabel = new Label(content, SWT.NONE); profileLabel.setText(local.getString("icsLoginD0")); profile = new Combo(content, SWT.DROP_DOWN | SWT.READ_ONLY); profile.add(local.getString("icsLoginD1")); profile.add(local.getString("icsLoginD2")); profile.add(local.getString("icsLoginD3")); profile.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String itemSelected = PROFILES[profile.getSelectionIndex()]; storeProfile(lastSelection); loadFromProfile(itemSelected); lastSelection = itemSelected; } }); handleLabel = new Label(content, SWT.NONE); handleLabel.setText(local.getString("icsLoginD4")); handleField = new Text(content, SWT.BORDER); handleField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); passwordLabel = new Label(content, SWT.NONE); passwordLabel.setText(local.getString("icsLoginD5")); passwordField = new Text(content, SWT.BORDER | SWT.PASSWORD); passwordField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); serverLabel = new Label(content, SWT.NONE); serverLabel.setText(local.getString("icsLoginD6")); serverField = new Text(content, SWT.BORDER); serverField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); portLabel = new Label(content, SWT.NONE); portLabel.setText(local.getString("icsLoginD7")); portField = new Text(content, SWT.BORDER); portField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); guestLoginCheckBox = new Button(content, SWT.CHECK); guestLoginCheckBox.setText(local.getString("icsLoginD8")); GridData data = new GridData(); data.horizontalSpan = 2; guestLoginCheckBox.setLayoutData(data); timesealEnabledCheckBox = new Button(content, SWT.CHECK); timesealEnabledCheckBox.setText(local.getString("icsLoginD9")); data = new GridData(); data.horizontalSpan = 2; timesealEnabledCheckBox.setLayoutData(data); if (isShowingAutoLogin) { autoLoginCheckBox = new Button(content, SWT.CHECK); autoLoginCheckBox.setText(local.getString("icsLoginD10")); data = new GridData(); data.horizontalSpan = 2; autoLoginCheckBox.setLayoutData(data); } if (isShowingSimulBug()) { simulBugButton = new Button(content, SWT.CHECK); simulBugButton.setText(local.getString("icsLoginD11")); data = new GridData(); data.horizontalSpan = 2; simulBugButton.setLayoutData(data); } loginButton = new Button(content, SWT.PUSH); loginButton.setText(local.getString("icsLoginD12")); data = new GridData(); data.horizontalSpan = 2; data.horizontalAlignment = SWT.CENTER; loginButton.setLayoutData(data); SelectionListener selectionListener = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (e.widget == guestLoginCheckBox || e.widget == timesealEnabledCheckBox) { adjustToCheckBoxControls(); } else if (e.widget == loginButton) { processLogin(); } } }; KeyListener keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == '\r' || e.character == '\r') { processLogin(); } } }; // Commented out because it doesn't allow for enter key login with GTK like I thought it would. // In OSX the selection box can't get focus, but in Linux it can which is a pain. //profile.addKeyListener(keyListener); //profile.addSelectionListener(selectionListener); handleField.addKeyListener(keyListener); passwordField.addKeyListener(keyListener); serverField.addKeyListener(keyListener); portField.addKeyListener(keyListener); guestLoginCheckBox.addKeyListener(keyListener); guestLoginCheckBox.addSelectionListener(selectionListener); timesealEnabledCheckBox.addKeyListener(keyListener); timesealEnabledCheckBox.addSelectionListener(selectionListener); // if statement needed to allow "another simultaneous connection" if (autoLoginCheckBox != null) { autoLoginCheckBox.addKeyListener(keyListener); } loginButton.addSelectionListener(selectionListener); String currentProfile = Raptor.getInstance().getPreferences() .getString(profilePrefix + "profile"); lastSelection = currentProfile; loadFromProfile(currentProfile); int selectedIndex = 0; for (int i = 0; i < PROFILES.length; i++) { if (StringUtils.equals(PROFILES[i], currentProfile)) { selectedIndex = i; break; } } profile.select(selectedIndex); adjustToCheckBoxControls(); content.pack(); parent.pack(); return content; } public void processLogin() { String handleText = handleField.getText(); String passwordText = passwordField.getText(); if (StringUtils.isNotEmpty(handleText) && (handleText.length() < 3 || handleText.length() > 17)) { MessageBox box = new MessageBox(content.getShell(), SWT.ERROR | SWT.OK); box .setMessage(local.getString("icsLoginD14")); box.setText(local.getString("icsLoginD15")); box.open(); } else if (StringUtils.isNotBlank(handleText) && !handleText.matches("[a-zA-Z]*")) { MessageBox box = new MessageBox(content.getShell(), SWT.ERROR | SWT.OK); box.setMessage(local.getString("icsLoginD17")); box.setText(local.getString("icsLoginD18")); box.open(); } else if (!guestLoginCheckBox.getSelection() && StringUtils.isBlank(handleText)) { MessageBox box = new MessageBox(content.getShell(), SWT.ERROR | SWT.OK); box .setMessage(local.getString("icsLoginD19")); box.setText(local.getString("icsLoginD20")); box.open(); } else if (!guestLoginCheckBox.getSelection() && StringUtils.isBlank(passwordText)) { MessageBox box = new MessageBox(content.getShell(), SWT.ERROR | SWT.OK); box .setMessage(local.getString("icsLoginD21")); box.setText(local.getString("icsLoginD22")); box.open(); } else { String itemSelected = PROFILES[profile.getSelectionIndex()]; lastSelection = itemSelected; storeProfile(itemSelected); try { Raptor.getInstance().getPreferences().save(); } catch (Throwable t) { } wasLoginPressed = true; if (isShowingSimulBug()) { isSimulBugLogin = simulBugButton.getSelection(); } close(); } } public boolean isShowingAutoLogin() { return isShowingAutoLogin; } public void setShowingAutoLogin(boolean isShowingAutoLogin) { this.isShowingAutoLogin = isShowingAutoLogin; } public String getSelectedProfile() { return lastSelection; } public boolean isShowingSimulBug() { return isShowingSimulBug; } public boolean isSimulBugLogin() { return isSimulBugLogin; } @Override public int open() { return super.open(); } public void setShowingSimulBug(boolean isShowingSimulBug) { this.isShowingSimulBug = isShowingSimulBug; } public void setSimulBugLogin(boolean isSimulBugLogin) { this.isSimulBugLogin = isSimulBugLogin; } public boolean wasLoginPressed() { return wasLoginPressed; } protected void adjustToCheckBoxControls() { if (guestLoginCheckBox.getSelection()) { passwordField.setText(""); passwordLabel.setEnabled(false); passwordField.setEnabled(false); handleLabel.setEnabled(true); handleField.setEnabled(true); } else { passwordLabel.setEnabled(true); passwordField.setEnabled(true); handleLabel.setEnabled(true); handleField.setEnabled(true); } } @Override protected void initializeBounds() { super.initializeBounds(); Shell shell = getShell(); Monitor primary = shell.getMonitor(); Rectangle bounds = primary.getBounds(); Rectangle rect = shell.getBounds(); int x = bounds.x + (bounds.width - rect.width) / 2; int y = bounds.y + (bounds.height - rect.height) / 2; shell.setLocation(x, y); } protected void loadFromProfile(String profileName) { RaptorPreferenceStore prefs = Raptor.getInstance().getPreferences(); String prefix = profilePrefix + profileName + "-"; handleField.setText(prefs.getString(prefix + "user-name")); serverField.setText(prefs.getString(prefix + "server-url")); portField.setText(prefs.getString(prefix + "port")); passwordField.setText(prefs.getString(prefix + "password")); guestLoginCheckBox.setSelection(prefs.getBoolean(prefix + "is-anon-guest") || prefs.getBoolean(prefix + "is-named-guest")); timesealEnabledCheckBox.setSelection(prefs.getBoolean(prefix + "timeseal-enabled")); if (autoLoginCheckBox != null) { autoLoginCheckBox.setSelection(prefs.getBoolean(profilePrefix + "auto-connect")); } LOG.info("Loaded loadFromProfile " + profileName); adjustToCheckBoxControls(); } protected void storeProfile(String profileName) { RaptorPreferenceStore prefs = Raptor.getInstance().getPreferences(); String prefix = profilePrefix + profileName + "-"; prefs.setValue(prefix + "user-name", StringUtils .defaultString(handleField.getText())); prefs.setValue(prefix + "server-url", StringUtils .defaultString(serverField.getText())); prefs.setValue(prefix + "password", StringUtils .defaultString(passwordField.getText())); try { prefs.setValue(prefix + "port", Integer.parseInt(StringUtils .defaultString(portField.getText()))); } catch (NumberFormatException nfe) { } prefs.setValue(prefix + "is-named-guest", guestLoginCheckBox .getSelection() && StringUtils.isNotBlank(handleField.getText())); prefs.setValue(prefix + "is-anon-guest", guestLoginCheckBox .getSelection() && StringUtils.isBlank(handleField.getText())); prefs.setValue(prefix + "timeseal-enabled", timesealEnabledCheckBox .getSelection()); if (autoLoginCheckBox != null) { prefs.setValue(profilePrefix + "auto-connect", autoLoginCheckBox .getSelection()); } // Don't store off the the profileName-profile here. // It should'nt be stored for fics2/bics2 logins. prefs.save(); LOG.info("Saved " + profileName); } }
package nl.mpi.kinnate.svg; import java.awt.BorderLayout; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.AffineTransform; import java.awt.geom.Dimension2D; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import javax.swing.JPanel; import javax.xml.parsers.DocumentBuilderFactory; import nl.mpi.arbil.data.ArbilComponentBuilder; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.userstorage.SessionStorage; import nl.mpi.arbil.util.BugCatcherManager; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.entityindexer.IndexerParameters; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.GraphSorter; import nl.mpi.kinnate.kintypestrings.KinTermGroup; import nl.mpi.kinnate.ui.GraphPanelContextMenu; import nl.mpi.kinnate.ui.KinDiagramPanel; import nl.mpi.kinnate.ui.MetadataPanel; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.apache.batik.bridge.UpdateManager; import org.apache.batik.dom.svg.SAXSVGDocumentFactory; import org.apache.batik.dom.svg.SVGDOMImplementation; import org.apache.batik.dom.util.SAXIOException; import org.apache.batik.swing.JSVGCanvas; import org.apache.batik.swing.JSVGScrollPane; import org.apache.batik.util.XMLResourceDescriptor; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.events.EventTarget; import org.w3c.dom.svg.SVGDocument; public class GraphPanel extends JPanel implements SavePanel { private JSVGScrollPane jSVGScrollPane; protected JSVGCanvas svgCanvas; protected SVGDocument doc; public MetadataPanel metadataPanel; private boolean requiresSave = false; private File svgFile = null; public GraphPanelSize graphPanelSize; protected ArrayList<UniqueIdentifier> selectedGroupId; protected String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI; public DataStoreSvg dataStoreSvg; public EntitySvg entitySvg; // private URI[] egoPathsTemp = null; public SvgUpdateHandler svgUpdateHandler; public MouseListenerSvg mouseListenerSvg; private MessageDialogHandler dialogHandler; private SessionStorage sessionStorage; // private EntityCollection entityCollection; final KinDiagramPanel kinDiagramPanel; public GraphPanel(KinDiagramPanel kinDiagramPanel, final ArbilWindowManager arbilWindowManager, SessionStorage sessionStorage, EntityCollection entityCollection, ArbilDataNodeLoader dataNodeLoader) { this.kinDiagramPanel = kinDiagramPanel; this.dialogHandler = arbilWindowManager; this.sessionStorage = sessionStorage; // this.entityCollection = entityCollection; dataStoreSvg = new DataStoreSvg(); entitySvg = new EntitySvg(dialogHandler); dataStoreSvg.setDefaults(); svgUpdateHandler = new SvgUpdateHandler(this, kinDiagramPanel, dialogHandler); selectedGroupId = new ArrayList<UniqueIdentifier>(); graphPanelSize = new GraphPanelSize(); this.setLayout(new BorderLayout()); boolean eventsEnabled = true; boolean selectableText = false; svgCanvas = new JSVGCanvas(new GraphUserAgent(this, dialogHandler, dataNodeLoader), eventsEnabled, selectableText); // svgCanvas.setMySize(new Dimension(600, 400)); svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC); // drawNodes(); svgCanvas.setEnableImageZoomInteractor(false); svgCanvas.setEnablePanInteractor(false); svgCanvas.setEnableRotateInteractor(false); svgCanvas.setEnableZoomInteractor(false); svgCanvas.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(final MouseWheelEvent e) { UpdateManager updateManager = svgCanvas.getUpdateManager(); if (updateManager != null) { updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { double scale = 1 - e.getUnitsToScroll() / 10.0; double tx = -e.getX() * (scale - 1); double ty = -e.getY() * (scale - 1); // System.out.println("scale: " + scale); // System.out.println("scale: " + svgCanvas.getRenderingTransform().getScaleX()); AffineTransform at = new AffineTransform(); if (e.isAltDown()) { at.translate(tx, ty); at.scale(scale, scale); } else if (e.isShiftDown()) { at.translate(tx, 0); } else { at.translate(0, ty); } at.concatenate(svgCanvas.getRenderingTransform()); // System.out.println("new scale: " + at.getScaleX()); if (at.getScaleX() > 0.1) { svgCanvas.setRenderingTransform(at); } } }); } e.consume(); // show a ToolTip or StatusBar to give hints "Hold modifier + mouse wheel to zoom" GraphPanel.this.kinDiagramPanel.setStatusBarText("hint: alt + mouse wheel to zoom; shift + mouse wheel to pan; mouse wheel to scroll."); } }); // svgCanvas.setEnableResetTransformInteractor(true); // svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas mouseListenerSvg = new MouseListenerSvg(kinDiagramPanel, this, sessionStorage, dialogHandler, entityCollection); svgCanvas.addMouseListener(mouseListenerSvg); svgCanvas.addMouseMotionListener(mouseListenerSvg); jSVGScrollPane = new JSVGScrollPane(svgCanvas); // svgCanvas.setBackground(Color.LIGHT_GRAY); this.add(BorderLayout.CENTER, jSVGScrollPane); svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(kinDiagramPanel, this, entityCollection, arbilWindowManager, dataNodeLoader, sessionStorage)); } // private void zoomDrawing() { // AffineTransform scaleTransform = new AffineTransform(); // scaleTransform.scale(1 - currentZoom / 10.0, 1 - currentZoom / 10.0); // System.out.println("currentZoom: " + currentZoom); //// svgCanvas.setRenderingTransform(scaleTransform); // Rectangle canvasBounds = this.getBounds(); // SVGRect bbox = ((SVGLocatable) doc.getRootElement()).getBBox(); // if (bbox != null) { // System.out.println("previousZoomedWith: " + bbox.getWidth()); //// SVGElement rootElement = doc.getRootElement(); //// if (currentWidth < canvasBounds.width) { // float drawingCenter = (currentWidth / 2); //// float drawingCenter = (bbox.getX() + (bbox.getWidth() / 2)); // float canvasCenter = (canvasBounds.width / 2); // zoomAffineTransform = new AffineTransform(); // zoomAffineTransform.translate((canvasCenter - drawingCenter), 1); // zoomAffineTransform.concatenate(scaleTransform); // svgCanvas.setRenderingTransform(zoomAffineTransform); public void setArbilTableModel(MetadataPanel metadataPanel) { this.metadataPanel = metadataPanel; } public void readSvg(URI svgFilePath, boolean savableType) { if (savableType) { svgFile = new File(svgFilePath); } else { svgFile = null; } String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser); try { doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toString()); svgCanvas.setDocument(doc); dataStoreSvg = DataStoreSvg.loadDataFromSvg(doc); if (dataStoreSvg.indexParameters == null) { dataStoreSvg.setDefaults(); } requiresSave = false; entitySvg.readEntityPositions(doc.getElementById("EntityGroup")); entitySvg.readEntityPositions(doc.getElementById("LabelsGroup")); entitySvg.readEntityPositions(doc.getElementById("GraphicsGroup")); configureDiagramGroups(); dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace)); // if (dataStoreSvg.graphData == null) { // return null; } catch (SAXIOException exception) { dialogHandler.addMessageDialogToQueue("Cannot open the diagram: " + exception.getMessage(), "Open Diagram"); } catch (IOException exception) { dialogHandler.addMessageDialogToQueue("Cannot open the diagram: " + exception.getMessage(), "Open Diagram"); } // svgCanvas.setSVGDocument(doc); return; // dataStoreSvg.graphData.getDataNodes(); } private void configureDiagramGroups() { Element svgRoot = doc.getDocumentElement(); // make sure the diagram group exisits Element diagramGroup = doc.getElementById("DiagramGroup"); if (diagramGroup == null) { diagramGroup = doc.createElementNS(svgNameSpace, "g"); diagramGroup.setAttribute("id", "DiagramGroup"); // add the diagram group to the root element (the 'svg' element) svgRoot.appendChild(diagramGroup); } Element previousElement = null; // add the graphics group below the entities and relations // add the relation symbols in a group below the relation lines // add the entity symbols in a group on top of the relation lines // add the labels group on top, also added on svg load if missing for (String groupForMouseListener : new String[]{"LabelsGroup", "EntityGroup", "RelationGroup", "GraphicsGroup"}) { // add any groups that are required and add them in the required order Element parentElement = doc.getElementById(groupForMouseListener); if (parentElement == null) { parentElement = doc.createElementNS(svgNameSpace, "g"); parentElement.setAttribute("id", groupForMouseListener); diagramGroup.insertBefore(parentElement, previousElement); } else { diagramGroup.insertBefore(parentElement, previousElement); // insert the node to make sure that it is in the diagram group and not in any other location // set up the mouse listeners that were lost in the save/re-open process if (!groupForMouseListener.equals("RelationGroup")) { // do not add mouse listeners to the relation group Node currentNode = parentElement.getFirstChild(); while (currentNode != null) { ((EventTarget) currentNode).addEventListener("mousedown", mouseListenerSvg, false); currentNode = currentNode.getNextSibling(); } } } previousElement = parentElement; } } public void generateDefaultSvg() { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); // set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places // in order to add the extra namespaces to the svg document we use a string and parse it // other methods have been tried but this is the most readable and the only one that actually works // I think this is mainly due to the way the svg dom would otherwise be constructed // others include: // doc.getDomConfig() // doc.getDocumentElement().setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:version", ""); // doc.getDocumentElement().setAttribute("xmlns:" + DataStoreSvg.kinDataNameSpace, DataStoreSvg.kinDataNameSpaceLocation); // this method of declaring multiple namespaces looks to me to be wrong but it is the only method that does not get stripped out by the transformer on save // Document doc = impl.createDocument(svgNS, "svg", null); // SVGDocument doc = svgCanvas.getSVGDocument(); String templateXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<svg xmlns:xlink=\"http: + "xmlns=\"http: + " zoomAndPan=\"magnify\" contentStyleType=\"text/css\" " + "preserveAspectRatio=\"xMidYMid meet\" version=\"1.0\"/>"; // DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); // doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null); String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser); doc = (SVGDocument) documentFactory.createDocument(svgNameSpace, new StringReader(templateXml)); entitySvg.insertSymbols(doc, svgNameSpace); configureDiagramGroups(); dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace)); svgCanvas.setSVGDocument(doc); dataStoreSvg.graphData = new GraphSorter(); } catch (IOException exception) { BugCatcherManager.getBugCatcher().logError(exception); } } private void saveSvg(File svgFilePath) { svgFile = svgFilePath; selectedGroupId.clear(); svgUpdateHandler.clearHighlights(); // make sure that any data changes such as the title/description in the kin term groups get updated into the file on save dataStoreSvg.storeAllData(doc); ArbilComponentBuilder.savePrettyFormatting(doc, svgFile); requiresSave = false; } private void printNodeNames(Node nodeElement) { System.out.println(nodeElement.getLocalName()); System.out.println(nodeElement.getNamespaceURI()); Node childNode = nodeElement.getFirstChild(); while (childNode != null) { printNodeNames(childNode); childNode = childNode.getNextSibling(); } } public String[] getKinTypeStrigs() { return dataStoreSvg.kinTypeStrings; } public void setKinTypeStrigs(String[] kinTypeStringArray) { // strip out any white space, blank lines and remove duplicates // this has set has been removed because it creates a discrepancy between what the user types and what is processed // HashSet<String> kinTypeStringSet = new HashSet<String>(); // for (String kinTypeString : kinTypeStringArray) { // if (kinTypeString != null && kinTypeString.trim().length() > 0) { // kinTypeStringSet.add(kinTypeString.trim()); // dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{}); dataStoreSvg.kinTypeStrings = kinTypeStringArray; } public IndexerParameters getIndexParameters() { return dataStoreSvg.indexParameters; } public KinTermGroup[] getkinTermGroups() { return dataStoreSvg.kinTermGroups; } public KinTermGroup addKinTermGroup() { ArrayList<KinTermGroup> kinTermsList = new ArrayList<KinTermGroup>(Arrays.asList(dataStoreSvg.kinTermGroups)); final KinTermGroup kinTermGroup = new KinTermGroup(); kinTermsList.add(kinTermGroup); dataStoreSvg.kinTermGroups = kinTermsList.toArray(new KinTermGroup[]{}); return kinTermGroup; } // public String[] getEgoUniquiIdentifiersList() { // return dataStoreSvg.egoIdentifierSet.toArray(new String[]{}); // public String[] getEgoIdList() { // return dataStoreSvg.egoIdentifierSet.toArray(new String[]{}); // public URI[] getEgoPaths() { // if (egoPathsTemp != null) { // return egoPathsTemp; // ArrayList<URI> returnPaths = new ArrayList<URI>(); // for (String egoId : dataStoreSvg.egoIdentifierSet) { // try { // String entityPath = getPathForElementId(egoId); //// if (entityPath != null) { // returnPaths.add(new URI(entityPath)); // } catch (URISyntaxException ex) { // GuiHelper.linorgBugCatcher.logError(ex); // // todo: warn user with a dialog // return returnPaths.toArray(new URI[]{}); // public void setRequiredEntities(URI[] egoPathArray, String[] egoIdentifierArray) { //// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements) // dataStoreSvg.requiredEntities = new HashSet<String>(Arrays.asList(egoIdentifierArray)); // public void addRequiredEntity(URI[] egoPathArray, String[] egoIdentifierArray) { //// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements) // dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray)); // public void removeEgo(String[] egoIdentifierArray) { // dataStoreSvg.egoIdentifierSet.removeAll(Arrays.asList(egoIdentifierArray)); public void setSelectedIds(UniqueIdentifier[] uniqueIdentifiers) { selectedGroupId.clear(); selectedGroupId.addAll(Arrays.asList(uniqueIdentifiers)); svgUpdateHandler.updateSvgSelectionHighlights(); // pan the diagram so that the selected are in the center svgUpdateHandler.panToSelected(uniqueIdentifiers); // mouseListenerSvg.updateSelectionDisplay(); } public UniqueIdentifier[] getSelectedIds() { return selectedGroupId.toArray(new UniqueIdentifier[]{}); } public EntityData getEntityForElementId(UniqueIdentifier uniqueIdentifier) { for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) { if (uniqueIdentifier.equals(entityData.getUniqueIdentifier())) { return entityData; } } return null; } public HashMap<UniqueIdentifier, EntityData> getEntitiesById(UniqueIdentifier[] uniqueIdentifiers) { ArrayList<UniqueIdentifier> identifierList = new ArrayList<UniqueIdentifier>(Arrays.asList(uniqueIdentifiers)); HashMap<UniqueIdentifier, EntityData> returnMap = new HashMap<UniqueIdentifier, EntityData>(); for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) { if (identifierList.contains(entityData.getUniqueIdentifier())) { returnMap.put(entityData.getUniqueIdentifier(), entityData); } } return returnMap; } // public boolean selectionContainsEgo() { // for (String selectedId : selectedGroupId) { // if (dataStoreSvg.egoIdentifierSet.contains(selectedId)) { // return true; // return false; public String getPathForElementId(UniqueIdentifier elementId) { // NamedNodeMap namedNodeMap = doc.getElementById(elementId).getAttributes(); // for (int attributeCounter = 0; attributeCounter < namedNodeMap.getLength(); attributeCounter++) { // System.out.println(namedNodeMap.item(attributeCounter).getNodeName()); // System.out.println(namedNodeMap.item(attributeCounter).getNamespaceURI()); // System.out.println(namedNodeMap.item(attributeCounter).getNodeValue()); Element entityElement = doc.getElementById(elementId.getAttributeIdentifier()); if (entityElement == null) { return null; } else { return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path"); } } public String getKinTypeForElementId(UniqueIdentifier elementId) { Element entityElement = doc.getElementById(elementId.getAttributeIdentifier()); if (entityElement != null) { return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kintype"); } else { return ""; } } public Dimension2D getDiagramSize() { return svgCanvas.getSVGDocumentSize(); // Element svgRoot = doc.getDocumentElement(); // String widthString = svgRoot.getAttribute("width"); // String heightString = svgRoot.getAttribute("height"); // return new Point(Integer.parseInt(widthString), Integer.parseInt(widthString)); } public void resetZoom() { svgUpdateHandler.requestResize(); } public void resetLayout() { // this requires that the entity data is loaded by recalculating the diagram at least once entitySvg = new EntitySvg(dialogHandler); dataStoreSvg.graphData.clearPreferredEntityLocations(); dataStoreSvg.graphData.setEntitys(dataStoreSvg.graphData.getDataNodes()); try { dataStoreSvg.graphData.placeAllNodes(entitySvg.entityPositions); drawNodes(); } catch (GraphSorter.UnsortablePointsException exception) { dialogHandler.addMessageDialogToQueue(exception.getMessage(), "Error, the graph is unsortable."); } } public UniqueIdentifier[] getDiagramUniqueIdentifiers() { return entitySvg.entityPositions.keySet().toArray(new UniqueIdentifier[0]); } public void clearEntityLocations(UniqueIdentifier[] selectedIdentifiers) { // all entity locations are now stored as preferred locations when the graph sorter completes // // change the entities stored location into a preferred location rather than a fixed location // for (UniqueIdentifier uniqueIdentifier : selectedIdentifiers) { // final Point entityLocation = entitySvg.getEntityLocation(uniqueIdentifier); // if (entityLocation != null) { // dataStoreSvg.graphData.setPreferredEntityLocation(new UniqueIdentifier[]{uniqueIdentifier}, entityLocation); entitySvg.clearEntityLocations(selectedIdentifiers); } public void drawNodes() { requiresSave = true; selectedGroupId.clear(); svgUpdateHandler.updateEntities(); } public void drawNodes(GraphSorter graphDataLocal) { kinDiagramPanel.setStatusBarText(graphDataLocal.getDataNodes().length + " entities shown"); dataStoreSvg.graphData = graphDataLocal; drawNodes(); if (graphDataLocal.getDataNodes().length == 0) { // if all entities have been removed then reset the zoom so that new nodes are going to been centered // todo: it would be better to move the window to cover the drawing area but not change the zoom // resetZoom(); } } public boolean hasSaveFileName() { return svgFile != null; } public File getFileName() { return svgFile; } public boolean requiresSave() { return requiresSave; } public void setRequiresSave() { requiresSave = true; } public void saveToFile() { saveSvg(svgFile); } public void saveToFile(File saveAsFile) { saveSvg(saveAsFile); } public void updateGraph() { throw new UnsupportedOperationException("Not supported yet."); } public void doActionCommand(MouseListenerSvg.ActionCode actionCode) { throw new UnsupportedOperationException("Not supported yet."); } public GraphPanel getGraphPanel() { return this; } }
package org.jetbrains.plugins.ipnb.format; import com.google.common.collect.Lists; import com.google.gson.*; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonWriter; import com.intellij.execution.ExecutionException; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.text.VersionComparatorUtil; import com.jetbrains.python.packaging.PyPackage; import com.jetbrains.python.packaging.PyPackageManager; import com.jetbrains.python.sdk.PythonSdkType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.ipnb.editor.panels.IpnbEditablePanel; import org.jetbrains.plugins.ipnb.editor.panels.IpnbFilePanel; import org.jetbrains.plugins.ipnb.format.cells.*; import org.jetbrains.plugins.ipnb.format.cells.output.*; import java.io.*; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.*; public class IpnbParser { private static final Logger LOG = Logger.getInstance(IpnbParser.class); private static final Gson gson = initGson(); @NotNull private static Gson initGson() { final GsonBuilder builder = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().registerTypeAdapter(IpnbCellRaw.class, new RawCellAdapter()) .registerTypeAdapter(IpnbFileRaw.class, new FileAdapter()).registerTypeAdapter(CellOutputRaw.class, new OutputsAdapter()) .registerTypeAdapter(OutputDataRaw.class, new OutputDataAdapter()) .registerTypeAdapter(CellOutputRaw.class, new CellOutputDeserializer()) .registerTypeAdapter(OutputDataRaw.class, new OutputDataDeserializer()) .registerTypeAdapter(IpnbCellRaw.class, new CellRawDeserializer()).serializeNulls(); return builder.create(); } @NotNull public static IpnbFile parseIpnbFile(@NotNull final CharSequence fileText, @NotNull final VirtualFile virtualFile) throws IOException { final String path = virtualFile.getPath(); IpnbFileRaw rawFile = gson.fromJson(fileText.toString(), IpnbFileRaw.class); if (rawFile == null) { int nbformat = isIpythonNewFormat(virtualFile) ? 4 : 3; return new IpnbFile(Collections.emptyMap(), nbformat, Lists.newArrayList(), path); } List<IpnbCell> cells = new ArrayList<IpnbCell>(); final IpnbWorksheet[] worksheets = rawFile.worksheets; if (worksheets == null) { for (IpnbCellRaw rawCell : rawFile.cells) { cells.add(rawCell.createCell()); } } else { for (IpnbWorksheet worksheet : worksheets) { final List<IpnbCellRaw> rawCells = worksheet.cells; for (IpnbCellRaw rawCell : rawCells) { cells.add(rawCell.createCell()); } } } return new IpnbFile(rawFile.metadata, rawFile.nbformat, cells, path); } public static boolean isIpythonNewFormat(@NotNull final VirtualFile virtualFile) { final Project project = ProjectUtil.guessProjectForFile(virtualFile); if (project != null) { final Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile); if (module != null) { final Sdk sdk = PythonSdkType.findPythonSdk(module); if (sdk != null) { try { final PyPackage ipython = PyPackageManager.getInstance(sdk).findPackage("ipython", true); if (ipython != null && VersionComparatorUtil.compare(ipython.getVersion(), "3.0") <= 0) { return false; } } catch (ExecutionException ignored) { } } } } return true; } @NotNull public static IpnbFile parseIpnbFile(@NotNull Document document, @NotNull final VirtualFile virtualFile) throws IOException { return parseIpnbFile(document.getImmutableCharSequence(), virtualFile); } public static void saveIpnbFile(@NotNull final IpnbFilePanel ipnbPanel) { final String json = newDocumentText(ipnbPanel); if (json == null) return; writeToFile(ipnbPanel.getIpnbFile().getPath(), json); } @Nullable public static String newDocumentText(@NotNull final IpnbFilePanel ipnbPanel) { final IpnbFile ipnbFile = ipnbPanel.getIpnbFile(); if (ipnbFile == null) return null; for (IpnbEditablePanel panel : ipnbPanel.getIpnbPanels()) { if (panel.isModified()) { panel.updateCellSource(); } } final IpnbFileRaw fileRaw = new IpnbFileRaw(); fileRaw.metadata = ipnbFile.getMetadata(); if (ipnbFile.getNbformat() == 4) { for (IpnbCell cell: ipnbFile.getCells()) { fileRaw.cells.add(IpnbCellRaw.fromCell(cell, ipnbFile.getNbformat())); } } else { final IpnbWorksheet worksheet = new IpnbWorksheet(); worksheet.cells.clear(); for (IpnbCell cell : ipnbFile.getCells()) { worksheet.cells.add(IpnbCellRaw.fromCell(cell, ipnbFile.getNbformat())); } fileRaw.worksheets = new IpnbWorksheet[]{worksheet}; } final StringWriter stringWriter = new StringWriter(); final JsonWriter writer = new JsonWriter(stringWriter); writer.setIndent(" "); gson.toJson(fileRaw, fileRaw.getClass(), writer); return stringWriter.toString(); } private static void writeToFile(@NotNull final String path, @NotNull final String json) { final File file = new File(path); try { final FileOutputStream fileOutputStream = new FileOutputStream(file); final OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8").newEncoder()); try { writer.write(json); } catch (IOException e) { LOG.error(e); } finally { try { writer.close(); fileOutputStream.close(); } catch (IOException e) { LOG.error(e); } } } catch (FileNotFoundException e) { LOG.error(e); } } @SuppressWarnings("unused") public static class IpnbFileRaw { IpnbWorksheet[] worksheets; List<IpnbCellRaw> cells = new ArrayList<IpnbCellRaw>(); Map<String, Object> metadata = new HashMap<String, Object>(); int nbformat = 4; int nbformat_minor; } private static class IpnbWorksheet { List<IpnbCellRaw> cells = new ArrayList<IpnbCellRaw>(); } @SuppressWarnings("unused") private static class IpnbCellRaw { String cell_type; Integer execution_count; Map<String, Object> metadata = new HashMap<String, Object>(); Integer level; List<CellOutputRaw> outputs; List<String> source; List<String> input; String language; Integer prompt_number; public static IpnbCellRaw fromCell(@NotNull final IpnbCell cell, int nbformat) { final IpnbCellRaw raw = new IpnbCellRaw(); if (cell instanceof IpnbEditableCell) { raw.metadata = ((IpnbEditableCell)cell).getMetadata(); } if (cell instanceof IpnbMarkdownCell) { raw.cell_type = "markdown"; raw.source = ((IpnbMarkdownCell)cell).getSource(); } else if (cell instanceof IpnbCodeCell) { raw.cell_type = "code"; final ArrayList<CellOutputRaw> outputRaws = new ArrayList<CellOutputRaw>(); for (IpnbOutputCell outputCell : ((IpnbCodeCell)cell).getCellOutputs()) { outputRaws.add(CellOutputRaw.fromOutput(outputCell, nbformat)); } raw.outputs = outputRaws; final Integer promptNumber = ((IpnbCodeCell)cell).getPromptNumber(); if (nbformat == 4) { raw.execution_count = promptNumber != null && promptNumber >= 0 ? promptNumber : null; raw.source = ((IpnbCodeCell)cell).getSource(); } else { raw.prompt_number = promptNumber != null && promptNumber >= 0 ? promptNumber : null; raw.language = ((IpnbCodeCell)cell).getLanguage(); raw.input = ((IpnbCodeCell)cell).getSource(); } } else if (cell instanceof IpnbRawCell) { raw.cell_type = "raw"; raw.source = ((IpnbRawCell)cell).getSource(); } else if (cell instanceof IpnbHeadingCell) { raw.cell_type = "heading"; raw.source = ((IpnbHeadingCell)cell).getSource(); raw.level = ((IpnbHeadingCell)cell).getLevel(); } return raw; } public IpnbCell createCell() { final IpnbCell cell; if (cell_type.equals("markdown")) { cell = new IpnbMarkdownCell(source, metadata); } else if (cell_type.equals("code")) { final List<IpnbOutputCell> outputCells = new ArrayList<IpnbOutputCell>(); for (CellOutputRaw outputRaw : outputs) { outputCells.add(outputRaw.createOutput()); } final Integer prompt = prompt_number != null ? prompt_number : execution_count; cell = new IpnbCodeCell(language == null ? "python" : language, input == null ? source : input, prompt, outputCells, metadata); } else if (cell_type.equals("raw")) { cell = new IpnbRawCell(source); } else if (cell_type.equals("heading")) { cell = new IpnbHeadingCell(source, level, metadata); } else { cell = null; } return cell; } } private static class CellOutputRaw { String ename; String name; String evalue; OutputDataRaw data; Integer execution_count; String png; String stream; String jpeg; List<String> html; List<String> latex; List<String> svg; Integer prompt_number; List<String> traceback; Map<String, Object> metadata; String output_type; List<String> text; public static CellOutputRaw fromOutput(@NotNull final IpnbOutputCell outputCell, int nbformat) { final CellOutputRaw raw = new CellOutputRaw(); raw.metadata = outputCell.getMetadata(); if (raw.metadata == null && !(outputCell instanceof IpnbStreamOutputCell) && !(outputCell instanceof IpnbErrorOutputCell)) { raw.metadata = Collections.emptyMap(); } if (outputCell instanceof IpnbPngOutputCell) { if (nbformat == 4) { final OutputDataRaw dataRaw = new OutputDataRaw(); dataRaw.png = ((IpnbPngOutputCell)outputCell).getBase64String(); dataRaw.text = outputCell.getText(); raw.data = dataRaw; raw.execution_count = outputCell.getPromptNumber(); raw.output_type = outputCell.getPromptNumber() != null ? "execute_result" : "display_data"; } else { raw.png = ((IpnbPngOutputCell)outputCell).getBase64String(); raw.text = outputCell.getText(); } } else if (outputCell instanceof IpnbSvgOutputCell) { if (nbformat == 4) { final OutputDataRaw dataRaw = new OutputDataRaw(); dataRaw.text = outputCell.getText(); dataRaw.svg = ((IpnbSvgOutputCell)outputCell).getSvg(); raw.data = dataRaw; raw.execution_count = outputCell.getPromptNumber(); raw.output_type = outputCell.getPromptNumber() != null ? "execute_result" : "display_data"; } else { raw.svg = ((IpnbSvgOutputCell)outputCell).getSvg(); raw.text = outputCell.getText(); } } else if (outputCell instanceof IpnbJpegOutputCell) { if (nbformat == 4) { final OutputDataRaw dataRaw = new OutputDataRaw(); dataRaw.text = outputCell.getText(); dataRaw.jpeg = Lists.newArrayList(((IpnbJpegOutputCell)outputCell).getBase64String()); raw.data = dataRaw; } else { raw.jpeg = ((IpnbJpegOutputCell)outputCell).getBase64String(); raw.text = outputCell.getText(); } } else if (outputCell instanceof IpnbLatexOutputCell) { if (nbformat == 4) { final OutputDataRaw dataRaw = new OutputDataRaw(); dataRaw.text = outputCell.getText(); dataRaw.latex = ((IpnbLatexOutputCell)outputCell).getLatex(); raw.data = dataRaw; raw.execution_count = outputCell.getPromptNumber(); raw.output_type = "execute_result"; } else { raw.latex = ((IpnbLatexOutputCell)outputCell).getLatex(); raw.text = outputCell.getText(); raw.prompt_number = outputCell.getPromptNumber(); } } else if (outputCell instanceof IpnbStreamOutputCell) { if (nbformat == 4) { raw.name = ((IpnbStreamOutputCell)outputCell).getStream(); } else { raw.stream = ((IpnbStreamOutputCell)outputCell).getStream(); } raw.text = outputCell.getText(); raw.output_type = "stream"; } else if (outputCell instanceof IpnbHtmlOutputCell) { if (nbformat == 4) { final OutputDataRaw dataRaw = new OutputDataRaw(); dataRaw.html = ((IpnbHtmlOutputCell)outputCell).getHtmls(); dataRaw.text = outputCell.getText(); raw.data = dataRaw; raw.execution_count = outputCell.getPromptNumber(); } else { raw.html = ((IpnbHtmlOutputCell)outputCell).getHtmls(); } raw.output_type = nbformat == 4 ? "execute_result" : "pyout"; } else if (outputCell instanceof IpnbErrorOutputCell) { raw.output_type = nbformat == 4 ? "error" : "pyerr"; raw.evalue = ((IpnbErrorOutputCell)outputCell).getEvalue(); raw.ename = ((IpnbErrorOutputCell)outputCell).getEname(); raw.traceback = outputCell.getText(); } else if (outputCell instanceof IpnbOutOutputCell) { if (nbformat == 4) { raw.execution_count = outputCell.getPromptNumber(); raw.output_type = "execute_result"; final OutputDataRaw dataRaw = new OutputDataRaw(); dataRaw.text = outputCell.getText(); raw.data = dataRaw; } else { raw.output_type = "pyout"; raw.prompt_number = outputCell.getPromptNumber(); raw.text = outputCell.getText(); } } else { raw.text = outputCell.getText(); } return raw; } public IpnbOutputCell createOutput() { List<String> text = this.text != null ? this.text : data != null ? data.text : Lists.newArrayList(); Integer prompt = execution_count != null ? execution_count : prompt_number; final IpnbOutputCell outputCell; if (png != null || (data != null && data.png != null)) { outputCell = new IpnbPngOutputCell(png == null ? StringUtil.join(data.png) : png, text, prompt, metadata); } else if (jpeg != null || (data != null && data.jpeg != null)) { outputCell = new IpnbJpegOutputCell(jpeg == null ? StringUtil.join(data.jpeg, "") : jpeg, text, prompt, metadata); } else if (svg != null || (data != null && data.svg != null)) { outputCell = new IpnbSvgOutputCell(svg == null ? data.svg : svg, text, prompt, metadata); } else if (html != null || (data != null && data.html != null)) { outputCell = new IpnbHtmlOutputCell(html == null ? data.html : html, text, prompt, metadata); } else if (latex != null || (data != null && data.latex != null)) { outputCell = new IpnbLatexOutputCell(latex == null ? data.latex : latex, prompt, text, metadata); } else if (stream != null || name != null) { outputCell = new IpnbStreamOutputCell(stream == null ? name : stream, text, prompt, metadata); } else if ("pyerr".equals(output_type) || "error".equals(output_type)) { outputCell = new IpnbErrorOutputCell(evalue, ename, traceback, prompt, metadata); } else if ("pyout".equals(output_type)) { outputCell = new IpnbOutOutputCell(text, prompt, metadata); } else if ("execute_result".equals(output_type) && data != null) { outputCell = new IpnbOutOutputCell(data.text, prompt, metadata); } else if ("display_data".equals(output_type)){ outputCell = new IpnbPngOutputCell(null, text, prompt, metadata); } else { outputCell = new IpnbOutputCell(text, prompt, metadata); } return outputCell; } } private static class OutputDataRaw { @SerializedName("image/png") String png; @SerializedName("text/html") List<String> html; @SerializedName("image/svg+xml") List<String> svg; @SerializedName("image/jpeg") List<String> jpeg; @SerializedName("text/latex") List<String> latex; @SerializedName("text/plain") List<String> text; } static class RawCellAdapter implements JsonSerializer<IpnbCellRaw> { @Override public JsonElement serialize(IpnbCellRaw cellRaw, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("cell_type", cellRaw.cell_type); if ("code".equals(cellRaw.cell_type)) { final Integer count = cellRaw.execution_count; if (count == null) { jsonObject.add("execution_count", JsonNull.INSTANCE); } else { jsonObject.addProperty("execution_count", count); } } if (cellRaw.metadata != null) { final JsonElement metadata = gson.toJsonTree(cellRaw.metadata); jsonObject.add("metadata", metadata); } if (cellRaw.level != null) { jsonObject.addProperty("level", cellRaw.level); } if (cellRaw.outputs != null) { final JsonElement outputs = gson.toJsonTree(cellRaw.outputs); jsonObject.add("outputs", outputs); } if (cellRaw.source != null) { final JsonElement source = gson.toJsonTree(cellRaw.source); jsonObject.add("source", source); } if (cellRaw.input != null) { final JsonElement input = gson.toJsonTree(cellRaw.input); jsonObject.add("input", input); } if (cellRaw.language != null) { jsonObject.addProperty("language", cellRaw.language); } if (cellRaw.prompt_number != null) { jsonObject.addProperty("prompt_number", cellRaw.prompt_number); } return jsonObject; } } static class FileAdapter implements JsonSerializer<IpnbFileRaw> { @Override public JsonElement serialize(IpnbFileRaw fileRaw, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); if (fileRaw.worksheets != null) { final JsonElement worksheets = gson.toJsonTree(fileRaw.worksheets); jsonObject.add("worksheets", worksheets); } if (fileRaw.cells != null) { final JsonElement cells = gson.toJsonTree(fileRaw.cells); jsonObject.add("cells", cells); } final JsonElement metadata = gson.toJsonTree(fileRaw.metadata); jsonObject.add("metadata", metadata); jsonObject.addProperty("nbformat", fileRaw.nbformat); jsonObject.addProperty("nbformat_minor", fileRaw.nbformat_minor); return jsonObject; } } static class CellRawDeserializer implements JsonDeserializer<IpnbCellRaw> { @Override public IpnbCellRaw deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject object = json.getAsJsonObject(); final IpnbCellRaw cellRaw = new IpnbCellRaw(); final JsonElement cell_type = object.get("cell_type"); if (cell_type != null) { cellRaw.cell_type = cell_type.getAsString(); } final JsonElement count = object.get("execution_count"); if (count != null) { cellRaw.execution_count = count.isJsonNull() ? null : count.getAsInt(); } final JsonElement metadata = object.get("metadata"); if (metadata != null) { cellRaw.metadata = gson.fromJson(metadata, Map.class); } final JsonElement level = object.get("level"); if (level != null) { cellRaw.level = level.getAsInt(); } final JsonElement outputsElement = object.get("outputs"); if (outputsElement != null) { final JsonArray outputs = outputsElement.getAsJsonArray(); cellRaw.outputs = Lists.newArrayList(); for (JsonElement output : outputs) { cellRaw.outputs.add(gson.fromJson(output, CellOutputRaw.class)); } } cellRaw.source = getStringOrArray("source", object); cellRaw.input = getStringOrArray("input", object); final JsonElement language = object.get("language"); if (language != null) { cellRaw.language = language.getAsString(); } final JsonElement number = object.get("prompt_number"); if (number != null) { cellRaw.prompt_number = number.getAsInt(); } return cellRaw; } } static class OutputDataDeserializer implements JsonDeserializer<OutputDataRaw> { @Override public OutputDataRaw deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject object = json.getAsJsonObject(); final OutputDataRaw dataRaw = new OutputDataRaw(); final JsonElement png = object.get("image/png"); if (png != null) { dataRaw.png = png.getAsString(); } dataRaw.html = getStringOrArray("text/html", object); dataRaw.svg = getStringOrArray("image/svg+xml", object); dataRaw.jpeg = getStringOrArray("image/jpeg", object); dataRaw.latex = getStringOrArray("text/latex", object); dataRaw.text = getStringOrArray("text/plain", object); return dataRaw; } } static class CellOutputDeserializer implements JsonDeserializer<CellOutputRaw> { @Override public CellOutputRaw deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject object = json.getAsJsonObject(); final CellOutputRaw cellOutputRaw = new CellOutputRaw(); final JsonElement ename = object.get("ename"); if (ename != null) { cellOutputRaw.ename = ename.getAsString(); } final JsonElement name = object.get("name"); if (name != null) { cellOutputRaw.name = name.getAsString(); } final JsonElement evalue = object.get("evalue"); if (evalue != null) { cellOutputRaw.evalue = evalue.getAsString(); } final JsonElement data = object.get("data"); if (data != null) { cellOutputRaw.data = gson.fromJson(data, OutputDataRaw.class); } final JsonElement count = object.get("execution_count"); if (count != null) { cellOutputRaw.execution_count = count.getAsInt(); } final JsonElement outputType = object.get("output_type"); if (outputType != null) { cellOutputRaw.output_type = outputType.getAsString(); } final JsonElement png = object.get("png"); if (png != null) { cellOutputRaw.png = png.getAsString(); } final JsonElement stream = object.get("stream"); if (stream != null) { cellOutputRaw.stream = stream.getAsString(); } final JsonElement jpeg = object.get("jpeg"); if (jpeg != null) { cellOutputRaw.jpeg = jpeg.getAsString(); } cellOutputRaw.html = getStringOrArray("html", object); cellOutputRaw.latex = getStringOrArray("latex", object); cellOutputRaw.svg = getStringOrArray("svg", object); final JsonElement promptNumber = object.get("prompt_number"); if (promptNumber != null) { cellOutputRaw.prompt_number = promptNumber.getAsInt(); } cellOutputRaw.text = getStringOrArray("text", object); cellOutputRaw.traceback = getStringOrArray("traceback", object); final JsonElement metadata = object.get("metadata"); if (metadata != null) { cellOutputRaw.metadata = gson.fromJson(metadata, Map.class); } return cellOutputRaw; } } @Nullable private static ArrayList<String> getStringOrArray(String name, JsonObject object) { final JsonElement jsonElement = object.get(name); final ArrayList<String> strings = Lists.newArrayList(); if (jsonElement == null) return null; if (jsonElement.isJsonArray()) { final JsonArray array = jsonElement.getAsJsonArray(); for (JsonElement element : array) { strings.add(element.getAsString()); } } else { strings.add(jsonElement.getAsString()); } return strings; } static class OutputsAdapter implements JsonSerializer<CellOutputRaw> { @Override public JsonElement serialize(CellOutputRaw cellRaw, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); if (cellRaw.ename != null) { jsonObject.addProperty("ename", cellRaw.ename); } if (cellRaw.name != null) { jsonObject.addProperty("name", cellRaw.name); } if (cellRaw.evalue != null) { jsonObject.addProperty("evalue", cellRaw.evalue); } if (cellRaw.data != null) { final JsonElement data = gson.toJsonTree(cellRaw.data); jsonObject.add("data", data); } if (cellRaw.execution_count != null) { jsonObject.addProperty("execution_count", cellRaw.execution_count); } if (cellRaw.png != null) { jsonObject.addProperty("png", cellRaw.png); } if (cellRaw.stream != null) { jsonObject.addProperty("stream", cellRaw.stream); } if (cellRaw.jpeg != null) { jsonObject.addProperty("jpeg", cellRaw.jpeg); } if (cellRaw.html != null) { final JsonElement html = gson.toJsonTree(cellRaw.html); jsonObject.add("html", html); } if (cellRaw.latex != null) { final JsonElement latex = gson.toJsonTree(cellRaw.latex); jsonObject.add("latex", latex); } if (cellRaw.svg != null) { final JsonElement svg = gson.toJsonTree(cellRaw.svg); jsonObject.add("svg", svg); } if (cellRaw.prompt_number != null) { jsonObject.addProperty("prompt_number", cellRaw.prompt_number); } if (cellRaw.traceback != null) { final JsonElement traceback = gson.toJsonTree(cellRaw.traceback); jsonObject.add("traceback", traceback); } if (cellRaw.metadata != null) { final JsonElement metadata = gson.toJsonTree(cellRaw.metadata); jsonObject.add("metadata", metadata); } if (cellRaw.output_type != null) { jsonObject.addProperty("output_type", cellRaw.output_type); } if (cellRaw.text != null) { final JsonElement text = gson.toJsonTree(cellRaw.text); jsonObject.add("text", text); } return jsonObject; } } static class OutputDataAdapter implements JsonSerializer<OutputDataRaw> { @Override public JsonElement serialize(OutputDataRaw cellRaw, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); if (cellRaw.png != null) { jsonObject.addProperty("image/png", cellRaw.png); } if (cellRaw.html != null) { final JsonElement html = gson.toJsonTree(cellRaw.html); jsonObject.add("text/html", html); } if (cellRaw.svg != null) { final JsonElement svg = gson.toJsonTree(cellRaw.svg); jsonObject.add("image/svg+xml", svg); } if (cellRaw.jpeg != null) { final JsonElement jpeg = gson.toJsonTree(cellRaw.jpeg); jsonObject.add("image/jpeg", jpeg); } if (cellRaw.latex != null) { final JsonElement latex = gson.toJsonTree(cellRaw.latex); jsonObject.add("text/latex", latex); } if (cellRaw.text != null) { final JsonElement text = gson.toJsonTree(cellRaw.text); jsonObject.add("text/plain", text); } return jsonObject; } } }
package generic; import org.junit.Rule; import org.junit.Test; import org.testcontainers.containers.Container; import org.testcontainers.containers.GenericContainer; import java.io.IOException; import static org.junit.Assert.assertEquals; public class CmdModifierTest { // hostname { @Rule public GenericContainer theCache = new GenericContainer<>("redis:3.0.2") .withCreateContainerCmdModifier(cmd -> cmd.withHostName("the-cache")); // memory { @Rule public GenericContainer memoryLimitedRedis = new GenericContainer<>("redis:3.0.2") .withCreateContainerCmdModifier(cmd -> cmd.withMemory((long) 8 * 1024 * 1024)) .withCreateContainerCmdModifier(cmd -> cmd.withMemorySwap((long) 12 * 1024 * 1024)); @Test public void testHostnameModified() throws IOException, InterruptedException { final Container.ExecResult execResult = theCache.execInContainer("hostname"); assertEquals("the-cache", execResult.getStdout().trim()); } @Test public void testMemoryLimitModified() throws IOException, InterruptedException { final Container.ExecResult execResult = memoryLimitedRedis.execInContainer("cat", "/sys/fs/cgroup/memory/memory.limit_in_bytes"); assertEquals("8388608", execResult.getStdout().trim()); } }
package io.syndesis.qe.upgrade; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.SoftAssertions; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.EnvVar; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.openshift.api.model.DeploymentConfig; import io.syndesis.qe.TestConfiguration; import io.syndesis.qe.endpoints.IntegrationsEndpoint; import io.syndesis.qe.utils.OpenShiftUtils; import io.syndesis.qe.utils.RestUtils; import io.syndesis.qe.utils.TestUtils; import lombok.extern.slf4j.Slf4j; import okhttp3.OkHttpClient; import okhttp3.Request; @Slf4j public class UpgradeSteps { private static final String SYNDESIS = Paths.get("..", "..", "syndesis").toAbsolutePath().toString(); private static final String UPGRADE_FOLDER = Paths.get(SYNDESIS, "tools", "upgrade").toFile().toString(); private static final String UPGRADE_TEMPLATE = Paths.get(SYNDESIS, "install", "syndesis.yml").toString(); private static final String VERSION_ENDPOINT = "/api/v1/version"; private static final String DOCKER_HUB_SYNDESIS_TAGS_URL = "https://hub.docker.com/v2/repositories/syndesis/syndesis-server/tags/?page_size=1024"; private static final String BACKUP_DIR = "/tmp/backup"; @Autowired private IntegrationsEndpoint integrationsEndpoint; private String integrationId; @When("^get upgrade versions$") public void getUpgradeVersions() { if (System.getProperty("syndesis.upgrade.version") == null) { // Parse "1.5" double version = Double.parseDouble(StringUtils.substring(System.getProperty("syndesis.version"), 0, 3)); Request request = new Request.Builder() .url(DOCKER_HUB_SYNDESIS_TAGS_URL) .build(); String response = ""; try { response = new OkHttpClient.Builder().build().newCall(request).execute().body().string(); } catch (IOException e) { log.error("Unable to get version from " + VERSION_ENDPOINT); e.printStackTrace(); } JSONArray jsonArray = new JSONObject(response).getJSONArray("results"); List<String> tags = new ArrayList<>(); for (Object o : jsonArray) { tags.add(((JSONObject) o).getString("name")); } // Use only daily tags corresponding to the latest major version Pattern pattern = Pattern.compile("^" + (version + "").replaceAll("\\.", "\\\\.") + "(\\.\\d+)?-\\d{8}$"); Collections.sort(tags); Collections.reverse(tags); for (String tag : tags) { Matcher matcher = pattern.matcher(tag); if (matcher.matches()) { if (System.getProperty("syndesis.upgrade.version") == null) { log.info("Setting syndesis.upgrade.version to " + tag); System.setProperty("syndesis.upgrade.version", tag); } } } // Get penultimate version - not daily outer: while (version >= 1.0) { version -= 0.1; pattern = Pattern.compile("^" + (version + "").replaceAll("\\.", "\\\\.") + "(\\.\\d+)?$"); for (String tag : tags) { Matcher matcher = pattern.matcher(tag); if (matcher.matches()) { log.info("Setting syndesis.version to " + tag); // Save the original syndesis version System.setProperty("syndesis.upgrade.backup.version", System.getProperty("syndesis.version")); System.setProperty("syndesis.version", tag); break outer; } } } } if (System.getProperty("syndesis.upgrade.old.version") != null) { // Allow to define daily tag using custom property, because you can't define daily version as "syndesis.version" // because there are no artifacts System.getProperty("syndesis.upgrade.backup.version", System.getProperty("syndesis.version")); System.setProperty("syndesis.version", System.getProperty("syndesis.upgrade.old.version")); } TestConfiguration.get().overrideSyndesisVersion(System.getProperty("syndesis.version")); log.info("Upgrade:"); log.info("Old version: " + System.getProperty("syndesis.version")); log.info("New version: " + System.getProperty("syndesis.upgrade.version")); } @When("^perform syndesis upgrade to newer version$") public void syndesisUpgrade() { ProcessBuilder pb = new ProcessBuilder(Paths.get(UPGRADE_FOLDER, "upgrade.sh").toString(), "--template ", UPGRADE_TEMPLATE, "--backup", BACKUP_DIR, "--oc-login", "oc login " + TestConfiguration.openShiftUrl() + " --token=" + OpenShiftUtils.client().getConfiguration().getOauthToken() + " -n " + TestConfiguration.openShiftNamespace(), "--migration", Paths.get(UPGRADE_FOLDER, "migration").toString()); pb.directory(new File(UPGRADE_FOLDER)); try { Process p = pb.start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } p.waitFor(); } catch (Exception e) { log.error("Error while running upgrade script: ", e); e.printStackTrace(); } } @When("^perform syndesis upgrade to newer version using operator$") public void upgradeUsingOperator() { OpenShiftUtils.client().imageStreams().withName("syndesis-operator").edit() .editSpec() .editFirstTag() .withName(System.getProperty("syndesis.version")) .editFrom() .withName("docker.io/syndesis/syndesis-operator:" + System.getProperty("syndesis.upgrade.version")) .endFrom() .endTag() .endSpec() .done(); } @Then("^verify syndesis \"([^\"]*)\" version$") public void verifyVersion(String version) { assertThat(getSyndesisVersion()).isEqualTo(System.getProperty("given".equals(version) ? "syndesis.version" : "syndesis.upgrade.version")); } @When("^perform test modifications$") public void performTestModifications() { modifyTemplate(); modifyDbScripts(); modifyUpgradeDbScript(); copyStatefulScripts(); getSyndesisCli(); } @When("^modify s2i tag in syndesis-server-config$") public void modifyS2iTag() { Map<String, String> data = OpenShiftUtils.client().configMaps().withName("syndesis-server-config").get().getData(); String yaml = data.get("application.yml"); yaml = yaml.replaceAll("syndesis-s2i:" + System.getProperty("syndesis.version"), "syndesis-s2i:" + System.getProperty("syndesis.upgrade.version")); data.put("application.yml", yaml); OpenShiftUtils.client().configMaps().withName("syndesis-server-config").edit().withData(data).done(); } private void modifyTemplate() { // Change the install template to use newer version String template; try { template = FileUtils.readFileToString(new File(UPGRADE_TEMPLATE), "UTF-8"); String version = StringUtils.substringBefore(StringUtils.substringAfter(template, "syndesis: ").substring(1), "\""); template = template.replaceAll(version, System.getProperty("syndesis.upgrade.version")); // Modify deployment config // This is easier than messing with yaml directly and it adds the env for syndesis-meta and syndesis-server if (!template.contains("- name: TEST")) { template = StringUtils.replaceAll(template, "tmp", "tmp\"\n - name: TEST\n value: \"UPGRADE"); } FileUtils.write(new File(UPGRADE_TEMPLATE), template, "UTF-8", false); } catch (IOException e) { log.error("Unable to modify template", e); } } private void modifyDbScripts() { integrationId = integrationsEndpoint.getIntegrationId("upgrade").get(); String upgradeResourcesPath = new File("src/test/resources/upgrade").getAbsolutePath(); // Replace placeholder in upgrade scripts createFileFromTemplate(upgradeResourcesPath, "up-98-template.js", "INTEGRATION_ID", integrationId); createFileFromTemplate(upgradeResourcesPath, "up-99-template.js", "INTEGRATION_ID", integrationId); } private void modifyUpgradeDbScript() { String upgradeResourcesPath = new File("src/test/resources/upgrade").toURI().toString(); // Make the syndesis-cli migrate to newest version and use scripts from resources String upgradeDb; try { upgradeDb = FileUtils.readFileToString(Paths.get(UPGRADE_FOLDER, "steps", "upgrade_10_migrate_db").toFile(), "UTF-8"); if (!upgradeDb.contains("-t 99")) { upgradeDb = upgradeDb.replaceAll("syndesis-cli.jar migrate", "syndesis-cli.jar migrate -t 99 -f " + upgradeResourcesPath); upgradeDb = upgradeDb.replaceAll("port=5432", "port=5433"); upgradeDb = upgradeDb.replaceAll("pod 5432", "pod 5433\\:5432"); FileUtils.write(Paths.get(UPGRADE_FOLDER, "steps", "upgrade_10_migrate_db").toFile(), upgradeDb, "UTF-8", false); } } catch (IOException e) { log.error("Unable to modify modify cli", e); } } private void copyStatefulScripts() { // Move the config change script to resource folder try { FileUtils.copyFile(new File("src/test/resources/upgrade/99-change-ui-config.sh"), Paths.get(UPGRADE_FOLDER, "migration", "resource", System.getProperty("syndesis.upgrade.version"), "99-change-ui-config.sh").toFile()); } catch (IOException e) { fail("Unable to copy scripts", e); } } @Then("^verify successful test modifications$") public void verifySuccessfulTestModifications() { verifyTestModifications(false); } @Then("^verify test modifications rollback") public void verifyTestModificationsRollback() { verifyTestModifications(true); } @When("^add rollback cause to upgrade script") public void addRollbackCause() { // Ideally this should be done in upgrade_60_restart_all but there is no rollback for that at the moment try { File scriptFile = Paths.get(UPGRADE_FOLDER, "steps", "upgrade_50_replace_template").toFile(); String script = FileUtils.readFileToString(scriptFile, "UTF-8"); FileUtils.write(scriptFile, StringUtils.replaceAll(script, "update_version \\$tag", "update_version \\$tag; exit 1"), "UTF-8"); } catch (IOException e) { log.error("Unable to manipulate file for rollback", e); } } @Then("^wait until upgrade pod is finished$") public void waitForUpgrade() { Optional<Pod> pod = OpenShiftUtils.getPodByPartialName("syndesis-upgrade"); int retries = 0; while (!pod.isPresent() && retries < 30) { TestUtils.sleepIgnoreInterrupt(5000L); retries++; pod = OpenShiftUtils.getPodByPartialName("syndesis-upgrade"); } retries = 0; log.info("Waiting for syndesis-upgrade pod to finish"); // 15 minutes while (!"Succeeded".equals(pod.get().getStatus().getPhase()) && retries < 180) { pod = OpenShiftUtils.getPodByPartialName("syndesis-upgrade"); TestUtils.sleepIgnoreInterrupt(5000L); retries++; } } private void verifyTestModifications(boolean rollback) { // ConfigMap label change ConfigMap cm = OpenShiftUtils.client().configMaps().withName("syndesis-ui-config").get(); // New ENV variable in syndesis-server and syndesis-meta EnvVar dcEnvVar = null; DeploymentConfig dc = OpenShiftUtils.client().deploymentConfigs().withName("syndesis-server").get(); for (EnvVar envVar : dc.getSpec().getTemplate().getSpec().getContainers().get(0).getEnv()) { if (envVar.getName().equals("TEST")) { dcEnvVar = envVar; break; } } final EnvVar finalDcEnvVar = dcEnvVar; if (rollback) { SoftAssertions.assertSoftly(softAssertions -> { softAssertions.assertThat(cm.getMetadata().getLabels().get("TEST")).isNull(); softAssertions.assertThat(finalDcEnvVar).isNull(); softAssertions.assertThat(integrationsEndpoint.get(integrationId).getName()).isEqualTo("upgrade"); softAssertions.assertThat(integrationsEndpoint.get(integrationId).getDescription().get()).isEqualTo("Awkward integration."); }); } else { SoftAssertions.assertSoftly(softAssertions -> { softAssertions.assertThat(cm.getMetadata().getLabels().get("TEST")).isEqualTo("UPGRADE"); softAssertions.assertThat(finalDcEnvVar.getValue()).isEqualTo("UPGRADE"); softAssertions.assertThat(integrationsEndpoint.get(integrationId).getName()).isEqualTo("UPGRADE INTEGRATION NAME"); softAssertions.assertThat(integrationsEndpoint.get(integrationId).getDescription().get()).isEqualTo("UPGRADE INTEGRATION DESCRIPTION"); }); } } private String getSyndesisVersion() { RestUtils.reset(); Request request = new Request.Builder() .url(RestUtils.getRestUrl() + VERSION_ENDPOINT) .header("Accept", "text/plain") .build(); try { return new OkHttpClient.Builder().build().newCall(request).execute().body().string(); } catch (IOException e) { log.error("Unable to get version from " + VERSION_ENDPOINT); e.printStackTrace(); } return null; } private void getSyndesisCli() { if (!Paths.get(UPGRADE_FOLDER, "syndesis-cli.jar").toFile().exists()) { log.info("Expecting to be run on jenkins, trying to copy ../../syndesis/app/server/cli/target/syndesis-cli.jar"); try { FileUtils.copyFile(Paths.get("../../syndesis/app/server/cli/target/syndesis-cli.jar").toFile(), Paths.get(UPGRADE_FOLDER, "syndesis-cli.jar").toFile()); } catch (IOException e) { log.error("Unable to copy syndesis-cli.jar"); } } } private void createFileFromTemplate(String folder, String templateFileName, String whatToReplace, String whatToUse) { try { File dest = Paths.get(folder, templateFileName.replaceAll("-template", "")).toFile(); dest.delete(); String content = FileUtils.readFileToString(Paths.get(folder, templateFileName).toFile(), "UTF-8"); FileUtils.write(dest, content.replaceAll(whatToReplace, whatToUse), "UTF-8", false); } catch (IOException e) { fail("Unable to modify scripts", e); } } @Given("^clean upgrade modifications$") public void cleanUpgradeModifications() { log.info("Running \"git checkout .\" in \"" + SYNDESIS + "\""); ProcessBuilder pb = new ProcessBuilder("git", "checkout", "."); pb.directory(new File(SYNDESIS)); try { Process p = pb.start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } p.waitFor(); } catch (Exception e) { log.error("Error while running script: ", e); e.printStackTrace(); } } }
package org.wiztools.restclient; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.XMLStreamException; import nu.xom.Attribute; import nu.xom.Builder; import nu.xom.Document; import nu.xom.Element; import nu.xom.Serializer; import nu.xom.ParsingException; import org.wiztools.commons.StringUtil; /** * * @author rsubramanian */ public final class XMLUtil { private XMLUtil() { } private static final Logger LOG = Logger.getLogger(XMLUtil.class.getName()); private static final String[] VERSIONS = new String[]{ "2.0", "2.1", "2.2a1", "2.2a2", "2.2", "2.3b1", "2.3", RCConstants.VERSION }; public static final String XML_MIME = "application/xml"; static { // Sort the version array for binary search Arrays.sort(VERSIONS); } private static void checkIfVersionValid(final String restVersion) throws XMLException { if (restVersion == null) { throw new XMLException("Attribute `version' not available for root element <rest-client>"); } int res = Arrays.binarySearch(VERSIONS, restVersion); if (res == -1) { throw new XMLException("Version not supported"); } } private static Document request2XML(final Request bean) throws XMLException { try { Element reqRootElement = new Element("rest-client"); // set version attributes to rest-client root tag Attribute versionAttributes = new Attribute("version", RCConstants.VERSION); reqRootElement.addAttribute(versionAttributes); Element reqChildElement = new Element("request"); Element reqChildSubElement = null; Element reqChildSubSubElement = null; // HTTP Version reqChildSubElement = new Element("http-version"); reqChildSubElement.appendChild(bean.getHttpVersion().versionNumber()); reqChildElement.appendChild(reqChildSubElement); // Redirect reqChildSubElement = new Element("auto-redirect"); reqChildSubElement.appendChild(Boolean.toString(bean.isAutoRedirect())); reqChildElement.appendChild(reqChildSubElement); // creating the URL child element reqChildSubElement = new Element("URL"); reqChildSubElement.appendChild(bean.getUrl().toString()); reqChildElement.appendChild(reqChildSubElement); // creating the method child element reqChildSubElement = new Element("method"); reqChildSubElement.appendChild(bean.getMethod().name()); reqChildElement.appendChild(reqChildSubElement); // creating the auth-methods child element List<HTTPAuthMethod> authMethods = bean.getAuthMethods(); if (authMethods == null || authMethods.size() > 0) { reqChildSubElement = new Element("auth-methods"); String methods = ""; for (HTTPAuthMethod authMethod : authMethods) { methods = methods + authMethod + ","; } String authenticationMethod = methods.substring(0, methods.length() == 0 ? 0 : methods.length() - 1); reqChildSubElement.appendChild(authenticationMethod); reqChildElement.appendChild(reqChildSubElement); // creating the auth-preemptive child element boolean authPreemptive = bean.isAuthPreemptive(); reqChildSubElement = new Element("auth-preemptive"); reqChildSubElement.appendChild(new Boolean(authPreemptive).toString()); reqChildElement.appendChild(reqChildSubElement); // creating the auth-host child element String authHost = bean.getAuthHost(); if (!StringUtil.isStrEmpty(authHost)) { reqChildSubElement = new Element("auth-host"); reqChildSubElement.appendChild(authHost); reqChildElement.appendChild(reqChildSubElement); } // creating the auth-realm child element String authRealm = bean.getAuthRealm(); if (!StringUtil.isStrEmpty(authRealm)) { reqChildSubElement = new Element("auth-realm"); reqChildSubElement.appendChild(authRealm); reqChildElement.appendChild(reqChildSubElement); } // creating the auth-username child element String authUsername = bean.getAuthUsername(); if (!StringUtil.isStrEmpty(authUsername)) { reqChildSubElement = new Element("auth-username"); reqChildSubElement.appendChild(authUsername); reqChildElement.appendChild(reqChildSubElement); } // creating the auth-password child element String authPassword = null; if (bean.getAuthPassword() != null) { authPassword = new String(bean.getAuthPassword()); if (!StringUtil.isStrEmpty(authPassword)) { String encPassword = Base64.encodeObject(authPassword); reqChildSubElement = new Element("auth-password"); reqChildSubElement.appendChild(encPassword); reqChildElement.appendChild(reqChildSubElement); } } } // Creating SSL elements String sslTruststore = bean.getSslTrustStore(); if (!StringUtil.isStrEmpty(sslTruststore)) { // 1. Create truststore entry reqChildSubElement = new Element("ssl-truststore"); reqChildSubElement.appendChild(sslTruststore); reqChildElement.appendChild(reqChildSubElement); // 2. Create password entry String sslPassword = new String(bean.getSslTrustStorePassword()); String encPassword = Base64.encodeObject(sslPassword); reqChildSubElement = new Element("ssl-truststore-password"); reqChildSubElement.appendChild(encPassword); reqChildElement.appendChild(reqChildSubElement); // 3. Create Hostname Verifier entry String sslHostnameVerifier = bean.getSslHostNameVerifier().name(); reqChildSubElement = new Element("ssl-hostname-verifier"); reqChildSubElement.appendChild(sslHostnameVerifier); reqChildElement.appendChild(reqChildSubElement); } // creating the headers child element Map<String, String> headers = bean.getHeaders(); if (!headers.isEmpty()) { reqChildSubElement = new Element("headers"); for (String key : headers.keySet()) { String value = headers.get(key); reqChildSubSubElement = new Element("header"); reqChildSubSubElement.addAttribute(new Attribute("key", key)); reqChildSubSubElement.addAttribute(new Attribute("value", value)); reqChildSubElement.appendChild(reqChildSubSubElement); } reqChildElement.appendChild(reqChildSubElement); } // creating the body child element ReqEntity rBean = bean.getBody(); if (rBean != null) { reqChildSubElement = new Element("body"); String contentType = rBean.getContentType(); String charSet = rBean.getCharSet(); String body = rBean.getBody(); reqChildSubElement.addAttribute(new Attribute("content-type", contentType)); reqChildSubElement.addAttribute(new Attribute("charset", charSet)); reqChildSubElement.appendChild(body); reqChildElement.appendChild(reqChildSubElement); } // creating the test-script child element String testScript = bean.getTestScript(); if (testScript != null) { reqChildSubElement = new Element("test-script"); reqChildSubElement.appendChild(testScript); reqChildElement.appendChild(reqChildSubElement); } reqRootElement.appendChild(reqChildElement); Document xomDocument = new Document(reqRootElement); return xomDocument; } catch (Exception ex) { throw new XMLException(ex.getMessage(), ex); } } private static Map<String, String> getHeadersFromHeaderNode(final Element node) throws XMLException { Map<String, String> m = new LinkedHashMap<String, String>(); for (int i = 0; i < node.getChildElements().size(); i++) { Element headerElement = node.getChildElements().get(i); if (!"header".equals(headerElement.getQualifiedName())) { throw new XMLException("<headers> element should contain only <header> elements"); } m.put(headerElement.getAttributeValue("key"), headerElement.getAttributeValue("value")); } return m; } private static Request xml2Request(final Document doc) throws MalformedURLException, XMLException { RequestBean requestBean = new RequestBean(); // get the rootNode Element rootNode = doc.getRootElement(); if (!"rest-client".equals(rootNode.getQualifiedName())) { throw new XMLException("Root node is not <rest-client>"); } // checking correct rest version checkIfVersionValid(rootNode.getAttributeValue("version")); // assign rootnode to current node and also finding 'request' node Element tNode = null; Element requestNode = null; // if more than two request element is present then throw the exception if (rootNode.getChildElements().size() != 1) { throw new XMLException("There can be only one child node for root node: <request>"); } // minimum one request element is present in xml if (rootNode.getFirstChildElement("request") == null) { throw new XMLException("The child node of <rest-client> should be <request>"); } requestNode = rootNode.getFirstChildElement("request"); for (int i = 0; i < requestNode.getChildElements().size(); i++) { tNode = requestNode.getChildElements().get(i); String nodeName = tNode.getQualifiedName(); if ("http-version".equals(nodeName)) { String t = tNode.getValue(); HTTPVersion httpVersion = "1.1".equals(t) ? HTTPVersion.HTTP_1_1 : HTTPVersion.HTTP_1_0; requestBean.setHttpVersion(httpVersion); } else if("auto-redirect".equals(nodeName)){ requestBean.setAutoRedirect(Boolean.valueOf(tNode.getValue())); } else if ("URL".equals(nodeName)) { URL url = new URL(tNode.getValue()); requestBean.setUrl(url); } else if ("method".equals(nodeName)) { requestBean.setMethod(HTTPMethod.get(tNode.getValue())); } else if ("auth-methods".equals(nodeName)) { String[] authenticationMethods = tNode.getValue().split(","); for (int j = 0; j < authenticationMethods.length; j++) { requestBean.addAuthMethod(HTTPAuthMethod.get(authenticationMethods[j])); } } else if ("auth-preemptive".equals(nodeName)) { if (tNode.getValue().equals("true")) { requestBean.setAuthPreemptive(true); } else { requestBean.setAuthPreemptive(false); } } else if ("auth-host".equals(nodeName)) { requestBean.setAuthHost(tNode.getValue()); } else if ("auth-realm".equals(nodeName)) { requestBean.setAuthRealm(tNode.getValue()); } else if ("auth-username".equals(nodeName)) { requestBean.setAuthUsername(tNode.getValue()); } else if ("auth-password".equals(nodeName)) { String password = (String) Base64.decodeToObject(tNode.getValue()); requestBean.setAuthPassword(password.toCharArray()); } else if ("ssl-truststore".equals(nodeName)) { String sslTrustStore = tNode.getValue(); requestBean.setSslTrustStore(sslTrustStore); } else if ("ssl-truststore-password".equals(nodeName)) { String sslTrustStorePassword = (String) Base64.decodeToObject(tNode.getValue()); requestBean.setSslTrustStorePassword(sslTrustStorePassword.toCharArray()); } else if("ssl-hostname-verifier".equals(nodeName)){ String sslHostnameVerifierStr = tNode.getValue(); SSLHostnameVerifier sslHostnameVerifier = SSLHostnameVerifier.valueOf(sslHostnameVerifierStr); requestBean.setSslHostNameVerifier(sslHostnameVerifier); } else if ("headers".equals(nodeName)) { Map<String, String> m = getHeadersFromHeaderNode(tNode); for (String key : m.keySet()) { requestBean.addHeader(key, m.get(key)); } } else if ("body".equals(nodeName)) { requestBean.setBody(new ReqEntityBean(tNode.getValue(), tNode.getAttributeValue("content-type"), tNode.getAttributeValue("charset"))); } else if ("test-script".equals(nodeName)) { requestBean.setTestScript(tNode.getValue()); } else { throw new XMLException("Invalid element encountered: <" + nodeName + ">"); } } return requestBean; } private static Document response2XML(final Response bean) throws XMLException { try { Element respRootElement = new Element("rest-client"); Element respChildElement = new Element("response"); Element respChildSubElement = null; Element respChildSubSubElement = null; // set version attributes to rest-client root tag Attribute versionAttributes = new Attribute("version", RCConstants.VERSION); respRootElement.addAttribute(versionAttributes); // adding first sub child element - execution-time and append to response child element respChildSubElement = new Element("execution-time"); respChildSubElement.appendChild(String.valueOf(bean.getExecutionTime())); respChildElement.appendChild(respChildSubElement); // adding second sub child element - status and code attributes and append to response child element respChildSubElement = new Element("status"); Attribute codeAttributes = new Attribute("code", String.valueOf(bean.getStatusCode())); respChildSubElement.addAttribute(codeAttributes); respChildSubElement.appendChild(bean.getStatusLine()); respChildElement.appendChild(respChildSubElement); // adding third sub child element - headers Map<String, String> headers = bean.getHeaders(); if (!headers.isEmpty()) { Attribute keyAttribute = null; Attribute valueAttribute = null; // creating sub child-child element respChildSubElement = new Element("headers"); for (String key : headers.keySet()) { String value = headers.get(key); respChildSubSubElement = new Element("header"); keyAttribute = new Attribute("key", key); valueAttribute = new Attribute("value", value); respChildSubSubElement.addAttribute(keyAttribute); respChildSubSubElement.addAttribute(valueAttribute); respChildSubElement.appendChild(respChildSubSubElement); } // add response child element - headers respChildElement.appendChild(respChildSubElement); } String responseBody = bean.getResponseBody(); if (responseBody != null) { //creating the body child element and append to response child element respChildSubElement = new Element("body"); respChildSubElement.appendChild(responseBody); respChildElement.appendChild(respChildSubElement); } // test result TestResult testResult = bean.getTestResult(); if (testResult != null) { //creating the test-result child element respChildSubElement = new Element("test-result"); // Counts: Element e_runCount = new Element("run-coun"); e_runCount.appendChild(String.valueOf(testResult.getRunCount())); Element e_failureCount = new Element("failure-coun"); e_failureCount.appendChild(String.valueOf(testResult.getFailureCount())); Element e_errorCount = new Element("error-coun"); e_errorCount.appendChild(String.valueOf(testResult.getErrorCount())); respChildSubElement.appendChild(e_runCount); respChildSubElement.appendChild(e_failureCount); respChildSubElement.appendChild(e_errorCount); // Failures if (testResult.getFailureCount() > 0) { Element e_failures = new Element("failures"); List<TestFailureResult> l = testResult.getFailures(); for (TestFailureResult b : l) { Element e_message = new Element("message"); e_message.appendChild(b.getExceptionMessage()); Element e_line = new Element("line-number"); e_line.appendChild(String.valueOf(b.getLineNumber())); Element e_failure = new Element("failure"); e_failure.appendChild(e_message); e_failure.appendChild(e_line); e_failures.appendChild(e_failure); } respChildSubElement.appendChild(e_failures); } //Errors if (testResult.getErrorCount() > 0) { Element e_errors = new Element("errors"); List<TestFailureResult> l = testResult.getErrors(); for (TestFailureResult b : l) { Element e_message = new Element("message"); e_message.appendChild(b.getExceptionMessage()); Element e_line = new Element("line-number"); e_line.appendChild(String.valueOf(b.getLineNumber())); Element e_error = new Element("error"); e_error.appendChild(e_message); e_error.appendChild(e_line); e_errors.appendChild(e_error); } respChildSubElement.appendChild(e_errors); } // Trace Element e_trace = new Element("trace"); e_trace.appendChild(testResult.toString()); respChildSubElement.appendChild(e_trace); respChildElement.appendChild(respChildSubElement); } respRootElement.appendChild(respChildElement); Document xomDocument = new Document(respRootElement); return xomDocument; } catch (Exception ex) { throw new XMLException(ex.getMessage(), ex); } } private static Response xml2Response(final Document doc) throws XMLException { ResponseBean responseBean = new ResponseBean(); // get the rootNode Element rootNode = doc.getRootElement(); if (!"rest-client".equals(rootNode.getQualifiedName())) { throw new XMLException("Root node is not <rest-client>"); } // checking correct rest version checkIfVersionValid(rootNode.getAttributeValue("version")); // assign rootnode to current node and also finding 'response' node Element tNode = null; Element responseNode = null; // if more than two request element is present then throw the exception if (rootNode.getChildElements().size() != 1) { throw new XMLException("There can be only one child node for root node: <response>"); } // minimum one response element is present in xml if (rootNode.getFirstChildElement("response") == null) { throw new XMLException("The child node of <rest-client> should be <response>"); } responseNode = rootNode.getFirstChildElement("response"); for (int i = 0; i < responseNode.getChildElements().size(); i++) { tNode = responseNode.getChildElements().get(i); String nodeName = tNode.getQualifiedName(); if ("execution-time".equals(nodeName)) { responseBean.setExecutionTime(Long.parseLong(tNode.getValue())); } else if ("status".equals(nodeName)) { responseBean.setStatusLine(tNode.getValue()); responseBean.setStatusCode(Integer.parseInt(tNode.getAttributeValue("code"))); } else if ("headers".equals(nodeName)) { Map<String, String> m = getHeadersFromHeaderNode(tNode); for (String key : m.keySet()) { responseBean.addHeader(key, m.get(key)); } } else if ("body".equals(nodeName)) { responseBean.setResponseBody(tNode.getValue()); } else if ("test-result".equals(nodeName)) { TestResultBean testResultBean = new TestResultBean(); for (int j = 0; j < tNode.getChildCount(); j++) { String nn = tNode.getQualifiedName(); if ("run-count".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("failure-count".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("error-count".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("failures".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("errors".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } } responseBean.setTestResult(testResultBean); } else { throw new XMLException("Unrecognized element found: <" + nodeName + ">"); } } return responseBean; } private static void writeXML(final Document doc, final File f) throws IOException, XMLException { try { OutputStream out = new FileOutputStream(f); out = new BufferedOutputStream(out); // getDocumentCharset(f) - to retrieve the charset encoding attribute Serializer serializer = new Serializer(out, getDocumentCharset(f)); serializer.write(doc); out.close(); } catch (IOException ex) { throw new XMLException(ex.getMessage(), ex); } } private static Document getDocumentFromFile(final File f) throws IOException, XMLException { try { Builder parser = new Builder(); Document doc = parser.build(f); return doc; } catch (ParsingException ex) { throw new XMLException(ex.getMessage(), ex); } catch (IOException ex) { throw new XMLException(ex.getMessage(), ex); } } public static String getDocumentCharset(final File f) throws IOException, XMLException { XMLEventReader reader = null; try { // using stax to get xml factory objects and read the input file XMLInputFactory inputFactory = XMLInputFactory.newInstance(); reader = inputFactory.createXMLEventReader(new FileInputStream(f)); XMLEvent event = reader.nextEvent(); // Always the first element is StartDocument // even if the XML does not have explicit declaration: StartDocument document = (StartDocument) event; return document.getCharacterEncodingScheme(); } catch (XMLStreamException ex) { throw new XMLException(ex.getMessage(), ex); } finally{ if(reader != null){ try{ reader.close(); } catch(XMLStreamException ex){ LOG.warning(ex.getMessage()); } } } } public static void writeRequestXML(final Request bean, final File f) throws IOException, XMLException { Document doc = request2XML(bean); writeXML(doc, f); } public static void writeResponseXML(final Response bean, final File f) throws IOException, XMLException { Document doc = response2XML(bean); writeXML(doc, f); } public static Request getRequestFromXMLFile(final File f) throws IOException, XMLException { Document doc = getDocumentFromFile(f); return xml2Request(doc); } public static Response getResponseFromXMLFile(final File f) throws IOException, XMLException { Document doc = getDocumentFromFile(f); return xml2Response(doc); } public static String indentXML(final String in) throws XMLException, IOException { try { Builder parser = new Builder(); Document doc = parser.build(in, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Serializer serializer = new Serializer(baos); serializer.setIndent(4); serializer.setMaxLength(69); serializer.write(doc); return new String(baos.toByteArray()); } catch (ParsingException ex) { // LOG.log(Level.SEVERE, null, ex); throw new XMLException("XML indentation failed.", ex); } } }
package com.rultor.stateful.sdb; import com.amazonaws.services.simpledb.model.DeleteAttributesRequest; import com.amazonaws.services.simpledb.model.GetAttributesRequest; import com.amazonaws.services.simpledb.model.GetAttributesResult; import com.amazonaws.services.simpledb.model.PutAttributesRequest; import com.amazonaws.services.simpledb.model.ReplaceableAttribute; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.aspects.RetryOnFailure; import com.jcabi.aspects.Tv; import com.jcabi.log.Logger; import com.rultor.aws.SDBClient; import com.rultor.spi.Wallet; import com.rultor.stateful.Lineup; import com.rultor.tools.Dollars; import com.rultor.tools.Time; import java.security.SecureRandom; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Lineup with synchronization through Amazon SimpleDB item. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.0 * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @Immutable @ToString @EqualsAndHashCode(of = { "client", "name" }) @Loggable(Loggable.DEBUG) @SuppressWarnings("PMD.DoNotUseThreads") public final class ItemLineup implements Lineup { /** * Attribute name. */ private static final String IDENTIFIER = "identifier"; /** * Randomizer. */ private static final Random RAND = new SecureRandom(); /** * Max waiting time in milliseconds. */ private static final long MAX = TimeUnit.MINUTES.toMillis(Tv.FIVE); /** * Wallet to charge. */ private final transient Wallet wallet; /** * SimpleDB client. */ private final transient SDBClient client; /** * Object name. */ private final transient String name; /** * Public ctor. * @param wlt Wallet to charge * @param obj Item name * @param clnt Client * @checkstyle ParameterNumber (7 lines) */ public ItemLineup( @NotNull(message = "wallet can't be NULL") final Wallet wlt, @NotNull(message = "object name can't be NULL") final String obj, @NotNull(message = "SimpleDB client can't be NULL") final SDBClient clnt) { this.wallet = wlt; this.name = obj; this.client = clnt; } /** * {@inheritDoc} */ @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") @Loggable(value = Loggable.DEBUG, limit = Integer.MAX_VALUE) public <T> T exec(final Callable<T> callable) throws Exception { final long start = System.currentTimeMillis(); try { while (true) { final Marker marker = new Marker(callable); if (!this.exists()) { this.save(marker); } final Marker saved = this.load(); if (saved.equals(marker)) { break; } if (saved.age() > ItemLineup.MAX) { this.remove(); continue; } Logger.info( this, "SDB item `%s/%s` is locked by %s for %[ms]s already...", this.client.domain(), this.name, saved, System.currentTimeMillis() - start ); TimeUnit.MILLISECONDS.sleep( ItemLineup.RAND.nextInt(Tv.THOUSAND) ); } return callable.call(); } finally { this.remove(); } } /** * {@inheritDoc} */ @Override @SuppressWarnings("PMD.AvoidCatchingGenericException") @Loggable(value = Loggable.DEBUG, limit = Integer.MAX_VALUE) public void exec(final Runnable runnable) { try { this.exec( new Callable<Void>() { @Override public Void call() throws Exception { runnable.run(); return null; } @Override public String toString() { return runnable.toString(); } } ); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } /** * Marker used in items. */ @Immutable @EqualsAndHashCode(of = "text") private static final class Marker { /** * Text of it. */ private final transient String text; /** * Ctor. * @param txt Text of the marker */ protected Marker(final String txt) { this.text = txt; } /** * Ctor. * @param callable Callable we're based on */ protected Marker(final Callable<?> callable) { this( String.format( "%s %d %s", new Time(), System.nanoTime(), callable ) ); } @Override public String toString() { return this.text; } /** * Get its age in milliseconds. * @return Milliseconds */ public long age() { final Time time; if (this.text.isEmpty()) { time = new Time(); } else { time = new Time(this.text.substring(0, this.text.indexOf(' '))); } return time.delta(new Time()); } } /** * Item exists in SimpleDB. * @return TRUE if it exists */ @RetryOnFailure(verbose = false) private boolean exists() { final long start = System.currentTimeMillis(); final GetAttributesResult result = this.client.get().getAttributes( new GetAttributesRequest() .withConsistentRead(true) .withDomainName(this.client.domain()) .withItemName(this.name) ); this.wallet.charge( Logger.format( // @checkstyle LineLength (1 line) "checked existence of AWS SimpleDB item `%s` in `%s` domain in %[ms]s", this.name, this.client.domain(), System.currentTimeMillis() - start ), new Dollars(Tv.FIVE) ); return !result.getAttributes().isEmpty(); } /** * Save text to SimpleDB object. * @param marker Content to save */ @RetryOnFailure(verbose = false) private void save(final Marker marker) { final long start = System.currentTimeMillis(); this.client.get().putAttributes( new PutAttributesRequest() .withDomainName(this.client.domain()) .withItemName(this.name) .withAttributes( new ReplaceableAttribute() .withName(ItemLineup.IDENTIFIER) .withValue(marker.toString()) .withReplace(true), new ReplaceableAttribute() .withName("time") .withValue(new Time().toString()) .withReplace(true) ) ); this.wallet.charge( Logger.format( "put AWS SimpleDB item `%s` into `%s` domain in %[ms]s", this.name, this.client.domain(), System.currentTimeMillis() - start ), new Dollars(Tv.FIVE) ); } /** * Load text from SimpleDB item (or empty if it doesn't exist). * @return The content loaded */ @RetryOnFailure(verbose = false) private Marker load() { final long start = System.currentTimeMillis(); final GetAttributesResult result = this.client.get().getAttributes( new GetAttributesRequest() .withConsistentRead(true) .withDomainName(this.client.domain()) .withItemName(this.name) .withAttributeNames(ItemLineup.IDENTIFIER) ); this.wallet.charge( Logger.format( "loaded AWS SimpleDB item `%s` from `%s` domain in %[ms]s", this.name, this.client.domain(), System.currentTimeMillis() - start ), new Dollars(Tv.FIVE) ); final String text; if (result.getAttributes().isEmpty()) { text = ""; } else { text = result.getAttributes().get(0).getValue(); } return new Marker(text); } /** * Remove object from SimpleDB. */ @RetryOnFailure(verbose = false) private void remove() { final long start = System.currentTimeMillis(); this.client.get().deleteAttributes( new DeleteAttributesRequest() .withDomainName(this.client.domain()) .withItemName(this.name) ); this.wallet.charge( Logger.format( "removed AWS SimpleDB item `%s` from `%s` domain in %[ms]s", this.name, this.client.domain(), System.currentTimeMillis() - start ), new Dollars(Tv.FIVE) ); } }
package io.vividcode.feature9.rx; import java.util.concurrent.Flow; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; public class DelayedSubscribers { public static void main(final String[] args) { final DelayedSubscribers delayedSubscribers = new DelayedSubscribers(); delayedSubscribers.publishWithSubmit(); System.out.println("==========="); delayedSubscribers.publishWithOffer(); System.out.println("==========="); delayedSubscribers.publishWithOfferTimeout(); } public void publishWithSubmit() { final SequenceGenerator sequenceGenerator = new SequenceGenerator(); this.publish(publisher -> publisher.submit(sequenceGenerator.get())); } public void publishWithOffer() { final SequenceGenerator sequenceGenerator = new SequenceGenerator(); this.publish(publisher -> publisher.offer(sequenceGenerator.get(), ((subscriber, value) -> { System.out.printf("%s dropped %s%n", subscriber, value); return true; }))); } public void publishWithOfferTimeout() { final SequenceGenerator sequenceGenerator = new SequenceGenerator(); this.publish(publisher -> publisher.offer( sequenceGenerator.get(), 1000, TimeUnit.MILLISECONDS, ((subscriber, value) -> { System.out.printf("%s dropped %s%n", subscriber, value); return true; }) )); } private void publish(final Consumer<PeriodicPublisher<Integer>> action) { final PeriodicPublisher<Integer> publisher = new PeriodicPublisher<>( action, 16, 50, 50, TimeUnit.MILLISECONDS); publisher.subscribe(new DelayedSubscriber<>("1")); publisher.subscribe(new DelayedSubscriber<>("2")); publisher.subscribe(new DelayedSubscriber<>("3")); publisher.waitForCompletion(); System.out.println("Publish completed"); try { Thread.sleep(5000); } catch (final InterruptedException e) { e.printStackTrace(); } } public static class SequenceGenerator implements Supplier<Integer> { private int count = 1; @Override public Integer get() { return this.count++; } } public static class DelayedSubscriber<T> implements Flow.Subscriber<T> { private final String id; private Flow.Subscription subscription; public DelayedSubscriber(final String id) { this.id = id; } @Override public void onSubscribe(final Flow.Subscription subscription) { this.subscription = subscription; System.out.printf("%s subscribed!%n", this.id); subscription.request(1); } @Override public void onNext(final T item) { this.subscription.request(1); try { Thread.sleep(100); } catch (final InterruptedException e) { e.printStackTrace(); } System.out.printf("%s processed: %s%n", this.id, item); } @Override public void onError(final Throwable throwable) { throwable.printStackTrace(); } @Override public void onComplete() { System.out.printf("%s completed!%n", this.id); } @Override public String toString() { return String.format("Subscriber %s", this.id); } } }
package cn.tinkling.prefs.sample; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import cn.tinkling.prefs.RemoteSharedPreferences; public class RemoteProvider extends ContentProvider { private RemoteSharedPreferences mRemotePrefs; @Override public boolean onCreate() { final SharedPreferences preferences = getContext().getSharedPreferences("preferences-bundle", Context.MODE_PRIVATE); mRemotePrefs = new RemoteSharedPreferences(preferences); return true; } @Nullable @Override public Bundle call(@NonNull String method, String arg, Bundle extras) { if ("getRemoteSharedPreferences".equals(method)) { Bundle bundle = new Bundle(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { bundle.putBinder("preferences", mRemotePrefs); } else { bundle.putParcelable("preferences", mRemotePrefs.getSharedPreferencesDescriptor()); } return bundle; } return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public String getType(Uri uri) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException("Not yet implemented"); } }
package com.elyria.engine; import android.arch.persistence.room.Room; import android.content.Context; import com.elyria.db.AppDatabase; public class SearchEngine { private AppDatabase db; private static class Holder { private static final SearchEngine INSTANCE = new SearchEngine(); } private SearchEngine() { } public static final SearchEngine getInstance() { return Holder.INSTANCE; } public void transData(Context context) { } public void initDatabase(Context context) { db = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database-name").build(); } }
package edu.umd.cs.findbugs; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.math.BigInteger; import java.security.MessageDigest; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.zip.GZIPInputStream; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.WillClose; import javax.xml.transform.TransformerException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.MissingClassException; import edu.umd.cs.findbugs.log.Profiler; import edu.umd.cs.findbugs.model.ClassFeatureSet; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.xml.Dom4JXMLOutput; import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; import edu.umd.cs.findbugs.xml.XMLOutputUtil; /** * An implementation of {@link BugCollection} that keeps the BugInstances * sorted by class (using the native comparison ordering of BugInstance's * compareTo() method as a tie-breaker). * * @see BugInstance * @author David Hovemeyer */ public class SortedBugCollection implements BugCollection { long analysisTimestamp = System.currentTimeMillis(); String analysisVersion = Version.RELEASE; private boolean withMessages = false; private boolean applySuppressions = false; public boolean isApplySuppressions() { return applySuppressions; } public void setApplySuppressions(boolean applySuppressions) { this.applySuppressions = applySuppressions; } private static final boolean REPORT_SUMMARY_HTML = SystemProperties.getBoolean("findbugs.report.SummaryHTML"); public long getAnalysisTimestamp() { return analysisTimestamp; } public void setAnalysisTimestamp(long timestamp) { analysisTimestamp = timestamp; } /** * Add a Collection of BugInstances to this BugCollection object. * This just calls add(BugInstance) for each instance in the input collection. * * @param collection the Collection of BugInstances to add */ public void addAll(Collection<BugInstance> collection) { for (BugInstance aCollection : collection) { add(aCollection); } } /** * Add a Collection of BugInstances to this BugCollection object. * * @param collection the Collection of BugInstances to add * @param updateActiveTime true if active time of added BugInstances should * be updated to match collection: false if not */ public void addAll(Collection<BugInstance> collection, boolean updateActiveTime) { for (BugInstance warning : collection) { add(warning, updateActiveTime); } } /** * Add a BugInstance to this BugCollection. * This just calls add(bugInstance, true). * * @param bugInstance the BugInstance * @return true if the BugInstance was added, or false if a matching * BugInstance was already in the BugCollection */ public boolean add(BugInstance bugInstance) { return add(bugInstance, true); } /** * Add an analysis error. * * @param message the error message */ public void addError(String message) { addError(message, null); } /** * Get the current AppVersion. */ public AppVersion getCurrentAppVersion() { return new AppVersion(getSequenceNumber()) .setReleaseName(getReleaseName()) .setTimestamp(getTimestamp()) .setNumClasses(getProjectStats().getNumClasses()) .setCodeSize(getProjectStats().getCodeSize()); } /** * Read XML data from given file into this object, * populating given Project as a side effect. * * @param fileName name of the file to read * @param project the Project */ public void readXML(String fileName, Project project) throws IOException, DocumentException { readXML(new File(fileName), project); } /** * Read XML data from given file into this object, * populating given Project as a side effect. * * @param file the file * @param project the Project */ public void readXML(File file, Project project) throws IOException, DocumentException { project.setCurrentWorkingDirectory(file.getParentFile()); InputStream in = new BufferedInputStream(new FileInputStream(file)); if (file.getName().endsWith(".gz")) { try { in = new GZIPInputStream(in); } catch (IOException e) { in.close(); throw e; } } readXML(in, project, file); } /** * Read XML data from given input stream into this * object, populating the Project as a side effect. * An attempt will be made to close the input stream * (even if an exception is thrown). * * @param in the InputStream * @param project the Project */ public void readXML(@WillClose InputStream in, Project project, File base) throws IOException, DocumentException { assert in != null; assert project != null; try { doReadXML(in, project, base); } finally { in.close(); } } public void readXML(@WillClose InputStream in, Project project) throws IOException, DocumentException { doReadXML(in, project, null); } private void doReadXML(@WillClose InputStream in, Project project, File base) throws IOException, DocumentException { SAXBugCollectionHandler handler = new SAXBugCollectionHandler(this, project, base); try { checkInputStream(in); Profiler.getInstance().start(handler.getClass()); XMLReader xr = null; try { xr = XMLReaderFactory.createXMLReader(); } catch (SAXException e) { AnalysisContext.logError("Couldn't create XMLReaderFactory", e); throw new DocumentException("Sax error ", e); } xr.setContentHandler(handler); xr.setErrorHandler(handler); Reader reader = Util.getReader(in); xr.parse(new InputSource(reader)); } catch (SAXParseException e) { throw new DocumentException("Parse error at line " + e.getLineNumber() + " : " + e.getColumnNumber(), e); } catch (SAXException e) { // FIXME: throw SAXException from method? throw new DocumentException("Sax error ", e); } finally { Util.closeSilently(in); Profiler.getInstance().end(handler.getClass()); } // Presumably, project is now up-to-date project.setModified(false); } /** * Write this BugCollection to a file as XML. * * @param fileName the file to write to * @param project the Project from which the BugCollection was generated */ public void writeXML(String fileName, Project project) throws IOException { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName)); writeXML(out, project); } /** * Write this BugCollection to a file as XML. * * @param file the file to write to * @param project the Project from which the BugCollection was generated */ public void writeXML(File file, Project project) throws IOException { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); writeXML(out, project); } /** * Convert the BugCollection into a dom4j Document object. * * @param project the Project from which the BugCollection was generated * @return the Document representing the BugCollection as a dom4j tree */ public Document toDocument(@Nonnull Project project) { //if (project == null) throw new NullPointerException("No project"); assert project != null; DocumentFactory docFactory = new DocumentFactory(); Document document = docFactory.createDocument(); Dom4JXMLOutput treeBuilder = new Dom4JXMLOutput(document); try { writeXML(treeBuilder, project); } catch (IOException e) { // Can't happen } return document; } /** * Write the BugCollection to given output stream as XML. * The output stream will be closed, even if an exception is thrown. * * @param out the OutputStream to write to * @param project the Project from which the BugCollection was generated */ public void writeXML(@WillClose OutputStream out, @Nonnull Project project) throws IOException { assert project != null; XMLOutput xmlOutput; //if (project == null) throw new NullPointerException("No project"); if (withMessages) { xmlOutput= new OutputStreamXMLOutput(out, "http://findbugs.sourceforge.net/xsl/default.xsl"); } else { xmlOutput= new OutputStreamXMLOutput(out); } writeXML(xmlOutput, project); } public void writePrologue(XMLOutput xmlOutput, Project project) throws IOException { xmlOutput.beginDocument(); xmlOutput.openTag(ROOT_ELEMENT_NAME, new XMLAttributeList() .addAttribute("version", analysisVersion) .addAttribute("sequence",String.valueOf(getSequenceNumber())) .addAttribute("timestamp", String.valueOf(getTimestamp())) .addAttribute("analysisTimestamp", String.valueOf(getAnalysisTimestamp())) .addAttribute("release", getReleaseName()) ); project.writeXML(xmlOutput); } // private String getQuickInstanceHash(BugInstance bugInstance) { // String hash = bugInstance.getInstanceHash(); // if (hash != null) return hash; // MessageDigest digest = null; // try { digest = MessageDigest.getInstance("MD5"); // } catch (Exception e2) { // // OK, we won't digest // assert true; // hash = bugInstance.getInstanceKey(); // if (digest != null) { // byte [] data = digest.digest(hash.getBytes()); // String tmp = new BigInteger(1,data).toString(16); // if (false) System.out.println(hash + " -> " + tmp); // hash = tmp; // bugInstance.setInstanceHash(hash); // return hash; public void computeBugHashes() { if (preciseHashOccurrenceNumbersAvailable) return; invalidateHashes(); MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (Exception e2) { // OK, we won't digest } HashMap<String, Integer> seen = new HashMap<String, Integer>(); for(BugInstance bugInstance : getCollection()) { String hash = bugInstance.getInstanceHash(); if (hash == null) { hash = bugInstance.getInstanceKey(); if (digest != null) { byte [] data = digest.digest(hash.getBytes()); String tmp = new BigInteger(1,data).toString(16); if (false) System.out.println(hash + " -> " + tmp); hash = tmp; } bugInstance.setInstanceHash(hash); } Integer count = seen.get(hash); if (count == null) { bugInstance.setInstanceOccurrenceNum(0); seen.put(hash,0); } else { bugInstance.setInstanceOccurrenceNum(count+1); seen.put(hash, count+1); } } for(BugInstance bugInstance : getCollection()) bugInstance.setInstanceOccurrenceMax(seen.get(bugInstance.getInstanceHash())); preciseHashOccurrenceNumbersAvailable = true; } /** * Write the BugCollection to an XMLOutput object. * The finish() method of the XMLOutput object is guaranteed * to be called. * * <p> * To write the SummaryHTML element, set property * findbugs.report.SummaryHTML to "true". * </p> * * @param xmlOutput the XMLOutput object * @param project the Project from which the BugCollection was generated */ public void writeXML(@WillClose XMLOutput xmlOutput, @Nonnull Project project) throws IOException { assert project != null; try { writePrologue(xmlOutput, project); if (withMessages) { computeBugHashes(); getProjectStats().computeFileStats(this); String commonBase = null; for(String s : project.getSourceDirList()) { if (commonBase == null) commonBase = s; else commonBase = commonBase.substring(0, commonPrefix(commonBase, s)); } if (commonBase != null && commonBase.length() > 0) { if (commonBase.indexOf("/./") > 0) commonBase = commonBase.substring(0,commonBase.indexOf("/.")); File base = new File(commonBase); if (base.exists() && base.isDirectory() && base.canRead()) SourceLineAnnotation.generateRelativeSource(base, project); } } if (earlyStats) getProjectStats().writeXML(xmlOutput,withMessages); // Write BugInstances for(BugInstance bugInstance : getCollection()) if (!applySuppressions || !project.getSuppressionFilter().match(bugInstance)) bugInstance.writeXML(xmlOutput, withMessages, false); writeEpilogue(xmlOutput); } finally { xmlOutput.finish(); SourceLineAnnotation.clearGenerateRelativeSource(); } } int commonPrefix(String s1, String s2) { int pos = 0; while (pos < s1.length() && pos < s2.length() && s1.charAt(pos) == s2.charAt(pos)) pos++; return pos; } boolean earlyStats = SystemProperties.getBoolean("findbugs.report.summaryFirst"); public void writeEpilogue(XMLOutput xmlOutput) throws IOException { if (withMessages) { writeBugCategories( xmlOutput); writeBugPatterns( xmlOutput); writeBugCodes( xmlOutput); } // Errors, missing classes emitErrors(xmlOutput); if (!earlyStats) { // Statistics getProjectStats().writeXML(xmlOutput, withMessages); } // // Class and method hashes // xmlOutput.openTag(CLASS_HASHES_ELEMENT_NAME); // for (Iterator<ClassHash> i = classHashIterator(); i.hasNext();) { // ClassHash classHash = i.next(); // classHash.writeXML(xmlOutput); // xmlOutput.closeTag(CLASS_HASHES_ELEMENT_NAME); // Class features xmlOutput.openTag("ClassFeatures"); for (Iterator<ClassFeatureSet> i = classFeatureSetIterator(); i.hasNext();) { ClassFeatureSet classFeatureSet = i.next(); classFeatureSet.writeXML(xmlOutput); } xmlOutput.closeTag("ClassFeatures"); // AppVersions xmlOutput.openTag(HISTORY_ELEMENT_NAME); for (Iterator<AppVersion> i = appVersionIterator(); i.hasNext();) { AppVersion appVersion = i.next(); appVersion.writeXML(xmlOutput); } xmlOutput.closeTag(HISTORY_ELEMENT_NAME); // Summary HTML if ( REPORT_SUMMARY_HTML ) { String html = getSummaryHTML(); if (html != null && !html.equals("")) { xmlOutput.openTag(SUMMARY_HTML_ELEMENT_NAME); xmlOutput.writeCDATA(html); xmlOutput.closeTag(SUMMARY_HTML_ELEMENT_NAME); } } xmlOutput.closeTag(ROOT_ELEMENT_NAME); } private void writeBugPatterns(XMLOutput xmlOutput) throws IOException { // Find bug types reported Set<String> bugTypeSet = new HashSet<String>(); for (Iterator<BugInstance> i = iterator(); i.hasNext();) { BugInstance bugInstance = i.next(); BugPattern bugPattern = bugInstance.getBugPattern(); if (bugPattern != null) { bugTypeSet.add(bugPattern.getType()); } } // Emit element describing each reported bug pattern for (String bugType : bugTypeSet) { BugPattern bugPattern = I18N.instance().lookupBugPattern(bugType); if (bugPattern == null) continue; XMLAttributeList attributeList = new XMLAttributeList(); attributeList.addAttribute("type", bugType); attributeList.addAttribute("abbrev", bugPattern.getAbbrev()); attributeList.addAttribute("category", bugPattern.getCategory()); if (bugPattern.getCWEid() != 0) { attributeList.addAttribute("cweid", Integer.toString(bugPattern.getCWEid())); } xmlOutput.openTag("BugPattern", attributeList); xmlOutput.openTag("ShortDescription"); xmlOutput.writeText(bugPattern.getShortDescription()); xmlOutput.closeTag("ShortDescription"); xmlOutput.openTag("Details"); xmlOutput.writeCDATA(bugPattern.getDetailText()); xmlOutput.closeTag("Details"); xmlOutput.closeTag("BugPattern"); } } private void writeBugCodes(XMLOutput xmlOutput) throws IOException { // Find bug codes reported Set<String> bugCodeSet = new HashSet<String>(); for (Iterator<BugInstance> i = iterator(); i.hasNext();) { BugInstance bugInstance = i.next(); String bugCode = bugInstance.getAbbrev(); if (bugCode != null) { bugCodeSet.add(bugCode); } } // Emit element describing each reported bug code for (String bugCodeAbbrev : bugCodeSet) { BugCode bugCode = I18N.instance().getBugCode(bugCodeAbbrev); String bugCodeDescription = bugCode.getDescription(); if (bugCodeDescription == null) continue; XMLAttributeList attributeList = new XMLAttributeList(); attributeList.addAttribute("abbrev", bugCodeAbbrev); if (bugCode.getCWEid() != 0) { attributeList.addAttribute("cweid", Integer.toString(bugCode.getCWEid())); } xmlOutput.openTag("BugCode", attributeList); xmlOutput.openTag("Description"); xmlOutput.writeText(bugCodeDescription); xmlOutput.closeTag("Description"); xmlOutput.closeTag("BugCode"); } } private void writeBugCategories(XMLOutput xmlOutput) throws IOException { // Find bug categories reported Set<String> bugCatSet = new HashSet<String>(); for (Iterator<BugInstance> i = iterator(); i.hasNext();) { BugInstance bugInstance = i.next(); BugPattern bugPattern = bugInstance.getBugPattern(); if (bugPattern != null) { bugCatSet.add(bugPattern.getCategory()); } } // Emit element describing each reported bug code for (String bugCat : bugCatSet) { String bugCatDescription = I18N.instance().getBugCategoryDescription(bugCat); if (bugCatDescription == null) continue; XMLAttributeList attributeList = new XMLAttributeList(); attributeList.addAttribute("category", bugCat); xmlOutput.openTag("BugCategory", attributeList); xmlOutput.openTag("Description"); xmlOutput.writeText(bugCatDescription); xmlOutput.closeTag("Description"); xmlOutput.closeTag("BugCategory"); } } private void emitErrors(XMLOutput xmlOutput) throws IOException { //System.err.println("Writing errors to XML output"); XMLAttributeList attributeList = new XMLAttributeList(); attributeList.addAttribute("errors", Integer.toString(errorList.size())); attributeList.addAttribute("missingClasses", Integer.toString(missingClassSet.size())); xmlOutput.openTag(ERRORS_ELEMENT_NAME,attributeList); // Emit Error elements describing analysis errors for (Iterator<AnalysisError> i = errorIterator(); i.hasNext(); ) { AnalysisError error = i.next(); xmlOutput.openTag(ERROR_ELEMENT_NAME); xmlOutput.openTag(ERROR_MESSAGE_ELEMENT_NAME); xmlOutput.writeText(error.getMessage()); xmlOutput.closeTag(ERROR_MESSAGE_ELEMENT_NAME); if (error.getExceptionMessage() != null) { xmlOutput.openTag(ERROR_EXCEPTION_ELEMENT_NAME); xmlOutput.writeText(error.getExceptionMessage()); xmlOutput.closeTag(ERROR_EXCEPTION_ELEMENT_NAME); String stackTrace[] = error.getStackTrace(); if (stackTrace != null) { for (String aStackTrace : stackTrace) { xmlOutput.openTag(ERROR_STACK_TRACE_ELEMENT_NAME); xmlOutput.writeText(aStackTrace); xmlOutput.closeTag(ERROR_STACK_TRACE_ELEMENT_NAME); } } if (false && error.getNestedExceptionMessage() != null) { xmlOutput.openTag(ERROR_EXCEPTION_ELEMENT_NAME); xmlOutput.writeText(error.getNestedExceptionMessage()); xmlOutput.closeTag(ERROR_EXCEPTION_ELEMENT_NAME); stackTrace = error.getNestedStackTrace(); if (stackTrace != null) { for (String aStackTrace : stackTrace) { xmlOutput.openTag(ERROR_STACK_TRACE_ELEMENT_NAME); xmlOutput.writeText(aStackTrace); xmlOutput.closeTag(ERROR_STACK_TRACE_ELEMENT_NAME); } } } } xmlOutput.closeTag(ERROR_ELEMENT_NAME); } // Emit missing classes XMLOutputUtil.writeElementList(xmlOutput, MISSING_CLASS_ELEMENT_NAME, missingClassIterator()); xmlOutput.closeTag(ERRORS_ELEMENT_NAME); } private void checkInputStream(InputStream in) throws IOException { if (in.markSupported()) { byte[] buf = new byte[200]; in.mark(buf.length); int numRead = 0; boolean isEOF = false; while (numRead < buf.length && !isEOF) { int n = in.read(buf, numRead, buf.length - numRead); if (n < 0) { isEOF = true; } else { numRead += n; } } in.reset(); BufferedReader reader = new BufferedReader(Util.getReader(new ByteArrayInputStream(buf))); try { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("<BugCollection")) { return; } } } finally { reader.close(); } throw new IOException("XML does not contain saved bug data"); } } /** * Clone all of the BugInstance objects in the source Collection * and add them to the destination Collection. * * @param dest the destination Collection * @param source the source Collection */ public static void cloneAll(Collection<BugInstance> dest, Collection<BugInstance> source) { for (BugInstance obj : source) { dest.add((BugInstance) obj.clone()); } } public static class BugInstanceComparator implements Comparator<BugInstance> { private BugInstanceComparator() {} public int compare(BugInstance lhs, BugInstance rhs) { ClassAnnotation lca = lhs.getPrimaryClass(); ClassAnnotation rca = rhs.getPrimaryClass(); if (lca == null || rca == null) throw new IllegalStateException("null class annotation: " + lca + "," + rca); int cmp = lca.getClassName().compareTo(rca.getClassName()); if (cmp != 0) return cmp; return lhs.compareTo(rhs); } public static final BugInstanceComparator instance = new BugInstanceComparator(); } public static class MultiversionBugInstanceComparator extends BugInstanceComparator { @Override public int compare(BugInstance lhs, BugInstance rhs) { int result = super.compare(lhs,rhs); if (result != 0) return result; long diff = lhs.getFirstVersion() - rhs.getFirstVersion(); if (diff == 0) diff = lhs.getLastVersion() - rhs.getLastVersion(); if (diff < 0) return -1; if (diff > 0) return 1; return 0; } public static final MultiversionBugInstanceComparator instance = new MultiversionBugInstanceComparator(); } private Comparator<BugInstance> comparator; private TreeSet<BugInstance> bugSet; private LinkedHashSet<AnalysisError> errorList; private TreeSet<String> missingClassSet; @CheckForNull private String summaryHTML; private ProjectStats projectStats; // private Map<String, ClassHash> classHashMap; private Map<String, ClassFeatureSet> classFeatureSetMap; private List<AppVersion> appVersionList; private boolean preciseHashOccurrenceNumbersAvailable = false; /** * Sequence number of the most-recently analyzed version * of the code. */ private long sequence; /** * Release name of the analyzed application. */ private String releaseName; /** * Current analysis timestamp. */ private long timestamp; /** * Constructor. * Creates an empty object. */ public SortedBugCollection() { this(new ProjectStats()); } /** * Constructor. * Creates an empty object. */ public SortedBugCollection(Comparator<BugInstance> comparator) { this(new ProjectStats(), comparator); } /** * Constructor. * Creates an empty object given an existing ProjectStats. * * @param projectStats the ProjectStats */ public SortedBugCollection(ProjectStats projectStats) { this(projectStats, MultiversionBugInstanceComparator.instance); } /** * Constructor. * Creates an empty object given an existing ProjectStats. * * @param projectStats the ProjectStats * @param comparator to use for sorting bug instances */ public SortedBugCollection(ProjectStats projectStats, Comparator<BugInstance> comparator) { this.projectStats = projectStats; this.comparator = comparator; bugSet = new TreeSet<BugInstance>(comparator); errorList = new LinkedHashSet<AnalysisError>() { @Override public boolean add(AnalysisError a) { if (this.size() > 1000) return false; return super.add(a); } }; missingClassSet = new TreeSet<String>(); summaryHTML = null; classFeatureSetMap = new TreeMap<String, ClassFeatureSet>(); sequence = 0L; appVersionList = new LinkedList<AppVersion>(); releaseName = ""; timestamp = -1L; } public boolean add(BugInstance bugInstance, boolean updateActiveTime) { preciseHashOccurrenceNumbersAvailable = false; if (updateActiveTime) { bugInstance.setFirstVersion(sequence); } return bugSet.add(bugInstance); } private void invalidateHashes() { preciseHashOccurrenceNumbersAvailable = false; } public boolean remove(BugInstance bugInstance) { invalidateHashes(); return bugSet.remove(bugInstance); } public Iterator<BugInstance> iterator() { return bugSet.iterator(); } public Collection<BugInstance> getCollection() { return bugSet; } public void addError(String message, Throwable exception) { if (exception instanceof MissingClassException) { MissingClassException e = (MissingClassException) exception; addMissingClass(AbstractBugReporter.getMissingClassName(e.getClassNotFoundException())); return; } if (exception instanceof ClassNotFoundException) { ClassNotFoundException e = (ClassNotFoundException) exception; addMissingClass(AbstractBugReporter.getMissingClassName(e)); return; } if (exception instanceof edu.umd.cs.findbugs.classfile.MissingClassException) { edu.umd.cs.findbugs.classfile.MissingClassException e = (edu.umd.cs.findbugs.classfile.MissingClassException) exception; addMissingClass(AbstractBugReporter.getMissingClassName(e.toClassNotFoundException())); return; } errorList.add(new AnalysisError(message, exception)); } public void addError(AnalysisError error) { errorList.add(error); } public void addMissingClass(String className) { if (className.length() == 0) return; if (className.startsWith("[")) { assert false : "Bad class name " + className; return; } missingClassSet.add(className); } public Iterator<AnalysisError> errorIterator() { return errorList.iterator(); } public Iterator<String> missingClassIterator() { return missingClassSet.iterator(); } public boolean contains(BugInstance bugInstance) { return bugSet.contains(bugInstance); } public BugInstance getMatching(BugInstance bugInstance) { SortedSet<BugInstance> tailSet = bugSet.tailSet(bugInstance); if (tailSet.isEmpty()) return null; BugInstance first = tailSet.first(); return bugInstance.equals(first) ? first : null; } public String getSummaryHTML() throws IOException { if ( summaryHTML == null ) { try { StringWriter writer = new StringWriter(); ProjectStats stats = getProjectStats(); stats.transformSummaryToHTML(writer); summaryHTML = writer.toString(); } catch (final TransformerException e) { IOException ioe = new IOException("Couldn't generate summary HTML"); ioe.initCause(e); throw ioe; } } return summaryHTML; } public ProjectStats getProjectStats() { return projectStats; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#lookupFromUniqueId(java.lang.String) */ @Deprecated public BugInstance lookupFromUniqueId(String uniqueId) { for(BugInstance bug : bugSet) if (bug.getInstanceHash().equals(uniqueId)) return bug; return null; } public long getSequenceNumber() { return sequence; } public void setSequenceNumber(long sequence) { this.sequence = sequence; } public SortedBugCollection duplicate() { SortedBugCollection dup = new SortedBugCollection((ProjectStats) projectStats.clone(), comparator); SortedBugCollection.cloneAll(dup.bugSet, this.bugSet); dup.errorList.addAll(this.errorList); dup.missingClassSet.addAll(this.missingClassSet); dup.summaryHTML = this.summaryHTML; // dup.classHashMap.putAll(this.classHashMap); dup.classFeatureSetMap.putAll(this.classFeatureSetMap); dup.sequence = this.sequence; dup.timestamp = this.timestamp; dup.releaseName = this.releaseName; for (AppVersion appVersion : appVersionList) { dup.appVersionList.add((AppVersion) appVersion.clone()); } return dup; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#clearBugInstances() */ public void clearBugInstances() { bugSet.clear(); invalidateHashes(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#getReleaseName() */ public String getReleaseName() { if (releaseName == null) return ""; return releaseName; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#setReleaseName(java.lang.String) */ public void setReleaseName(String releaseName) { this.releaseName = releaseName; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#appVersionIterator() */ public Iterator<AppVersion> appVersionIterator() { return appVersionList.iterator(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#addAppVersion(edu.umd.cs.findbugs.AppVersion) */ public void addAppVersion(AppVersion appVersion) { appVersionList.add(appVersion); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#clearAppVersions() */ public void clearAppVersions() { appVersionList.clear(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#createEmptyCollectionWithMetadata() */ public SortedBugCollection createEmptyCollectionWithMetadata() { SortedBugCollection dup = new SortedBugCollection((ProjectStats) projectStats.clone(), comparator); dup.errorList.addAll(this.errorList); dup.missingClassSet.addAll(this.missingClassSet); dup.summaryHTML = this.summaryHTML; dup.classFeatureSetMap.putAll(this.classFeatureSetMap); dup.sequence = this.sequence; dup.analysisVersion = this.analysisVersion; dup.analysisTimestamp = dup.analysisTimestamp; dup.timestamp = this.timestamp; dup.releaseName = this.releaseName; for (AppVersion appVersion : appVersionList) { dup.appVersionList.add((AppVersion) appVersion.clone()); } return dup; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#setTimestamp(long) */ public void setTimestamp(long timestamp) { this.timestamp = timestamp; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#getTimestamp() */ public long getTimestamp() { return timestamp; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#getClassFeatureSet(java.lang.String) */ public ClassFeatureSet getClassFeatureSet(String className) { return classFeatureSetMap.get(className); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#setClassFeatureSet(edu.umd.cs.findbugs.model.ClassFeatureSet) */ public void setClassFeatureSet(ClassFeatureSet classFeatureSet) { classFeatureSetMap.put(classFeatureSet.getClassName(), classFeatureSet); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#classFeatureSetIterator() */ public Iterator<ClassFeatureSet> classFeatureSetIterator() { return classFeatureSetMap.values().iterator(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#clearClassFeatures() */ public void clearClassFeatures() { classFeatureSetMap.clear(); } /** * @param withMessages The withMessages to set. */ public void setWithMessages(boolean withMessages) { this.withMessages = withMessages; } /** * @return Returns the withMessages. */ public boolean getWithMessages() { return withMessages; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#getAppVersionFromSequenceNumber(int) */ public AppVersion getAppVersionFromSequenceNumber(long target) { for(AppVersion av : appVersionList) if (av.getSequenceNumber() == target) return av; if(target == this.getSequenceNumber()) return this.getCurrentAppVersion(); return null; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.BugCollection#findBug(java.lang.String, java.lang.String, int) */ public BugInstance findBug(String instanceHash, String bugType, int lineNumber) { for(BugInstance bug : bugSet) if (bug.getInstanceHash().equals(instanceHash) && bug.getBugPattern().getType().equals(bugType) && bug.getPrimarySourceLineAnnotation().getStartLine() == lineNumber) return bug; return null; } /** * @param version */ public void setAnalysisVersion(String version) { this.analysisVersion = version; } public String getAnalysisVersion() { return this.analysisVersion; } } // vim:ts=4
package com.foc.business.workflow.implementation; import java.sql.Date; import java.util.ArrayList; import java.util.Comparator; import com.foc.Globals; import com.foc.access.FocDataMap; import com.foc.admin.FocUser; import com.foc.business.notifier.FocNotificationConst; import com.foc.business.notifier.FocNotificationEvent; import com.foc.business.notifier.FocNotificationManager; import com.foc.db.DBManager; import com.foc.desc.FocConstructor; import com.foc.desc.FocDesc; import com.foc.desc.FocObject; import com.foc.desc.field.FDateTimeField; import com.foc.desc.field.FField; import com.foc.desc.field.FListField; import com.foc.list.FocList; import com.foc.list.FocListElement; import com.foc.log.HashedDocument; import com.foc.log.IFocLogLastHash; import com.foc.property.FObject; import com.foc.property.FProperty; import com.foc.serializer.FSerializer; import com.foc.serializer.FSerializerDictionary; import com.foc.util.Encryptor; import com.foc.util.Utils; public class Loggable { private ILoggable iLoggable = null; public Loggable(ILoggable focObject){ iLoggable = focObject; } public void dispose(){ iLoggable = null; } public ILoggable getILoggable() { return iLoggable; } public FocObject getFocObject(){ return (FocObject) iLoggable; } public FocDesc getFocDesc(){ FocObject focObj = getFocObject(); return focObj.getThisFocDesc(); } public ILoggableDesc getILoggableDesc(){ return (ILoggableDesc) getFocDesc(); } public LoggableDesc getLoggableDesc(){ return getILoggableDesc().iWorkflow_getWorkflowDesc(); } public FocDesc getWFLogDesc() { FocDesc logFocDesc = null; LoggableDesc loggableDesc = getLoggableDesc(); if(loggableDesc != null && getFocDesc() != null){ FListField listField = (FListField) getFocDesc().getFieldByID(loggableDesc.getFieldID_LogList()); if(listField != null) { logFocDesc = listField.getFocDesc(); } } return logFocDesc; } public FocList getLogList(){ return getLogList(false); } public FocList getLogList(boolean forceReload){ FocList list = null; LoggableDesc loggableDesc = getLoggableDesc(); if(loggableDesc != null && getFocObject() != null){ list = (FocList) getFocObject().getPropertyList(loggableDesc.getFieldID_LogList()); if(list != null){ list.setDirectlyEditable(false); list.setDirectImpactOnDatabase(true); if(list.getOrderComparator() == null){ list.setOrderComparator(new Comparator<FocListElement>(){ @Override public int compare(FocListElement e1, FocListElement e2){ WFLog o1 = (WFLog) e1.getFocObject(); WFLog o2 = (WFLog) e2.getFocObject(); long l = o1.getDateTime().getTime() - o2.getDateTime().getTime(); int ret = 0; if(l < 0) ret = -1; if(l > 0) ret = 1; return ret; } }); } if(forceReload) list.reloadFromDB(); } } return list; } public FocUser getLastModifUser(){ LoggableDesc workflowDesc = getLoggableDesc(); return (FocUser) getFocObject().getPropertyObject(workflowDesc.getFieldID_LastModificationUser()); } public void setLastModifUser(FocUser user){ LoggableDesc workflowDesc = getLoggableDesc(); getFocObject().setPropertyObject(workflowDesc.getFieldID_LastModificationUser(), user); } public void setLastModifUserRef(long ref){ LoggableDesc workflowDesc = getLoggableDesc(); FObject objProp = (FObject) getFocObject().getFocProperty(workflowDesc.getFieldID_LastModificationUser()); objProp.setLocalReferenceInt(ref); } public Date getLastModifDate(){ LoggableDesc workflowDesc = getLoggableDesc(); return getFocObject().getPropertyDate(workflowDesc.getFieldID_LastModificationDate()); } public void setLastModifDate(Date date){ LoggableDesc workflowDesc = getLoggableDesc(); getFocObject().setPropertyDate_WithoutListeners(workflowDesc.getFieldID_LastModificationDate(), date); } public String getLastModifDateSQLString(){ LoggableDesc workflowDesc = getLoggableDesc(); FProperty prop = getFocObject().getFocProperty(workflowDesc.getFieldID_LastModificationDate()); return prop != null ? prop.getSqlString() : null; } public void updateLastModified(FocUser user, Date dateTime) { if(getLoggableDesc() != null && getFocObject() != null) { long ref = getFocObject().getReferenceInt(); if(ref > 0) { FocDesc focDesc = getFocDesc(); long userRef = user != null ? user.getReferenceInt() : 0; setLastModifDate(dateTime); setLastModifUserRef(userRef); FDateTimeField lastModifDateFld = (FDateTimeField) focDesc.getFieldByID(getLoggableDesc().getFieldID_LastModificationDate()); FField lastModifUserFld = focDesc.getFieldByID(getLoggableDesc().getFieldID_LastModificationUser()); if(lastModifDateFld != null && lastModifUserFld != null) { StringBuffer buffer = null; if(focDesc.getProvider() == DBManager.PROVIDER_MYSQL) { buffer = new StringBuffer("UPDATE " + focDesc.getStorageName_ForSQL() + " "); buffer.append("set "+lastModifUserFld.getDBName()+" = "+userRef+" "); buffer.append(", "+lastModifDateFld.getDBName()+" = "+getLastModifDateSQLString()+" "); buffer.append(" where "+focDesc.getRefFieldName()+" = "+ref+" "); } else { buffer = new StringBuffer("UPDATE \"" + focDesc.getStorageName_ForSQL() + "\" "); buffer.append("set \""+lastModifUserFld.getDBName()+"\" = "+userRef+" "); buffer.append(", \""+lastModifDateFld.getDBName()+"\" = "+getLastModifDateSQLString()+" "); buffer.append(" where \""+focDesc.getRefFieldName()+"\" = "+ref+" "); } Globals.getApp().getDataSource().command_ExecuteRequest(buffer); } }else { setLastModifDate(dateTime); setLastModifUser(user); } } } protected void fillLogLine(WFLog log, int event){ if(log != null){ log.setEventType(event); if(log != null){ log.setUser(Globals.getApp().getUser_ForThisSession()); if(log.getUser() == null){ } log.setDateTime(Globals.getDBManager().getCurrentTimeStamp_AsTime()); } if(event == WFLogDesc.EVENT_MODIFICATION || event == WFLogDesc.EVENT_CREATION) { updateLastModified(log.getUser(), log.getDateTime()); } } } public void addLogLine(int event){ //setArea(workflow.iWorkflow_getComputedSite()); FocList focList = getLogList(); if(focList != null){ WFLog log = (WFLog) focList.newEmptyItem(); fillLogLine(log, event); } } // public void addLogLine(){ // int event = WFLogDesc.EVENT_NONE; // if(getFocObject().isCreated()){ // event = WFLogDesc.EVENT_CREATION; // }else if(getFocObject().isModified()) {// && !isCanceled()){ // event = WFLogDesc.EVENT_MODIFICATION; // addLogLine(event); public long insertLogLine(int event) { return insertLogLine(event, null); } public long insertLogLine(int event, String comment) {//, String sqlRequest return insertLogLine(event, comment, null); } public long insertLogLine(int event, String comment, String changes) {//, String sqlRequest long ref = 0; FocDesc logFocDesc = getWFLogDesc(); FocObject focObj = getFocObject(); if(logFocDesc != null && focObj != null && focObj.hasRealReference()) { FocConstructor constr = new FocConstructor(logFocDesc, null); WFLog log = (WFLog) constr.newItem(); if(log != null) { log.setCreated(true); log.setLogSubjectReference(focObj.getReferenceInt()); fillLogLine(log, event); if(!Utils.isStringEmpty(comment)) log.setComment(comment); if(!Utils.isStringEmpty(changes)) log.setChanges(changes); //Preparing the JSON with the latest version StringBuffer buff = new StringBuffer(); FSerializer ser = FSerializerDictionary.getInstance().newSerializer(focObj, buff, FSerializer.TYPE_JSON); if(ser != null) { ser.serializeToBuffer(); String fullJson = buff.toString(); if(!Utils.isStringEmpty(fullJson)) { log.setDocZip(fullJson); log.setDocVersion(ser.getVersion()); log.setDocHash(Encryptor.encrypt_MD5(fullJson)); } } //If the Event is open we check with the last HASH if(log.getEventType() == WFLogDesc.EVENT_OPENED) { fetchLastDocHashForChecking(new LastHashHandler(log.getDocZip(), log.getDocHash(), log.getDocVersion())); } log.validate(false); ref = log.getReferenceInt(); if(Globals.getApp() != null) { log.setObjectLogged(focObj); Globals.getApp().logListenerNotification(log); } log.dispose(); } } else { Globals.logString("Internal Exception: Could not insert log line"); } return ref; } private void fetchLastDocHashForChecking(IFocLogLastHash lastHashHandler) { FocObject focObj = getFocObject(); if(focObj != null && focObj.getThisFocDesc() != null && focObj.getReferenceInt() > 0) { HashedDocument hashed = new HashedDocument(focObj.getThisFocDesc().getStorageName(), focObj.getReferenceInt()); ArrayList<HashedDocument> array = new ArrayList<HashedDocument>(); array.add(hashed); Globals.getApp().logListenerGetLastHash(array, lastHashHandler); } } public class LastHashHandler implements IFocLogLastHash { private String fullDocComputed = null; private String hashComputed = null; private int versionOfComputed = 0; public LastHashHandler(String fullDocComputed, String hashComputed, int versionOfComputed) { this.fullDocComputed = fullDocComputed; this.hashComputed = hashComputed; this.versionOfComputed = versionOfComputed; } @Override public void lastLog(ArrayList<HashedDocument> lastHashedDoc) { /* FocObject focObj = getFocObject(); if(lastHashedDoc == null) { //If lastHashedDoc == null we compute from the log tables in FOC FocList list = getLogList(false); if(list != null) { list.loadIfNotLoadedFromDB(); if(list.size() > 0) { WFLog log = (WFLog) list.getFocObject(list.size()-1); if(log != null && log.getDocVersion() > 0 && !Utils.isStringEmpty(log.getDocZip())) { lastHashedDoc = new HashedDocument(); lastHashedDoc.setDocument(log.getDocZip()); lastHashedDoc.setVersion(log.getDocVersion()); lastHashedDoc.setHash(log.getDocHash()); } } } } //If lastHashedDoc is null this means we will not check anything if(lastHashedDoc != null) { //If the last saved version is lower than the new computed one we need to compute another if(lastHashedDoc.getVersion() != versionOfComputed && lastHashedDoc.getVersion() > 0) { StringBuffer buff = new StringBuffer(); FSerializer ser = FSerializerDictionary.getInstance().newSerializer(focObj, buff, FSerializer.TYPE_JSON, lastHashedDoc.getVersion()); if(ser != null) { ser.serializeToBuffer(); fullDocComputed = buff.toString(); if(!Utils.isStringEmpty(fullDocComputed)) { hashComputed = Encryptor.encrypt_MD5(fullDocComputed); versionOfComputed = lastHashedDoc.getVersion(); } } } if(!hashComputed.equals(lastHashedDoc.getHash())){ notifyForHashDiscrepancy(focObj, fullDocComputed, lastHashedDoc.getDocument(), versionOfComputed, lastHashedDoc.getVersion(), hashComputed, lastHashedDoc.getHash()); } } */ } } public static void notifyForHashDiscrepancy(FocObject focObj, String computedDoc, String storedDoc, int computedVersion, int storedVersion, String computedHash, String storedHash) { Globals.logString(" Globals.logString("--- "+focObj.getThisFocDesc().getStorageName()+" : "+focObj.getReferenceInt()); try { FocDataMap focDataMap = new FocDataMap(focObj); focDataMap.putString("TABLE_NAME", focObj.getThisFocDesc().getStorageName()); focDataMap.putString("COMPUTED_DOC", computedDoc); focDataMap.putString("EXPECTED_DOC", storedDoc); focDataMap.putString("COMPUTED_VERSION", String.valueOf(computedVersion)); focDataMap.putString("EXPECTED_VERSION", String.valueOf(storedVersion)); focDataMap.putString("COMPUTED_HASH", computedHash); focDataMap.putString("EXPECTED_HASH", storedHash); FocNotificationManager.getInstance().fireEvent(new FocNotificationEvent(FocNotificationConst.EVT_DOC_HASH_MISSMATCH, focDataMap)); }catch(Exception e){ Globals.logException(e); } } }
package bt.metainfo; import bt.bencoding.BtParseException; import bt.tracker.AnnounceKey; import org.junit.Before; import org.junit.Test; import java.net.MalformedURLException; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class MetadataServiceTest { private IMetadataService metadataService; @Before public void setUp() { metadataService = new MetadataService(); } @Test public void testBuildTorrent_SingleFile() throws Exception { Torrent torrent = metadataService.fromUrl(MetadataServiceTest.class.getResource("single_file.torrent")); assertHasAttributes(torrent, new AnnounceKey("http://jupiter.gx/ann"), "Arch-Uni-i686.iso", 524288L, 1766, 925892608L); assertNotNull(torrent.getFiles()); assertEquals(1, torrent.getFiles().size()); // TODO: add check for the torrent file } @Test public void testBuildTorrent_MultiFile() throws Exception { try { Torrent torrent = metadataService.fromUrl(MetadataServiceTest.class.getResource("multi_file.torrent")); AnnounceKey announceKey = new AnnounceKey(Arrays.asList( Collections.singletonList("http://jupiter.gx/ann"), Collections.singletonList("http://jupiter.local/announce") )); assertHasAttributes(torrent, announceKey, "BEWARE_BACH", 4194304L, 1329, 5573061611L); assertNotNull(torrent.getFiles()); assertEquals(6, torrent.getFiles().size()); } catch (Exception e) { e.printStackTrace(); } // TODO: add checks for all torrent files } private void assertHasAttributes(Torrent torrent, AnnounceKey announceKey, String name, long chunkSize, int chunkHashesCount, long size) throws MalformedURLException { assertTrue(torrent.getAnnounceKeyOptional().isPresent()); assertEquals(announceKey, torrent.getAnnounceKeyOptional().get()); assertEquals(name, torrent.getName()); assertEquals(chunkSize, torrent.getChunkSize()); int actualChunkHashesCount = 0; for (byte[] hash : torrent.getChunkHashes()) { assertEquals(20, hash.length); actualChunkHashesCount++; } assertEquals(chunkHashesCount, actualChunkHashesCount); assertEquals(size, torrent.getSize()); } @Test public void testBuildTorrent_ParseExceptionContents() { String metainfo = "d8:announce15:http://t.co/ann byte[] bytes = metainfo.getBytes(Charset.forName("ASCII")); BtParseException exception = null; try { metadataService.fromByteArray(bytes); } catch (BtParseException e) { exception = e; } assertNotNull(exception); assertArrayEquals(Arrays.copyOfRange(bytes, 0, 30), exception.getScannedContents()); } }
package io.spacedog.examples; import java.util.Optional; import java.util.Random; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.spacedog.client.SpaceClient; import io.spacedog.client.SpaceRequest; import io.spacedog.client.SpaceTarget; import io.spacedog.utils.DataPermission; import io.spacedog.utils.Json; import io.spacedog.utils.JsonGenerator; import io.spacedog.utils.Schema; import io.spacedog.utils.StripeSettings; public class Caremen extends SpaceClient { static final Backend DEV = new Backend( "caredev", "caredev", "hi caredev", "david@spacedog.io"); private Backend backend; private JsonGenerator generator = new JsonGenerator(); private Random random = new Random(); @Test public void initCaremenBackend() { backend = DEV; SpaceRequest.configuration().target(SpaceTarget.production); // resetBackend(backend); // initInstallations(); // initVehiculeTypes(); // initStripeSettings(); // setSchema(buildCourseSchema(), backend); // setSchema(buildDriverSchema(), backend); // setSchema(buildCustomerSchema(), backend); // setSchema(buildCourseLogSchema(), backend); // setSchema(buildCustomerCompanySchema(), backend); // setSchema(buildCompanySchema(), backend); // createDrivers(); } void initStripeSettings() { StripeSettings settings = new StripeSettings(); settings.secretKey = SpaceRequest.configuration().testStripeSecretKey(); SpaceClient.saveSettings(backend, settings); } static Schema buildCustomerSchema() { return Schema.builder("customer") .acl("user", DataPermission.create, DataPermission.search, DataPermission.update) .acl("admin", DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("credentialsId").examples("khljgGFJHfvlkHMhjh") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .string("phone").examples("+ 33 6 42 01 67 56") .object("billing") .text("name").french().examples("In-tact SARL") .text("street").french().examples("9 rue Titon") .string("zipcode").examples("75011") .text("town").examples("Paris") .close() .close() .build(); } static Schema buildCustomerCompanySchema() { return Schema.builder("customercompany") .acl("user", DataPermission.read_all) .acl("admin", DataPermission.create, DataPermission.update_all, DataPermission.delete_all, DataPermission.search) .string("companyId") .string("companyName") .build(); } void initInstallations() { SpaceRequest.delete("/1/schema/installation").adminAuth(backend).go(200, 404); SpaceRequest.put("/1/schema/installation").adminAuth(backend).go(201); Schema schema = SpaceClient.getSchema("installation", backend); schema.acl("key", DataPermission.create, DataPermission.read, DataPermission.update, DataPermission.delete); schema.acl("user", DataPermission.create, DataPermission.read, DataPermission.update, DataPermission.delete); schema.acl("admin", DataPermission.search, DataPermission.update_all, DataPermission.delete_all); SpaceClient.setSchema(schema, backend); } static Schema buildCourseSchema() { return Schema.builder("course") .acl("user", DataPermission.create, DataPermission.read, DataPermission.search, DataPermission.update) .acl("driver", DataPermission.search, DataPermission.update_all) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("status") .string("requestedVehiculeType").examples("classic") .timestamp("requestedPickupTimestamp").examples("2016-07-12T14:00:00.000Z") .timestamp("pickupTimestamp").examples("2016-07-12T14:00:00.000Z") .timestamp("dropoffTimestamp").examples("2016-07-12T14:00:00.000Z") .text("noteForDriver") .floatt("fare").examples(23.82)// in euros .longg("time").examples(1234567)// in millis .integer("distance").examples(12345)// in meters .string("customerId") .object("customer") .string("id") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .string("phone").examples("+ 33 6 42 01 67 56") .close() .object("payment") .string("companyId") .string("companyName") .object("stripe") .string("customerId") .string("cardId") .string("paymentId") .close() .close() .object("from") .text("address").french().examples("8 rue Titon 75011 Paris") .geopoint("geopoint") .close() .object("to") .text("address").french().examples("8 rue Pierre Dupont 75010 Paris") .geopoint("geopoint") .close() .object("driver") .string("driverId").examples("robert") .floatt("gain").examples("10.23") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .string("phone").examples("+ 33 6 42 01 67 56") .string("photo") .examples("http://s3-eu-west-1.amazonaws.com/spacedog-artefact/SpaceDog-Logo-Transp-130px.png")// .object("vehicule") .string("type").examples("classic") .string("brand").examples("Peugeot", "Renault") .string("model").examples("508", "Laguna", "Talisman") .string("color").examples("black", "white", "pink") .string("licencePlate").examples("BM-500-FG") .close() .close() .build(); } void createDrivers() { Schema schema = buildDriverSchema(); createDriver("marcel", schema); createDriver("gerard", schema); createDriver("robert", schema); createDriver("suzanne", schema); } void createDriver(String username, Schema schema) { String password = "hi " + username; String email = (username.startsWith("driver") ? "driver" : username) + "@caremen.com"; Optional<User> optional = SpaceClient.login(backend.backendId, username, password, 200, 401); User credentials = optional.isPresent() ? optional.get() : SpaceClient.signUp(backend, username, password, email); SpaceRequest.put("/1/credentials/" + credentials.id + "/roles/driver").adminAuth(backend).go(200); ObjectNode driver = generator.gen(schema, 0); driver.put("status", "working"); driver.put("credentialsId", credentials.id); driver.put("firstname", credentials.username); driver.put("lastname", credentials.username.charAt(0) + "."); JsonNode where = Json.object("lat", 48.844 + (random.nextFloat() / 10), "lon", 2.282 + (random.nextFloat() / 10)); Json.set(driver, "lastLocation.where", where); SpaceRequest.post("/1/data/driver").adminAuth(backend).body(driver).go(201); } static Schema buildDriverSchema() { return Schema.builder("driver") .acl("user", DataPermission.search) .acl("driver", DataPermission.search, DataPermission.update_all) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("credentialsId").examples("khljgGFJHfvlkHMhjh") .string("status").examples("working") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .text("homeAddress").french().examples("52 rue Michel Ange 75016 Paris") .string("phone").examples("+ 33 6 42 01 67 56") .string("photo") .examples("http://s3-eu-west-1.amazonaws.com/spacedog-artefact/SpaceDog-Logo-Transp-130px.png")// .object("lastLocation") .geopoint("where") .timestamp("when") .close() .object("vehicule") .string("type").examples("classic") .string("brand").examples("Peugeot", "Renault") .string("model").examples("508", "Laguna", "Talisman") .string("color").examples("black", "white", "pink") .string("licencePlate").examples("BM-500-RF") .close() .object("RIB") .text("bankName").french().examples("Société Générale") .string("bankCode").examples("SOGEFRPP") .string("accountIBAN").examples("FR568768757657657689") .close() .close() .build(); } static Schema buildCourseLogSchema() { return Schema.builder("courselog") .acl("driver", DataPermission.create) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.delete_all) .string("courseId") .string("driverId") .string("status") .geopoint("where") .close() .build(); } Schema buildCompanySchema() { return Schema.builder("company") .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .text("name") .text("address") .string("status") .string("vatId") .close() .build(); } void initVehiculeTypes() { ObjectNode node = Json.objectBuilder() .object("classic") .put("type", "classic") .put("name", "Berline Classic") .put("description", "Standard") .put("minimumPrice", 10) .put("passengers", 4) .end() .object("premium") .put("type", "premium") .put("name", "Berline Premium") .put("description", "Haut de gamme") .put("minimumPrice", 15) .put("passengers", 4) .end() .object("green") .put("type", "green") .put("name", "GREEN BERLINE") .put("description", "Electric cars") .put("minimumPrice", 15) .put("passengers", 4) .end() .object("break") .put("type", "break") .put("name", "BREAK") .put("description", "Grand coffre") .put("minimumPrice", 15) .put("passengers", 4) .end() .object("van") .put("type", "van") .put("name", "VAN") .put("description", "Mini bus") .put("minimumPrice", 15) .put("passengers", 6) .end() .build(); SpaceRequest.put("/1/settings/vehiculeTypes") .adminAuth(backend).body(node).go(201); } }
class RectangleCounter { }
package ucar.nc2.iosp.grib; import ucar.grib.GribChecker; import ucar.grib.GribIndexName; import ucar.grib.grib2.Grib2WriteIndex; import ucar.grib.grib1.Grib1WriteIndex; import ucar.nc2.dt.fmrc.ForecastModelRunInventory; import java.util.List; import java.util.ArrayList; import java.util.Calendar; import java.io.*; // Purpose: walks directory structure making Grib Indexes as needed. // Uses a configuration file to designate which dirs to index public final class GribBinaryIndexer { /** * delete all indexes, it makes a complete rebuild */ private static boolean removeGBX = false; /* * dirs to inspect */ private List<String> dirs = new ArrayList<String>(); /* * reads in the configuration file * */ private boolean readConf(String conf) throws IOException { InputStream ios = new FileInputStream(conf); BufferedReader dataIS = new BufferedReader(new InputStreamReader(ios)); while (true) { String line = dataIS.readLine(); if (line == null) { break; } if (line.startsWith(" continue; } dirs.add(line); //System.out.println( line ); } ios.close(); return true; } /* * clears all IndexLock in the directories * */ private void clearLocks() { for (String dir : dirs) { File f = new File(dir + "/IndexLock"); if (f.exists()) { f.delete(); System.out.println("Cleared lock " + dir + "/IndexLock"); } else { System.out.println("In directory " + dir); } } } /* * walks the directory trees setting IndexLocks * */ private void indexer() throws IOException { System.out.println("Start " + Calendar.getInstance().getTime().toString()); long start = System.currentTimeMillis(); for (String dir : dirs) { File d = new File(dir); if (!d.exists()) { System.out.println("Dir " + dir + " doesn't exists"); continue; } File dl = new File(dir + "/IndexLock"); if (dl.exists()) { System.out.println("Exiting " + dir + " another Indexer working here"); continue; } //System.out.println( "In directory "+ dir ); dl.createNewFile(); // create a lock while indexing dir checkDirs(d); dl.delete(); // delete lock when done } System.out.println("End " + Calendar.getInstance().getTime().toString()); System.out.println("Total time in ms " + (System.currentTimeMillis() - start )); } /* * checkDirs is a recursive routine used to walk the directory tree in a * depth first search checking the index of GRIB files . */ private void checkDirs(File dir) throws IOException { if (dir.isDirectory()) { System.out.println("In directory " + dir.getParent() + "/" + dir.getName()); String[] children = dir.list(); for (String aChildren : children) { if (aChildren.equals("IndexLock")) continue; //System.out.println( "children i ="+ children[ i ]); File child = new File(dir, aChildren); //System.out.println( "child ="+ child.getName() ); if (child.isDirectory()) { checkDirs(child); // skip index *gbx and inventory *xml files } else if (aChildren.endsWith(GribIndexName.oldSuffix ) || aChildren.endsWith(GribIndexName.currentSuffix) || aChildren.endsWith("xml") || aChildren.endsWith("tmp") || //index in creation process aChildren.length() == 0) { // zero length file, ugh... } else { checkIndex(dir, child); } } } else { } } /* * checks the status of index files * */ private void checkIndex(File dir, File grib) throws IOException { String[] args = new String[2]; //File gbx = new File(dir, grib.getName() + ".gbx"); //File gbx = new File( GribIndexName.getNew( dir.getParent() +"/"+ grib.getName() )); File gbx = new File( GribIndexName.getCurrentSuffix( grib.getPath() )); if (removeGBX && gbx.exists()) gbx.delete(); //System.out.println( "index ="+ gbx.getName() ); //args[0] = grib.getParent() + "/" + grib.getName(); args[0] = grib.getPath(); //args[1] = grib.getParent() + "/" + gbx.getName(); args[1] = gbx.getPath(); //System.out.println( "args ="+ args[ 0] +" "+ args[ 1 ] ); if (gbx.exists()) { // skip files older than 3 hours if ((System.currentTimeMillis() - grib.lastModified()) > 10800000) return; // skip indexes that have a length of 0, most likely there is a index problem if (gbx.length() == 0) { System.out.println("ERROR " + args[1] + " has length zero"); return; } } if (grib.getName().endsWith("grib1")) { grib1check(grib, gbx, args); } else if (grib.getName().endsWith("grib2")) { grib2check(grib, gbx, args); } else { // else check file for Grib version ucar.unidata.io.RandomAccessFile raf = new ucar.unidata.io.RandomAccessFile(args[0], "r"); //System.out.println("Grib "+ args[ 0 ] ); int result = GribChecker.getEdition(raf); if (result == 2) { //System.out.println("Valid Grib Edition 2 File"); grib2check(grib, gbx, args); } else if (result == 1) { //System.out.println("Valid Grib Edition 1 File"); grib1check(grib, gbx, args); } else { System.out.println("Not a Grib File " + args[0]); } raf.close(); } } /* * indexes or extends Grib1 files plus creates inventories files * */ private void grib1check(File grib, File gbx, String[] args) { // args 0 grib name, args 1 grib index name try { if (gbx.exists()) { // gbx older then grib if (grib.lastModified() < gbx.lastModified()) return; // grib, gbx, gribName, gbxName, false(make index) long start = System.currentTimeMillis(); new Grib1WriteIndex().extendGribIndex(grib, gbx, args[0], args[1], false); System.out.println("IndexExtending " + grib.getName() +" took "+ (System.currentTimeMillis() - start) +" ms BufferSize "+ Grib2WriteIndex.indexRafBufferSize); ForecastModelRunInventory.open(null, args[0], ForecastModelRunInventory.OPEN_FORCE_NEW, true); } else { // create index // grib, gribName, gbxName, false(make index) long start = System.currentTimeMillis(); new Grib1WriteIndex().writeGribIndex(grib, args[0], args[1], false); System.out.println("Indexing " + grib.getName() +" took "+ (System.currentTimeMillis() - start) +" ms BufferSize "+ Grib2WriteIndex.indexRafBufferSize); ForecastModelRunInventory.open(null, args[0], ForecastModelRunInventory.OPEN_FORCE_NEW, true); } } catch (Exception e) { e.printStackTrace(); System.out.println("Caught Exception doing index or inventory for " + grib.getName()); } } /* * indexes or extends Grib2 files plus creates inventories files * */ private void grib2check(File grib, File gbx, String[] args) { try { if (gbx.exists()) { // gbx older than grib, no need to check if (grib.lastModified() < gbx.lastModified()) { return; } // grib, gbx, gribName, gbxName, false(make index) long start = System.currentTimeMillis(); new Grib2WriteIndex().extendGribIndex(grib, gbx, args[0], args[1], false); System.out.println("IndexExtending " + grib.getName() +" took "+ (System.currentTimeMillis() - start) +" ms BufferSize "+ Grib2WriteIndex.indexRafBufferSize); ForecastModelRunInventory.open(null, args[0], ForecastModelRunInventory.OPEN_FORCE_NEW, true); } else { // create index // grib, gribName, gbxName, false(make index) long start = System.currentTimeMillis(); new Grib2WriteIndex().writeGribIndex(grib, args[0], args[1], false); System.out.println("Indexing " + grib.getName() +" took "+ (System.currentTimeMillis() - start) +" ms BufferSize "+ Grib2WriteIndex.indexRafBufferSize); ForecastModelRunInventory.open(null, args[0], ForecastModelRunInventory.OPEN_FORCE_NEW, true); } } catch (Exception e) { e.printStackTrace(); System.out.println("Caught Exception doing index or inventory for " + grib.getName()); } } static public boolean test() throws IOException { GribBinaryIndexer gi = new GribBinaryIndexer(); String[] args = new String[ 2 ]; args[ 0 ] = "C:/data/grib/g2p5U.grib2"; args[ 1 ] = GribIndexName.getCurrentSuffix( args[ 0 ] ); File grib = new File( args[ 0 ]); File gbx = new File( args[ 1 ]); gi.grib2check( grib, gbx, args); return true; } /** * main. * * @param args can be clear and the GribIndexer.conf file * @throws IOException on io error */ // process command line switches static public void main(String[] args) throws IOException { //if( test() ) // return; GribBinaryIndexer gbi = new GribBinaryIndexer(); boolean clear = false; for (String arg : args) { if (arg.equals("clear")) { clear = true; System.out.println("Clearing Index locks"); continue; } else if (arg.equals("remove")) { removeGBX = true; System.out.println("Removing all indexes"); continue; } // else conf file File f = new File(arg); if (!f.exists()) { System.out.println("Conf file " + arg + " doesn't exist: "); return; } // read in conf file gbi.readConf(arg); } if (clear) { gbi.clearLocks(); return; } // Grib Index files in dirs gbi.indexer(); } }
package org.commacq.db.csv; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.concurrent.ThreadSafe; import org.apache.commons.lang3.StringEscapeUtils; import org.commacq.CompositeIdEncoding; import org.commacq.CompositeIdEncodingEscaped; import org.commacq.CsvLine; import org.commacq.db.EntityConfig; import org.commacq.db.StringColumnValueConverter; /** * So, why choose to write yet another implementation * of a CSV utility? By taking total control over the * behaviour of this aspect of the program, we can ensure * that the output is exactly as desired and that the * performance is optimised without any compromises to * fitting in with a more generic library. We can avoid * creating temporary objects like string arrays and * instead go straight to CSV output lines. Seen as what * this server does all day is turn resultsets into CSV * it seems like a reasonable investment. * * NULL is represented by absolutely no value between the * commas; for example: a,b,,d * Blank space is regarded as special and must be quoted; * for example: a,b,"",d * * Dates are yyyy-MM-dd and are not surrounded by quotes. * Timestamps are yyyy-MM-ddTHH:mm:ssZZ (with timezone specified) * and are not surrounded by quotes. * * If you want different behaviour, change your select statement * to return a string with exactly the format you want. Use * your database features rather than falling back to the default * behaviour provided by this class. Or, if you really want, * override the behaviour in this class and plug in your own * instance of this CsvParser. * * BigDecimals are always in non-scientific notation and * quoted to the precision that they arrive in (with trailing * zeros if required). If you want to change the precision, * do it in your database select statement. They are not * surrounded by quotes. */ @ThreadSafe public class CsvMarshaller { public static final char COMMA = ','; public static final char QUOTE = '"'; public static final String EMPTY_STRING = "\"\""; public static final StringColumnValueConverter stringColumnValueConverter = new StringColumnValueConverter(); private final CompositeIdEncoding compositeIdEncoding = new CompositeIdEncodingEscaped(); private ThreadLocal<StringBuilder> stringBuilder = new ThreadLocal<StringBuilder>() { protected StringBuilder initialValue() { return new StringBuilder(2048); }; @Override public StringBuilder get() { StringBuilder returnMe = super.get(); returnMe.setLength(0); //Blank out the string builder for its next use return returnMe; } }; public CsvLine toCsvLine(ResultSet result, EntityConfig entityConfig) throws SQLException { StringBuilder builder = stringBuilder.get(); ResultSetMetaData metaData = result.getMetaData(); int columnCount = metaData.getColumnCount(); if(columnCount <= 0) { throw new SQLException("No columns to consider"); } String id = null; //Will never end up being null. Compiler isn't clever enough to detect that. int startFromColumn; if(entityConfig.getCompositeIdColumns() != null) { //Haven't calculated the id yet; will have to prefix it to the line afterwards startFromColumn = 1; } else { String idValue = getColumnValue(result, metaData.getColumnType(1), 1); id = StringEscapeUtils.escapeCsv(idValue); startFromColumn = 2; //We've already processed column 1: id. builder.append(id); } Map<String, String> groupValues = new HashMap<String, String>(entityConfig.getGroups().size()); Map<String, String> compositeKeyValues = null; if(entityConfig.getCompositeIdColumns() != null) { compositeKeyValues = new HashMap<String, String>(entityConfig.getCompositeIdColumns().size()); } for (int i = startFromColumn; i <= metaData.getColumnCount(); i++) { builder.append(COMMA); String columnValue = getColumnValue(result, metaData.getColumnType(i), i); appendEscapedCsvEntry(builder, columnValue); String columnLabel = metaData.getColumnLabel(i); if(entityConfig.getGroups().contains(columnLabel)) { groupValues.put(columnLabel, columnValue); } if(compositeKeyValues != null) { if(entityConfig.getCompositeIdColumns().contains(columnLabel)) { compositeKeyValues.put(columnLabel, columnValue); } } } if(compositeKeyValues != null) { String[] components = new String[entityConfig.getCompositeIdColumns().size()]; int index = 0; for(String compositeColumn : entityConfig.getCompositeIdColumns()) { String value = compositeKeyValues.get(compositeColumn); if(value == null) { throw new RuntimeException("Null value in composite key column: " + compositeColumn); } components[index++] = value; } id = StringEscapeUtils.escapeCsv(compositeIdEncoding.createCompositeId(components)); builder.insert(0, id); } return new CsvLine(id, builder.toString(), groupValues); } /** * Column labels not column names. * We want to take account of the "as" clause */ public String getColumnLabelsAsCsvLine(ResultSetMetaData metaData, Collection<String> groups) throws SQLException { int columnCount = metaData.getColumnCount(); SortedSet<String> copyOfGroups = new TreeSet<String>(groups); StringBuilder builder = stringBuilder.get(); if(columnCount > 0) { String columnLabel = metaData.getColumnLabel(1); appendEscapedCsvEntry(builder, columnLabel); copyOfGroups.remove(columnLabel); } for(int i = 2; i <= columnCount; i++) { builder.append(COMMA); String columnLabel = metaData.getColumnLabel(i); appendEscapedCsvEntry(builder, columnLabel); copyOfGroups.remove(columnLabel); } if(!copyOfGroups.isEmpty()) { throw new SQLException("Groups specified that are not contained as columns in the query results: " + copyOfGroups); } return builder.toString(); } /** * Adds the CSV entry, escaping where required. Does not add a comma. * @return the String that was appended */ protected void appendEscapedCsvEntry(final StringBuilder builder, final String value) { if(value == null) { //nulls end up as separators with nothing inbetween ,, return; } if(value.isEmpty()) { //Empty string is treated as a special case to differentiate //it from null. It's quoted. builder.append(EMPTY_STRING); return; } String escapedString = StringEscapeUtils.escapeCsv(value); builder.append(escapedString); } protected String getColumnValue(ResultSet rs, int colType, int colIndex) throws SQLException { return stringColumnValueConverter.getColumnValue(rs, colType, colIndex); } }
package org.pocketcampus.shared.plugin.social; import org.pocketcampus.shared.plugin.authentication.AuthToken; public class User { private final String firstName_; private final String lastName_; private final String sciper_; private String sessionId_; public User(String firstName, String lastName, String sciper) { valid(firstName, lastName, sciper); this.firstName_ = firstName; this.lastName_ = lastName; this.sciper_ = sciper; this.sessionId_ = null; } public User(String id) { if(id == null) throw new IllegalArgumentException(); String[] data = id.split("\\."); if(data.length != 3) throw new IllegalArgumentException(); valid(data[0], data[1], data[2]); this.lastName_ = underscoreToNice(data[0]); this.firstName_ = underscoreToNice(data[1]); this.sciper_ = data[2]; this.sessionId_ = null; } public String getSessionId() { return sessionId_; } public void setSessionId(String sessionId) { if(sessionId == null || sessionId.length() != AuthToken.SESSION_ID_SIZE) throw new IllegalArgumentException(); this.sessionId_ = sessionId; } public String getFirstName() { return firstName_; } public String getLastName() { return lastName_; } public String getSciper() { return sciper_; } private static void valid(String first, String last, String sciper) { } private static String niceToUnderscore(final String s) { String rtrn = ""; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c != ' ') rtrn+=c; else rtrn+='_'; } return rtrn; } private static String underscoreToNice(final String s) { String rtrn = ""; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c != '_') rtrn+=c; else rtrn+=' '; } return rtrn; } public String getIdFormat() { return niceToUnderscore(lastName_) + "." + niceToUnderscore(firstName_) + "." + sciper_; } private String getNiceFormat() { String fullName = firstName_ + " " + lastName_; String out = null; // try { // out = new String(fullName.getBytes("ISO-8859-1")); // } catch(UnsupportedEncodingException e) { out = fullName; return out; } @Override public int hashCode() { return getIdFormat().hashCode(); } @Override public String toString() { return getNiceFormat(); } }
/* * $Id$ * $URL$ */ package org.subethamail.web.action.auth; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.subethamail.web.Backend; import org.tagonist.RedirectException; /** * If the user is logged in, issue a redirect to the * destination specified by actionParam "dest". If * dest is not supplied, defaults to /home.jsp. * * An auto login will occur if proper cookies are available. * * @author Jeff Schnitzer */ public class AuthRedirect extends AutoLogin { @SuppressWarnings("unused") private static Log log = LogFactory.getLog(AuthRedirect.class); protected void execute2() throws Exception { if (this.isLoggedIn()) { String loc = null; String siteUrl = Backend.instance().getAdmin().getDefaultSiteUrl().toString(); if ("http://needsconfiguration/se/".equals(siteUrl)) loc = this.getCtx().getRequest().getContextPath(); else loc = siteUrl; String redir = this.getActionParam("dest"); if (redir != null) loc = loc + redir; else loc = loc + "home.jsp"; throw new RedirectException(this.getCtx().getResponse().encodeRedirectURL(loc)); } } }
package com.googlecode.goclipse.builder; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.Util; import com.googlecode.goclipse.Activator; import com.googlecode.goclipse.Environment; import com.googlecode.goclipse.go.lang.lexer.Lexer; import com.googlecode.goclipse.go.lang.lexer.Tokenizer; import com.googlecode.goclipse.go.lang.model.Import; import com.googlecode.goclipse.go.lang.parser.ImportParser; import com.googlecode.goclipse.preferences.PreferenceConstants; import com.googlecode.goclipse.utils.ObjectUtils; /** * GoCompiler provides the GoClipse interface to the go build tool. */ public class GoCompiler { private static final QualifiedName COMPILER_VERSION_QN = new QualifiedName(Activator.PLUGIN_ID, "compilerVersion"); /** environment for build */ private Map<String, String> env; private String version; private long versionLastUpdated = 0; public GoCompiler() {} /** * Returns the current compiler version (ex. "6g version release.r58 8787"). * Returns null if we were unable to recover the compiler version. The * returned string should be treated as an opaque token. * * @return the current compiler version */ public static String getCompilerVersion() { String version = null; IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); String compilerPath = preferenceStore.getString(PreferenceConstants.GO_TOOL_PATH); if (compilerPath == null || compilerPath.length() == 0) { return null; } try { String[] cmd = { compilerPath, GoConstants.GO_VERSION_COMMAND }; Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec(cmd); try { p.waitFor(); } catch (InterruptedException e) { Activator.logInfo(e); } InputStream is = p.getInputStream(); InputStream es = p.getErrorStream(); StreamAsLines output = new StreamAsLines(); StreamAsLines errors = new StreamAsLines(); output.process(is); errors.process(es); final String GO_VERSION = "go version "; for (String line : output.getLines()) { if (line != null && line.startsWith(GO_VERSION)) { version = line.substring(GO_VERSION.length()); break; } } } catch (IOException e) { Activator.logInfo(e); } return version; } /** * TODO this needs to be centralized into a common index... * * @param file * @return * @throws IOException */ private List<Import> getImports(File file) throws IOException { Lexer lexer = new Lexer(); Tokenizer tokenizer = new Tokenizer(lexer); ImportParser importParser = new ImportParser(tokenizer); BufferedReader reader = new BufferedReader(new FileReader(file)); String temp = ""; StringBuilder builder = new StringBuilder(); while( (temp = reader.readLine()) != null ) { builder.append(temp); builder.append("\n"); } reader.close(); lexer.scan(builder.toString()); List<Import> imports = importParser.getImports(); return imports; } /** * @param project * @param target */ public void goGetDependencies(final IProject project, IProgressMonitor monitor, java.io.File target) { final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); final IPath projectLocation = project.getLocation(); final String compilerPath = preferenceStore.getString(PreferenceConstants.GO_TOOL_PATH); final IFile file = project.getFile(target.getAbsolutePath().replace(projectLocation.toOSString(), "")); try { /** * TODO Allow the user to set the go get locations * manually. */ List<Import> imports = getImports(target); List<String> cmd = new ArrayList<String>(); List<Import> extImports = new ArrayList<Import>(); monitor.beginTask("Importing external libraries for "+file.getName()+":", 5); for (Import imp: imports) { if (imp.getName().startsWith("code.google.com") || imp.getName().startsWith("github.com") || imp.getName().startsWith("bitbucket.org") || imp.getName().startsWith("launchpad.net") || imp.getName().contains(".git") || imp.getName().contains(".svn") || imp.getName().contains(".hg") || imp.getName().contains(".bzr") ){ cmd.add(imp.getName()); extImports.add(imp); } } monitor.worked(1); //String[] cmd = { compilerPath, GoConstants.GO_GET_COMMAND, "-u" }; cmd.add(0, "-u"); cmd.add(0, "-fix"); cmd.add(0, GoConstants.GO_GET_COMMAND); cmd.add(0, compilerPath); String goPath = buildGoPath(project, projectLocation, true); String PATH = System.getenv("PATH"); ProcessBuilder builder = new ProcessBuilder(cmd).directory(target.getParentFile()); builder.environment().put(GoConstants.GOROOT, Environment.INSTANCE.getGoRoot(project)); builder.environment().put(GoConstants.GOPATH, goPath); builder.environment().put("PATH", PATH); Process p = builder.start(); monitor.worked(3); try { p.waitFor(); } catch (InterruptedException e) { Activator.logInfo(e); } InputStream is = p.getInputStream(); InputStream es = p.getErrorStream(); StreamAsLines sal = new StreamAsLines(); sal.setCombineLines(true); sal.process(is); sal.process(es); Activator.logInfo(sal.getLinesAsString()); boolean exMsg = true; try { project.deleteMarkers(MarkerUtilities.MARKER_ID, false, IResource.DEPTH_ZERO); } catch (CoreException e1) { Activator.logError(e1); } MarkerUtilities.deleteFileMarkers(file); if (sal.getLines().size() > 0) { for (String line : sal.getLines()) { if (line.startsWith("package")) { String impt = line.substring(0,line.indexOf(" -")); impt = impt.replaceFirst("package ", ""); for (Import i:extImports) { if (i.path.equals(impt)) { MarkerUtilities.addMarker(file, i.getLine(), line.substring(line.indexOf(" -")+2), IMarker.SEVERITY_ERROR); } } } else if (line.contains(".go:")) { try { String[] split = line.split(":"); String path = "GOPATH/"+split[0].substring(split[0].indexOf("/src/")+5); IFile extfile = project.getFile(path); int lineNumber = Integer.parseInt(split[1]); String msg = split[3]; if(extfile!=null && extfile.exists()){ MarkerUtilities.addMarker(extfile, lineNumber, msg, IMarker.SEVERITY_ERROR); } else if (exMsg) { exMsg = false; MarkerUtilities.addMarker(file, "There are problems with the external imports in this file.\n" + "You may want to attempt to resolve them outside of eclipse.\n" + "Here is the GOPATH to use: \n\t"+goPath); } } catch (Exception e){ Activator.logError(e); } } } } monitor.worked(1); } catch (IOException e1) { Activator.logInfo(e1); } } /** * @param projectLocation * @return */ public static String buildGoPath(IProject project, final IPath projectLocation, boolean extGoRootFavored) { String delim = ":"; if (Util.isWindows()){ delim = ";"; } String goPath = projectLocation.toOSString(); String[] path = Environment.INSTANCE.getGoPath(project); final String GOPATH = path[0]; if (GOPATH != null && GOPATH != "") { if (extGoRootFavored) { goPath = GOPATH + delim + goPath; } else { goPath = goPath + delim + GOPATH; } } for(int i = 1; i < path.length; i++){ goPath = goPath + delim + path[i]; } return goPath; } /** * @param project * @param pmonitor * @param fileList */ public void compileCmd(final IProject project, IProgressMonitor pmonitor, java.io.File target) { final IPath projectLocation = project.getLocation(); final IFile file = project.getFile(target.getAbsolutePath().replace(projectLocation.toOSString(), "")); final String pkgPath = target.getParentFile().getAbsolutePath().replace(projectLocation.toOSString(), ""); final IPath binFolder = Environment.INSTANCE.getBinOutputFolder(project); final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); final String compilerPath = preferenceStore.getString(PreferenceConstants.GO_TOOL_PATH); final String outExtension = (Util.isWindows() ? ".exe" : ""); try { // the path exist to find the cc String path = System.getenv("PATH"); String outPath = null; String[] cmd = {}; MarkerUtilities.deleteFileMarkers(file); if(Environment.INSTANCE.isCmdSrcFolder(project, (IFolder)file.getParent())){ outPath = projectLocation.toOSString() + File.separator + binFolder + File.separator + target.getName().replace(GoConstants.GO_SOURCE_FILE_EXTENSION, outExtension); cmd = new String[]{ compilerPath, GoConstants.GO_BUILD_COMMAND, GoConstants.COMPILER_OPTION_O, outPath, file.getName() }; } else { MarkerUtilities.deleteFileMarkers(file.getParent()); outPath = projectLocation.toOSString() + File.separator + binFolder + File.separator + target.getParentFile().getName() + outExtension; cmd = new String[] { compilerPath, GoConstants.GO_BUILD_COMMAND, GoConstants.COMPILER_OPTION_O, outPath }; } String goPath = buildGoPath(project, projectLocation, false); ProcessBuilder builder = new ProcessBuilder(cmd).directory(target.getParentFile()); builder.environment().put(GoConstants.GOROOT, Environment.INSTANCE.getGoRoot(project)); builder.environment().put(GoConstants.GOPATH, goPath); builder.environment().put("PATH", path); Process p = builder.start(); try { p.waitFor(); } catch (InterruptedException e) { Activator.logInfo(e); } refreshProject(project, pmonitor); readAndProcessOutput(project, file, pkgPath, p); } catch (IOException e1) { Activator.logInfo(e1); } } /** * * @param output * @param project * @param relativeTargetDir */ private void processCompileOutput(final StreamAsLines output, final IProject project, final String relativeTargetDir, final IFile file) { boolean iswindows = Util.isWindows(); for (String line : output.getLines()) { if (line.startsWith(" continue; } else if(line.startsWith("can't load package:")) { /* * when building a main package mixed with a * lib package this error occurs and is not * specific to any one file. It is related * to the organization of the project. */ IContainer container = file.getParent(); if(container instanceof IFolder){ IFolder folder = (IFolder)container; MarkerUtilities.addMarker(folder, 0, line, IMarker.SEVERITY_ERROR); } continue; } int goPos = line.indexOf(GoConstants.GO_SOURCE_FILE_EXTENSION); if (goPos > 0) { int fileNameLength = goPos + GoConstants.GO_SOURCE_FILE_EXTENSION.length(); // Strip the prefix off the error message String fileName = line.substring(0, fileNameLength); fileName = fileName.replace(project.getLocation().toOSString(), ""); fileName = iswindows?fileName:fileName.substring(fileName.indexOf(":") + 1).trim(); // Determine the type of error message if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } else if (fileName.startsWith("." + File.separator)) { fileName = relativeTargetDir.substring(1) + File.separator + fileName.substring(2); } else if (line.startsWith("can't")) { fileName = relativeTargetDir.substring(1); } else { fileName = relativeTargetDir.substring(1) + File.separator + fileName; } // find the resource if possible IResource resource = project.findMember(fileName); if (resource == null && file != null) { resource = file; } else if (resource == null) { resource = project; } // Create the error message String msg = line.substring(fileNameLength + 1); String[] str = msg.split(":", 3); int location = -1; // marker for trouble int messageStart = msg.indexOf(": "); try { location = Integer.parseInt(str[0]); } catch (NumberFormatException nfe) {} // Determine how to mark the message if (location != -1 && messageStart != -1) { String message = msg.substring(messageStart + 2); MarkerUtilities.addMarker(resource, location, message, IMarker.SEVERITY_ERROR); } else { // play safe. to show something in UI MarkerUtilities.addMarker(resource, 1, line, IMarker.SEVERITY_ERROR); } } else { // runtime.main: undefined: main.main MarkerUtilities.addMarker(file, 1, line, IMarker.SEVERITY_ERROR); } } } /** * @param project * @param pmonitor * @param fileList */ public void compilePkg(final IProject project, IProgressMonitor pmonitor, final String pkgpath, java.io.File target) { final IPath projectLocation = project.getLocation(); final IFile file = project.getFile(target.getAbsolutePath().replace(projectLocation.toOSString(), "")); final String pkgPath = target.getParentFile().getAbsolutePath().replace(projectLocation.toOSString(), ""); final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); final String compilerPath = preferenceStore.getString(PreferenceConstants.GO_TOOL_PATH); try { String[] cmd = { compilerPath, GoConstants.GO_BUILD_COMMAND, GoConstants.COMPILER_OPTION_O, pkgpath, "." }; String goPath = buildGoPath(project, projectLocation, false); // PATH so go can find cc String path = System.getenv("PATH"); String goroot = Environment.INSTANCE.getGoRoot(project); ProcessBuilder builder = new ProcessBuilder(cmd).directory(target.getParentFile()); builder.environment().put(GoConstants.GOROOT, goroot); builder.environment().put(GoConstants.GOPATH, goPath); builder.environment().put("PATH", path); Process p = builder.start(); try { p.waitFor(); } catch (InterruptedException e) { Activator.logInfo(e); } refreshProject(project, pmonitor); clearPackageErrorMessages(project, pkgPath); readAndProcessOutput(project, file, pkgPath, p); } catch (IOException e1) { Activator.logInfo(e1); } } /** * @param project * @param file * @param pkgPath * @param p */ private void readAndProcessOutput(final IProject project, final IFile file, final String pkgPath, Process p) { InputStream is = p.getInputStream(); InputStream es = p.getErrorStream(); StreamAsLines sal = new StreamAsLines(); sal.setCombineLines(true); sal.process(is); sal.process(es); if (sal.getLines().size() > 0) { processCompileOutput(sal, project, pkgPath, file); } } /** * @param project * @param pmonitor */ private void refreshProject(final IProject project, IProgressMonitor pmonitor) { try { project.refreshLocal(IResource.DEPTH_INFINITE, pmonitor); } catch (CoreException e) { Activator.logInfo(e); } } /** * @param project * @param pkgPath */ private void clearPackageErrorMessages(final IProject project, final String pkgPath) { IFolder folder = project.getFolder(pkgPath); try { for (IResource res:folder.members()){ if(res instanceof IFile){ MarkerUtilities.deleteFileMarkers(res); } } } catch (CoreException e) { Activator.logError(e); } } /** * * @return */ public String getVersion() { // The getCompilerVersion() call takes about ~30 msec to compute. // Because it's expensive, // we cache the value for a short time. final long TEN_SECONDS = 10 * 1000; if ((System.currentTimeMillis() - versionLastUpdated) > TEN_SECONDS) { version = getCompilerVersion(); versionLastUpdated = System.currentTimeMillis(); } return version; } /** * * @param project * @param dependencies * @return */ private boolean dependenciesExist(IProject project, String[] dependencies) { ArrayList<String> sourceDependencies = new ArrayList<String>(); for (String dependency : dependencies) { if (dependency.endsWith(GoConstants.GO_SOURCE_FILE_EXTENSION)) { sourceDependencies.add(dependency); } } return GoBuilder.dependenciesExist(project, sourceDependencies.toArray(new String[] {})); } /** * @param project */ public void updateVersion(IProject project) { try { project.setPersistentProperty(COMPILER_VERSION_QN, getVersion()); } catch (CoreException ex) { Activator.logError(ex); } } /** * @param project * @return */ public boolean requiresRebuild(IProject project) { String storedVersion; try { storedVersion = project.getPersistentProperty(COMPILER_VERSION_QN); } catch (CoreException ex) { storedVersion = null; } String currentVersion = getVersion(); if (currentVersion == null) { // We were not able to get the latest compiler version - don't force // a rebuild. return false; } else { return !ObjectUtils.objectEquals(storedVersion, currentVersion); } } }
package org.skyve.impl.bind; import java.beans.Introspector; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.StringTokenizer; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.comparators.ComparatorChain; import org.skyve.CORE; import org.skyve.domain.Bean; import org.skyve.domain.ChildBean; import org.skyve.domain.HierarchicalBean; import org.skyve.domain.MapBean; import org.skyve.domain.PersistentBean; import org.skyve.domain.messages.DomainException; import org.skyve.domain.messages.Message; import org.skyve.domain.messages.SkyveException; import org.skyve.domain.messages.ValidationException; import org.skyve.domain.types.DateOnly; import org.skyve.domain.types.DateTime; import org.skyve.domain.types.Decimal; import org.skyve.domain.types.Decimal10; import org.skyve.domain.types.Decimal2; import org.skyve.domain.types.Decimal5; import org.skyve.domain.types.Enumeration; import org.skyve.domain.types.OptimisticLock; import org.skyve.domain.types.TimeOnly; import org.skyve.domain.types.Timestamp; import org.skyve.domain.types.converters.Converter; import org.skyve.domain.types.converters.Format; import org.skyve.impl.metadata.customer.CustomerImpl; import org.skyve.impl.metadata.model.document.DocumentImpl; import org.skyve.impl.metadata.model.document.field.ConvertableField; import org.skyve.impl.metadata.model.document.field.Field; import org.skyve.impl.util.NullTolerantBeanComparator; import org.skyve.impl.util.ThreadSafeFactory; import org.skyve.impl.util.UtilImpl; import org.skyve.metadata.MetaDataException; import org.skyve.metadata.SortDirection; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.model.Attribute; import org.skyve.metadata.model.Extends; import org.skyve.metadata.model.Attribute.AttributeType; import org.skyve.metadata.model.document.Bizlet.DomainValue; import org.skyve.metadata.model.document.Collection; import org.skyve.metadata.model.document.Collection.CollectionType; import org.skyve.metadata.model.document.Collection.Ordering; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.model.document.DomainType; import org.skyve.metadata.model.document.Relation; import org.skyve.metadata.module.Module; import org.skyve.metadata.user.User; import org.skyve.persistence.DocumentQuery; import org.skyve.util.Binder; import org.skyve.util.Binder.TargetMetaData; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; /** * Provides utilities for getting and setting simple and compound bean properties. */ public final class BindUtil { private static final String DEFAULT_DISPLAY_DATE_FORMAT = "dd/MM/yyyy"; private static final DeproxyingPropertyUtilsBean PROPERTY_UTILS = new DeproxyingPropertyUtilsBean(); public static String formatMessage(Customer customer, String message, Bean... beans) { StringBuilder result = new StringBuilder(message); int openCurlyBraceIndex = result.indexOf("{"); while (openCurlyBraceIndex >= 0) { if ((openCurlyBraceIndex == 0) || // first char is '{' // '{' is present and not escaped with a preceding '\' - ie \{ is escaped ((openCurlyBraceIndex > 0) && (result.charAt(openCurlyBraceIndex - 1) != '\\'))) { int closedCurlyBraceIndex = result.indexOf("}", openCurlyBraceIndex); String binding = result.substring(openCurlyBraceIndex + 1, closedCurlyBraceIndex); boolean found = false; Exception cause = null; for (Bean bean : beans) { String documentName = bean.getBizDocument(); if (documentName != null) { try { // Try to get the value from this bean // Do not use BindUtil.getMetaDataForBinding as it may not be a document // property, it could be a condition or an implicit property. String displayValue = BindUtil.getDisplay(customer, bean, binding); result.replace(openCurlyBraceIndex, closedCurlyBraceIndex + 1, displayValue); openCurlyBraceIndex = result.indexOf("{", openCurlyBraceIndex + 1); found = true; break; } catch (Exception e) { cause = e; } } } if (! found) { StringBuilder exMessage = new StringBuilder(); exMessage.append("Bean"); if (beans.length > 1) { exMessage.append("s"); } exMessage.append(" - "); for (int offset = 0; offset < beans.length; offset++) { Bean bean = beans[offset]; exMessage.append(bean.getBizDocument()); if (offset - 1 < beans.length) { exMessage.append(", "); } } exMessage.append(" do"); if (beans.length == 1) { exMessage.append("es"); } exMessage.append(" not contain binding - "); exMessage.append(binding); if (cause == null) { throw new MetaDataException(exMessage.toString()); } throw new MetaDataException(exMessage.toString(), cause); } } else { // escaped { found - ie "\{" - remove the escape chars and move on to the next pair of {} result.replace(openCurlyBraceIndex - 1, openCurlyBraceIndex, ""); openCurlyBraceIndex = result.indexOf("{", openCurlyBraceIndex); // NB openCurlyBracedIndex was not decremented but a char was removed } } return result.toString().replace("\\}", "}"); // remove any escaped closing curly braces now } public static boolean messageIsBound(String message) { boolean bound = false; int openCurlyBraceIndex = message.indexOf('{'); while ((! bound) && openCurlyBraceIndex >= 0) { bound = (openCurlyBraceIndex == 0) || // first char is '{' // '{' is present and not escaped with a preceding '\' - ie \{ is escaped ((openCurlyBraceIndex > 0) && (message.charAt(openCurlyBraceIndex - 1) != '\\')); } return bound; } public static boolean messageBindingsAreValid(Customer customer, Module module, Document document, String message) { boolean valid = true; StringBuilder result = new StringBuilder(message); int openCurlyBraceIndex = result.indexOf("{"); while (valid && (openCurlyBraceIndex >= 0)) { if ((openCurlyBraceIndex == 0) || // first char is '{' // '{' is present and not escaped with a preceding '\' - ie \{ is escaped ((openCurlyBraceIndex > 0) && (result.charAt(openCurlyBraceIndex - 1) != '\\'))) { int closedCurlyBraceIndex = result.indexOf("}", openCurlyBraceIndex); if (closedCurlyBraceIndex < 0) { valid = false; } else { String binding = result.substring(openCurlyBraceIndex + 1, closedCurlyBraceIndex); if (binding.isEmpty()) { valid = false; } else { try { // Check the binding in this bean TargetMetaData target = BindUtil.getMetaDataForBinding(customer, module, document, binding); if (target == null) { valid = false; } openCurlyBraceIndex = result.indexOf("{", openCurlyBraceIndex + 1); } catch (Exception e) { valid = false; } } } } else { // escaped { found - ie "\{" - remove the escape chars and move on to the next pair of {} result.replace(openCurlyBraceIndex - 1, openCurlyBraceIndex, ""); openCurlyBraceIndex = result.indexOf("{", openCurlyBraceIndex); // NB openCurlyBracedIndex was not decremented but a char was removed } } return valid; } /** * Place the bindingPrefix + '.' + <existing expression> wherever a binding expression - {<expression>} occurs. * @param message The message to process. Can be null. * @param bindingPrefix The binding prefix to prefix with. * @return The prefixed message or null if message argument was null. */ public static String prefixMessageBindings(String message, String bindingPrefix) { if (message == null) { return null; } String bindingPrefixAndDot = bindingPrefix + '.'; StringBuilder result = new StringBuilder(message); int openCurlyBraceIndex = result.indexOf("{"); while (openCurlyBraceIndex >= 0) { if ((openCurlyBraceIndex == 0) || // first char is '{' // '{' is present and not escaped with a preceding '\' - ie \{ is escaped ((openCurlyBraceIndex > 0) && (result.charAt(openCurlyBraceIndex - 1) != '\\'))) { result.insert(openCurlyBraceIndex + 1, bindingPrefixAndDot); openCurlyBraceIndex = result.indexOf("{", openCurlyBraceIndex + 1); } } return result.toString(); } public static String negateCondition(String condition) { String result = null; if (condition != null) { if ("true".equals(condition)) { result = "false"; } else if ("false".equals(condition)) { result = "true"; } else if (condition.startsWith("not")) { result = Introspector.decapitalize(condition.substring(3)); } else { StringBuilder sb = new StringBuilder(condition.length() + 3); sb.append("not").append(Character.valueOf(Character.toUpperCase(condition.charAt(0)))); sb.append(condition.substring(1)); result = sb.toString(); } } return result; } /** * Provides implicit conversions for types that do not require coercion, * that is they can be converted without input and without loss of precision. * * @param type * @param value * @return */ public static Object convert(Class<?> type, Object value) { Object result = value; if (value != null) { if (type.equals(Integer.class)) { if ((! (value instanceof Integer)) && (value instanceof Number)) { result = new Integer(((Number) value).intValue()); } } else if (type.equals(Long.class)) { if ((! (value instanceof Long)) && (value instanceof Number)) { result = new Long(((Number) value).longValue()); } } else if (type.equals(Short.class)) { if ((! (value instanceof Short)) && (value instanceof Number)) { result = new Short(((Number) value).shortValue()); } } else if (type.equals(Float.class)) { if ((! (value instanceof Float)) && (value instanceof Number)) { result = new Float(((Number) value).floatValue()); } } else if (type.equals(Double.class)) { if ((! (value instanceof Double)) && (value instanceof Number)) { result = new Double(((Number) value).doubleValue()); } } else if (type.equals(BigDecimal.class)) { if (! (value instanceof BigDecimal)) { result = new BigDecimal(value.toString()); } } else if (type.equals(Decimal2.class)) { if (! (value instanceof Decimal2)) { result = new Decimal2(value.toString()); } } else if (type.equals(Decimal5.class)) { if (! (value instanceof Decimal5)) { result = new Decimal5(value.toString()); } } else if (type.equals(Decimal10.class)) { if (! (value instanceof Decimal10)) { result = new Decimal10(value.toString()); } } else if (type.equals(DateOnly.class)) { if ((! (value instanceof DateOnly)) && (value instanceof Date)) { result = new DateOnly(((Date) value).getTime()); } } else if (type.equals(TimeOnly.class)) { if ((! (value instanceof TimeOnly)) && (value instanceof Date)) { result = new TimeOnly(((Date) value).getTime()); } } else if (type.equals(DateTime.class)) { if ((! (value instanceof DateTime)) && (value instanceof Date)) { result = new DateTime(((Date) value).getTime()); } } else if (type.equals(Timestamp.class)) { if ((! (value instanceof Timestamp)) && (value instanceof Date)) { result = new Timestamp(((Date) value).getTime()); } } else if (type.equals(Geometry.class)) { if (value instanceof String) { try { result = new WKTReader().read((String) value); } catch (ParseException e) { throw new DomainException(value + " is not valid WKT", e); } } } // NB type.isEnum() doesn't work as our enums implement another interface // NB Enumeration.class.isAssignableFrom(type) doesn't work as enums are not assignable as they are a synthesised class else if (Enum.class.isAssignableFrom(type)) { if (value instanceof String) { // Since we can't test for assignable, see if we can see the Enumeration interface Class<?>[] interfaces = type.getInterfaces(); if ((interfaces.length == 1) && (Enumeration.class.equals(interfaces[0]))) { try { result = type.getMethod(Enumeration.FROM_CODE_METHOD_NAME, String.class).invoke(null, value); if (result == null) { result = type.getMethod(Enumeration.FROM_DESCRIPTION_METHOD_NAME, String.class).invoke(null, value); } } catch (Exception e) { throw new DomainException(value + " is not a valid enumerated value in type " + type, e); } } if (result == null) { result = Enum.valueOf(type.asSubclass(Enum.class), (String) value); } } } } return result; } /** * This method is synchronized as {@link Converter#fromDisplayValue(Object)} requires synchronization. * Explicit type coercion using the <code>converter</code> if supplied, or by java language coercion. * * @param attribute Used for type conversion. Can be <code>null</code>. * @param type * @param displayValue * @return */ public static synchronized Object fromString(Customer customer, Converter<?> converter, Class<?> type, String stringValue, boolean fromSerializedFormat) { Object result = null; try { if ((! fromSerializedFormat) && (converter != null)) { result = converter.fromDisplayValue(stringValue); } else if (type.equals(String.class)) { result = stringValue; } else if (type.equals(Integer.class)) { if(converter!=null){ result = converter.fromDisplayValue(stringValue); } else { result = new Integer(stringValue); } } else if (type.equals(Long.class)) { result = new Long(stringValue); } else if (type.equals(Float.class)) { result = new Float(stringValue); } else if (type.equals(Double.class)) { result = new Double(stringValue); } else if (type.equals(BigDecimal.class)) { result = new BigDecimal(stringValue); } else if (type.equals(Decimal2.class)) { result = new Decimal2(stringValue); } else if (type.equals(Decimal5.class)) { result = new Decimal5(stringValue); } else if (type.equals(Decimal10.class)) { result = new Decimal10(stringValue); } else if (type.equals(Boolean.class)) { result = Boolean.valueOf(stringValue.equals("true")); } else if (type.equals(DateOnly.class)) { if (fromSerializedFormat) { result = new DateOnly(stringValue); } else { Date date = customer.getDefaultDateConverter().fromDisplayValue(stringValue); result = new DateOnly(date.getTime()); } } else if (type.equals(TimeOnly.class)) { if (fromSerializedFormat) { result = new TimeOnly(stringValue); } else { Date date = customer.getDefaultTimeConverter().fromDisplayValue(stringValue); result = new TimeOnly(date.getTime()); } } else if (type.equals(DateTime.class)) { if (fromSerializedFormat) { result = new DateTime(stringValue); } else { Date date = customer.getDefaultDateTimeConverter().fromDisplayValue(stringValue); result = new DateTime(date.getTime()); } } else if (type.equals(Timestamp.class)) { if (fromSerializedFormat) { result = new Timestamp(stringValue); } else { Date date = customer.getDefaultTimestampConverter().fromDisplayValue(stringValue); result = new Timestamp(date.getTime()); } } else if (Geometry.class.isAssignableFrom(type)) { result = new WKTReader().read(stringValue); } else if (Date.class.isAssignableFrom(type)) { result = new java.sql.Timestamp(ThreadSafeFactory.getDateFormat(DEFAULT_DISPLAY_DATE_FORMAT).parse(stringValue).getTime()); } else if (type.equals(OptimisticLock.class)) { result = new OptimisticLock(stringValue); } // NB type.isEnum() doesn't work as our enums implement another interface // NB Enumeration.class.isAssignableFrom(type) doesn't work as enums are not assignable as they are a synthesised class else if (Enum.class.isAssignableFrom(type)) { result = convert(type, stringValue); } else { throw new IllegalStateException("BindUtil.setPropertyFromDisplay() - Can't convert type " + type); } } catch (Exception e) { if (e instanceof SkyveException) { throw (SkyveException) e; } throw new DomainException(e); } return result; } /** * This method is synchronized as {@link Converter#toDisplayValue(Object)} requires synchronization. * * @param converter Can be <code>null</code>. * @param object * @return */ @SuppressWarnings("unchecked") private static synchronized String toDisplay(Customer customer, @SuppressWarnings("rawtypes") Converter converter, List<DomainValue> domainValues, Object value) { String result = ""; try { if (value == null) { // do nothing as result is already empty } else if (domainValues != null) { if (value instanceof Enumeration) { result = ((Enumeration) value).toDescription(); } else { boolean found = false; String codeValue = value.toString(); for (DomainValue domainValue : domainValues) { if (domainValue.getCode().equals(codeValue)) { result = domainValue.getDescription(); found = true; break; } } if (! found) { result = codeValue; } } } else if (converter != null) { result = converter.toDisplayValue(convert(converter.getAttributeType().getImplementingType(), value)); } else if (value instanceof DateOnly) { result = customer.getDefaultDateConverter().toDisplayValue((DateOnly) value); } else if (value instanceof TimeOnly) { result = customer.getDefaultTimeConverter().toDisplayValue((TimeOnly) value); } else if (value instanceof DateTime) { result = customer.getDefaultDateTimeConverter().toDisplayValue((DateTime) value); } else if (value instanceof Timestamp) { result = customer.getDefaultTimestampConverter().toDisplayValue((Timestamp) value); } else if (value instanceof Date) { result = ThreadSafeFactory.getDateFormat(DEFAULT_DISPLAY_DATE_FORMAT).format((Date) value); } else if (value instanceof Boolean) { result = (((Boolean) value).booleanValue() ? "Yes" : "No"); } else { result = value.toString(); } } catch (Exception e) { if (e instanceof SkyveException) { throw (SkyveException) e; } throw new DomainException(e); } return result; } @SuppressWarnings({"rawtypes", "unchecked"}) public static Object getSerialized(Customer customer, Bean bean, String binding) { Object result = null; try { result = BindUtil.get(bean, binding); String documentName = bean.getBizDocument(); if (documentName != null) { Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, documentName); try { TargetMetaData target = BindUtil.getMetaDataForBinding(customer, module, document, binding); Attribute attribute = target.getAttribute(); if (attribute instanceof ConvertableField) { Converter<?> converter = ((ConvertableField) attribute).getConverterForCustomer(customer); if (converter != null) { Format format = converter.getFormat(); if (format != null) { result = format.toDisplayValue(result); } } } } catch (MetaDataException e) { // The binding may be a column alias with no metadata, so do nothing when this occurs } } } catch (Exception e) { if (e instanceof SkyveException) { throw (SkyveException) e; } throw new DomainException(e); } return result; } public static String getDisplay(Customer customer, Bean bean, String binding) { Converter<?> converter = null; List<DomainValue> domainValues = null; Object value = get(bean, binding); String documentName = bean.getBizDocument(); if (documentName != null) { Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, documentName); TargetMetaData target = null; Attribute attribute = null; try { target = BindUtil.getMetaDataForBinding(customer, module, document, binding); attribute = target.getAttribute(); } catch (MetaDataException e) { // do nothing } if (attribute instanceof Field) { Field field = (Field) attribute; if (field instanceof ConvertableField) { converter = ((ConvertableField) field).getConverterForCustomer(customer); } DomainType domainType = field.getDomainType(); if (domainType != null) { DocumentImpl internalDocument = (DocumentImpl) document; if (DomainType.dynamic.equals(domainType)) { // Get the real deal if this is a MapBean from a query Bean realBean = bean; if (bean instanceof MapBean) { realBean = (Bean) ((MapBean) bean).get(DocumentQuery.THIS_ALIAS); } int lastDotIndex = binding.lastIndexOf('.'); if (lastDotIndex >= 0) { Bean owningBean = (Bean) get(realBean, binding.substring(0, lastDotIndex)); if ((owningBean != null) && (target != null)) { internalDocument = (DocumentImpl) target.getDocument(); domainValues = internalDocument.getDomainValues((CustomerImpl) customer, domainType, field, owningBean); } } else { domainValues = internalDocument.getDomainValues((CustomerImpl) customer, domainType, field, realBean); } } else { domainValues = internalDocument.getDomainValues((CustomerImpl) customer, domainType, field, null); } } } } return toDisplay(customer, converter, domainValues, value); } /** * Given a list of bindings, create a compound one. ie binding1.binding2.binding3 etc * * @param bindings * @return */ public static String createCompoundBinding(String... bindings) { StringBuilder result = new StringBuilder(64); for (String simpleBinding : bindings) { result.append(simpleBinding).append('.'); } result.setLength(result.length() - 1); return result.toString(); } /** * Given a simple binding and an index, create a compound one. ie binding[index] */ public static String createIndexedBinding(String binding, int index) { StringBuilder result = new StringBuilder(64); result.append(binding).append('[').append(index).append(']'); return result.toString(); } /** * Replace '.', '[' & ']' with '_' to make valid client identifiers. */ public static String sanitiseBinding(String binding) { String result = null; if (binding != null) { result = binding.replace('.', '_').replace('[', '_').replace(']', '_'); } return result; } /** * Replace '_' with either '[', ']' or '_' depending on the context to make valid binding expressions from client identifiers. */ public static String unsanitiseBinding(String binding) { String result = null; if (binding != null) { result = binding.replaceAll("\\_(\\d*)\\_", "\\[$1\\]"); result = result.replace('_', '.'); } return result; } /** * Check to see if the element is in the list. If not, then add it. * * @param owner * @param binding * @param element * @return The found or added element. */ @SuppressWarnings("unchecked") public static Bean ensureElementIsInCollection(Bean owner, String binding, Bean element) { List<Bean> list = (List<Bean>) get(owner, binding); String elementId = element.getBizId(); // check each bean in the list to see if its ID is the same for (Bean existing : list) { if (elementId.equals(existing.getBizId())) { return existing; } } list.add(element); return element; } /** * Return the element found or null if not found. * * @param owner * @param binding * @param elementBizId * @return The found element or null. */ @SuppressWarnings("unchecked") public static Bean getElementInCollection(Bean owner, String binding, String elementBizId) { List<Bean> list = (List<Bean>) get(owner, binding); return getElementInCollection(list, elementBizId); } public static <T extends Bean> T getElementInCollection(List<T> list, String elementBizId) { // check each bean in the list to see if its ID is the same for (T existing : list) { if (elementBizId.equals(existing.getBizId())) { return existing; } } return null; } public static <T extends Bean> void setElementInCollection(List<T> list, T element) { // Set each occurrence in the list where the bizIds are the same String elementBizId = element.getBizId(); for (int i = 0, l = list.size(); i < l; i++) { if (elementBizId.equals(list.get(i).getBizId())) { list.set(i, element); } } } /** * Sort a collection by its order metadata. * * @param bean The bean that ultimately has the collection. * @param customer The customer of the owningBean. * @param module The module of the owningBean. * @param document The document of the owningBean. * @param collectionBinding The (possibly compound) collection binding (from Document context). */ public static void sortCollectionByMetaData(Bean bean, Customer customer, Module module, Document document, String collectionBinding) { // Cater for compound bindings here Bean owningBean = bean; int lastDotIndex = collectionBinding.lastIndexOf('.'); // compound binding if (lastDotIndex > 0) { owningBean = (Bean) BindUtil.get(owningBean, collectionBinding.substring(0, lastDotIndex)); } TargetMetaData target = BindUtil.getMetaDataForBinding(customer, module, document, collectionBinding); Collection targetCollection = (Collection) target.getAttribute(); sortCollectionByMetaData(owningBean, targetCollection); } /** * Sort the beans collection by the order metadata provided. * * @param owningBean The bean with collection in it. * @param collection The metadata representing the collection. * This method does not cater for compound binding expressions. * Use {@link sortCollectionByMetaData(Customer, Module, Document, Bean, String)} for that. */ @SuppressWarnings("unchecked") public static void sortCollectionByMetaData(Bean owningBean, Collection collection) { // We only sort by ordinal if this is a child collection as bizOrdinal is on the elements. // For aggregation/composition, bizOrdinal is on the joining table and handled automatically boolean sortByOrdinal = Boolean.TRUE.equals(collection.getOrdered()) && (CollectionType.child.equals(collection.getType())); if (sortByOrdinal || (! collection.getOrdering().isEmpty())) { List<Bean> details = (List<Bean>) BindUtil.get(owningBean, collection.getName()); sortCollectionByOrdering(details, sortByOrdinal, collection.getOrdering()); } } /** * Sort a collection of java beans by an arbitrary ordering list. * The list can be of any type, not just Bean. * * @param beans The list to sort * @param ordering The sort order */ public static void sortCollectionByOrdering(List<?> beans, Ordering... ordering) { sortCollectionByOrdering(beans, false, Arrays.asList(ordering)); } @SuppressWarnings("unchecked") private static void sortCollectionByOrdering(List<?> beans, boolean finallySortByOrdinal, List<Ordering> ordering) { if (beans != null) { ComparatorChain comparatorChain = new ComparatorChain(); if (finallySortByOrdinal) { comparatorChain.addComparator(new NullTolerantBeanComparator(Bean.ORDINAL_NAME), false); } for (Ordering order : ordering) { comparatorChain.addComparator(new NullTolerantBeanComparator(order.getBy()), SortDirection.descending.equals(order.getSort())); } // Test if the collection is sorted before sorting as // Collections.sort() will affect the dirtiness of a hibernate collection boolean unsorted = false; Object smallerBean = null; for (Object bean : beans) { if (smallerBean != null) { if (comparatorChain.compare(smallerBean, bean) > 0) { unsorted = true; break; } } smallerBean = bean; } if (unsorted) { Collections.sort(beans, comparatorChain); } } } /** * Get a simple or compound <code>bean</code> property value. * * @param bean The bean to get the property value from. * @param fullyQualifiedAttributeName The fully qualified name of a bean property, separating components with a '.'. * Examples would be "identifier" {simple} or "identifier.clientId" {compound}. */ public static Object get(Object bean, String fullyQualifiedPropertyName) { if (bean instanceof MapBean) { return ((MapBean) bean).get(fullyQualifiedPropertyName); } Object result = null; Object currentBean = bean; StringTokenizer tokenizer = new StringTokenizer(fullyQualifiedPropertyName, "."); while (tokenizer.hasMoreTokens()) { String simplePropertyName = tokenizer.nextToken(); try { result = PROPERTY_UTILS.getProperty(currentBean, simplePropertyName); } catch (Exception e) { UtilImpl.LOGGER.severe("Could not BindUtil.get(" + bean + ", " + fullyQualifiedPropertyName + ")!"); UtilImpl.LOGGER.severe("The subsequent stack trace relates to obtaining bean property " + simplePropertyName + " from " + currentBean); UtilImpl.LOGGER.severe("If the stack trace contains something like \"Unknown property '" + simplePropertyName + "' on class 'class <blahblah>$$EnhancerByCGLIB$$$<blahblah>'\"" + " then you'll need to use Util.deproxy() before trying to bind to properties in the hibernate proxy."); UtilImpl.LOGGER.severe("See https://github.com/skyvers/skyve-cookbook/blob/master/README.md#deproxy for details"); UtilImpl.LOGGER.severe("Exception message = " + e.getMessage()); throw new MetaDataException(e); } if (result == null) { break; } currentBean = result; } return result; } @SuppressWarnings("unchecked") public static Object get(Map<String, Object> map, String binding) { String alias = sanitiseBinding(binding); Object result = null; if (map.containsKey(binding)) { result = map.get(binding); } else if (map.containsKey(alias)) { result = map.get(alias); } else { Object currentMap = map; StringTokenizer tokenizer = new StringTokenizer(binding, "."); while (tokenizer.hasMoreTokens()) { String simpleKey = tokenizer.nextToken(); if (currentMap instanceof Map<?, ?>) { result = ((Map<String, Object>) currentMap).get(simpleKey); } if (result == null) { break; } currentMap = result; } } return result; } public static void convertAndSet(Object bean, String propertyName, Object value) { Class<?> type = getPropertyType(bean, propertyName); set(bean, propertyName, convert(type, value)); } /** * Set a simple or compound <code>bean</code> property value. * * @param bean The bean to set the property value in. * @param value The value to the bean property value to. * @param fullyQualifiedPropertyName The fully qualified name of a bean property, separating components with a '.'. * Examples would be "identifier" {simple} or "identifier.clientId" {compound}. */ public static void set(Object bean, String fullyQualifiedPropertyName, Object value) { try { Object valueToSet = value; // empty strings to null if ((valueToSet != null) && valueToSet.equals("")) { valueToSet = null; } if (valueToSet != null) { Class<?> propertyType = BindUtil.getPropertyType(bean, fullyQualifiedPropertyName); // if we are setting a String value to a non-string property then // use an appropriate constructor or static valueOf() if (String.class.equals(valueToSet.getClass()) && (! String.class.equals(propertyType))) { try { valueToSet = propertyType.getConstructor(valueToSet.getClass()).newInstance(valueToSet); } catch (NoSuchMethodException e) { valueToSet = propertyType.getMethod("valueOf", String.class).invoke(null, valueToSet); } } // Convert the value to String if required if (String.class.equals(propertyType)) { valueToSet = valueToSet.toString(); } // if (we have a String property) } PROPERTY_UTILS.setProperty(bean, fullyQualifiedPropertyName, valueToSet); } catch (Exception e) { if (e instanceof SkyveException) { throw (SkyveException) e; } throw new MetaDataException(e); } } public static Class<?> getPropertyType(Object bean, String propertyName) { try { return PROPERTY_UTILS.getPropertyType(bean, propertyName); } catch (Exception e) { throw new MetaDataException(e); } } public static boolean isWriteable(Object bean, String propertyName) { try { return (PROPERTY_UTILS.getWriteMethod(PROPERTY_UTILS.getPropertyDescriptor(bean, propertyName)) != null); } catch (Exception e) { throw new MetaDataException(e); } } /** * The list of Scalar types - where recursion down the object Graph stops */ private static final Class<?>[] scalarTypes = new Class<?>[] {Boolean.class, Byte.class, Character.class, Double.class, Float.class, Integer.class, Long.class, Short.class, String.class, StringBuffer.class, BigInteger.class, BigDecimal.class, Date.class, Decimal.class, Enum.class}; /** * Determine if the propertyType is a scalar type - one that can be presented meaningfully using a Single value. * * @param propertyType The <code>Class</code> object that represents the property type * @return <code>true</code> if propertyType is scalar, otherwise return <code>false</code>. */ public static final boolean isAScalarType(Class<?> propertyType) { boolean found = propertyType.isPrimitive(); // is the property type built-in // iterate through scalarTypes looking for a type // that the propertyType can be assigned to for (int scalarTypeIndex = 0; (scalarTypeIndex < scalarTypes.length) && (! found); scalarTypeIndex++) { found = (scalarTypes[scalarTypeIndex].isAssignableFrom(propertyType)); } return found; } /** * Determine if an attribute name is an implicit attribute. * * @param attributeName */ public static final boolean isImplicit(String attributeName) { return (HierarchicalBean.PARENT_ID.equals(attributeName) || ChildBean.PARENT_NAME.equals(attributeName) || Bean.DOCUMENT_ID.equals(attributeName) || Bean.CUSTOMER_NAME.equals(attributeName) || Bean.DATA_GROUP_ID.equals(attributeName) || Bean.USER_ID.equals(attributeName) || Bean.BIZ_KEY.equals(attributeName) || Bean.ORDINAL_NAME.equals(attributeName) || Bean.CREATED_KEY.equals(attributeName) || Bean.NOT_CREATED_KEY.equals(attributeName) || Bean.PERSISTED_KEY.equals(attributeName) || Bean.NOT_PERSISTED_KEY.equals(attributeName) || Bean.CHANGED_KEY.equals(attributeName) || Bean.NOT_CHANGED_KEY.equals(attributeName) || Bean.MODULE_KEY.equals(attributeName) || Bean.DOCUMENT_KEY.equals(attributeName) || PersistentBean.LOCK_NAME.equals(attributeName) || PersistentBean.VERSION_NAME.equals(attributeName) || PersistentBean.TAGGED_NAME.equals(attributeName) || PersistentBean.FLAG_COMMENT_NAME.equals(attributeName)); } // NB properties must be a sorted map to ensure that the shortest properties // are processed first - ie User.contact is populated before User.contact.firstName, // otherwise the firstName new value will be tromped... public static void populateProperties(User user, Bean bean, SortedMap<String, Object> properties, boolean fromSerializedFormat) { ValidationException e = new ValidationException(); // Do nothing unless both arguments have been specified if ((bean == null) || (properties == null)) { return; } // Loop through the property name/value pairs to be set for (String name : properties.keySet()) { // Identify the property name and value(s) to be assigned if (name == null) { continue; } Object value = properties.get(name); // Perform the assignment for this property try { populateProperty(user, bean, name, value, fromSerializedFormat); } catch (Exception ex) { System.err.println("Exception thrown when populating from the request."); ex.printStackTrace(); e.getMessages().add(new Message(name, value + " is invalid.")); } } if (! e.getMessages().isEmpty()) { throw e; } } public static void populateProperty(User user, Bean bean, String propertyName, Object propertyValue, boolean fromSerializedFormat) { String name = propertyName; Object value = propertyValue; Customer customer = user.getCustomer(); Module beanModule = customer.getModule(bean.getBizModule()); Document beanDocument = beanModule.getDocument(customer, bean.getBizDocument()); // Resolve any nested expression to get the actual target bean Object target = bean; int delim = findLastNestedIndex(name); String targetBinding = null; if (delim >= 0) { targetBinding = name.substring(0, delim); target = BindUtil.instantiateAndGet(user, beanModule, beanDocument, bean, targetBinding); name = name.substring(delim + 1); } if (target == null) { if ((value == null) || value.equals("") || (targetBinding == null)) { return; } } // Declare local variables we will require String propName = null; // Simple name of target property Class<?> type = null; // Java type of target property int index = -1; // Indexed subscript value (if any) String key = null; // Mapped key value (if any) // Calculate the property name, index, and key values propName = name; int i = propName.indexOf(PropertyUtils.INDEXED_DELIM); if (i >= 0) { int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2); try { index = Integer.parseInt(propName.substring(i + 1, k)); } catch (NumberFormatException e) { // do nothing } propName = propName.substring(0, i); } int j = propName.indexOf(PropertyUtils.MAPPED_DELIM); if (j >= 0) { int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2); try { key = propName.substring(j + 1, k); } catch (IndexOutOfBoundsException e) { // do nothing } propName = propName.substring(0, j); } if ((! List.class.isAssignableFrom(BindUtil.getPropertyType(target, propName))) && (! BindUtil.isWriteable(target, propName))) { return; } Converter<?> converter = null; // Calculate the property type if (target instanceof Bean) { Bean targetBean = (Bean) target; try { type = getPropertyType(targetBean, propName); } catch (Exception e) { return; } String documentName = targetBean.getBizDocument(); if (documentName != null) { Module module = customer.getModule(targetBean.getBizModule()); Document document = module.getDocument(customer, documentName); // NB Use getMetaDataForBinding() to ensure we find attributes from base documents inherited TargetMetaData propertyTarget = BindUtil.getMetaDataForBinding(customer, module, document, propName); Attribute attribute = propertyTarget.getAttribute(); if (attribute instanceof ConvertableField) { converter = ((ConvertableField) attribute).getConverterForCustomer(user.getCustomer()); } else if (attribute instanceof Collection) { // ensure that collection elements are filled for the binding BindUtil.instantiateAndGet(user, beanModule, beanDocument, bean, name); } else { // id of a reference here if ("".equals(value)) { value = null; } } } } // Convert the specified value to the required type Object newValue = null; String stringValue = null; if (value instanceof String) { stringValue = ((String) value).trim(); } else if (value instanceof String[]) { stringValue = ((String[]) value)[0]; if (stringValue != null) { stringValue = stringValue.trim(); } } if (stringValue != null) { if (! stringValue.isEmpty()) { newValue = fromString(user.getCustomer(), converter, type, stringValue, fromSerializedFormat); } } else { newValue = value; } // Invoke the setter method try { if (index >= 0) { PROPERTY_UTILS.setIndexedProperty(target, propName, index, newValue); } else if (key != null) { PROPERTY_UTILS.setMappedProperty(target, propName, key, newValue); } else { convertAndSet(target, propName, newValue); } } catch (Exception e) { throw new MetaDataException("Cannot set " + propName, e); } } private static int findLastNestedIndex(String expression) { // walk back from the end to the start // and find the first index that int bracketCount = 0; for (int i = expression.length() - 1; i >= 0; i char at = expression.charAt(i); switch (at) { case PropertyUtils.NESTED_DELIM: if (bracketCount < 1) { return i; } break; case PropertyUtils.MAPPED_DELIM: case PropertyUtils.INDEXED_DELIM: // not bothered which --bracketCount; break; case PropertyUtils.MAPPED_DELIM2: case PropertyUtils.INDEXED_DELIM2: // not bothered which ++bracketCount; break; default: } } // can't find any return -1; } public static void copy(final Bean from, final Bean to) { final Customer c = CORE.getUser().getCustomer(); final Module m = c.getModule(from.getBizModule()); final Document d = m.getDocument(c, from.getBizDocument()); for (final Attribute attribute : d.getAllAttributes()) { final String attributeName = attribute.getName(); if (attribute.getAttributeType() == AttributeType.collection) { copyCollection(from, to, attributeName); continue; } if (attribute.getAttributeType() == AttributeType.inverseMany) { copyCollection(from, to, attributeName); continue; } Binder.set(to, attributeName, Binder.get(from, attributeName)); } } // TODO clearing colTo issues a delete statement in hibernate, this method should process each collection item. @SuppressWarnings("unchecked") private static void copyCollection(final Bean from, final Bean to, final String attributeName) { List<Bean> colFrom = (List<Bean>) BindUtil.get(from, attributeName); List<Bean> colTo = (List<Bean>) BindUtil.get(to, attributeName); colTo.clear(); colTo.addAll(colFrom); } /** * Get the parent document and attribute for a binding expression. * This will traverse the binding (across documents and references * over the '.' and '[]' found in the expression) to find the ultimate document * and attribute that the binding points to. * * @param customer The customer to do this for. * @param module The module to start at (with respect to) * @param document The document to start at (with respect to) * @param binding The binding expression. * @return The document and attribute that the binding expression points to. * The document is never null whereas the attribute can be null if' * the binding expression ultimately resolves to an implicit attribute * like bizKey or bizId or the like. */ public static TargetMetaData getMetaDataForBinding(Customer customer, Module module, Document document, String binding) { Document navigatingDocument = document; Module navigatingModule = module; Attribute attribute = null; StringTokenizer tokenizer = new StringTokenizer(binding, "."); while (tokenizer.hasMoreTokens()) { String fieldName = tokenizer.nextToken(); int openBraceIndex = fieldName.indexOf('['); if (openBraceIndex > -1) { fieldName = fieldName.substring(0, openBraceIndex); } int openParenthesisIndex = fieldName.indexOf("ElementById("); if (openParenthesisIndex > -1) { fieldName = fieldName.substring(0, openParenthesisIndex); } attribute = navigatingDocument.getAttribute(fieldName); Extends inherits = navigatingDocument.getExtends(); while ((attribute == null) && (inherits != null)) { Document baseDocument = navigatingModule.getDocument(customer, inherits.getDocumentName()); attribute = baseDocument.getAttribute(fieldName); inherits = baseDocument.getExtends(); } if (tokenizer.hasMoreTokens()) { if (ChildBean.PARENT_NAME.equals(fieldName)) { inherits = navigatingDocument.getExtends(); String parentDocumentName = navigatingDocument.getParentDocumentName(); while ((parentDocumentName == null) && (inherits != null)) { Document baseDocument = navigatingModule.getDocument(customer, inherits.getDocumentName()); parentDocumentName = baseDocument.getParentDocumentName(); inherits = baseDocument.getExtends(); } if (parentDocumentName == null) { throw new MetaDataException(navigatingDocument.getOwningModuleName() + '.' + navigatingDocument.getName() + " @ " + binding + " does not exist (token [parent] doesn't check out as " + navigatingDocument.getName() + " is not a child document)"); } navigatingDocument = navigatingModule.getDocument(customer, parentDocumentName); } else if (attribute instanceof Relation) { navigatingDocument = navigatingModule.getDocument(customer, ((Relation) attribute).getDocumentName()); } else { throw new MetaDataException(navigatingDocument.getOwningModuleName() + '.' + navigatingDocument.getName() + " @ " + binding + " does not exist (token [" + tokenizer.nextToken() + "] doesn't check out)"); } navigatingModule = customer.getModule(navigatingDocument.getOwningModuleName()); } else { // ignore validating implicit attributes if ((attribute == null) && (! isImplicit(fieldName))) { throw new MetaDataException(navigatingDocument.getOwningModuleName() + '.' + navigatingDocument.getName() + " @ " + binding + " does not exist (last attribute not in document)"); } } } return new TargetMetaData(navigatingDocument, attribute); } @SuppressWarnings("unchecked") public static Object instantiateAndGet(User user, Module module, Document document, Bean bean, String binding) { Customer customer = user.getCustomer(); Document navigatingDocument = document; Attribute attribute = null; Object owner = bean; Object value = null; StringTokenizer tokenizer = new StringTokenizer(binding, "."); while (tokenizer.hasMoreTokens()) { String bindingPart = tokenizer.nextToken(); String fieldName = bindingPart; int openBraceIndex = fieldName.indexOf('['); if (openBraceIndex > -1) { fieldName = fieldName.substring(0, openBraceIndex); } // Cater for the "parent" property if (ChildBean.PARENT_NAME.equals(fieldName)) { navigatingDocument = navigatingDocument.getParentDocument(customer); } else { // NB Use getMetaDataForBinding() to ensure we find attributes from base documents inherited TargetMetaData target = BindUtil.getMetaDataForBinding(customer, module, navigatingDocument, fieldName); attribute = target.getAttribute(); if (attribute == null) { throw new IllegalArgumentException(fieldName + " within " + binding + "doesn't check out"); } navigatingDocument = module.getDocument(customer, ((Relation) attribute).getDocumentName()); if ((tokenizer.hasMoreTokens()) && (attribute instanceof Relation)) { // do nothing here } else { if (tokenizer.hasMoreTokens()) { throw new IllegalArgumentException(binding + " does not exist (token " + tokenizer.nextToken() + " doesn't check out)"); } } } try { try { value = BindUtil.get(owner, bindingPart); } catch (IndexOutOfBoundsException e) { if (attribute != null) { Document collectionDocument = module.getDocument(customer, ((Relation) attribute).getDocumentName()); // Get the collection and add the new instance int closedBraceIndex = bindingPart.length() - 1; String collectionBinding = bindingPart.substring(0, openBraceIndex); int collectionIndex = Integer.parseInt(bindingPart.substring(openBraceIndex + 1, closedBraceIndex)); List<Bean> collection = (List<Bean>) BindUtil.get(owner, collectionBinding); // parameters are ordered alphabetically, // so we should receive the array bindings in ascending order // but they may not be contiguous (some are deleted) while (collection.size() <= collectionIndex) { Bean fillerElement = collectionDocument.newInstance(user); if (fillerElement instanceof ChildBean) { try { ((ChildBean<Bean>) fillerElement).setParent((Bean) owner); } catch (ClassCastException cce) { // continue on - this child bean is being linked to // by some other document as an "aggregation" // IE the owner variable above is not the parent document // but some aggregating document } } collection.add(fillerElement); } value = collection.get(collectionIndex); } } if (value == null) { value = navigatingDocument.newInstance(user); BindUtil.set(owner, bindingPart, value); } owner = value; } catch (Exception e) { throw new MetaDataException(e); } } return value; } /** * Fashion a type identifier from the given string. * @param string * @return A valid java type identifier. Title case. */ public static String toJavaTypeIdentifier(String string) { StringBuilder sb = new StringBuilder(toJavaInstanceIdentifier(string)); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); return sb.toString(); } /** * Fashion an instance identifier from the given string. * @param string * @return A valid java instance identifier. Camel case. */ public static String toJavaInstanceIdentifier(String string) { StringBuilder sb = new StringBuilder(string); removeInvalidCharacters(sb); sb.setCharAt(0, Character.toLowerCase(sb.charAt(0))); return sb.toString(); } /** * Fashion a static identifier from the given string. * @param string * @return A valid java static identifier. Upper Case with underscores. */ public static String toJavaStaticIdentifier(String string) { String javaIdentifierName = toJavaInstanceIdentifier(string); StringBuilder sb = new StringBuilder(javaIdentifierName.length() + 5); for (int i = 0, l = javaIdentifierName.length(); i < l; i++) { char ch = javaIdentifierName.charAt(i); if (Character.isUpperCase(ch)) { boolean nextCharLowerCase = false; boolean prevCharLowerCase = false; int nextIndex = i + 1; int prevIndex = i - 1; if (nextIndex < l) { char nextChar = javaIdentifierName.charAt(nextIndex); nextCharLowerCase = Character.isLowerCase(nextChar); } if(prevIndex >= 0) { char prevChar = javaIdentifierName.charAt(prevIndex); prevCharLowerCase = Character.isLowerCase(prevChar); } // if the previous char was upper case then don't add an underscore if ((prevCharLowerCase || nextCharLowerCase) && (i > 0)) { sb.append('_'); } sb.append(ch); } else { sb.append(Character.toUpperCase(ch)); } } return sb.toString(); } private static void removeInvalidCharacters(StringBuilder sb) { int i = 0; boolean whiteSpaceOrUnderscore = false; while (i < sb.length()) { if (i == 0) { if (Character.isJavaIdentifierStart(sb.charAt(0)) && (sb.charAt(0) != '_')) { i++; } else { sb.deleteCharAt(0); } } else { if (Character.isJavaIdentifierPart(sb.charAt(i)) && (sb.charAt(i) != '_')) { if (whiteSpaceOrUnderscore) { sb.setCharAt(i, Character.toUpperCase(sb.charAt(i))); } whiteSpaceOrUnderscore = false; i++; } else { if (Character.isWhitespace(sb.charAt(i)) || (sb.charAt(i) == '_')) { whiteSpaceOrUnderscore = true; } sb.deleteCharAt(i); } } } } }
package com.carrotsearch.hppc.hash; public final class MurmurHash2 { private static final int M = 0x5bd1e995; private static final int R = 24; private static final int SEED = 0xdeadbeef; private MurmurHash2() { // no instances. } /** * Hashes a 4-byte sequence (Java int). */ public static int hash(int k) { k *= M; k ^= k >>> R; k *= M; k ^= SEED * M; k ^= k >>> 13; k *= M; k ^= k >>> 15; return k; } /** * Hashes a 8-byte sequence (Java long). */ public static int hash(long v) { int k = (int) (v >>> 32); k *= M; k ^= k >>> R; k *= M; int h = SEED * M; h ^= k; k = (int) v; k *= M; k ^= k >>> R; k *= M; h *= M; h ^= k; h ^= h >>> 13; h *= M; h ^= h >>> 15; return h; } }
package ru.job4j.professions; import java.util.ArrayList; public class Teacher extends Profession { private String firstSubject; private String secondSublect; public ArrayList<String> listOfClass; public Teacher(){ listOfClass = new ArrayList<>(); } public String getFirstSubject() { return firstSubject; } public void setFirstSubject(String firstSubject) { this.firstSubject = firstSubject; } public String getSecondSublect() { return secondSublect; } public void setSecondSublect(String secondSublect) { this.secondSublect = secondSublect; } public void teachClass(String schoolClass){ listOfClass.add(schoolClass); } }
package ru.skorikov; import java.util.Arrays; class StartUI { private Input input; private StartUI(Input input) { this.input = input; } private void init() { Tracker tracker = new Tracker(); boolean exit = false; do { for (MenuLevel menuLevel : MenuLevel.values()) { System.out.println(menuLevel.ordinal() + ". " + menuLevel.getNameMenuLevel()); } int selectNumber = Integer.MIN_VALUE; String select = input.ask("Select:"); if (select.matches("[0-6]*")) { selectNumber = Integer.parseInt(select); } else { System.out.println("Number please!"); continue; } switch (MenuLevel.values()[selectNumber]) { case ADD: String name = input.ask("Enter Item name:"); String description = input.ask("Enter Item description:"); if (tracker.getPosition() < 10) { Item item = new Item(name, description); tracker.add(item); } else { System.out.println("Нет места."); System.out.println("Удалите одну или несколько заявок."); } break; case SHOWALL: System.out.println(Arrays.asList(tracker.findAll())); break; case EDIT: String idItem = input.ask("Enter ID item:"); if (tracker.findeById(idItem) != null) { String newName = input.ask("Enter new name:"); String newDescription = input.ask("Enter new description"); Item editItem = new Item(newName, newDescription); tracker.update(idItem, editItem); System.out.println("Item changed."); } else { System.out.println("Item not found."); } break; case DELETE: String findIdItem = input.ask("Enter ID item:"); Item findItem = tracker.findeById(findIdItem); if (findItem == null) { System.out.println("Item not found."); } else { tracker.delete(findItem); System.out.println("Item deleted."); } break; case FINDBYID: String findItemById = input.ask("Enter ID item:"); if (tracker.findeById(findItemById) != null) { tracker.findeById(findItemById); System.out.println(findItemById); } else { System.out.println("Item not found."); } break; case FINDBYNAME: String findItemByName = input.ask("Enter Name item:"); if (tracker.findeByName(findItemByName) != null) { tracker.findeByName(findItemByName); System.out.println(findItemByName); } else { System.out.println("Item not found."); } break; case EXIT: String vopros = input.ask("Exit programm: y/n?"); if ((vopros.equals("y")) || (vopros.equals("Y"))) { exit = true; } else { break; } default: break; } } while (!exit); } public static void main(String[] args) { Input input = new ConsoleInput(); new StartUI(input).init(); } }
package ru.job4j.menutracker; import ru.job4j.models.Item; import java.util.Random; import java.util.List; import java.util.ArrayList; public class Tracker { private List<Item> items = new ArrayList<Item>(); private int position; private static final Random RN = new Random(); String generateId() { return String.valueOf(RN.nextInt()); } public Item add(Item item) { item.setId(generateId()); items.add(item); return item; } public void update(Item item) { items.set(items.indexOf(item), item); } public void delete(Item item) { items.remove(item); } public List<Item> findAll() { List<Item> buf = new ArrayList<>(); buf.addAll(items); return buf; } public List<Item> findByName(String key) { List<Item> result = new ArrayList<Item>(); for (Item item : items) { if (item.getName().equals(key)) { result.add(item); } } return result; } public Item findById(String id) { Item result = null; Item searchItem = new Item(null, null, 0); searchItem.setId(id); int i = items.indexOf(searchItem); if (i >= 0) { result = items.get(i); } return result; } }
package ru.job4j.test; public class GitRebaseBatch { public static void main(String[] args) { System.out.println("Commit 1"); System.out.println("Commit 2"); System.out.println("Commit 3"); } }
package ru.job4j.sql.magnit; import java.sql.*; import java.util.ArrayList; public class StoreSQL { Config config; Connection connection; public StoreSQL(Config config) throws SQLException { this.config = config; connection = DriverManager.getConnection(Constant.URL_BASE_POSTGRES, Constant.NAME, Constant.PASSWORD); } public ArrayList<Entry> get(int n) { ArrayList<Entry> list = new ArrayList<>(); try { Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM entry"); while(rs.next()) { list.add(new Entry(rs.getString("columnName"))); } rs.close(); st.close(); } catch (SQLException e) { e.printStackTrace(); } return list; } public void generate(int n) { try { connection.setAutoCommit(false); PreparedStatement statement = connection.prepareStatement("INSERT INTO entry (id, name) " + "VALUES (?, ?)"); for (int i = 0; i < n; i++) { statement.setInt(1, i); statement.setString(2,"someName " + i ); statement.addBatch(); } int[] count = statement.executeBatch(); connection.commit(); } catch (SQLException e) { } } }
package ru.job4j.threads; /** * class WordsSpaces */ public class WordsSpaces { /** * method calculateWordsSpaces. * @param str - incoming string. * @throws InterruptedException - exception. */ private static void calculateWordsSpaces(String str) throws InterruptedException { System.out.println("Start calculating"); System.out.println(str); Thread wordCalcThread = new Thread(new WordsCalc(str)); Thread spaceCalcThread = new Thread(new SpacesCalc(str)); wordCalcThread.start(); spaceCalcThread.start(); Thread.sleep(100); wordCalcThread.interrupt(); spaceCalcThread.interrupt(); System.out.println("Finish"); } /** * method main. * @param args - args. * @throws InterruptedException - exception. */ public static void main(String[] args) throws InterruptedException { String string = "Some words with some spaces"; calculateWordsSpaces(string); } } /** * class WordsCalc. */ class WordsCalc implements Runnable { /** str.*/ private String str; /** * constructor. * @param str - srt. */ WordsCalc(String str) { this.str = str; } /** * method wordCalc. * @param str - string. * @return string length. */ private int wordCalc(String str) { int numberOfWords = 0; for (int i = 0, j = 0; i < str.length(); i++) { if (!Thread.currentThread().isInterrupted()) { if (str.charAt(i) == ' ') { numberOfWords++; j = i; } if (i == str.length() - 1 && j != i) { numberOfWords++; } } else { break; } } return numberOfWords; } /** * method run. */ @Override public void run() { if (!Thread.currentThread().isInterrupted()) { System.out.println(String.format("The number of words: %s", wordCalc(str))); } else { System.out.println("Thread WordCalc was interrupted."); } } } /** * class SpacesCalc. */ class SpacesCalc implements Runnable { /** string.*/ private String str; /** * constructor. * @param str - string. */ SpacesCalc(String str) { this.str = str; } /** * method wordCalc. * @param str - string. * @return number of spaces. */ private int spacesCalc(String str) { int result = 0; for (int i = 0; i < str.length(); i++) { if (Thread.currentThread().isInterrupted()) { break; } if (str.charAt(i) == ' ') { result++; } } return result; } /** * method run. */ @Override public void run() { if (!Thread.currentThread().isInterrupted()) { System.out.println(String.format("The number of spaces: %s", spacesCalc(str))); } else { System.out.println("Thread SpaceCalc was interrupted."); } } }
package ru.job4j.map; import java.util.Calendar; import java.util.Objects; /** * Class User. * * @author Tatyana Fukova * @version $I$ */ public class User { private String name; private int children; private Calendar birthday; public User(String name, int children, Calendar birthday) { this.name = name; this.children = children; this.birthday = birthday; } /* @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + children; result = 31 * result + (birthday != null ? birthday.hashCode() : 0); return result; } */ @Override public boolean equals(Object obj) { boolean isEquals = false; if (this == obj) { isEquals = true; } if (!isEquals && obj != null && this.getClass() == obj.getClass()) { User user = (User) obj; if (this.name.equals(user.name) && this.children == user.children && this.birthday.equals(user.birthday)) { isEquals = true; } } return isEquals; } }
package org.intermine.metadata; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.File; import java.io.BufferedWriter; import java.io.FileWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import org.intermine.modelproduction.xml.InterMineModelParser; import org.intermine.sql.Database; import org.intermine.util.PropertiesUtil; import org.intermine.util.StringUtil; /** * Class to handle persistence of an intermine objectstore's metadata to the objectstore's database * @author Mark Woodbridge */ public class MetadataManager { public static final String METADATA_TABLE = "intermine_metadata"; /** * Name of the key under which to store the serialized version of the model */ public static final String MODEL = "model"; /** * Name of the key under which to store the serialized version of the key definitions */ public static final String KEY_DEFINITIONS = "keyDefs"; /** * Name of the key under which to store the serialized version of the class descriptions */ public static final String CLASS_DESCRIPTIONS = "classDescs"; /** * Store a (key, value) pair in the metadata table of the database * @param database the database * @param key the key * @param value the value * @throws SQLException if an error occurs */ public static void store(Database database, String key, String value) throws SQLException { Connection connection = database.getConnection(); boolean autoCommit = connection.getAutoCommit(); try { connection.setAutoCommit(true); connection.createStatement().execute("DELETE FROM " + METADATA_TABLE + " where key = '" + key + "'"); connection.createStatement().execute("INSERT INTO " + METADATA_TABLE + " (key, value) " + "VALUES('" + key + "', '" + StringUtil.duplicateQuotes(value) + "')"); } finally { connection.setAutoCommit(autoCommit); connection.close(); } } /** * Retrieve the value for a given key from the metadata table of the database * @param database the database * @param key the key * @return the value * @throws SQLException if an error occurs */ public static String retrieve(Database database, String key) throws SQLException { String value = null; Connection connection = database.getConnection(); try { String sql = "SELECT value FROM " + METADATA_TABLE + " WHERE key='" + key + "'"; ResultSet rs = connection.createStatement().executeQuery(sql); if (!rs.next()) { throw new RuntimeException("No value found in database for key " + key); } value = rs.getString(1); } finally { connection.close(); } return value; } /** * Load a named model from the classpath * @param name the model name * @return the model */ public static Model loadModel(String name) { String filename = getFilename(MODEL, name); InputStream is = Model.class.getClassLoader().getResourceAsStream(filename); if (is == null) { throw new IllegalArgumentException("Model definition file '" + filename + "' cannot be found"); } Model model = null; try { model = new InterMineModelParser().process(new InputStreamReader(is)); } catch (Exception e) { throw new RuntimeException("Error parsing model definition file '" + filename + "'"); } return model; } /** * Save a model, in serialized form, to the specified directory * @param model the model * @param destDir the destination directory * @throws IOException if an error occurs */ public static void saveModel(Model model, File destDir) throws IOException { write(model.toString(), new File(destDir, getFilename(MODEL, model.getName()))); } /** * Load the key definitions file for the named model from the classpath * @param modelName the model name * @return the key definitions */ public static Properties loadKeyDefinitions(String modelName) { return PropertiesUtil.loadProperties(getFilename(KEY_DEFINITIONS, modelName)); } /** * Save the key definitions, in serialized form, to the specified directory * @param properties the key definitions * @param destDir the destination directory * @param modelName the name of the associated model, used the generate the filename * @throws IOException if an error occurs */ public static void saveKeyDefinitions(String properties, File destDir, String modelName) throws IOException { write(properties, new File(destDir, getFilename(KEY_DEFINITIONS, modelName))); } /** * Load the class descriptions file for the named model from the classpath * @param modelName the model name * @return the class descriptions */ public static Properties loadClassDescriptions(String modelName) { return PropertiesUtil.loadProperties(getFilename(CLASS_DESCRIPTIONS, modelName)); } /** * Save the class descriptions, in serialized form, to the specified directory * @param properties the class descriptions * @param destDir the destination directory * @param modelName the name of the associated model, used the generate the filename * @throws IOException if an error occurs */ public static void saveClassDescriptions(String properties, File destDir, String modelName) throws IOException { write(properties, new File(destDir, getFilename(CLASS_DESCRIPTIONS, modelName))); } private static String getFilename(String key, String modelName) { String filename = modelName + "_" + key; if (MODEL.equals(key)) { return filename += ".xml"; } else if (KEY_DEFINITIONS.equals(key) || CLASS_DESCRIPTIONS.equals(key)) { return filename += ".properties"; } throw new IllegalArgumentException("Unrecognised key '" + key + "'"); } private static void write(String string, File file) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(string); writer.close(); } }
package org.xtreemfs.osd.rwre; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import org.xtreemfs.common.uuids.ServiceUUID; import org.xtreemfs.common.uuids.UnknownUUIDException; import org.xtreemfs.common.xloc.XLocations; import org.xtreemfs.foundation.SSLOptions; import org.xtreemfs.foundation.buffer.ASCIIString; import org.xtreemfs.foundation.buffer.BufferPool; import org.xtreemfs.foundation.buffer.ReusableBuffer; import org.xtreemfs.foundation.flease.Flease; import org.xtreemfs.foundation.flease.FleaseConfig; import org.xtreemfs.foundation.flease.FleaseMessageSenderInterface; import org.xtreemfs.foundation.flease.FleaseStage; import org.xtreemfs.foundation.flease.FleaseStatusListener; import org.xtreemfs.foundation.flease.FleaseViewChangeListenerInterface; import org.xtreemfs.foundation.flease.comm.FleaseMessage; import org.xtreemfs.foundation.flease.proposer.FleaseException; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.pbrpc.client.PBRPCException; import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication; import org.xtreemfs.foundation.pbrpc.client.RPCNIOSocketClient; import org.xtreemfs.foundation.pbrpc.client.RPCResponse; import org.xtreemfs.foundation.pbrpc.client.RPCResponseAvailableListener; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse; import org.xtreemfs.foundation.pbrpc.utils.ErrorUtils; import org.xtreemfs.osd.InternalObjectData; import org.xtreemfs.osd.OSDRequest; import org.xtreemfs.osd.OSDRequestDispatcher; import org.xtreemfs.osd.operations.EventRWRStatus; import org.xtreemfs.osd.operations.OSDOperation; import org.xtreemfs.osd.rwre.ReplicatedFileState.ReplicaState; import org.xtreemfs.osd.stages.Stage; import org.xtreemfs.osd.stages.StorageStage.DeleteObjectsCallback; import org.xtreemfs.osd.stages.StorageStage.InternalGetMaxObjectNoCallback; import org.xtreemfs.osd.stages.StorageStage.WriteObjectCallback; import org.xtreemfs.osd.storage.CowPolicy; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.FileCredentials; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.OSDWriteResponse; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.AuthoritativeReplicaState; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectData; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectVersion; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectVersionMapping; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ReplicaStatus; import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceClient; /** * * @author bjko */ public class RWReplicationStage extends Stage implements FleaseMessageSenderInterface { public static final int STAGEOP_REPLICATED_WRITE = 1; public static final int STAGEOP_CLOSE = 2; public static final int STAGEOP_PROCESS_FLEASE_MSG = 3; public static final int STAGEOP_PREPAREOP = 5; public static final int STAGEOP_TRUNCATE = 6; public static final int STAGEOP_GETSTATUS = 7; public static final int STAGEOP_INTERNAL_AUTHSTATE = 10; public static final int STAGEOP_INTERNAL_OBJFETCHED = 11; public static final int STAGEOP_LEASE_STATE_CHANGED = 13; public static final int STAGEOP_INTERNAL_STATEAVAIL = 14; public static final int STAGEOP_INTERNAL_DELETE_COMPLETE = 15; public static final int STAGEOP_FORCE_RESET = 16; public static final int STAGEOP_INTERNAL_MAXOBJ_AVAIL = 17; public static final int STAGEOP_INTERNAL_BACKUP_AUTHSTATE = 18; public static enum Operation { READ, WRITE, TRUNCATE, INTERNAL_UPDATE, INTERNAL_TRUNCATE }; private final RPCNIOSocketClient client; private final OSDServiceClient osdClient; private final Map<String,ReplicatedFileState> files; private final Map<ASCIIString,String> cellToFileId; private final OSDRequestDispatcher master; private final FleaseStage fstage; private final RPCNIOSocketClient fleaseClient; private final OSDServiceClient fleaseOsdClient; private final ASCIIString localID; private int numObjsInFlight; private static final int MAX_OBJS_IN_FLIGHT = 10; private static final int MAX_PENDING_PER_FILE = 10; private static final int MAX_EXTERNAL_REQUESTS_IN_Q = 250; private final Queue<ReplicatedFileState> filesInReset; private final FleaseMasterEpochThread masterEpochThread; private final AtomicInteger externalRequestsInQueue; public RWReplicationStage(OSDRequestDispatcher master, SSLOptions sslOpts, int maxRequestsQueueLength) throws IOException { super("RWReplSt", maxRequestsQueueLength); this.master = master; client = new RPCNIOSocketClient(sslOpts, 15000, 60000*5, "RWReplicationStage"); fleaseClient = new RPCNIOSocketClient(sslOpts, 15000, 60000*5, "RWReplicationStage (flease)"); osdClient = new OSDServiceClient(client,null); fleaseOsdClient = new OSDServiceClient(fleaseClient,null); files = new HashMap<String, ReplicatedFileState>(); cellToFileId = new HashMap<ASCIIString,String>(); numObjsInFlight = 0; filesInReset = new LinkedList(); externalRequestsInQueue = new AtomicInteger(0); localID = new ASCIIString(master.getConfig().getUUID().toString()); masterEpochThread = new FleaseMasterEpochThread(master.getStorageStage().getStorageLayout(), maxRequestsQueueLength); FleaseConfig fcfg = new FleaseConfig(master.getConfig().getFleaseLeaseToMS(), master.getConfig().getFleaseDmaxMS(), master.getConfig().getFleaseDmaxMS(), null, localID.toString(), master.getConfig().getFleaseRetries()); fstage = new FleaseStage(fcfg, master.getConfig().getObjDir()+"/", this, false, new FleaseViewChangeListenerInterface() { @Override public void viewIdChangeEvent(ASCIIString cellId, int viewId) { throw new UnsupportedOperationException("Not supported yet."); } }, new FleaseStatusListener() { @Override public void statusChanged(ASCIIString cellId, Flease lease) { //FIXME: change state eventLeaseStateChanged(cellId, lease, null); } @Override public void leaseFailed(ASCIIString cellID, FleaseException error) { //change state //flush pending requests eventLeaseStateChanged(cellID, null, error); } }, masterEpochThread); fstage.setLifeCycleListener(master); } @Override public void start() { masterEpochThread.start(); client.start(); fleaseClient.start(); fstage.start(); super.start(); } @Override public void shutdown() { client.shutdown(); fleaseClient.shutdown(); fstage.shutdown(); masterEpochThread.shutdown(); super.shutdown(); } @Override public void waitForStartup() throws Exception { masterEpochThread.waitForStartup(); client.waitForStartup(); fleaseClient.waitForStartup(); fstage.waitForStartup(); super.waitForStartup(); } public void waitForShutdown() throws Exception { client.waitForShutdown(); fleaseClient.waitForShutdown(); fstage.waitForShutdown(); masterEpochThread.waitForShutdown(); super.waitForShutdown(); } public void eventReplicaStateAvailable(String fileId, ReplicaStatus localState, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_STATEAVAIL, new Object[]{fileId,localState,error}, null, null); } public void eventForceReset(FileCredentials credentials, XLocations xloc) { this.enqueueOperation(STAGEOP_FORCE_RESET, new Object[]{credentials, xloc}, null, null); } public void eventDeleteObjectsComplete(String fileId, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_DELETE_COMPLETE, new Object[]{fileId,error}, null, null); } void eventObjectFetched(String fileId, ObjectVersionMapping object, InternalObjectData data, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_OBJFETCHED, new Object[]{fileId,object,data,error}, null, null); } void eventSetAuthState(String fileId, AuthoritativeReplicaState authState, ReplicaStatus localState, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_AUTHSTATE, new Object[]{fileId,authState, localState, error}, null, null); } void eventLeaseStateChanged(ASCIIString cellId, Flease lease, FleaseException error) { this.enqueueOperation(STAGEOP_LEASE_STATE_CHANGED, new Object[]{cellId,lease,error}, null, null); } void eventMaxObjAvail(String fileId, long maxObjVer, long fileSize, long truncateEpoch, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_MAXOBJ_AVAIL, new Object[]{fileId,maxObjVer,error}, null, null); } public void eventBackupReplicaReset(String fileId, AuthoritativeReplicaState authState, ReplicaStatus localState, FileCredentials credentials, XLocations xloc) { this.enqueueOperation(STAGEOP_INTERNAL_BACKUP_AUTHSTATE, new Object[]{fileId,authState, localState, credentials, xloc}, null, null); } private void executeSetAuthState(final ReplicaStatus localState, final AuthoritativeReplicaState authState, ReplicatedFileState state, final String fileId) { // Calculate what we need to do locally based on the local state. boolean resetRequired = localState.getTruncateEpoch() < authState.getTruncateEpoch(); // Create a list of missing objects. Map<Long, Long> objectsToBeDeleted = new HashMap(); for (ObjectVersion localObject : localState.getObjectVersionsList()) { // Never delete any object which is newer than auth state! if (localObject.getObjectVersion() <= authState.getMaxObjVersion()) { objectsToBeDeleted.put(localObject.getObjectNumber(), localObject.getObjectVersion()); } } // Delete everything that is older or not part of the authoritative state. for (ObjectVersionMapping authObject : authState.getObjectVersionsList()) { Long version = objectsToBeDeleted.get(authObject.getObjectNumber()); if ((version != null) && (version == authObject.getObjectVersion())) { objectsToBeDeleted.remove(authObject.getObjectNumber()); } } Map<Long, ObjectVersionMapping> missingObjects = new HashMap(); for (ObjectVersionMapping authObject : authState.getObjectVersionsList()) { missingObjects.put(authObject.getObjectNumber(), authObject); } for (ObjectVersion localObject : localState.getObjectVersionsList()) { ObjectVersionMapping object = missingObjects.get(localObject.getObjectNumber()); if ((object != null) && (localObject.getObjectVersion() >= object.getObjectVersion())) { missingObjects.remove(localObject.getObjectNumber()); } } if (!missingObjects.isEmpty() || !objectsToBeDeleted.isEmpty() || (localState.getTruncateEpoch() < authState.getTruncateEpoch())) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this, "(R:%s) replica RESET required updates for: %s", localID, state.getFileId()); } state.setObjectsToFetch(new LinkedList(missingObjects.values())); filesInReset.add(state); // Start by deleting the old objects. master.getStorageStage().deleteObjects(fileId, state.getsPolicy(), authState.getTruncateEpoch(), objectsToBeDeleted, new DeleteObjectsCallback() { @Override public void deleteObjectsComplete(ErrorResponse error) { eventDeleteObjectsComplete(fileId, error); } }); } else { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this, "(R:%s) replica RESET finished (replica is up-to-date): %s", localID, state.getFileId()); } doOpen(state); } } private void processLeaseStateChanged(StageRequest method) { try { final ASCIIString cellId = (ASCIIString) method.getArgs()[0]; final Flease lease = (Flease) method.getArgs()[1]; final FleaseException error = (FleaseException) method.getArgs()[2]; if (error == null) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) lease change event: %s, %s",localID, cellId, lease); } } else { Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) lease error in cell %s: %s",localID, cellId, error); } final String fileId = cellToFileId.get(cellId); if (fileId != null) { ReplicatedFileState state = files.get(fileId); assert(state != null); boolean leaseOk = false; if (error == null) { boolean localIsPrimary = (lease.getLeaseHolder() != null) && (lease.getLeaseHolder().equals(localID)); ReplicaState oldState = state.getState(); state.setLocalIsPrimary(localIsPrimary); state.setLease(lease); // Error handling for timeouts on the primary. if (oldState == ReplicaState.PRIMARY &&lease.getLeaseHolder() == null && lease.getLeaseTimeout_ms() == 0) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"(R:%s) was primary, lease error in cell %s, restarting replication: %s",localID, cellId,lease,error); failed(state, ErrorUtils.getInternalServerError(new IOException(fileId +": lease timed out, renew failed")), "processLeaseStateChanged"); } else { if ( (state.getState() == ReplicaState.BACKUP) || (state.getState() == ReplicaState.PRIMARY) || (state.getState() == ReplicaState.WAITING_FOR_LEASE) ) { if (localIsPrimary) { //notify onPrimary if (oldState != ReplicaState.PRIMARY) { state.setMasterEpoch(lease.getMasterEpochNumber()); doPrimary(state); } } else { if (oldState != ReplicaState.BACKUP) { state.setMasterEpoch(FleaseMessage.IGNORE_MASTER_EPOCH); doBackup(state); } } } } } else { failed(state, ErrorUtils.getInternalServerError(error), "processLeaseStateChanged (error != null)"); } } } catch (Exception ex) { Logging.logMessage(Logging.LEVEL_ERROR, this, "Exception was thrown and caught while processing the change of the lease state." + " This is an error in the code. Please report it! Caught exception: "); Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processBackupAuthoritativeState(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final AuthoritativeReplicaState authState = (AuthoritativeReplicaState) method.getArgs()[1]; final ReplicaStatus localState = (ReplicaStatus) method.getArgs()[2]; final FileCredentials credentials = (FileCredentials) method.getArgs()[3]; final XLocations loc = (XLocations) method.getArgs()[4]; ReplicatedFileState state = getState(credentials, loc, true); switch (state.getState()) { case INITIALIZING: case OPEN: case WAITING_FOR_LEASE: { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) enqueued backup reset for file %s",localID, fileId); state.addPendingRequest(method); break; } case BACKUP: { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) backup reset triggered by AUTHSTATE request for file %s",localID, fileId); state.setState(ReplicaState.RESET); executeSetAuthState(localState, authState, state, fileId); break; } case RESET: default: { // Ignore. Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) auth state ignored, already in reset for file %s",localID, fileId); } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processSetAuthoritativeState(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final AuthoritativeReplicaState authState = (AuthoritativeReplicaState) method.getArgs()[1]; final ReplicaStatus localState = (ReplicaStatus) method.getArgs()[2]; final ErrorResponse error = (ErrorResponse) method.getArgs()[3]; ReplicatedFileState state = files.get(fileId); if (state == null) { Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) set AUTH for unknown file: %s",localID, fileId); return; } if (error != null) { failed(state, error, "processSetAuthoritativeState"); } else { executeSetAuthState(localState, authState, state, fileId); } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processDeleteObjectsComplete(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final ErrorResponse error = (ErrorResponse) method.getArgs()[1]; ReplicatedFileState state = files.get(fileId); if (state != null) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) deleted all objects requested by RESET for %s with %s",localID,state.getFileId(), ErrorUtils.formatError(error)); } if (error != null) { failed(state, error, "processDeleteObjectsComplete"); } else { fetchObjects(); } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void fetchObjects() { while (numObjsInFlight < MAX_OBJS_IN_FLIGHT) { ReplicatedFileState file = filesInReset.poll(); if (file == null) break; if (!file.getObjectsToFetch().isEmpty()) { ObjectVersionMapping o = file.getObjectsToFetch().remove(0); file.setNumObjectsPending(file.getNumObjectsPending()+1); numObjsInFlight++; fetchObject(file.getFileId(), o); } if (!file.getObjectsToFetch().isEmpty()) { filesInReset.add(file); } } } private void fetchObject(final String fileId, final ObjectVersionMapping record) { ReplicatedFileState state = files.get(fileId); if (state == null) { return; } try { final ServiceUUID osd = new ServiceUUID(record.getOsdUuidsList().get(0)); //fetch that object if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) file %s, fetch object %d (version %d) from %s", localID, fileId,record.getObjectNumber(),record.getObjectVersion(),osd); RPCResponse r = osdClient.xtreemfs_rwr_fetch(osd.getAddress(), RPCAuthentication.authNone, RPCAuthentication.userService, state.getCredentials(), fileId, record.getObjectNumber(), record.getObjectVersion()); r.registerListener(new RPCResponseAvailableListener() { @Override public void responseAvailable(RPCResponse r) { try { ObjectData metadata = (ObjectData) r.get(); InternalObjectData data = new InternalObjectData(metadata, r.getData()); eventObjectFetched(fileId, record, data, null); } catch (PBRPCException ex) { // Transform exception into correct ErrorResponse. // TODO(mberlin): Generalize this functionality by returning "Throwable" instead of // "ErrorResponse" to the event* functions. // The "ErrorResponse" shall be created in the last 'step' at the // invocation of failed(). eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ex.getErrorType(), ex.getPOSIXErrno(), ex.toString(), ex)); } catch (Exception ex) { eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ErrorType.IO_ERROR, POSIXErrno.POSIX_ERROR_NONE, ex.toString(), ex)); } finally { r.freeBuffers(); } } }); } catch (IOException ex) { eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex)); } } private void processObjectFetched(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final ObjectVersionMapping record = (ObjectVersionMapping) method.getArgs()[1]; final InternalObjectData data = (InternalObjectData) method.getArgs()[2]; final ErrorResponse error = (ErrorResponse) method.getArgs()[3]; ReplicatedFileState state = files.get(fileId); if (state != null) { if (error != null) { numObjsInFlight fetchObjects(); failed(state, error, "processObjectFetched"); } else { final int bytes = data.getData().remaining(); master.getStorageStage().writeObjectWithoutGMax(fileId, record.getObjectNumber(), state.getsPolicy(), 0, data.getData(), CowPolicy.PolicyNoCow, null, false, record.getObjectVersion(), null, new WriteObjectCallback() { @Override public void writeComplete(OSDWriteResponse result, ErrorResponse error) { if (error != null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"cannot write object locally: %s",ErrorUtils.formatError(error)); } } }); master.getPreprocStage().pingFile(fileId); master.objectReplicated(); master.replicatedDataReceived(bytes); numObjsInFlight final int numPendingFile = state.getNumObjectsPending()-1; state.setNumObjectsPending(numPendingFile); state.getPolicy().objectFetched(record.getObjectVersion()); if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) fetched object for replica, file %s, remaining %d",localID, fileId,numPendingFile); fetchObjects(); if (numPendingFile == 0) { //reset complete! Logging.logMessage(Logging.LEVEL_INFO, Category.replication, this,"(R:%s) RESET complete for file %s",localID, fileId); doOpen(state); } } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void doReset(final ReplicatedFileState file, long updateObjVer) { if (file.getState() == ReplicaState.RESET) { if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"file %s is already in RESET",file.getFileId()); return; } if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s",localID, file.getFileId(),file.getState(),ReplicaState.RESET); } file.setState(ReplicaState.RESET); if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica RESET started: %s (update objVer=%d)",localID, file.getFileId(),updateObjVer); } OSDOperation op = master.getInternalEvent(EventRWRStatus.class); op.startInternalEvent(new Object[]{file.getFileId(),file.getsPolicy()}); } private void processReplicaStateAvailExecReset(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final ReplicaStatus localReplicaState = (ReplicaStatus) method.getArgs()[1]; final ErrorResponse error = (ErrorResponse) method.getArgs()[2]; final ReplicatedFileState state = files.get(fileId); if (state != null) { if (error != null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"local state for %s failed: %s", state.getFileId(), error); failed(state, error, "processReplicaStateAvailExecReset"); } else { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) local state for %s available.", localID, state.getFileId()); } state.getPolicy().executeReset(state.getCredentials(), localReplicaState, new ReplicaUpdatePolicy.ExecuteResetCallback() { @Override public void finished(AuthoritativeReplicaState authState) { eventSetAuthState(state.getFileId(), authState, localReplicaState, null); } @Override public void failed(ErrorResponse error) { eventSetAuthState(state.getFileId(), null, null, error); } }); } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processForceReset(StageRequest method) { try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; ReplicatedFileState state = getState(credentials, loc, true); if (!state.isForceReset()) { state.setForceReset(true); } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void doWaitingForLease(final ReplicatedFileState file) { if (file.getPolicy().requiresLease()) { if (file.isCellOpen()) { if (file.isLocalIsPrimary()) { doPrimary(file); } else { doBackup(file); } } else { file.setCellOpen(true); if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s", localID,file.getFileId(),file.getState(),ReplicaState.WAITING_FOR_LEASE); } try { file.setState(ReplicaState.WAITING_FOR_LEASE); List<InetSocketAddress> osdAddresses = new ArrayList(); for (ServiceUUID osd : file.getPolicy().getRemoteOSDUUIDs()) { osdAddresses.add(osd.getAddress()); } fstage.openCell(file.getPolicy().getCellId(), osdAddresses, true); //wait for lease... } catch (UnknownUUIDException ex) { failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex), "doWaitingForLease"); } } } else { //become primary immediately doPrimary(file); } } private void doOpen(final ReplicatedFileState file) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this,"(R:%s) replica state changed for %s from %s to %s",localID, file.getFileId(),file.getState(),ReplicaState.OPEN); } file.setState(ReplicaState.OPEN); if (file.getPendingRequests().size() > 0) { doWaitingForLease(file); } } private void doPrimary(final ReplicatedFileState file) { assert(file.isLocalIsPrimary()); try { if (file.getPolicy().onPrimary((int)file.getMasterEpoch()) && !file.isPrimaryReset()) { file.setPrimaryReset(true); doReset(file,ReplicaUpdatePolicy.UNLIMITED_RESET); } else { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s", localID, file.getFileId(),file.getState(),ReplicaState.PRIMARY); } file.setPrimaryReset(false); file.setState(ReplicaState.PRIMARY); while (!file.getPendingRequests().isEmpty()) { StageRequest m = file.getPendingRequests().remove(0); enqueuePrioritized(m); } } } catch (IOException ex) { failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex), "doPrimary"); } } private void doBackup(final ReplicatedFileState file) { assert(!file.isLocalIsPrimary()); //try { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s", localID, file.getFileId(),file.getState(),ReplicaState.BACKUP); } file.setPrimaryReset(false); file.setState(ReplicaState.BACKUP); while (!file.getPendingRequests().isEmpty()) { StageRequest m = file.getPendingRequests().remove(0); enqueuePrioritized(m); } /*} catch (IOException ex) { failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex)); }*/ } private void failed(ReplicatedFileState file, ErrorResponse ex, String methodName) { Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) replica for file %s failed (in method: %s): %s", localID, file.getFileId(), methodName, ErrorUtils.formatError(ex)); file.setPrimaryReset(false); file.setState(ReplicaState.OPEN); file.setCellOpen(false); fstage.closeCell(file.getPolicy().getCellId(), false); for (StageRequest rq : file.getPendingRequests()) { RWReplicationCallback callback = (RWReplicationCallback) rq.getCallback(); if (callback != null) { callback.failed(ex); } } file.getPendingRequests().clear(); } private void enqueuePrioritized(StageRequest rq) { while (!q.offer(rq)) { StageRequest otherRq = q.poll(); otherRq.sendInternalServerError(new IllegalStateException("internal queue overflow, cannot enqueue operation for processing.")); Logging.logMessage(Logging.LEVEL_DEBUG, this, "Dropping request from rwre queue due to overload"); } } public static interface RWReplicationCallback { public void success(long newObjectVersion); public void redirect(String redirectTo); public void failed(ErrorResponse ex); } /*public void openFile(FileCredentials credentials, XLocations locations, boolean forceReset, RWReplicationCallback callback, OSDRequest request) { this.enqueueOperation(STAGEOP_OPEN, new Object[]{credentials,locations,forceReset}, request, callback); }*/ protected void enqueueExternalOperation(int stageOp, Object[] arguments, OSDRequest request, ReusableBuffer createdViewBuffer, Object callback) { if (externalRequestsInQueue.get() >= MAX_EXTERNAL_REQUESTS_IN_Q) { Logging.logMessage(Logging.LEVEL_WARN, this, "RW replication stage is overloaded, request %d for %s dropped", request.getRequestId(), request.getFileId()); request.sendInternalServerError(new IllegalStateException("RW replication stage is overloaded, request dropped")); // Make sure that the data buffer is returned to the pool if // necessary, as some operations create view buffers on the // data. Otherwise, a 'finalized but not freed before' warning // may occur. if (createdViewBuffer != null) { assert (createdViewBuffer.getRefCount() >= 2); BufferPool.free(createdViewBuffer); } } else { externalRequestsInQueue.incrementAndGet(); this.enqueueOperation(stageOp, arguments, request, createdViewBuffer, callback); } } public void prepareOperation(FileCredentials credentials, XLocations xloc, long objNo, long objVersion, Operation op, RWReplicationCallback callback, OSDRequest request) { this.enqueueExternalOperation(STAGEOP_PREPAREOP, new Object[]{credentials,xloc,objNo,objVersion,op}, request, null, callback); } public void replicatedWrite(FileCredentials credentials, XLocations xloc, long objNo, long objVersion, InternalObjectData data, ReusableBuffer createdViewBuffer, RWReplicationCallback callback, OSDRequest request) { this.enqueueExternalOperation(STAGEOP_REPLICATED_WRITE, new Object[]{credentials,xloc,objNo,objVersion,data}, request, createdViewBuffer, callback); } public void replicateTruncate(FileCredentials credentials, XLocations xloc, long newFileSize, long newObjectVersion, RWReplicationCallback callback, OSDRequest request) { this.enqueueExternalOperation(STAGEOP_TRUNCATE, new Object[]{credentials,xloc,newFileSize,newObjectVersion}, request, null, callback); } public void fileClosed(String fileId) { this.enqueueOperation(STAGEOP_CLOSE, new Object[]{fileId}, null, null); } public void receiveFleaseMessage(ReusableBuffer message, InetSocketAddress sender) { //this.enqueueOperation(STAGEOP_PROCESS_FLEASE_MSG, new Object[]{message,sender}, null, null); try { FleaseMessage msg = new FleaseMessage(message); BufferPool.free(message); msg.setSender(sender); fstage.receiveMessage(msg); } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } public void getStatus(StatusCallback callback) { this.enqueueOperation(STAGEOP_GETSTATUS, new Object[]{}, null, callback); } public static interface StatusCallback { public void statusComplete(Map<String,Map<String,String>> status); } @Override public void sendMessage(FleaseMessage message, InetSocketAddress recipient) { ReusableBuffer data = BufferPool.allocate(message.getSize()); message.serialize(data); data.flip(); try { RPCResponse r = fleaseOsdClient.xtreemfs_rwr_flease_msg(recipient, RPCAuthentication.authNone, RPCAuthentication.userService, master.getHostName(),master.getConfig().getPort(),data); r.registerListener(new RPCResponseAvailableListener() { @Override public void responseAvailable(RPCResponse r) { r.freeBuffers(); } }); } catch (IOException ex) { Logging.logError(Logging.LEVEL_ERROR, this, ex); } } @Override protected void processMethod(StageRequest method) { switch (method.getStageMethod()) { case STAGEOP_REPLICATED_WRITE : { externalRequestsInQueue.decrementAndGet(); processReplicatedWrite(method); break; } case STAGEOP_TRUNCATE : { externalRequestsInQueue.decrementAndGet(); processReplicatedTruncate(method); break; } case STAGEOP_CLOSE : processFileClosed(method); break; case STAGEOP_PROCESS_FLEASE_MSG : processFleaseMessage(method); break; case STAGEOP_PREPAREOP : { externalRequestsInQueue.decrementAndGet(); processPrepareOp(method); break; } case STAGEOP_INTERNAL_AUTHSTATE : processSetAuthoritativeState(method); break; case STAGEOP_LEASE_STATE_CHANGED : processLeaseStateChanged(method); break; case STAGEOP_INTERNAL_OBJFETCHED : processObjectFetched(method); break; case STAGEOP_INTERNAL_STATEAVAIL : processReplicaStateAvailExecReset(method); break; case STAGEOP_INTERNAL_DELETE_COMPLETE : processDeleteObjectsComplete(method); break; case STAGEOP_INTERNAL_MAXOBJ_AVAIL : processMaxObjAvail(method); break; case STAGEOP_INTERNAL_BACKUP_AUTHSTATE: processBackupAuthoritativeState(method); break; case STAGEOP_FORCE_RESET : processForceReset(method); break; case STAGEOP_GETSTATUS : processGetStatus(method); break; default : throw new IllegalArgumentException("no such stageop"); } } private void processFleaseMessage(StageRequest method) { try { final ReusableBuffer data = (ReusableBuffer) method.getArgs()[0]; final InetSocketAddress sender = (InetSocketAddress) method.getArgs()[1]; FleaseMessage msg = new FleaseMessage(data); BufferPool.free(data); msg.setSender(sender); fstage.receiveMessage(msg); } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processFileClosed(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; ReplicatedFileState state = files.remove(fileId); if (state != null) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"closing file %s",fileId); } state.getPolicy().closeFile(); if (state.getPolicy().requiresLease()) fstage.closeCell(state.getPolicy().getCellId(), false); cellToFileId.remove(state.getPolicy().getCellId()); } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private ReplicatedFileState getState(FileCredentials credentials, XLocations loc, boolean forceReset) throws IOException { final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = files.get(fileId); if (state == null) { if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"open file: "+fileId); //"open" file state = new ReplicatedFileState(fileId,loc, master.getConfig().getUUID(), fstage, osdClient); files.put(fileId,state); state.setCredentials(credentials); state.setForceReset(forceReset); cellToFileId.put(state.getPolicy().getCellId(),fileId); assert(state.getState() == ReplicaState.INITIALIZING); master.getStorageStage().internalGetMaxObjectNo(fileId, loc.getLocalReplica().getStripingPolicy(), new InternalGetMaxObjectNoCallback() { @Override public void maxObjectNoCompleted(long maxObjNo, long fileSize, long truncateEpoch, ErrorResponse error) { eventMaxObjAvail(fileId, maxObjNo, fileSize, truncateEpoch, error); } }); } return state; } private void processMaxObjAvail(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final Long maxObjVersion = (Long) method.getArgs()[1]; final ErrorResponse error = (ErrorResponse) method.getArgs()[2]; if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) max obj avail for file: "+fileId+" max="+maxObjVersion, localID); ReplicatedFileState state = files.get(fileId); if (state == null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"received maxObjAvail event for unknow file: %s",fileId); return; } assert(state.getState() == ReplicaState.INITIALIZING); state.getPolicy().setLocalObjectVersion(maxObjVersion); doOpen(state); } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this, ex); } } private void processReplicatedWrite(StageRequest method) { final RWReplicationCallback callback = (RWReplicationCallback) method.getCallback(); try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; final Long objNo = (Long) method.getArgs()[2]; final Long objVersion = (Long) method.getArgs()[3]; final InternalObjectData objData = (InternalObjectData) method.getArgs()[4]; final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = files.get(fileId); if (state == null) { BufferPool.free(objData.getData()); callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "file is not open!")); return; } state.setCredentials(credentials); state.getPolicy().executeWrite(credentials, objNo, objVersion, objData, new ReplicaUpdatePolicy.ClientOperationCallback() { @Override public void finsihed() { callback.success(objVersion); } @Override public void failed(ErrorResponse error) { callback.failed(error); } }); } catch (Exception ex) { ex.printStackTrace(); callback.failed(ErrorUtils.getInternalServerError(ex)); } } private void processReplicatedTruncate(StageRequest method) { final RWReplicationCallback callback = (RWReplicationCallback) method.getCallback(); try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; final Long newFileSize = (Long) method.getArgs()[2]; final Long newObjVersion = (Long) method.getArgs()[3]; final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = files.get(fileId); if (state == null) { callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "file is not open!")); return; } state.setCredentials(credentials); state.getPolicy().executeTruncate(credentials, newFileSize, newObjVersion, new ReplicaUpdatePolicy.ClientOperationCallback() { @Override public void finsihed() { callback.success(newObjVersion); } @Override public void failed(ErrorResponse error) { callback.failed(error); } }); } catch (Exception ex) { ex.printStackTrace(); callback.failed(ErrorUtils.getInternalServerError(ex)); } } private void processPrepareOp(StageRequest method) { final RWReplicationCallback callback = (RWReplicationCallback)method.getCallback(); try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; final Long objVersion = (Long) method.getArgs()[3]; final Operation op = (Operation) method.getArgs()[4]; final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = getState(credentials, loc, false); if ((op == Operation.INTERNAL_UPDATE) || (op == Operation.INTERNAL_TRUNCATE)) { switch (state.getState()) { case WAITING_FOR_LEASE: case INITIALIZING: case RESET: case OPEN: { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"enqeue update for %s (state is %s)",fileId,state.getState()); } if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "rejecting request: too many requests (is: %d, max %d) in queue for file %s", state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId); } callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file")); return; } else { state.getPendingRequests().add(method); } if (state.getState() == ReplicaState.OPEN) { //immediately change to backup mode...no need to check the lease doWaitingForLease(state); } return; } } boolean needsReset = state.getPolicy().onRemoteUpdate(objVersion, state.getState()); if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"%s needs reset: %s",fileId,needsReset); } if (needsReset) { state.getPendingRequests().add(method); doReset(state,objVersion); } else { callback.success(0); } } else { state.setCredentials(credentials); switch (state.getState()) { case WAITING_FOR_LEASE: case INITIALIZING: case RESET : { if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "rejecting request: too many requests (is: %d, max %d) in queue for file %s", state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId); } callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file")); } else { state.getPendingRequests().add(method); } return; } case OPEN : { if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "rejecting request: too many requests (is: %d, max %d) in queue for file %s", state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId); } callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file")); return; } else { state.getPendingRequests().add(method); } doWaitingForLease(state); return; } } try { long newVersion = state.getPolicy().onClientOperation(op,objVersion,state.getState(),state.getLease()); callback.success(newVersion); } catch (RedirectToMasterException ex) { callback.redirect(ex.getMasterUUID()); } catch (RetryException ex) { final ErrorResponse err = ErrorUtils.getInternalServerError(ex); failed(state, err, "processPrepareOp"); if (state.getState() == ReplicaState.BACKUP || state.getState() == ReplicaState.PRIMARY) { // Request is not in queue, we must notify // callback. callback.failed(err); } } } } catch (Exception ex) { ex.printStackTrace(); callback.failed(ErrorUtils.getInternalServerError(ex)); } } private void processGetStatus(StageRequest method) { final StatusCallback callback = (StatusCallback)method.getCallback(); try { Map<String,Map<String,String>> status = new HashMap(); Map<ASCIIString,FleaseMessage> fleaseState = fstage.getLocalState(); for (String fileId : this.files.keySet()) { Map<String,String> fStatus = new HashMap(); final ReplicatedFileState fState = files.get(fileId); final ASCIIString cellId = fState.getPolicy().getCellId(); fStatus.put("policy",fState.getPolicy().getClass().getSimpleName()); fStatus.put("peers (OSDs)",fState.getPolicy().getRemoteOSDUUIDs().toString()); fStatus.put("pending requests", fState.getPendingRequests() == null ? "0" : ""+fState.getPendingRequests().size()); fStatus.put("cellId", cellId.toString()); String primary = "unknown"; if ((fState.getLease() != null) && (!fState.getLease().isEmptyLease())) { if (fState.getLease().isValid()) { if (fState.isLocalIsPrimary()) { primary = "primary"; } else { primary = "backup ( primary is "+fState.getLease().getLeaseHolder()+")"; } } else { primary = "outdated lease: "+fState.getLease().getLeaseHolder(); } } fStatus.put("role", primary); status.put(fileId,fStatus); } callback.statusComplete(status); } catch (Exception ex) { ex.printStackTrace(); callback.statusComplete(null); } } }
package com.dgrid.helpers.impl; import java.util.Date; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.danga.MemCached.MemCachedClient; import com.danga.MemCached.SockIOPool; import com.dgrid.errors.TransportException; import com.dgrid.gen.InvalidApiKey; import com.dgrid.helpers.MemcacheHelper; import com.dgrid.service.DGridClient; public class MemcacheHelperImpl implements MemcacheHelper { private Log log = LogFactory.getLog(getClass()); private DGridClient gridClient; private MemCachedClient client = new MemCachedClient(); public void setGridClient(DGridClient gridClient) { this.gridClient = gridClient; } public void init() throws TransportException, InvalidApiKey { log.trace("init()"); SockIOPool pool = SockIOPool.getInstance(); String serverString = gridClient.getSetting("memcache.servers", "localhost:11211"); String[] servers = serverString.split(" "); boolean compat = Boolean.parseBoolean(gridClient.getSetting( "memcache.compatibility", Boolean.toString(false))); if (compat) { pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH); client.setPrimitiveAsString(true); client.setSanitizeKeys(false); } pool.setServers(servers); pool.initialize(); } @Override public boolean add(String key, Object value) { log.trace("add()"); return client.add(key, value); } @Override public boolean add(String key, Object value, Date expiry) { log.trace("add()"); return client.add(key, value, expiry); } @Override public boolean add(String key, Object value, Date expiry, int hashCode) { log.trace("add()"); return client.add(key, value, expiry, hashCode); } @Override public boolean add(String key, Object value, int hashCode) { log.trace("add()"); return client.add(key, value, hashCode); } @Override public long addOrDecr(String key) { log.trace("addOrDecr()"); return client.addOrDecr(key); } @Override public long addOrDecr(String key, long inc) { log.trace("addOrDecr()"); return client.addOrDecr(key, inc); } @Override public long addOrDecr(String key, long inc, int hashCode) { log.trace("addOrDecr()"); return client.addOrDecr(key, inc, hashCode); } @Override public long addOrIncr(String key) { log.trace("addOrIncr()"); return client.addOrIncr(key); } @Override public long addOrIncr(String key, long inc) { log.trace("addOrIncr()"); return client.addOrIncr(key, inc); } @Override public long addOrIncr(String key, long inc, int hashCode) { log.trace("addOrIncr()"); return client.addOrIncr(key, inc, hashCode); } @Override public boolean delete(String key) { log.trace("delete()"); return client.delete(key); } @Override public boolean delete(String key, Date expiry) { log.trace("delete()"); return client.delete(key, expiry); } @Override public boolean delete(String key, int hashCode, Date expiry) { log.trace("delete()"); return client.delete(key, hashCode, expiry); } @Override public boolean flushAll() { log.trace("flushAll()"); return client.flushAll(); } @Override public Object get(String key) { log.trace("get()"); return client.get(key); } @Override public Object get(String key, int hashCode) { log.trace("get()"); return client.get(key, hashCode); } @Override public long getCounter(String key) { log.trace("getCounter()"); return client.getCounter(key); } @Override public long getCounter(String key, int hashCode) { log.trace("getCounter()"); return client.getCounter(key, hashCode); } @Override public MemCachedClient getMemCachedClient() { log.trace("getMemCachedClient()"); return client; } @Override public boolean keyExists(String key) { log.trace("keyExists()"); return client.keyExists(key); } @Override public boolean replace(String key, Object value) { log.trace("replace()"); return client.replace(key, value); } @Override public boolean replace(String key, Object value, Date expiry) { log.trace("replace()"); return client.replace(key, value, expiry); } @Override public boolean replace(String key, Object value, Date expiry, int hashCode) { log.trace("replace()"); return client.replace(key, value, expiry, hashCode); } @Override public boolean set(String key, Object value) { log.trace("set()"); return client.set(key, value); } @Override public boolean set(String key, Object value, Date expiry) { log.trace("set()"); return client.set(key, value, expiry); } @Override public boolean set(String key, Object value, Date expiry, int hashCode) { log.trace("set()"); return client.set(key, value, expiry, hashCode); } @Override public boolean set(String key, Object value, int hashCode) { log.trace("set()"); return client.set(key, value, hashCode); } @Override public Map stats() { log.trace("stats()"); return client.stats(); } @Override public boolean storeCounter(String key, long counter) { log.trace("storeCounter()"); return client.storeCounter(key, counter); } @Override public boolean storeCounter(String key, long counter, int hashCode) { log.trace("storeCounter()"); return client.storeCounter(key, counter, hashCode); } }
package joliex.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; import jolie.runtime.ValueVector; public class ExecService extends JavaService { public Value exec( Value request ) throws FaultException { List< String > command = new LinkedList< String >(); String[] str = request.strValue().split( " " ); command.addAll( Arrays.asList( str ) ); for( Value v : request.getChildren( "args" ) ) { command.add( v.strValue() ); } ProcessBuilder builder = new ProcessBuilder( command ); if ( request.hasChildren( "workingDirectory" ) ) { builder.directory( new File( request.getFirstChild( "workingDirectory" ).strValue() ) ); } try { Value response = Value.create(); boolean stdOutConsoleEnable = false; Process p = builder.start(); StreamGobbler outputStreamGobbler = new StreamGobbler( p.getInputStream() ); if ( request.hasChildren( "stdOutConsoleEnable" ) ) { if ( request.getFirstChild( "stdOutConsoleEnable" ).boolValue() ) { outputStreamGobbler.start(); stdOutConsoleEnable = true; } } ValueVector waitFor = request.children().get( "waitFor" ); if ( waitFor == null || waitFor.first().intValue() > 0 ) { int exitCode = p.waitFor(); response.getNewChild( "exitCode" ).setValue( exitCode ); if ( !stdOutConsoleEnable ) { int len = p.getInputStream().available(); if ( len > 0 ) { char[] buffer = new char[ len ]; BufferedReader reader = new BufferedReader( new InputStreamReader( p.getInputStream() ) ); reader.read( buffer, 0, len ); response.setValue( new String( buffer ) ); } } if ( p.getErrorStream() != null ) { int len = p.getErrorStream().available(); if ( len > 0 ) { char[] buffer = new char[ len ]; BufferedReader reader = new BufferedReader( new InputStreamReader( p.getErrorStream() ) ); reader.read( buffer, 0, len ); response.getFirstChild( "stderr" ).setValue( new String( buffer ) ); } } if ( outputStreamGobbler.isAlive() ) { outputStreamGobbler.join(); } p.getInputStream().close(); p.getErrorStream().close(); p.getOutputStream().close(); } return response; } catch( Exception e ) { throw new FaultException( e ); } } private class StreamGobbler extends Thread { InputStream is; private StreamGobbler( InputStream is ) { this.is = is; } @Override public void run() { try { InputStreamReader isr = new InputStreamReader( is ); BufferedReader br = new BufferedReader( isr ); String line = null; while( (line = br.readLine()) != null ) { System.out.println( line ); } } catch( IOException ioe ) { ioe.printStackTrace(); } } } }
package org.eclipse.jetty.io; import org.eclipse.jetty.util.thread.Timeout; public interface AsyncEndPoint extends ConnectedEndPoint { /** * Dispatch the endpoint to a thread to attend to it. * */ public void asyncDispatch(); /** Schedule a write dispatch. * Set the endpoint to not be writable and schedule a dispatch when * it becomes writable. */ public void scheduleWrite(); /** Schedule a call to the idle timeout */ public void scheduleIdle(); /** Cancel a call to the idle timeout */ public void cancelIdle(); public boolean isWritable(); /** * @return True if IO has been successfully performed since the last call to {@link #hasProgressed()} */ public boolean hasProgressed(); public void scheduleTimeout(Timeout.Task task, long timeoutMs); public void cancelTimeout(Timeout.Task task); }
package edu.ucsf.lava.core.importer.model; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; import edu.ucsf.lava.core.file.model.ImportFile; import edu.ucsf.lava.core.model.EntityBase; public class ImportLog extends EntityBase { public static String DEBUG_MSG = "DEBUG"; public static String ERROR_MSG = "ERROR"; public static String WARNING_MSG = "WARNING"; public static String INFO_MSG = "INFO"; private Timestamp importTimestamp; private String importedBy; private ImportFile dataFile; private String definitionName; private Integer totalRecords; // record imported (generally means row inserted, though populating an "empty" record could // qualify as an import instead of an update private Integer imported; // update to existing data, mutually exclusive with imported private Integer updated; // record already existed so no import or update private Integer alreadyExist; // record not imported due to an error private Integer errors; // record imported or updated, but with a warning private Integer warnings; private String notes; // entered by user when doing the import private List<ImportLogMessage> messages = new ArrayList<ImportLogMessage>(); // warnings, errors public ImportLog(){ super(); this.totalRecords = 0; this.imported = 0; this.updated = 0; this.alreadyExist = 0; this.errors = 0; this.warnings = 0; this.importTimestamp = new Timestamp(new Date().getTime()); } public Timestamp getImportTimestamp() { return importTimestamp; } public void setImportTimestamp(Timestamp importTimestamp) { this.importTimestamp = importTimestamp; } public String getImportedBy() { return importedBy; } public void setImportedBy(String importedBy) { this.importedBy = importedBy; } public ImportFile getDataFile() { return dataFile; } public void setDataFile(ImportFile dataFile) { this.dataFile = dataFile; } public String getDefinitionName() { return definitionName; } public void setDefinitionName(String definitionName) { this.definitionName = definitionName; } public Integer getTotalRecords() { return totalRecords; } public void setTotalRecords(Integer totalRecords) { this.totalRecords = totalRecords; } public Integer getImported() { return imported; } public void setImported(Integer imported) { this.imported = imported; } public Integer getAlreadyExist() { return alreadyExist; } public Integer getUpdated() { return updated; } public void setUpdated(Integer updated) { this.updated = updated; } public void setAlreadyExist(Integer alreadyExist) { this.alreadyExist = alreadyExist; } public Integer getErrors() { return errors; } public void setErrors(Integer errors) { this.errors = errors; } public Integer getWarnings() { return warnings; } public void setWarnings(Integer warnings) { this.warnings = warnings; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public List<ImportLogMessage> getMessages() { return messages; } public void setMessages(List<ImportLogMessage> messages) { this.messages = messages; } public void addMessage(String type, Integer lineNum, String msg) { ImportLogMessage logMessage = new ImportLogMessage(type, lineNum, msg); this.messages.add(logMessage); } public void addDebugMessage(Integer lineNum, String msg) { this.addMessage(DEBUG_MSG, lineNum, msg); } public void addErrorMessage(Integer lineNum, String msg) { this.addMessage(ERROR_MSG, lineNum, msg); } public void addWarningMessage(Integer lineNum, String msg) { this.addMessage(WARNING_MSG, lineNum, msg); } public void addInfoMessage(Integer lineNum, String msg) { this.addMessage(INFO_MSG, lineNum, msg); } public void incTotalRecords() { this.totalRecords++; } public void incImported() { this.imported++; } public void incUpdated() { this.updated++; } public void incAlreadyExist() { this.alreadyExist++; } public void incErrors() { this.errors++; } public void incWarnings() { this.warnings++; } public String getSummaryBlock() { StringBuffer sb = new StringBuffer("Total=").append(this.getTotalRecords()).append(", "); sb.append("Imported=").append(this.getImported()).append(", "); sb.append("Updated=").append(this.getUpdated()).append("\n"); sb.append("Already Exists=").append(this.getAlreadyExist()).append(", "); sb.append("Errors=").append(this.getErrors()).append(", "); sb.append("Warnings=").append(this.getWarnings()); return sb.toString(); } public static class ImportLogMessage implements Serializable { private String type; private Integer lineNum; private String message; public ImportLogMessage(){ super(); } public ImportLogMessage(String type, Integer lineNum, String message) { this.type = type; this.lineNum = lineNum; this.message = message; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Integer getLineNum() { return lineNum; } public void setLineNum(Integer lineNum) { this.lineNum = lineNum; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } }
package edu.stru.lesson.one; public class HomeworkPartTwo { public static void main (String[] args){ Point p1 = new Point(9.5,3); Point p2 = new Point(8,1); System.out.println("Расстояние между точкой A("+p1.x+";"+p1.y+") и точкой B("+p2.x+";"+p2.y+")="+distance(p1,p2)); } public static double distance(Point p1, Point p2){ return Math.sqrt(Math.pow(p1.x-p2.x, 2) + Math.pow(p1.y-p2.y, 2) ); } }
package com.xlythe.textmanager.text; import com.xlythe.textmanager.Message; import com.xlythe.textmanager.MessageCallback; import com.xlythe.textmanager.MessageManager; import com.xlythe.textmanager.MessageThread; import com.xlythe.textmanager.User; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * Manages sms and mms messages */ public class TextManager implements MessageManager { /** * Return all message threads * */ public List<MessageThread> getThreads() { return new ArrayList<MessageThread>(); } /** * Return all message threads * */ public void getThreads(MessageCallback<List<MessageThread>> callback) {} /** * Register an observer to get callbacks every time messages are added, deleted, or changed. * */ public void registerObserver() { } /** * Get all messages involving that user. * */ public List<Message> getMessages(User user) { return new ArrayList<Message>(); } /** * Get all messages involving that user. * */ public void getMessages(User user, MessageCallback<List<Message>> callback) { } /** * Return all messages containing the text. * */ public List<Message> search(String text) { LinkedList<Message> messages = new LinkedList<Message>(); for(MessageThread t : getThreads()) { for(Message m : t.getMessages()) { if(m.getText() != null) { if(m.getText().contains(text)) { messages.add(m); } } } } return messages; } /** * Return all messages containing the text. * */ public void search(String text, MessageCallback<List<Message>> callback) { } }
package scal.io.liger.adapter; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.HashMap; import java.util.List; import scal.io.liger.Constants; import scal.io.liger.R; import scal.io.liger.model.Card; import scal.io.liger.model.ClipCard; import scal.io.liger.model.MediaFile; import scal.io.liger.view.ReorderableRecyclerView; import scal.io.liger.view.Util; public class OrderMediaAdapter extends RecyclerView.Adapter<OrderMediaAdapter.ViewHolder> implements ReorderableAdapter { public static final String TAG = "OrderMediaAdapter"; private ReorderableRecyclerView mRecyclerView; private HashMap<Card, Long> mCardToStableId = new HashMap<>(); private List<Card> mClipCards; private String mMedium; private OnReorderListener mReorderListener; public interface OnReorderListener { /** * The item at firstIndex switched places with the item * at secondIndex */ public void onReorder(int firstIndex, int secondIndex); } @Override public void swapItems(int positionOne, int positionTwo) { Card itemOne = mClipCards.get(positionOne); mClipCards.set(positionOne, mClipCards.get(positionTwo)); mClipCards.set(positionTwo, itemOne); notifyItemChanged(positionOne); notifyItemChanged(positionTwo); if (mReorderListener != null) mReorderListener.onReorder(positionOne, positionTwo); } public static class ViewHolder extends RecyclerView.ViewHolder { public ImageView thumbnail; public TextView title; public ImageView draggable; public ViewHolder(View v) { super(v); thumbnail = (ImageView) v.findViewById(R.id.thumbnail); title = (TextView) v.findViewById(R.id.title); draggable = (ImageView) v.findViewById(R.id.draggable); } } public OrderMediaAdapter(ReorderableRecyclerView recyclerView, List<Card> cards, String medium) { mRecyclerView = recyclerView; mClipCards = cards; mMedium = medium; long id = 0; for (Card card : mClipCards) { mCardToStableId.put(card, id++); } } public void setOnReorderListener(OnReorderListener listener) { mReorderListener = listener; } @Override public OrderMediaAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int i) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.order_media_clip_item, parent, false); // set the view's size, margins, paddings and layout parameters return new ViewHolder(v); } @Override public void onBindViewHolder(OrderMediaAdapter.ViewHolder viewHolder, int position) { Context context = viewHolder.thumbnail.getContext(); // TESTING ((View) viewHolder.draggable.getParent()).setTag(position); viewHolder.draggable.setTag(position); viewHolder.draggable.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: //Log.i(TAG, "sending reorder drag to recyclerview for position " + v.getTag()); mRecyclerView.startReorderDrag((View) v.getParent(), event, (Integer) v.getTag()); } return false; } }); Card cm = mClipCards.get(position); ClipCard ccm = null; if (cm instanceof ClipCard) { ccm = (ClipCard) cm; } else { return; // Should filter ArrayList at construction so we don't have meaningless list items } String title = null; if (cm.getTitle() == null || cm.getTitle().length() == 0) { String goal = ((ClipCard) cm).getFirstGoal(); title = String.format("%s: %s", ((ClipCard) cm).getClipType(), goal); } else { title = cm.getTitle(); } viewHolder.title.setText(title); String mediaPath = null; MediaFile mf = ccm.getSelectedMediaFile(); if (mf == null) { Log.e(this.getClass().getName(), "no media file was found"); } else { mediaPath = mf.getPath(); } //File mediaFile = null; Uri mediaURI = null; if (mediaPath != null) { /* mediaFile = MediaHelper.loadFileFromPath(ccm.getStoryPath().buildZipPath(mediaPath)); if(mediaFile.exists() && !mediaFile.isDirectory()) { mediaURI = Uri.parse(mediaFile.getPath()); } */ mediaURI = Uri.parse(mediaPath); } if (mMedium != null && mediaURI != null) { if (mMedium.equals(Constants.VIDEO)) { Bitmap videoFrame = mf.getThumbnail(viewHolder.title.getContext()); if (videoFrame != null) { viewHolder.thumbnail.setImageBitmap(videoFrame); } return; } else if (mMedium.equals(Constants.PHOTO)) { viewHolder.thumbnail.setImageURI(mediaURI); return; } else if (mMedium.equals(Constants.AUDIO)) { int drawable = R.drawable.audio_waveform; viewHolder.thumbnail.setImageDrawable(context.getResources().getDrawable(drawable)); return; } } } @Override public int getItemCount() { return mClipCards.size(); } @Override public long getItemId (int position) { if (position < mClipCards.size() && position >= 0) { return mCardToStableId.get(mClipCards.get(position)); } return RecyclerView.NO_ID; } }
package com.jmedeisis.windowview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.util.AttributeSet; import android.util.Log; import android.view.Surface; import android.view.WindowManager; import android.widget.ImageView; /** An ImageView that automatically pans in response to device tilt. Currently only supports {@link android.widget.ImageView.ScaleType#CENTER_CROP}. */ public class WindowView extends ImageView implements SensorEventListener { private static final String LOG_TAG = "WindowView"; private final SensorManager sensorManager; private float latestYaw; private float latestPitch; private float latestRoll; // 1 radian = 57.2957795 degrees private static final float DEGREES_PER_RADIAN = 57.2957795f; private static final int NUM_FILTER_SAMPLES = 15; private static final float LOW_PASS_COEFF = 0.5f; private final Filter yawFilter; private final Filter pitchFilter; private final Filter rollFilter; /** @see {@link android.view.Display#getRotation()}. */ private final int screenRotation; private final float[] rotationMatrix = new float[9]; private final float[] rotationMatrixTemp = new float[9]; private final float[] rotationMatrixOrigin = new float[9]; private final float[] orientation = new float[3]; private final float[] orientationOrigin = new float[3]; private final float[] latestAccelerations = new float[3]; private final float[] latestMagFields = new float[3]; private boolean haveOrigin = false; private boolean haveGravData = false; private boolean haveAccelData = false; private boolean haveMagData = false; // TODO make set-able, +xml attribs private static final float MAX_PITCH = 30; private static final float MAX_ROLL = 30; private static final float HORIZONTAL_ORIGIN = 0; private static final float VERTICAL_ORIGIN = 0; public static enum Mode { /** Measures absolute yaw / pitch / roll (i.e. relative to the world). */ ABSOLUTE, /** Measures yaw / pitch / roll relative to the starting orientation. */ RELATIVE } // TODO make set-able, +xml attribs private Mode mode = Mode.RELATIVE; // layout private boolean heightMatches; private float widthDifference; private float heightDifference; // debug private static final boolean DEBUG_TILT = true; private static final boolean DEBUG_IMAGE = false; private static final boolean DEBUG_LIFECYCLE = false; private final static int DEBUG_TEXT_SIZE = 32; private final Paint debugTextPaint; public WindowView(Context context) { this(context, null); } public WindowView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public WindowView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); yawFilter = new Filter(NUM_FILTER_SAMPLES, LOW_PASS_COEFF, 0); pitchFilter = new Filter(NUM_FILTER_SAMPLES, LOW_PASS_COEFF, 0); rollFilter = new Filter(NUM_FILTER_SAMPLES, LOW_PASS_COEFF, 0); screenRotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation(); debugTextPaint = new Paint(); debugTextPaint.setColor(Color.MAGENTA); debugTextPaint.setTextSize(DEBUG_TEXT_SIZE); debugTextPaint.setTypeface(Typeface.MONOSPACE); setScaleType(ScaleType.CENTER_CROP); } @Override public void onWindowFocusChanged(boolean hasWindowFocus){ super.onWindowFocusChanged(hasWindowFocus); if(DEBUG_LIFECYCLE) Log.d(LOG_TAG, "onWindowFocusChanged(), hasWindowFocus: " + hasWindowFocus); if(hasWindowFocus){ registerListeners(); } else { unregisterListeners(); } } private void registerListeners(){ if(DEBUG_LIFECYCLE) Log.d(LOG_TAG, "Started listening to sensor events."); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY), SensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME); } private void unregisterListeners(){ if(DEBUG_LIFECYCLE) Log.d(LOG_TAG, "Stopped listening to sensor events."); sensorManager.unregisterListener(this); } @Override protected void onAttachedToWindow(){ super.onAttachedToWindow(); if(DEBUG_LIFECYCLE) Log.d(LOG_TAG, "onAttachedToWindow()"); registerListeners(); } @Override protected void onDetachedFromWindow(){ super.onDetachedFromWindow(); if(DEBUG_LIFECYCLE) Log.d(LOG_TAG, "onDetachedFromWindow()"); unregisterListeners(); } @SuppressWarnings("UnusedAssignment") @Override protected void onDraw(Canvas canvas){ // -1 -> 1 float translateX = 0f; float translateY = 0f; if(heightMatches){ // only let user tilt horizontally translateX = (-HORIZONTAL_ORIGIN + clampAbsoluteFloating(HORIZONTAL_ORIGIN, latestRoll, MAX_ROLL)) / MAX_ROLL; } else { // only let user tilt vertically translateY = (VERTICAL_ORIGIN - clampAbsoluteFloating(VERTICAL_ORIGIN, latestPitch, MAX_PITCH)) / MAX_PITCH; } canvas.save(); canvas.translate(Math.round((widthDifference / 2) * translateX), Math.round((heightDifference / 2) * translateY)); super.onDraw(canvas); canvas.restore(); // TODO DEBUG int i = 0; if(DEBUG_IMAGE){ debugText(canvas, i++, "width " + getWidth()); debugText(canvas, i++, "height " + getHeight()); debugText(canvas, i++, "img width " + getScaledImageWidth()); debugText(canvas, i++, "img height " + getScaledImageHeight()); debugText(canvas, i++, "tx " + translateX); debugText(canvas, i++, "ty " + translateY); debugText(canvas, i++, "height matches " + heightMatches); } if(DEBUG_TILT){ debugText(canvas, i++, mode + " mode"); if(haveOrigin){ SensorManager.getOrientation(rotationMatrixOrigin, orientationOrigin); debugText(canvas, i++, "org yaw " + orientationOrigin[0]*DEGREES_PER_RADIAN); debugText(canvas, i++, "org pitch " + orientationOrigin[1]*DEGREES_PER_RADIAN); debugText(canvas, i++, "org roll " + orientationOrigin[2]*DEGREES_PER_RADIAN); } debugText(canvas, i++, "yaw " + latestYaw); debugText(canvas, i++, "pitch " + latestPitch); debugText(canvas, i++, "roll " + latestRoll); debugText(canvas, i++, "MAX_PITCH " + MAX_PITCH); debugText(canvas, i++, "MAX_ROLL " + MAX_ROLL); debugText(canvas, i++, "HOR ORIGIN " + HORIZONTAL_ORIGIN); debugText(canvas, i++, "VER ORIGIN " + VERTICAL_ORIGIN); switch(screenRotation){ case Surface.ROTATION_0: debugText(canvas, i++, "ROTATION_0"); break; case Surface.ROTATION_90: debugText(canvas, i++, "ROTATION_90"); break; case Surface.ROTATION_180: debugText(canvas, i++, "ROTATION_180"); break; case Surface.ROTATION_270: debugText(canvas, i++, "ROTATION_270"); break; } } } private void debugText(Canvas canvas, int i, String text){ canvas.drawText(text, DEBUG_TEXT_SIZE, (2 + i) * DEBUG_TEXT_SIZE, debugTextPaint); } private float clampAbsoluteFloating(float origin, float value, float maxAbsolute){ return value < origin ? Math.max(value, origin - maxAbsolute) : Math.min(value, origin + maxAbsolute); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh){ heightMatches = !widthRatioGreater(w, h, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight()); widthDifference = getScaledImageWidth() - getWidth(); heightDifference = getScaledImageHeight() - getHeight(); } private static boolean widthRatioGreater(float width, float height, float otherWidth, float otherHeight){ return height / otherHeight < width / otherWidth; } private float getScaledImageWidth(){ final ScaleType scaleType = getScaleType(); float intrinsicImageWidth = getDrawable().getIntrinsicWidth(); float intrinsicImageHeight = getDrawable().getIntrinsicHeight(); if(ScaleType.CENTER_CROP == scaleType){ if(widthRatioGreater(getWidth(), getHeight(), intrinsicImageWidth, intrinsicImageHeight)){ intrinsicImageWidth = getWidth(); } else { intrinsicImageWidth *= getHeight() / intrinsicImageHeight; } return intrinsicImageWidth; } return 0f; } private float getScaledImageHeight(){ final ScaleType scaleType = getScaleType(); float intrinsicImageWidth = getDrawable().getIntrinsicWidth(); float intrinsicImageHeight = getDrawable().getIntrinsicHeight(); if(ScaleType.CENTER_CROP == scaleType){ if(widthRatioGreater(getWidth(), getHeight(), intrinsicImageWidth, intrinsicImageHeight)){ intrinsicImageHeight *= getWidth() / intrinsicImageWidth; } else { intrinsicImageHeight = getHeight(); } return intrinsicImageHeight; } return 0f; } @Override public void setScaleType(ScaleType scaleType){ if(ScaleType.CENTER_CROP != scaleType) throw new IllegalArgumentException("Image scale type " + scaleType + " is not supported by WindowView. Use CENTER_CROP instead."); super.setScaleType(scaleType); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // nothing to do here.. } @Override public void onSensorChanged(SensorEvent event) { switch(event.sensor.getType()){ case Sensor.TYPE_GRAVITY: System.arraycopy(event.values, 0, latestAccelerations, 0, 3); haveGravData = true; break; case Sensor.TYPE_ACCELEROMETER: if(haveGravData){ // gravity sensor data is better! let's not listen to the accelerometer anymore sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)); break; } System.arraycopy(event.values, 0, latestAccelerations, 0, 3); haveAccelData = true; break; case Sensor.TYPE_MAGNETIC_FIELD: System.arraycopy(event.values, 0, latestMagFields, 0, 3); haveMagData = true; break; } if(haveDataNecessaryToComputeOrientation()){ computeOrientation(); } } /** @return true if both {@link #latestAccelerations} and {@link #latestMagFields} have valid values. */ private boolean haveDataNecessaryToComputeOrientation(){ return (haveGravData || haveAccelData) && haveMagData; } /** * Computes the latest rotation, and stores it in {@link #rotationMatrix}.<p> * Should only be called if {@link #haveDataNecessaryToComputeOrientation()} returns true, * else result may be undefined. * @return true if rotation was retrieved and recalculated, false otherwise. */ private boolean computeRotationMatrix(){ if(SensorManager.getRotationMatrix(rotationMatrixTemp, null, latestAccelerations, latestMagFields)){ switch(screenRotation){ case Surface.ROTATION_0: SensorManager.remapCoordinateSystem(rotationMatrixTemp, SensorManager.AXIS_X, SensorManager.AXIS_Y, rotationMatrix); break; case Surface.ROTATION_90: SensorManager.remapCoordinateSystem(rotationMatrixTemp, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, rotationMatrix); break; case Surface.ROTATION_180: SensorManager.remapCoordinateSystem(rotationMatrixTemp, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y, rotationMatrix); break; case Surface.ROTATION_270: SensorManager.remapCoordinateSystem(rotationMatrixTemp, SensorManager.AXIS_MINUS_Y, SensorManager.AXIS_X, rotationMatrix); break; } return true; } return false; } /** * Computes the latest orientation and stores it in {@link #orientation}. * Also updates {@link #latestYaw}, {@link #latestPitch} and {@link #latestRoll} * as filtered versions of {@link #orientation}. */ private void computeOrientation(){ synchronized(rotationMatrix){ if(computeRotationMatrix()){ switch(mode){ case ABSOLUTE: // get absolute yaw / pitch / roll SensorManager.getOrientation(rotationMatrix, orientation); break; case RELATIVE: if(!haveOrigin){ updateOrigin(); } // get yaw / pitch / roll relative to original rotation SensorManager.getAngleChange(orientation, rotationMatrix, rotationMatrixOrigin); break; } /* [0] : yaw, rotation around z axis * [1] : pitch, rotation around x axis * [2] : roll, rotation around y axis */ final float yaw = orientation[0] * DEGREES_PER_RADIAN; final float pitch = orientation[1] * DEGREES_PER_RADIAN; final float roll = orientation[2] * DEGREES_PER_RADIAN; latestYaw = yawFilter.push(yaw); latestPitch = pitchFilter.push(pitch); latestRoll = rollFilter.push(roll); // redraw image invalidate(); } } } /** Manually resets the orientation origin. Has no effect unless the mode is {@link com.jmedeisis.windowview.WindowView.Mode#RELATIVE}. */ public boolean resetOrigin(){ if(haveDataNecessaryToComputeOrientation()){ synchronized(rotationMatrix){ if(computeRotationMatrix()){ updateOrigin(); return true; } } } return false; } /** Resets the internal orientation origin matrix. {@link #computeRotationMatrix()} must have been called prior. */ private void updateOrigin(){ System.arraycopy(rotationMatrix, 0, rotationMatrixOrigin, 0, 9); haveOrigin = true; } /** Determines the mapping of orientation to image offset. See {@link com.jmedeisis.windowview.WindowView.Mode}. */ public void setMode(Mode mode){ this.mode = mode; haveOrigin = false; // TODO reset other parameters? test } /** Ring buffer low-pass filter. */ private class Filter { float[] buffer; float sum; int lastIndex; float factor; public Filter(int samples, float factor, float initialValue){ buffer = new float[samples]; this.factor = factor; lastIndex = 0; reset(initialValue); } public void reset(float value){ sum = value * buffer.length; for(int i = 0; i < buffer.length; i++){ buffer[i] = value; } } /** * Pushes new sample to filter. * @return new smoothed value. */ public float push(float value){ // do low-pass value = buffer[lastIndex] + factor * (value - buffer[lastIndex]); // subtract oldest sample sum -= buffer[lastIndex]; // add new sample sum += value; buffer[lastIndex] = value; // advance index lastIndex = lastIndex >= buffer.length - 1? 0 : lastIndex + 1; return get(); } /** @return smoothed value. */ public float get(){ return sum / buffer.length; } } }
package com.proxerme.library.api; import com.proxerme.library.entitiy.ProxerResponse; import com.squareup.moshi.JsonDataException; import okhttp3.Request; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import java.io.IOException; import java.net.SocketTimeoutException; /** * TODO: Describe class * * @author Ruben Gees */ public final class ProxerCall<T> { private final Call<ProxerResponse<T>> internalCall; public ProxerCall(@NotNull final Call<ProxerResponse<T>> call) { this.internalCall = call; } public T execute() throws ProxerException { try { return processResponse(internalCall.execute()); } catch (ProxerException error) { throw error; } catch (SocketTimeoutException error) { throw new ProxerException(ProxerException.ErrorType.TIMEOUT); } catch (IOException error) { throw new ProxerException(ProxerException.ErrorType.IO); } catch (JsonDataException error) { throw new ProxerException(ProxerException.ErrorType.PARSING); } catch (Throwable error) { throw new ProxerException(ProxerException.ErrorType.UNKNOWN); } } public void enqueue(@Nullable final ProxerCallback<T> callback, @Nullable final ProxerErrorCallback errorCallback) { internalCall.enqueue(new Callback<ProxerResponse<T>>() { @Override public void onResponse(final Call<ProxerResponse<T>> call, final Response<ProxerResponse<T>> response) { try { if (callback != null) { callback.onSuccess(processResponse(response)); } } catch (ProxerException error) { if (errorCallback != null) { errorCallback.onError(error); } } } @Override public void onFailure(final Call<ProxerResponse<T>> call, final Throwable error) { if (errorCallback != null) { if (error instanceof SocketTimeoutException) { errorCallback.onError(new ProxerException(ProxerException.ErrorType.TIMEOUT)); } else if (error instanceof IOException) { errorCallback.onError(new ProxerException(ProxerException.ErrorType.IO)); } else if (error instanceof JsonDataException) { errorCallback.onError(new ProxerException(ProxerException.ErrorType.PARSING)); } else { errorCallback.onError(new ProxerException(ProxerException.ErrorType.UNKNOWN)); } } } }); } public boolean isExecuted() { return internalCall.isExecuted(); } public void cancel() { internalCall.cancel(); } public boolean isCanceled() { return internalCall.isCanceled(); } @SuppressWarnings("CloneDoesntCallSuperClone") public ProxerCall<T> clone() { return new ProxerCall<>(internalCall.clone()); } public Request request() { return internalCall.request(); } private T processResponse(@NotNull final Response<ProxerResponse<T>> response) throws ProxerException { if (response.isSuccessful()) { final ProxerResponse<T> proxerResponse = response.body(); if (proxerResponse.isSuccessful()) { return proxerResponse.getData(); } else { throw new ProxerException(ProxerException.ErrorType.SERVER, proxerResponse.getCode(), proxerResponse.getMessage()); } } else { throw new ProxerException(ProxerException.ErrorType.IO); } } }
package com.sksamuel.jqm4gwt.form; import com.google.gwt.user.client.ui.SubmitButton; import com.sksamuel.jqm4gwt.button.JQMButton; /** * @author Stephen K Samuel samspade79@gmail.com 18 May 2011 04:17:45 * * An implementation of a submit button. Submit buttons are tightly * integrated with forms and have special semantics when added to a * {@link JQMForm} * */ public class JQMSubmit extends JQMButton { /** Nullary constructor. */ public JQMSubmit() { this(null); } /** * Create a {@link JQMSubmit} with the given label */ public JQMSubmit(String text) { super(new SubmitButton(text)); addStyleName("jqm4gwt-submit"); } }
package no.finntech.capturandro; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.media.ExifInterface; import android.net.Uri; import android.provider.MediaStore; import java.io.File; import java.io.IOException; import java.util.ArrayList; import no.finntech.capturandro.asynctask.DownloadPicasaImageAsyncTask; import no.finntech.capturandro.callbacks.CapturandroCallback; import no.finntech.capturandro.util.BitmapUtil; import static no.finntech.capturandro.Config.STORED_IMAGE_HEIGHT; import static no.finntech.capturandro.Config.STORED_IMAGE_WIDTH; public class Capturandro { private final static String[] PICASA_CONTENT_PROVIDERS = { "content://com.android.gallery3d.provider", "content://com.google.android.gallery3d", "content://com.android.sec.gallery3d", "content://com.sec.android.gallery3d", "content://com.google.android.apps.photos" }; private final static String[] FILE_PATH_COLUMNS = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME }; private final Activity activity; private final String filenamePrefix; private final File storageDirectoryPath; private final int galleryIntentResultCode; private final int cameraIntentResultCode; private CapturandroCallback capturandroCallback; private String filename; public static class Builder { private CapturandroCallback capturandroCallback; private String filenamePrefix; private File storageDirectoryPath; private Activity activity; private int galleryIntentResultCode; private int cameraIntentResultCode; public Builder(Activity activity) { this.activity = activity; } public Builder withCameraCallback(CapturandroCallback capturandroCallback) { this.capturandroCallback = capturandroCallback; return this; } public Builder withFilenamePrefix(String filenamePrefix) { this.filenamePrefix = filenamePrefix + "_"; return this; } public Builder withStorageDirectoryPath(File storageDirectoryPath) { this.storageDirectoryPath = storageDirectoryPath; return this; } public Builder withGalleryIntentResultCode(int galleryIntentResultCode) { this.galleryIntentResultCode = galleryIntentResultCode; return this; } public Builder withCameraIntentResultCode(int cameraIntentResultCode) { this.cameraIntentResultCode = cameraIntentResultCode; return this; } public Capturandro build() { return new Capturandro(this); } } public Capturandro(Builder builder) { this.activity = builder.activity; this.capturandroCallback = builder.capturandroCallback; this.filenamePrefix = builder.filenamePrefix; this.storageDirectoryPath = builder.storageDirectoryPath; this.galleryIntentResultCode = builder.galleryIntentResultCode; this.cameraIntentResultCode = builder.cameraIntentResultCode; } public void importImageFromCamera() { importImageFromCamera(getUniqueFilename()); } public void importImageFromCamera(String filename) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(getStorageDirectoryPath(), filename))); this.filename = filename; activity.startActivityForResult(intent, cameraIntentResultCode); } public void importImageFromGallery() { importImageFromGallery(getUniqueFilename()); } public void importImageFromGallery(String filename) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); this.filename = filename; activity.startActivityForResult(intent, galleryIntentResultCode); } public void onActivityResult(int reqCode, int resultCode, Intent intent) throws IllegalArgumentException { if (capturandroCallback == null) { throw new IllegalStateException("Unable to import image. Have you implemented CapturandroCallback?"); } if (reqCode == cameraIntentResultCode) { if (resultCode == Activity.RESULT_OK) { if (filename != null) { File fileToStore = new File(getStorageDirectoryPath(), filename); try { fileToStore.createNewFile(); } catch (IOException e) { capturandroCallback.onCameraImportFailure(e); } saveBitmap(filename, fileToStore, fileToStore); } else { capturandroCallback.onCameraImportFailure(new IllegalArgumentException("Image could not be added")); } } } else if (reqCode == galleryIntentResultCode) { Uri selectedImage = null; if (intent != null) { selectedImage = intent.getData(); } if (isUserAttemptingToAddVideo(selectedImage)) { capturandroCallback.onCameraImportFailure(new IllegalArgumentException("Videos can't be added")); // break; } if (selectedImage != null) { handleImageFromGallery(selectedImage, filename); } } } private void saveBitmap(String imageFilename, File inFile, File outFile) { try { // Store Exif information as it is not kept when image is copied ExifInterface exifInterface = BitmapUtil.getExifFromFile(inFile); if (exifInterface != null) { BitmapUtil.resizeAndRotateAndSaveBitmapFile(inFile, outFile, exifInterface, STORED_IMAGE_WIDTH, STORED_IMAGE_HEIGHT); } else { BitmapUtil.resizeAndSaveBitmapFile(outFile, STORED_IMAGE_WIDTH, STORED_IMAGE_HEIGHT); } capturandroCallback.onCameraImportSuccess(imageFilename); } catch (IllegalArgumentException e) { capturandroCallback.onCameraImportFailure(e); } } private void handleImageFromGallery(Uri selectedImage, String filename) { Cursor cursor = activity.getContentResolver().query(selectedImage, FILE_PATH_COLUMNS, null, null, null); if (cursor != null) { cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATA); if (isPicasaAndroid3Image(selectedImage) || imageIsRemote(cursor)) { fetchPicasaAndroid3Image(selectedImage, filename, cursor); } else { fetchLocalGalleryImageFile(filename, cursor, columnIndex); } cursor.close(); } } private boolean isPicasaAndroid3Image(Uri selectedImage) { for (String picasaContentProvider : PICASA_CONTENT_PROVIDERS) { if (selectedImage.toString().startsWith(picasaContentProvider)) { return true; } } return false; } private boolean imageIsRemote(Cursor cursor) { int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME); if (columnIndex != -1 && (cursor.getString(columnIndex).startsWith("http: return true; } return false; } private void fetchPicasaAndroid3Image(Uri selectedImage, String filename, Cursor cursor) { int columnIndex; columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME); if (columnIndex != -1) { fetchPicasaImage(selectedImage, filename); } } private void fetchPicasaImage(Uri selectedImage, String filename) { if (capturandroCallback == null) { throw new IllegalStateException("Unable to import image. Have you implemented CapturandroCallback?"); } new DownloadPicasaImageAsyncTask(activity, selectedImage, filename, capturandroCallback).execute(); } private void fetchLocalGalleryImageFile(String filename, Cursor cursor, int columnIndex) { // Resize and save so that the image is still kept if the user deletes the original image from Gallery File inFile = new File(cursor.getString(columnIndex)); if (filename == null) { filename = getUniqueFilename(); } File outFile = new File(activity.getExternalCacheDir(), filename); saveBitmap(filename, inFile, outFile); } private boolean isUserAttemptingToAddVideo(Uri selectedImage) { return selectedImage != null && selectedImage.toString().startsWith("content://media/external/video/"); } public void handleImageIfSentFromGallery(Intent intent) { if (isReceivingImage(intent)) { handleSendImages(getImagesFromIntent(intent)); } } public ArrayList<Uri> getImagesFromIntent(Intent intent) { ArrayList<Uri> imageUris = new ArrayList<Uri>(); String action = intent.getAction(); if (Intent.ACTION_SEND.equals(action)) { if (intent.hasExtra(Intent.EXTRA_STREAM)) { imageUris.add((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM)); } } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) { if (intent.hasExtra(Intent.EXTRA_STREAM)) { imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); } } return imageUris; } private void handleSendImages(ArrayList<Uri> imagesFromIntent) { for (Uri imageUri : imagesFromIntent) { handleImageFromGallery(imageUri, getUniqueFilename()); } } private boolean isReceivingImage(Intent intent) { String action = intent.getAction(); String mimeType = intent.getType(); return (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) && (mimeType != null && mimeType.startsWith("image")); } public void setCapturandroCallback(CapturandroCallback capturandroCallback) { this.capturandroCallback = capturandroCallback; } private String getUniqueFilename() { return filenamePrefix + System.currentTimeMillis() + ".jpg"; } public File getStorageDirectoryPath() { if (storageDirectoryPath == null || !storageDirectoryPath.equals("")) { return activity.getExternalCacheDir(); } else { return storageDirectoryPath; } } }
package pl.magosa.microbe; import org.apache.commons.collections4.queue.CircularFifoQueue; import org.apache.commons.math3.stat.regression.SimpleRegression; import java.util.Map; public class TeacherController { protected Teacher teacher; protected double goal; protected double learningRate; protected double learningRateIncRatio; protected double learningRateDecRatio; protected double maximumErrorIncRatio; protected double maximumLearningRate; protected int slopeMinEpoches; protected int slopeMaxEpoches; protected boolean debug; protected int debugEveryNEpoches; protected double currentError; protected double currentErrorBackup; protected double lastError; protected double lastErrorBackup; protected double slope; protected boolean hasSlope = false; protected long epoch; protected SimpleRegression regression; protected CircularFifoQueue<Double> slopeFifo; public TeacherController(final Teacher teacher) { this.teacher = teacher; regression = new SimpleRegression(); setGoal(0.05); setLearningRate(0.01); setLearningRateIncRatio(1.05); setLearningRateDecRatio(0.70); setMaximumErrorIncRatio(1.04); setMaximumLearningRate(0.25); setSlopeMinEpoches(20); setSlopeMaxEpoches(100); setDebug(false); setDebugInterval(10); } public void setGoal(final double goal) { this.goal = goal; } public void setLearningRate(final double learningRate) { if (learningRate <= 0.0) { throw new RuntimeException("learningRate rate must be higher than 0.0"); } if (learningRate > 1.0) { throw new RuntimeException("learningRate rate can't be greater than 1.0"); } this.learningRate = learningRate; } public void setLearningRateIncRatio(final double learningRateIncRatio) { if (learningRateIncRatio <= 1.0) { throw new RuntimeException("learningRateIncRatio must be higher than 1.0"); } this.learningRateIncRatio = learningRateIncRatio; } public void setLearningRateDecRatio(final double learningRateDecRatio) { if (learningRateDecRatio >= 1.0) { throw new RuntimeException("learningRateDecRatio must be lower than 1.0"); } if (learningRateDecRatio <= 0.0) { throw new RuntimeException("learningRateDecRatio must be higher than 0.0"); } this.learningRateDecRatio = learningRateDecRatio; } public void setMaximumErrorIncRatio(final double maximumErrorIncRatio) { if (maximumErrorIncRatio <= 1.0) { throw new RuntimeException("maximumErrorIncRatio must be higher than 1.0"); } this.maximumErrorIncRatio = maximumErrorIncRatio; } public void setMaximumLearningRate(final double maximumLearningRate) { if (learningRate <= 0.0) { throw new RuntimeException("maximumLearningRate rate must be higher than 0.0"); } if (learningRate > 1.0) { throw new RuntimeException("maximumLearningRate rate can't be greater than 1.0"); } this.maximumLearningRate = maximumLearningRate; } public void setSlopeMinEpoches(final int slopeMinEpoches) { if (slopeMinEpoches <= 0) { throw new RuntimeException("slopeMinEpoches must be higher than 0"); } this.slopeMinEpoches = slopeMinEpoches; } public void setSlopeMaxEpoches(final int slopeMaxEpoches) { if (slopeMaxEpoches <= 0) { throw new RuntimeException("slopeMaxEpoches must be higher than 0"); } this.slopeMaxEpoches = slopeMaxEpoches; } public void setDebug(final boolean debug) { this.debug = debug; } public void setDebugInterval(final int epoches) { if (epoches <= 0) { throw new RuntimeException("debugEveryNEpoches must be higher than 0"); } this.debugEveryNEpoches = epoches; } protected void printDebug() { System.out.printf("Epoch = % d\n", epoch); System.out.printf("Previous error = % .10f\n", lastError); System.out.printf("Current error = % .10f\n", currentError); if (hasSlope) { System.out.printf("Error slope = % .10f\n", slope); } else { System.out.printf("Error slope = not yet\n"); } System.out.printf("Learning rate = % .10f\n", learningRate); System.out.println(); } public void train() { slopeFifo = new CircularFifoQueue<>(slopeMaxEpoches); teacher.setLearningRate(learningRate); teacher.calculateSquaredErrorEpoch(); lastError = currentError = teacher.getError(); for (epoch = 1; ; epoch++) { currentErrorBackup = currentError; lastErrorBackup = lastError; lastError = teacher.getError(); if (teacher.train(1, goal)) { break; } currentError = teacher.getError(); slopeFifo.add(currentError); if (slopeFifo.size() >= slopeMinEpoches) { regression.clear(); int x = 0; for (Double y : slopeFifo) { regression.addData(x++, y); } slope = regression.getSlope(); hasSlope = true; } if ((currentError / lastError) > maximumErrorIncRatio) { teacher.rollback(); learningRate = learningRate * learningRateDecRatio; currentError = currentErrorBackup; lastError = lastErrorBackup; } else if (hasSlope && (slope < -0.00001)) { learningRate = learningRate * learningRateIncRatio; } if (learningRate > maximumLearningRate) { learningRate = maximumLearningRate; } teacher.setLearningRate(learningRate); if (debug && (epoch % debugEveryNEpoches == 0)) { printDebug(); } } } }
package com.facebook.litho; import static com.facebook.litho.AccessibilityUtils.isAccessibilityEnabled; import static com.facebook.litho.ComponentHostUtils.maybeInvalidateAccessibilityState; import static com.facebook.litho.MountItem.isTouchableDisabled; import static com.facebook.litho.ThreadUtils.assertMainThread; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v4.util.SparseArrayCompat; import android.support.v4.view.ViewCompat; import android.text.TextUtils; import android.util.AttributeSet; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityNodeInfo; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.proguard.annotations.DoNotStrip; import java.util.ArrayList; import java.util.List; /** * A {@link ViewGroup} that can host the mounted state of a {@link Component}. This is used * by {@link MountState} to wrap mounted drawables to handle click events and update drawable * states accordingly. */ @DoNotStrip public class ComponentHost extends ViewGroup { private final SparseArrayCompat<MountItem> mMountItems = new SparseArrayCompat<>(); private SparseArrayCompat<MountItem> mScrapMountItemsArray; private final SparseArrayCompat<MountItem> mViewMountItems = new SparseArrayCompat<>(); private SparseArrayCompat<MountItem> mScrapViewMountItemsArray; private final SparseArrayCompat<MountItem> mDrawableMountItems = new SparseArrayCompat<>(); private SparseArrayCompat<MountItem> mScrapDrawableMountItems; private final ArrayList<MountItem> mDisappearingItems = new ArrayList<>(); private CharSequence mContentDescription; private Object mViewTag; private SparseArray<Object> mViewTags; private boolean mWasInvalidatedWhileSuppressed; private boolean mWasInvalidatedForAccessibilityWhileSuppressed; private boolean mSuppressInvalidations; private final InterleavedDispatchDraw mDispatchDraw = new InterleavedDispatchDraw(); private final @Nullable List<ComponentHost> mScrapHosts; private int[] mChildDrawingOrder = new int[0]; private boolean mIsChildDrawingOrderDirty; private long mParentHostMarker; private boolean mInLayout; @Nullable private ComponentAccessibilityDelegate mComponentAccessibilityDelegate; private boolean mIsComponentAccessibilityDelegateSet = false; private ComponentClickListener mOnClickListener; private ComponentLongClickListener mOnLongClickListener; private ComponentFocusChangeListener mOnFocusChangeListener; private ComponentTouchListener mOnTouchListener; private EventHandler<InterceptTouchEvent> mOnInterceptTouchEventHandler; private TouchExpansionDelegate mTouchExpansionDelegate; public ComponentHost(Context context) { this(context, null); } public ComponentHost(Context context, AttributeSet attrs) { this(new ComponentContext(context), attrs); } public ComponentHost(ComponentContext context) { this(context, null); } public ComponentHost(ComponentContext context, AttributeSet attrs) { super(context, attrs); setWillNotDraw(false); setChildrenDrawingOrderEnabled(true); refreshAccessibilityDelegatesIfNeeded(isAccessibilityEnabled(context)); mScrapHosts = ComponentsConfiguration.scrapHostRecyclingForComponentHosts ? new ArrayList<ComponentHost>(3) : null; } /** * Sets the parent host marker for this host. * @param parentHostMarker marker that indicates which {@link ComponentHost} hosts this host. */ void setParentHostMarker(long parentHostMarker) { mParentHostMarker = parentHostMarker; } /** * @return an id indicating which {@link ComponentHost} hosts this host. */ long getParentHostMarker() { return mParentHostMarker; } /** * Mounts the given {@link MountItem} with unique index. * @param index index of the {@link MountItem}. Guaranteed to be the same index as is passed for * the corresponding {@code unmount(index, mountItem)} call. * @param mountItem item to be mounted into the host. * @param bounds the bounds of the item that is to be mounted into the host */ public void mount(int index, MountItem mountItem, Rect bounds) { final Object content = mountItem.getContent(); if (content instanceof Drawable) { mountDrawable(index, mountItem, bounds); } else if (content instanceof View) { mViewMountItems.put(index, mountItem); mountView((View) content, mountItem.getFlags()); maybeRegisterTouchExpansion(index, mountItem); } mMountItems.put(index, mountItem); maybeInvalidateAccessibilityState(mountItem); } void unmount(MountItem item) { final int index = mMountItems.keyAt(mMountItems.indexOfValue(item)); unmount(index, item); } /** * Unmounts the given {@link MountItem} with unique index. * @param index index of the {@link MountItem}. Guaranteed to be the same index as was passed for * the corresponding {@code mount(index, mountItem)} call. * @param mountItem item to be unmounted from the host. */ public void unmount(int index, MountItem mountItem) { final Object content = mountItem.getContent(); if (content instanceof Drawable) { unmountDrawable(index, mountItem); } else if (content instanceof View) { unmountView((View) content); ComponentHostUtils.removeItem(index, mViewMountItems, mScrapViewMountItemsArray); mIsChildDrawingOrderDirty = true; maybeUnregisterTouchExpansion(index, mountItem); } ComponentHostUtils.removeItem(index, mMountItems, mScrapMountItemsArray); releaseScrapDataStructuresIfNeeded(); maybeInvalidateAccessibilityState(mountItem); } void startUnmountDisappearingItem(int index, MountItem mountItem) { final Object content = mountItem.getContent(); if (!(content instanceof View)) { throw new RuntimeException("Cannot unmount non-view item"); } mIsChildDrawingOrderDirty = true; maybeUnregisterTouchExpansion(index, mountItem); ComponentHostUtils.removeItem(index, mViewMountItems, mScrapViewMountItemsArray); ComponentHostUtils.removeItem(index, mMountItems, mScrapMountItemsArray); releaseScrapDataStructuresIfNeeded(); mDisappearingItems.add(mountItem); } void unmountDisappearingItem(MountItem disappearingItem) { if (!mDisappearingItems.remove(disappearingItem)) { final String key = (disappearingItem.getViewNodeInfo() != null) ? disappearingItem.getViewNodeInfo().getTransitionKey() : null; throw new RuntimeException( "Tried to remove non-existent disappearing item, transitionKey: " + key); } final View content = (View) disappearingItem.getContent(); unmountView(content); maybeInvalidateAccessibilityState(disappearingItem); } boolean hasDisappearingItems() { return mDisappearingItems.size() > 0; } List<String> getDisappearingItemKeys() { if (!hasDisappearingItems()) { return null; } final List<String> keys = new ArrayList<>(); for (int i = 0, size = mDisappearingItems.size(); i < size; i++) { keys.add(mDisappearingItems.get(i).getViewNodeInfo().getTransitionKey()); } return keys; } private void maybeMoveTouchExpansionIndexes(MountItem item, int oldIndex, int newIndex) { final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo(); if (viewNodeInfo == null) { return; } final Rect expandedTouchBounds = viewNodeInfo.getExpandedTouchBounds(); if (expandedTouchBounds == null || mTouchExpansionDelegate == null) { return; } mTouchExpansionDelegate.moveTouchExpansionIndexes( oldIndex, newIndex); } void maybeRegisterTouchExpansion(int index, MountItem mountItem) { final ViewNodeInfo viewNodeInfo = mountItem.getViewNodeInfo(); if (viewNodeInfo == null) { return; } final Rect expandedTouchBounds = viewNodeInfo.getExpandedTouchBounds(); if (expandedTouchBounds == null) { return; } if (mTouchExpansionDelegate == null) { mTouchExpansionDelegate = new TouchExpansionDelegate(this); setTouchDelegate(mTouchExpansionDelegate); } mTouchExpansionDelegate.registerTouchExpansion( index, (View) mountItem.getContent(), expandedTouchBounds); } void maybeUnregisterTouchExpansion(int index, MountItem mountItem) { final ViewNodeInfo viewNodeInfo = mountItem.getViewNodeInfo(); if (viewNodeInfo == null) { return; } if (mTouchExpansionDelegate == null || viewNodeInfo.getExpandedTouchBounds() == null) { return; } mTouchExpansionDelegate.unregisterTouchExpansion(index); } /** * Tries to recycle a scrap host attached to this host. * @return The host view to be recycled. */ ComponentHost recycleHost() { if (mScrapHosts == null) { return null; } if (mScrapHosts.size() > 0) { final ComponentHost host = mScrapHosts.remove(0); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { // We are bringing the re-used host to the front because before API 17, Android doesn't // take into account the children drawing order when dispatching ViewGroup touch events, // but it just traverses its children list backwards. bringChildToFront(host); } // The recycled host is immediately re-mounted in mountView(), therefore setting // the flag here is redundant, but future proof. mIsChildDrawingOrderDirty = true; return host; } return null; } /** * @return number of {@link MountItem}s that are currently mounted in the host. */ int getMountItemCount() { return mMountItems.size(); } /** * @return the {@link MountItem} that was mounted with the given index. */ MountItem getMountItemAt(int index) { return mMountItems.valueAt(index); } /** * Hosts are guaranteed to have only one accessible component * in them due to the way the view hierarchy is constructed in {@link LayoutState}. * There might be other non-accessible components in the same hosts such as * a background/foreground component though. This is why this method iterates over * all mount items in order to find the accessible one. */ MountItem getAccessibleMountItem() { for (int i = 0; i < getMountItemCount(); i++) { MountItem item = getMountItemAt(i); if (item.isAccessible()) { return item; } } return null; } /** * @return list of drawables that are mounted on this host. */ public List<Drawable> getDrawables() { final List<Drawable> drawables = new ArrayList<>(mDrawableMountItems.size()); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { Drawable drawable = (Drawable) mDrawableMountItems.valueAt(i).getContent(); drawables.add(drawable); } return drawables; } /** * @return the text content that is mounted on this host. */ @DoNotStrip public TextContent getTextContent() { return ComponentHostUtils.extractTextContent( ComponentHostUtils.extractContent(mMountItems)); } /** * @return the image content that is mounted on this host. */ public ImageContent getImageContent() { return ComponentHostUtils.extractImageContent( ComponentHostUtils.extractContent(mMountItems)); } /** * @return the content descriptons that are set on content mounted on this host */ @Override public CharSequence getContentDescription() { return mContentDescription; } /** * Host views implement their own content description handling instead of * just delegating to the underlying view framework for performance reasons as * the framework sets/resets content description very frequently on host views * and the underlying accessibility notifications might cause performance issues. * This is safe to do because the framework owns the accessibility state and * knows how to update it efficiently. */ @Override public void setContentDescription(CharSequence contentDescription) { mContentDescription = contentDescription; if (!TextUtils.isEmpty(contentDescription) && ViewCompat.getImportantForAccessibility(this) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { setImportantForAccessibility(ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } invalidateAccessibilityState(); } @Override public void setImportantForAccessibility(int mode) { if (mode != ViewCompat.getImportantForAccessibility(this)) { super.setImportantForAccessibility(mode); } } @Override public void setTag(int key, Object tag) { super.setTag(key, tag); if (key == R.id.component_node_info && tag != null) { refreshAccessibilityDelegatesIfNeeded(isAccessibilityEnabled(getContext())); if (mComponentAccessibilityDelegate != null) { mComponentAccessibilityDelegate.setNodeInfo((NodeInfo) tag); } } } /** * Moves the MountItem associated to oldIndex in the newIndex position. This happens when a * LithoView needs to re-arrange the internal order of its items. If an item is already * present in newIndex the item is guaranteed to be either unmounted or moved to a different index * by subsequent calls to either {@link ComponentHost#unmount(int, MountItem)} or * {@link ComponentHost#moveItem(MountItem, int, int)}. * * @param item The item that has been moved. * @param oldIndex The current index of the MountItem. * @param newIndex The new index of the MountItem. */ void moveItem(MountItem item, int oldIndex, int newIndex) { if (item == null && mScrapMountItemsArray != null) { item = mScrapMountItemsArray.get(oldIndex); } if (item == null) { return; } maybeMoveTouchExpansionIndexes(item, oldIndex, newIndex); final Object content = item.getContent(); if (content instanceof Drawable) { moveDrawableItem(item, oldIndex, newIndex); } else if (content instanceof View) { mIsChildDrawingOrderDirty = true; startTemporaryDetach(((View) content)); if (mViewMountItems.get(newIndex) != null) { ensureScrapViewMountItemsArray(); ComponentHostUtils.scrapItemAt(newIndex, mViewMountItems, mScrapViewMountItemsArray); } ComponentHostUtils.moveItem(oldIndex, newIndex, mViewMountItems, mScrapViewMountItemsArray); } if (mMountItems.get(newIndex) != null) { ensureScrapMountItemsArray(); ComponentHostUtils.scrapItemAt(newIndex, mMountItems, mScrapMountItemsArray); } ComponentHostUtils.moveItem(oldIndex, newIndex, mMountItems, mScrapMountItemsArray); releaseScrapDataStructuresIfNeeded(); if (content instanceof View) { finishTemporaryDetach(((View) content)); } } /** * Sets view tag on this host. * @param viewTag the object to set as tag. */ public void setViewTag(Object viewTag) { mViewTag = viewTag; } /** * Sets view tags on this host. * @param viewTags the map containing the tags by id. */ public void setViewTags(SparseArray<Object> viewTags) { mViewTags = viewTags; } /** * Sets a click listener on this host. * @param listener The listener to set on this host. */ void setComponentClickListener(ComponentClickListener listener) { mOnClickListener = listener; this.setOnClickListener(listener); } /** * @return The previously set click listener */ ComponentClickListener getComponentClickListener() { return mOnClickListener; } /** * Sets a long click listener on this host. * @param listener The listener to set on this host. */ void setComponentLongClickListener(ComponentLongClickListener listener) { mOnLongClickListener = listener; this.setOnLongClickListener(listener); } /** * @return The previously set long click listener */ ComponentLongClickListener getComponentLongClickListener() { return mOnLongClickListener; } /** * Sets a focus change listener on this host. * @param listener The listener to set on this host. */ void setComponentFocusChangeListener(ComponentFocusChangeListener listener) { mOnFocusChangeListener = listener; this.setOnFocusChangeListener(listener); } /** * @return The previously set focus change listener */ ComponentFocusChangeListener getComponentFocusChangeListener() { return mOnFocusChangeListener; } /** * Sets a touch listener on this host. * @param listener The listener to set on this host. */ void setComponentTouchListener(ComponentTouchListener listener) { mOnTouchListener = listener; setOnTouchListener(listener); } /** * Sets an {@link EventHandler} that will be invoked when * {@link ComponentHost#onInterceptTouchEvent} is called. * @param interceptTouchEventHandler the handler to be set on this host. */ void setInterceptTouchEventHandler(EventHandler<InterceptTouchEvent> interceptTouchEventHandler) { mOnInterceptTouchEventHandler = interceptTouchEventHandler; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (mOnInterceptTouchEventHandler != null) { return EventDispatcherUtils.dispatchOnInterceptTouch(mOnInterceptTouchEventHandler, ev); } return super.onInterceptTouchEvent(ev); } /** * @return The previous set touch listener. */ public ComponentTouchListener getComponentTouchListener() { return mOnTouchListener; } /** * This is used to collapse all invalidation calls on hosts during mount. * While invalidations are suppressed, the hosts will simply bail on * invalidations. Once the suppression is turned off, a single invalidation * will be triggered on the affected hosts. */ void suppressInvalidations(boolean suppressInvalidations) { if (mSuppressInvalidations == suppressInvalidations) { return; } mSuppressInvalidations = suppressInvalidations; if (!mSuppressInvalidations) { if (mWasInvalidatedWhileSuppressed) { this.invalidate(); mWasInvalidatedWhileSuppressed = false; } if (mWasInvalidatedForAccessibilityWhileSuppressed) { this.invalidateAccessibilityState(); mWasInvalidatedForAccessibilityWhileSuppressed = false; } } } /** * Invalidates the accessibility node tree in this host. */ void invalidateAccessibilityState() { if (!mIsComponentAccessibilityDelegateSet) { return; } if (mSuppressInvalidations) { mWasInvalidatedForAccessibilityWhileSuppressed = true; return; } if (mComponentAccessibilityDelegate != null && implementsVirtualViews()) { mComponentAccessibilityDelegate.invalidateRoot(); } } @Override public boolean dispatchHoverEvent(MotionEvent event) { return (mComponentAccessibilityDelegate != null && implementsVirtualViews() && mComponentAccessibilityDelegate.dispatchHoverEvent(event)) || super.dispatchHoverEvent(event); } private boolean implementsVirtualViews() { MountItem item = getAccessibleMountItem(); return item != null && item.getComponent().implementsExtraAccessibilityNodes(); } public List<CharSequence> getContentDescriptions() { final List<CharSequence> contentDescriptions = new ArrayList<>(); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { final NodeInfo nodeInfo = mDrawableMountItems.valueAt(i).getNodeInfo(); if (nodeInfo == null) { continue; } final CharSequence contentDescription = nodeInfo.getContentDescription(); if (contentDescription != null) { contentDescriptions.add(contentDescription); } } final CharSequence hostContentDescription = getContentDescription(); if (hostContentDescription != null) { contentDescriptions.add(hostContentDescription); } return contentDescriptions; } private void mountView(View view, int flags) { view.setDuplicateParentStateEnabled(MountItem.isDuplicateParentState(flags)); mIsChildDrawingOrderDirty = true; // A host has been recycled and is already attached. if (view instanceof ComponentHost && view.getParent() == this) { finishTemporaryDetach(view); view.setVisibility(VISIBLE); return; } LayoutParams lp = view.getLayoutParams(); if (lp == null) { lp = generateDefaultLayoutParams(); view.setLayoutParams(lp); } if (mInLayout) { super.addViewInLayout(view, -1, view.getLayoutParams(), true); } else { super.addView(view, -1, view.getLayoutParams()); } } private void unmountView(View view) { mIsChildDrawingOrderDirty = true; if (mScrapHosts != null && view instanceof ComponentHost) { final ComponentHost componentHost = (ComponentHost) view; view.setVisibility(GONE); // In Gingerbread the View system doesn't invalidate // the parent if a child become invisible. invalidate(); startTemporaryDetach(componentHost); mScrapHosts.add(componentHost); } else if (mInLayout) { super.removeViewInLayout(view); } else { super.removeView(view); } } TouchExpansionDelegate getTouchExpansionDelegate() { return mTouchExpansionDelegate; } @Override public void dispatchDraw(Canvas canvas) { mDispatchDraw.start(canvas); super.dispatchDraw(canvas); // Cover the case where the host has no child views, in which case // getChildDrawingOrder() will not be called and the draw index will not // be incremented. This will also cover the case where drawables must be // painted after the last child view in the host. if (mDispatchDraw.isRunning()) { mDispatchDraw.drawNext(); } mDispatchDraw.end(); DebugDraw.draw(this, canvas); } @Override protected int getChildDrawingOrder(int childCount, int i) { updateChildDrawingOrderIfNeeded(); // This method is called in very different contexts within a ViewGroup // e.g. when handling input events, drawing, etc. We only want to call // the draw methods if the InterleavedDispatchDraw is active. if (mDispatchDraw.isRunning()) { mDispatchDraw.drawNext(); } return mChildDrawingOrder[i]; } @Override public boolean onTouchEvent(MotionEvent event) { assertMainThread(); boolean handled = false; if (isEnabled()) { // Iterate drawable from last to first to respect drawing order. for (int i = mDrawableMountItems.size() - 1; i >= 0; i final MountItem item = mDrawableMountItems.valueAt(i); if (item.getContent() instanceof Touchable && !isTouchableDisabled(item.getFlags())) { final Touchable t = (Touchable) item.getContent(); if (t.shouldHandleTouchEvent(event) && t.onTouchEvent(event, this)) { handled = true; break; } } } } if (!handled) { handled = super.onTouchEvent(event); } return handled; } void performLayout(boolean changed, int l, int t, int r, int b) { } @Override protected final void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; performLayout(changed, l, t, r, b); mInLayout = false; } @Override public void requestLayout() { // Don't request a layout if it will be blocked by any parent. Requesting a layout that is // then ignored by an ancestor means that this host will remain in a state where it thinks that // it has requested layout, and will therefore ignore future layout requests. This will lead to // problems if a child (e.g. a ViewPager) requests a layout later on, since the request will be // wrongly ignored by this host. ViewParent parent = this; while (parent instanceof ComponentHost) { final ComponentHost host = (ComponentHost) parent; if (!host.shouldRequestLayout()) { return; } parent = parent.getParent(); } super.requestLayout(); } protected boolean shouldRequestLayout() { // Don't bubble during layout. return !mInLayout; } @Override @SuppressLint("MissingSuperCall") protected boolean verifyDrawable(Drawable who) { return true; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { final MountItem mountItem = mDrawableMountItems.valueAt(i); ComponentHostUtils.maybeSetDrawableState( this, (Drawable) mountItem.getContent(), mountItem.getFlags(), mountItem.getNodeInfo()); } } @Override public void jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState(); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { final Drawable drawable = (Drawable) mDrawableMountItems.valueAt(i).getContent(); DrawableCompat.jumpToCurrentState(drawable); } } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { final Drawable drawable = (Drawable) mDrawableMountItems.valueAt(i).getContent(); drawable.setVisible(visibility == View.VISIBLE, false); } } @DoNotStrip @Override public Object getTag() { if (mViewTag != null) { return mViewTag; } return super.getTag(); } @Override public Object getTag(int key) { if (mViewTags != null) { final Object value = mViewTags.get(key); if (value != null) { return value; } } return super.getTag(key); } @Override public void invalidate(Rect dirty) { if (mSuppressInvalidations) { mWasInvalidatedWhileSuppressed = true; return; } super.invalidate(dirty); } @Override public void invalidate(int l, int t, int r, int b) { if (mSuppressInvalidations) { mWasInvalidatedWhileSuppressed = true; return; } super.invalidate(l, t, r, b); } @Override public void invalidate() { if (mSuppressInvalidations) { mWasInvalidatedWhileSuppressed = true; return; } super.invalidate(); } protected void refreshAccessibilityDelegatesIfNeeded(boolean isAccessibilityEnabled) { if (isAccessibilityEnabled == mIsComponentAccessibilityDelegateSet) { return; } if (isAccessibilityEnabled && mComponentAccessibilityDelegate == null) { mComponentAccessibilityDelegate = new ComponentAccessibilityDelegate(this); } ViewCompat.setAccessibilityDelegate( this, isAccessibilityEnabled ? mComponentAccessibilityDelegate : null); mIsComponentAccessibilityDelegateSet = isAccessibilityEnabled; if (!isAccessibilityEnabled) { return; } for (int i = 0, size = getChildCount(); i < size; i++) { final View child = getChildAt(i); if (child instanceof ComponentHost) { ((ComponentHost) child).refreshAccessibilityDelegatesIfNeeded(true); } else { final NodeInfo nodeInfo = (NodeInfo) child.getTag(R.id.component_node_info); if (nodeInfo != null) { ViewCompat.setAccessibilityDelegate( child, new ComponentAccessibilityDelegate(child, nodeInfo)); } } } } @Override public void setAccessibilityDelegate(View.AccessibilityDelegate accessibilityDelegate) { super.setAccessibilityDelegate(accessibilityDelegate); // We cannot compare against mComponentAccessibilityDelegate directly, since it is not the // delegate that we receive here. Instead, we'll set this to true at the point that we set that // delegate explicitly. mIsComponentAccessibilityDelegateSet = false; } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override public void addView(View child) { throw new UnsupportedOperationException( "Adding Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override public void addView(View child, int index) { throw new UnsupportedOperationException( "Adding Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { throw new UnsupportedOperationException( "Adding Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override protected boolean addViewInLayout( View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout) { throw new UnsupportedOperationException( "Adding Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override protected void attachViewToParent(View child, int index, ViewGroup.LayoutParams params) { throw new UnsupportedOperationException( "Adding Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override public void removeView(View view) { throw new UnsupportedOperationException( "Removing Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override public void removeViewInLayout(View view) { throw new UnsupportedOperationException( "Removing Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override public void removeViewsInLayout(int start, int count) { throw new UnsupportedOperationException( "Removing Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override public void removeViewAt(int index) { throw new UnsupportedOperationException( "Removing Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override public void removeViews(int start, int count) { throw new UnsupportedOperationException( "Removing Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override public void removeAllViewsInLayout() { throw new UnsupportedOperationException( "Removing Views manually within LithoViews is not supported"); } /** * Litho handles adding/removing views automatically using mount/unmount calls. Manually adding/ * removing views will mess up Litho's bookkeeping of added views and cause weird crashes down the * line. */ @Deprecated @Override protected void removeDetachedView(View child, boolean animate) { throw new UnsupportedOperationException( "Removing Views manually within LithoViews is not supported"); } /** * Manually adds a View as a child of this ComponentHost for the purposes of testing. **This * should only be used for tests as this is not safe and will likely cause weird crashes if used * in a production environment**. */ @VisibleForTesting public void addViewForTest(View view) { final LayoutParams params = view.getLayoutParams() == null ? generateDefaultLayoutParams() : view.getLayoutParams(); super.addView(view, -1, params); } /** * Returns the Drawable associated with this ComponentHost for animations, for example the * background Drawable, or the drawable that otherwise has a transitionKey on it that has caused * it to be hosted in this ComponentHost. * * <p>The core purpose of exposing this drawable is so that when animating the bounds of this * ComponentHost, we also properly animate the bounds of this main Drawable at the same time. */ public @Nullable Drawable getLinkedDrawableForAnimation() { for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { final MountItem mountItem = mDrawableMountItems.valueAt(i); if ((mountItem.getFlags() & MountItem.FLAG_IS_TRANSITION_KEY_SET) != 0) { return (Drawable) mountItem.getContent(); } } return null; } private void updateChildDrawingOrderIfNeeded() { if (!mIsChildDrawingOrderDirty) { return; } final int childCount = getChildCount(); if (mChildDrawingOrder.length < childCount) { mChildDrawingOrder = new int[childCount + 5]; } int index = 0; final int viewMountItemCount = mViewMountItems.size(); for (int i = 0, size = viewMountItemCount; i < size; i++) { final View child = (View) mViewMountItems.valueAt(i).getContent(); mChildDrawingOrder[index++] = indexOfChild(child); } // Draw disappearing items on top of mounted views. for (int i = 0, size = mDisappearingItems.size(); i < size; i++) { final View child = (View) mDisappearingItems.get(i).getContent(); mChildDrawingOrder[index++] = indexOfChild(child); } if (mScrapHosts != null) { for (int i = 0, size = mScrapHosts.size(); i < size; i++) { final View child = mScrapHosts.get(i); mChildDrawingOrder[index++] = indexOfChild(child); } } mIsChildDrawingOrderDirty = false; } private void ensureScrapViewMountItemsArray() { if (mScrapViewMountItemsArray == null) { mScrapViewMountItemsArray = ComponentsPools.acquireScrapMountItemsArray(); } } private void ensureScrapMountItemsArray() { if (mScrapMountItemsArray == null) { mScrapMountItemsArray = ComponentsPools.acquireScrapMountItemsArray(); } } private void releaseScrapDataStructuresIfNeeded() { if (mScrapMountItemsArray != null && mScrapMountItemsArray.size() == 0) { ComponentsPools.releaseScrapMountItemsArray(mScrapMountItemsArray); mScrapMountItemsArray = null; } if (mScrapViewMountItemsArray != null && mScrapViewMountItemsArray.size() == 0) { ComponentsPools.releaseScrapMountItemsArray(mScrapViewMountItemsArray); mScrapViewMountItemsArray = null; } } private void mountDrawable(int index, MountItem mountItem, Rect bounds) { assertMainThread(); mDrawableMountItems.put(index, mountItem); final Drawable drawable = (Drawable) mountItem.getContent(); final DisplayListDrawable displayListDrawable = mountItem.getDisplayListDrawable(); ComponentHostUtils.mountDrawable( this, displayListDrawable != null ? displayListDrawable : drawable, bounds, mountItem.getFlags(), mountItem.getNodeInfo()); } private void unmountDrawable(int index, MountItem mountItem) { assertMainThread(); final Drawable contentDrawable = (Drawable) mountItem.getContent(); final Drawable drawable = mountItem.getDisplayListDrawable() == null ? contentDrawable : mountItem.getDisplayListDrawable(); if (ComponentHostUtils.existsScrapItemAt(index, mScrapDrawableMountItems)) { mScrapDrawableMountItems.remove(index); } else { mDrawableMountItems.remove(index); } drawable.setCallback(null); this.invalidate(drawable.getBounds()); releaseScrapDataStructuresIfNeeded(); } private void moveDrawableItem(MountItem item, int oldIndex, int newIndex) { assertMainThread(); // When something is already present in newIndex position we need to keep track of it. if (mDrawableMountItems.get(newIndex) != null) { ensureScrapDrawableMountItemsArray(); ComponentHostUtils.scrapItemAt(newIndex, mDrawableMountItems, mScrapDrawableMountItems); } // Move the MountItem in the new position. ComponentHostUtils.moveItem(oldIndex, newIndex, mDrawableMountItems, mScrapDrawableMountItems); // Drawing order changed, invalidate the whole view. this.invalidate(); releaseScrapDataStructuresIfNeeded(); } private void ensureScrapDrawableMountItemsArray() { if (mScrapDrawableMountItems == null) { mScrapDrawableMountItems = ComponentsPools.acquireScrapMountItemsArray(); } } private static void startTemporaryDetach(View view) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Cancel any pending clicks. view.cancelPendingInputEvents(); } // The ComponentHost's parent will send an ACTION_CANCEL if it's going to receive // other motion events for the recycled child. ViewCompat.dispatchStartTemporaryDetach(view); } private static void finishTemporaryDetach(View view) { ViewCompat.dispatchFinishTemporaryDetach(view); } /** * Encapsulates the logic for drawing a set of views and drawables respecting * their drawing order withing the component host i.e. allow interleaved views * and drawables to be drawn with the correct z-index. */ private class InterleavedDispatchDraw { private Canvas mCanvas; private int mDrawIndex; private int mItemsToDraw; private InterleavedDispatchDraw() { } private void start(Canvas canvas) { mCanvas = canvas; mDrawIndex = 0; mItemsToDraw = mMountItems.size(); } private boolean isRunning() { return (mCanvas != null && mDrawIndex < mItemsToDraw); } private void drawNext() { if (mCanvas == null) { return; } for (int i = mDrawIndex, size = mMountItems.size(); i < size; i++) { final MountItem mountItem = mMountItems.valueAt(i); final Object content = mountItem.getDisplayListDrawable() != null ? mountItem.getDisplayListDrawable() : mountItem.getContent(); // During a ViewGroup's dispatchDraw() call with children drawing order enabled, // getChildDrawingOrder() will be called before each child view is drawn. This // method will only draw the drawables "between" the child views and the let // the host draw its children as usual. This is why views are skipped here. if (content instanceof View) { mDrawIndex = i + 1; return; } final boolean isTracing = ComponentsSystrace.isTracing(); if (isTracing) { ComponentsSystrace.beginSection(getTraceName(mountItem)); } ((Drawable) content).draw(mCanvas); if (isTracing) { ComponentsSystrace.endSection(); } } mDrawIndex = mItemsToDraw; } private void end() { mCanvas = null; } } private static String getTraceName(MountItem mountItem) { String traceName = "draw: " + mountItem.getComponent().getSimpleName(); final DisplayListDrawable displayListDrawable = mountItem.getDisplayListDrawable(); if (displayListDrawable != null && displayListDrawable.willDrawDisplayList()) { traceName += "DL"; } return traceName; } @Override public boolean performAccessibilityAction(int action, Bundle arguments) { // The view framework requires that a contentDescription be set for the // getIterableTextForAccessibility method to work. If one isn't set, all text granularity // actions will be ignored. if (action == AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY || action == AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY) { CharSequence contentDesc = null; if (!TextUtils.isEmpty(getContentDescription())) { contentDesc = getContentDescription(); } else if (getContentDescriptions().size() != 0) { contentDesc = TextUtils.join(", ", getContentDescriptions()); } else if (getTextContent().getTextItems().size() != 0) { contentDesc = TextUtils.join(", ", getTextContent().getTextItems()); } if (contentDesc == null) { return false; } mContentDescription = contentDesc; super.setContentDescription(mContentDescription); } return super.performAccessibilityAction(action, arguments); } }
package com.facebook.litho; import static com.facebook.litho.AccessibilityUtils.isAccessibilityEnabled; import static com.facebook.litho.ComponentHostUtils.maybeInvalidateAccessibilityState; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.VisibleForTesting; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v4.util.SparseArrayCompat; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import com.facebook.proguard.annotations.DoNotStrip; import java.util.ArrayList; import java.util.List; /** * A {@link ViewGroup} that can host the mounted state of a {@link Component}. This is used * by {@link MountState} to wrap mounted drawables to handle click events and update drawable * states accordingly. */ @DoNotStrip public class ComponentHost extends ViewGroup { private final SparseArrayCompat<MountItem> mMountItems = new SparseArrayCompat<>(); private SparseArrayCompat<MountItem> mScrapMountItemsArray; private final SparseArrayCompat<MountItem> mViewMountItems = new SparseArrayCompat<>(); private SparseArrayCompat<MountItem> mScrapViewMountItemsArray; private final SparseArrayCompat<MountItem> mDrawableMountItems = new SparseArrayCompat<>(); private SparseArrayCompat<MountItem> mScrapDrawableMountItems; private final SparseArrayCompat<Touchable> mTouchables = new SparseArrayCompat<>(); private SparseArrayCompat<Touchable> mScrapTouchables; private final ArrayList<MountItem> mDisappearingItems = new ArrayList<>(); private CharSequence mContentDescription; private Object mViewTag; private SparseArray<Object> mViewTags; private boolean mWasInvalidatedWhileSuppressed; private boolean mWasInvalidatedForAccessibilityWhileSuppressed; private boolean mSuppressInvalidations; private final InterleavedDispatchDraw mDispatchDraw = new InterleavedDispatchDraw(); private final List<ComponentHost> mScrapHosts = new ArrayList<>(3); private int[] mChildDrawingOrder = new int[0]; private boolean mIsChildDrawingOrderDirty; private long mParentHostMarker; private boolean mInLayout; private final ComponentAccessibilityDelegate mComponentAccessibilityDelegate; private boolean mIsComponentAccessibilityDelegateSet = false; private ComponentClickListener mOnClickListener; private ComponentLongClickListener mOnLongClickListener; private ComponentFocusChangeListener mOnFocusChangeListener; private ComponentTouchListener mOnTouchListener; private EventHandler<InterceptTouchEvent> mOnInterceptTouchEventHandler; private TouchExpansionDelegate mTouchExpansionDelegate; public ComponentHost(Context context) { this(context, null); } public ComponentHost(Context context, AttributeSet attrs) { this(new ComponentContext(context), attrs); } public ComponentHost(ComponentContext context) { this(context, null); } public ComponentHost(ComponentContext context, AttributeSet attrs) { super(context, attrs); setWillNotDraw(false); setChildrenDrawingOrderEnabled(true); mComponentAccessibilityDelegate = new ComponentAccessibilityDelegate(this); refreshAccessibilityDelegatesIfNeeded(isAccessibilityEnabled(context)); } /** * Sets the parent host marker for this host. * @param parentHostMarker marker that indicates which {@link ComponentHost} hosts this host. */ void setParentHostMarker(long parentHostMarker) { mParentHostMarker = parentHostMarker; } /** * @return an id indicating which {@link ComponentHost} hosts this host. */ long getParentHostMarker() { return mParentHostMarker; } /** * Mounts the given {@link MountItem} with unique index. * @param index index of the {@link MountItem}. Guaranteed to be the same index as is passed for * the corresponding {@code unmount(index, mountItem)} call. * @param mountItem item to be mounted into the host. * @param bounds the bounds of the item that is to be mounted into the host */ public void mount(int index, MountItem mountItem, Rect bounds) { final Object content = mountItem.getContent(); if (content instanceof Drawable) { mountDrawable(index, mountItem, bounds); } else if (content instanceof View) { mViewMountItems.put(index, mountItem); mountView((View) content, mountItem.getFlags()); maybeRegisterTouchExpansion(index, mountItem); } mMountItems.put(index, mountItem); maybeInvalidateAccessibilityState(mountItem); } void unmount(MountItem item) { final int index = mMountItems.keyAt(mMountItems.indexOfValue(item)); unmount(index, item); } /** * Unmounts the given {@link MountItem} with unique index. * @param index index of the {@link MountItem}. Guaranteed to be the same index as was passed for * the corresponding {@code mount(index, mountItem)} call. * @param mountItem item to be unmounted from the host. */ public void unmount(int index, MountItem mountItem) { final Object content = mountItem.getContent(); if (content instanceof Drawable) { unmountDrawable(index, mountItem); } else if (content instanceof View) { unmountView((View) content); ComponentHostUtils.removeItem(index, mViewMountItems, mScrapViewMountItemsArray); mIsChildDrawingOrderDirty = true; maybeUnregisterTouchExpansion(index, mountItem); } ComponentHostUtils.removeItem(index, mMountItems, mScrapMountItemsArray); releaseScrapDataStructuresIfNeeded(); maybeInvalidateAccessibilityState(mountItem); } void startUnmountDisappearingItem(int index, MountItem mountItem) { final Object content = mountItem.getContent(); if (!(content instanceof View)) { throw new RuntimeException("Cannot unmount non-view item"); } mIsChildDrawingOrderDirty = true; maybeUnregisterTouchExpansion(index, mountItem); ComponentHostUtils.removeItem(index, mViewMountItems, mScrapViewMountItemsArray); ComponentHostUtils.removeItem(index, mMountItems, mScrapMountItemsArray); releaseScrapDataStructuresIfNeeded(); mDisappearingItems.add(mountItem); } void unmountDisappearingItem(MountItem disappearingItem) { if (!mDisappearingItems.remove(disappearingItem)) { final String key = (disappearingItem.getViewNodeInfo() != null) ? disappearingItem.getViewNodeInfo().getTransitionKey() : null; throw new RuntimeException( "Tried to remove non-existent disappearing item, transitionKey: " + key); } final View content = (View) disappearingItem.getContent(); unmountView(content); maybeInvalidateAccessibilityState(disappearingItem); } boolean hasDisappearingItems() { return mDisappearingItems.size() > 0; } List<String> getDisappearingItemKeys() { if (!hasDisappearingItems()) { return null; } final List<String> keys = new ArrayList<>(); for (int i = 0, size = mDisappearingItems.size(); i < size; i++) { keys.add(mDisappearingItems.get(i).getViewNodeInfo().getTransitionKey()); } return keys; } private void maybeMoveTouchExpansionIndexes(MountItem item, int oldIndex, int newIndex) { final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo(); if (viewNodeInfo == null) { return; } final Rect expandedTouchBounds = viewNodeInfo.getExpandedTouchBounds(); if (expandedTouchBounds == null || mTouchExpansionDelegate == null) { return; } mTouchExpansionDelegate.moveTouchExpansionIndexes( oldIndex, newIndex); } void maybeRegisterTouchExpansion(int index, MountItem mountItem) { final ViewNodeInfo viewNodeInfo = mountItem.getViewNodeInfo(); if (viewNodeInfo == null) { return; } final Rect expandedTouchBounds = viewNodeInfo.getExpandedTouchBounds(); if (expandedTouchBounds == null) { return; } if (mTouchExpansionDelegate == null) { mTouchExpansionDelegate = new TouchExpansionDelegate(this); setTouchDelegate(mTouchExpansionDelegate); } mTouchExpansionDelegate.registerTouchExpansion( index, (View) mountItem.getContent(), expandedTouchBounds); } void maybeUnregisterTouchExpansion(int index, MountItem mountItem) { final ViewNodeInfo viewNodeInfo = mountItem.getViewNodeInfo(); if (viewNodeInfo == null) { return; } if (mTouchExpansionDelegate == null || viewNodeInfo.getExpandedTouchBounds() == null) { return; } mTouchExpansionDelegate.unregisterTouchExpansion(index); } /** * Tries to recycle a scrap host attached to this host. * @return The host view to be recycled. */ ComponentHost recycleHost() { if (mScrapHosts.size() > 0) { final ComponentHost host = mScrapHosts.remove(0); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { // We are bringing the re-used host to the front because before API 17, Android doesn't // take into account the children drawing order when dispatching ViewGroup touch events, // but it just traverses its children list backwards. bringChildToFront(host); } // The recycled host is immediately re-mounted in mountView(), therefore setting // the flag here is redundant, but future proof. mIsChildDrawingOrderDirty = true; return host; } return null; } /** * @return number of {@link MountItem}s that are currently mounted in the host. */ int getMountItemCount() { return mMountItems.size(); } /** * @return the {@link MountItem} that was mounted with the given index. */ MountItem getMountItemAt(int index) { return mMountItems.valueAt(index); } /** * Hosts are guaranteed to have only one accessible component * in them due to the way the view hierarchy is constructed in {@link LayoutState}. * There might be other non-accessible components in the same hosts such as * a background/foreground component though. This is why this method iterates over * all mount items in order to find the accessible one. */ MountItem getAccessibleMountItem() { for (int i = 0; i < getMountItemCount(); i++) { MountItem item = getMountItemAt(i); if (item.isAccessible()) { return item; } } return null; } /** * @return list of drawables that are mounted on this host. */ public List<Drawable> getDrawables() { final List<Drawable> drawables = new ArrayList<>(mDrawableMountItems.size()); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { Drawable drawable = (Drawable) mDrawableMountItems.valueAt(i).getContent(); drawables.add(drawable); } return drawables; } /** * @return the text content that is mounted on this host. */ @DoNotStrip public TextContent getTextContent() { return ComponentHostUtils.extractTextContent( ComponentHostUtils.extractContent(mMountItems)); } /** * @return the image content that is mounted on this host. */ public ImageContent getImageContent() { return ComponentHostUtils.extractImageContent( ComponentHostUtils.extractContent(mMountItems)); } /** * @return the content descriptons that are set on content mounted on this host */ @Override public CharSequence getContentDescription() { return mContentDescription; } /** * Host views implement their own content description handling instead of * just delegating to the underlying view framework for performance reasons as * the framework sets/resets content description very frequently on host views * and the underlying accessibility notifications might cause performance issues. * This is safe to do because the framework owns the accessibility state and * knows how to update it efficiently. */ @Override public void setContentDescription(CharSequence contentDescription) { mContentDescription = contentDescription; invalidateAccessibilityState(); } @Override public void setImportantForAccessibility(int mode) { if (mode != ViewCompat.getImportantForAccessibility(this)) { super.setImportantForAccessibility(mode); } } @Override public void setTag(int key, Object tag) { super.setTag(key, tag); if (key == R.id.component_node_info && tag != null) { mComponentAccessibilityDelegate.setNodeInfo((NodeInfo) tag); refreshAccessibilityDelegatesIfNeeded(isAccessibilityEnabled(getContext())); } } /** * Moves the MountItem associated to oldIndex in the newIndex position. This happens when a * LithoView needs to re-arrange the internal order of its items. If an item is already * present in newIndex the item is guaranteed to be either unmounted or moved to a different index * by subsequent calls to either {@link ComponentHost#unmount(int, MountItem)} or * {@link ComponentHost#moveItem(MountItem, int, int)}. * * @param item The item that has been moved. * @param oldIndex The current index of the MountItem. * @param newIndex The new index of the MountItem. */ void moveItem(MountItem item, int oldIndex, int newIndex) { if (item == null && mScrapMountItemsArray != null) { item = mScrapMountItemsArray.get(oldIndex); } if (item == null) { return; } maybeMoveTouchExpansionIndexes(item, oldIndex, newIndex); final Object content = item.getContent(); if (content instanceof Drawable) { moveDrawableItem(item, oldIndex, newIndex); } else if (content instanceof View) { mIsChildDrawingOrderDirty = true; startTemporaryDetach(((View) content)); if (mViewMountItems.get(newIndex) != null) { ensureScrapViewMountItemsArray(); ComponentHostUtils.scrapItemAt(newIndex, mViewMountItems, mScrapViewMountItemsArray); } ComponentHostUtils.moveItem(oldIndex, newIndex, mViewMountItems, mScrapViewMountItemsArray); } if (mMountItems.get(newIndex) != null) { ensureScrapMountItemsArray(); ComponentHostUtils.scrapItemAt(newIndex, mMountItems, mScrapMountItemsArray); } ComponentHostUtils.moveItem(oldIndex, newIndex, mMountItems, mScrapMountItemsArray); releaseScrapDataStructuresIfNeeded(); if (content instanceof View) { finishTemporaryDetach(((View) content)); } } /** * Sets view tag on this host. * @param viewTag the object to set as tag. */ public void setViewTag(Object viewTag) { mViewTag = viewTag; } /** * Sets view tags on this host. * @param viewTags the map containing the tags by id. */ public void setViewTags(SparseArray<Object> viewTags) { mViewTags = viewTags; } /** * Sets a click listener on this host. * @param listener The listener to set on this host. */ void setComponentClickListener(ComponentClickListener listener) { mOnClickListener = listener; this.setOnClickListener(listener); } /** * @return The previously set click listener */ ComponentClickListener getComponentClickListener() { return mOnClickListener; } /** * Sets a long click listener on this host. * @param listener The listener to set on this host. */ void setComponentLongClickListener(ComponentLongClickListener listener) { mOnLongClickListener = listener; this.setOnLongClickListener(listener); } /** * @return The previously set long click listener */ ComponentLongClickListener getComponentLongClickListener() { return mOnLongClickListener; } /** * Sets a focus change listener on this host. * @param listener The listener to set on this host. */ void setComponentFocusChangeListener(ComponentFocusChangeListener listener) { mOnFocusChangeListener = listener; this.setOnFocusChangeListener(listener); } /** * @return The previously set focus change listener */ ComponentFocusChangeListener getComponentFocusChangeListener() { return mOnFocusChangeListener; } /** * Sets a touch listener on this host. * @param listener The listener to set on this host. */ void setComponentTouchListener(ComponentTouchListener listener) { mOnTouchListener = listener; setOnTouchListener(listener); } /** * Sets an {@link EventHandler} that will be invoked when * {@link ComponentHost#onInterceptTouchEvent} is called. * @param interceptTouchEventHandler the handler to be set on this host. */ void setInterceptTouchEventHandler(EventHandler<InterceptTouchEvent> interceptTouchEventHandler) { mOnInterceptTouchEventHandler = interceptTouchEventHandler; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (mOnInterceptTouchEventHandler != null) { return EventDispatcherUtils.dispatchOnInterceptTouch(mOnInterceptTouchEventHandler, ev); } return super.onInterceptTouchEvent(ev); } /** * @return The previous set touch listener. */ public ComponentTouchListener getComponentTouchListener() { return mOnTouchListener; } /** * This is used to collapse all invalidation calls on hosts during mount. * While invalidations are suppressed, the hosts will simply bail on * invalidations. Once the suppression is turned off, a single invalidation * will be triggered on the affected hosts. */ void suppressInvalidations(boolean suppressInvalidations) { if (mSuppressInvalidations == suppressInvalidations) { return; } mSuppressInvalidations = suppressInvalidations; if (!mSuppressInvalidations) { if (mWasInvalidatedWhileSuppressed) { this.invalidate(); mWasInvalidatedWhileSuppressed = false; } if (mWasInvalidatedForAccessibilityWhileSuppressed) { this.invalidateAccessibilityState(); mWasInvalidatedForAccessibilityWhileSuppressed = false; } } } /** * Invalidates the accessibility node tree in this host. */ void invalidateAccessibilityState() { if (!mIsComponentAccessibilityDelegateSet) { return; } if (mSuppressInvalidations) { mWasInvalidatedForAccessibilityWhileSuppressed = true; return; } if (mComponentAccessibilityDelegate != null && implementsVirtualViews()) { mComponentAccessibilityDelegate.invalidateRoot(); } } @Override public boolean dispatchHoverEvent(MotionEvent event) { return (mComponentAccessibilityDelegate != null && implementsVirtualViews() && mComponentAccessibilityDelegate.dispatchHoverEvent(event)) || super.dispatchHoverEvent(event); } private boolean implementsVirtualViews() { MountItem item = getAccessibleMountItem(); return item != null && item.getComponent().getLifecycle().implementsExtraAccessibilityNodes(); } public List<CharSequence> getContentDescriptions() { final List<CharSequence> contentDescriptions = new ArrayList<>(); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { final NodeInfo nodeInfo = mDrawableMountItems.valueAt(i).getNodeInfo(); if (nodeInfo == null) { continue; } final CharSequence contentDescription = nodeInfo.getContentDescription(); if (contentDescription != null) { contentDescriptions.add(contentDescription); } } final CharSequence hostContentDescription = getContentDescription(); if (hostContentDescription != null) { contentDescriptions.add(hostContentDescription); } return contentDescriptions; } private void mountView(View view, int flags) { view.setDuplicateParentStateEnabled(MountItem.isDuplicateParentState(flags)); mIsChildDrawingOrderDirty = true; // A host has been recycled and is already attached. if (view instanceof ComponentHost && view.getParent() == this) { finishTemporaryDetach(view); view.setVisibility(VISIBLE); return; } LayoutParams lp = view.getLayoutParams(); if (lp == null) { lp = generateDefaultLayoutParams(); view.setLayoutParams(lp); } if (mInLayout) { addViewInLayout(view, -1, view.getLayoutParams(), true); } else { addView(view, -1, view.getLayoutParams()); } } private void unmountView(View view) { mIsChildDrawingOrderDirty = true; if (view instanceof ComponentHost) { final ComponentHost componentHost = (ComponentHost) view; view.setVisibility(GONE); // In Gingerbread the View system doesn't invalidate // the parent if a child become invisible. invalidate(); startTemporaryDetach(componentHost); mScrapHosts.add(componentHost); } else if (mInLayout) { removeViewInLayout(view); } else { removeView(view); } } TouchExpansionDelegate getTouchExpansionDelegate() { return mTouchExpansionDelegate; } @Override public void dispatchDraw(Canvas canvas) { mDispatchDraw.start(canvas); super.dispatchDraw(canvas); // Cover the case where the host has no child views, in which case // getChildDrawingOrder() will not be called and the draw index will not // be incremented. This will also cover the case where drawables must be // painted after the last child view in the host. if (mDispatchDraw.isRunning()) { mDispatchDraw.drawNext(); } mDispatchDraw.end(); DebugDraw.draw(this, canvas); } @Override protected int getChildDrawingOrder(int childCount, int i) { updateChildDrawingOrderIfNeeded(); // This method is called in very different contexts within a ViewGroup // e.g. when handling input events, drawing, etc. We only want to call // the draw methods if the InterleavedDispatchDraw is active. if (mDispatchDraw.isRunning()) { mDispatchDraw.drawNext(); } return mChildDrawingOrder[i]; } @Override public boolean onTouchEvent(MotionEvent event) { boolean handled = false; if (isEnabled()) { // Iterate drawable from last to first to respect drawing order. for (int size = mTouchables.size(), i = size - 1; i >= 0; i final Touchable t = mTouchables.valueAt(i); if (t.shouldHandleTouchEvent(event) && t.onTouchEvent(event, this)) { handled = true; break; } } } if (!handled) { handled = super.onTouchEvent(event); } return handled; } void performLayout(boolean changed, int l, int t, int r, int b) { } @Override protected final void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; performLayout(changed, l, t, r, b); mInLayout = false; } @Override public void requestLayout() { // Don't request a layout if it will be blocked by any parent. Requesting a layout that is // then ignored by an ancestor means that this host will remain in a state where it thinks that // it has requested layout, and will therefore ignore future layout requests. This will lead to // problems if a child (e.g. a ViewPager) requests a layout later on, since the request will be // wrongly ignored by this host. ViewParent parent = this; while (parent instanceof ComponentHost) { final ComponentHost host = (ComponentHost) parent; if (!host.shouldRequestLayout()) { return; } parent = parent.getParent(); } super.requestLayout(); } protected boolean shouldRequestLayout() { // Don't bubble during layout. return !mInLayout; } @Override @SuppressLint("MissingSuperCall") protected boolean verifyDrawable(Drawable who) { return true; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { final MountItem mountItem = mDrawableMountItems.valueAt(i); ComponentHostUtils.maybeSetDrawableState( this, (Drawable) mountItem.getContent(), mountItem.getFlags(), mountItem.getNodeInfo()); } } @Override public void jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState(); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { final Drawable drawable = (Drawable) mDrawableMountItems.valueAt(i).getContent(); DrawableCompat.jumpToCurrentState(drawable); } } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); for (int i = 0, size = mDrawableMountItems.size(); i < size; i++) { final Drawable drawable = (Drawable) mDrawableMountItems.valueAt(i).getContent(); drawable.setVisible(visibility == View.VISIBLE, false); } } @DoNotStrip @Override public Object getTag() { if (mViewTag != null) { return mViewTag; } return super.getTag(); } @Override public Object getTag(int key) { if (mViewTags != null) { final Object value = mViewTags.get(key); if (value != null) { return value; } } return super.getTag(key); } @Override public void invalidate(Rect dirty) { if (mSuppressInvalidations) { mWasInvalidatedWhileSuppressed = true; return; } super.invalidate(dirty); } @Override public void invalidate(int l, int t, int r, int b) { if (mSuppressInvalidations) { mWasInvalidatedWhileSuppressed = true; return; } super.invalidate(l, t, r, b); } @Override public void invalidate() { if (mSuppressInvalidations) { mWasInvalidatedWhileSuppressed = true; return; } super.invalidate(); } protected void refreshAccessibilityDelegatesIfNeeded(boolean isAccessibilityEnabled) { if (isAccessibilityEnabled == mIsComponentAccessibilityDelegateSet) { return; } ViewCompat.setAccessibilityDelegate( this, isAccessibilityEnabled ? mComponentAccessibilityDelegate : null); mIsComponentAccessibilityDelegateSet = isAccessibilityEnabled; for (int i = 0, size = getChildCount(); i < size; i++) { final View child = getChildAt(i); if (child instanceof ComponentHost) { ((ComponentHost) child).refreshAccessibilityDelegatesIfNeeded(isAccessibilityEnabled); } else { final NodeInfo nodeInfo = (NodeInfo) child.getTag(R.id.component_node_info); if (nodeInfo != null) { ViewCompat.setAccessibilityDelegate( child, isAccessibilityEnabled ? new ComponentAccessibilityDelegate(child, nodeInfo) : null); } } } } @Override public void setAccessibilityDelegate(AccessibilityDelegate accessibilityDelegate) { super.setAccessibilityDelegate(accessibilityDelegate); // We cannot compare against mComponentAccessibilityDelegate directly, since it is not the // delegate that we receive here. Instead, we'll set this to true at the point that we set that // delegate explicitly. mIsComponentAccessibilityDelegateSet = false; } private void updateChildDrawingOrderIfNeeded() { if (!mIsChildDrawingOrderDirty) { return; } final int childCount = getChildCount(); if (mChildDrawingOrder.length < childCount) { mChildDrawingOrder = new int[childCount + 5]; } int index = 0; final int viewMountItemCount = mViewMountItems.size(); for (int i = 0, size = viewMountItemCount; i < size; i++) { final View child = (View) mViewMountItems.valueAt(i).getContent(); mChildDrawingOrder[index++] = indexOfChild(child); } // Draw disappearing items on top of mounted views. for (int i = 0, size = mDisappearingItems.size(); i < size; i++) { final View child = (View) mDisappearingItems.get(i).getContent(); mChildDrawingOrder[index++] = indexOfChild(child); } for (int i = 0, size = mScrapHosts.size(); i < size; i++) { final View child = mScrapHosts.get(i); mChildDrawingOrder[index++] = indexOfChild(child); } mIsChildDrawingOrderDirty = false; } private void ensureScrapViewMountItemsArray() { if (mScrapViewMountItemsArray == null) { mScrapViewMountItemsArray = ComponentsPools.acquireScrapMountItemsArray(); } } private void ensureScrapMountItemsArray() { if (mScrapMountItemsArray == null) { mScrapMountItemsArray = ComponentsPools.acquireScrapMountItemsArray(); } } private void releaseScrapDataStructuresIfNeeded() { if (mScrapMountItemsArray != null && mScrapMountItemsArray.size() == 0) { ComponentsPools.releaseScrapMountItemsArray(mScrapMountItemsArray); mScrapMountItemsArray = null; } if (mScrapViewMountItemsArray != null && mScrapViewMountItemsArray.size() == 0) { ComponentsPools.releaseScrapMountItemsArray(mScrapViewMountItemsArray); mScrapViewMountItemsArray = null; } } private void mountDrawable(int index, MountItem mountItem, Rect bounds) { mDrawableMountItems.put(index, mountItem); final Drawable drawable = (Drawable) mountItem.getContent(); final DisplayListDrawable displayListDrawable = mountItem.getDisplayListDrawable(); ComponentHostUtils.mountDrawable( this, displayListDrawable != null ? displayListDrawable : drawable, bounds, mountItem.getFlags(), mountItem.getNodeInfo()); if (drawable instanceof Touchable && !MountItem.isTouchableDisabled(mountItem.getFlags())) { mTouchables.put(index, (Touchable) drawable); } } private void unmountDrawable(int index, MountItem mountItem) { final Drawable contentDrawable = (Drawable) mountItem.getContent(); final Drawable drawable = mountItem.getDisplayListDrawable() == null ? contentDrawable : mountItem.getDisplayListDrawable(); if (ComponentHostUtils.existsScrapItemAt(index, mScrapDrawableMountItems)) { mScrapDrawableMountItems.remove(index); } else { mDrawableMountItems.remove(index); } drawable.setCallback(null); if (contentDrawable instanceof Touchable && !MountItem.isTouchableDisabled(mountItem.getFlags())) { if (ComponentHostUtils.existsScrapItemAt(index, mScrapTouchables)) { mScrapTouchables.remove(index); } else { mTouchables.remove(index); } } this.invalidate(drawable.getBounds()); releaseScrapDataStructuresIfNeeded(); } private void moveDrawableItem(MountItem item, int oldIndex, int newIndex) { // When something is already present in newIndex position we need to keep track of it. if (mDrawableMountItems.get(newIndex) != null) { ensureScrapDrawableMountItemsArray(); ComponentHostUtils.scrapItemAt(newIndex, mDrawableMountItems, mScrapDrawableMountItems); } if (mTouchables.get(newIndex) != null) { ensureScrapTouchablesArray(); ComponentHostUtils.scrapItemAt(newIndex, mTouchables, mScrapTouchables); } // Move the MountItem in the new position. If the mount item was a Touchable we need to reflect // this change also in the Touchables SparseArray. ComponentHostUtils.moveItem(oldIndex, newIndex, mDrawableMountItems, mScrapDrawableMountItems); if (item.getContent() instanceof Touchable) { ComponentHostUtils.moveItem(oldIndex, newIndex, mTouchables, mScrapTouchables); } // Drawing order changed, invalidate the whole view. this.invalidate(); releaseScrapDataStructuresIfNeeded(); } private void ensureScrapDrawableMountItemsArray() { if (mScrapDrawableMountItems == null) { mScrapDrawableMountItems = ComponentsPools.acquireScrapMountItemsArray(); } } private void ensureScrapTouchablesArray() { if (mScrapTouchables == null) { mScrapTouchables = ComponentsPools.acquireScrapTouchablesArray(); } } private static void startTemporaryDetach(View view) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Cancel any pending clicks. view.cancelPendingInputEvents(); } // The ComponentHost's parent will send an ACTION_CANCEL if it's going to receive // other motion events for the recycled child. ViewCompat.dispatchStartTemporaryDetach(view); } private static void finishTemporaryDetach(View view) { ViewCompat.dispatchFinishTemporaryDetach(view); } @VisibleForTesting SparseArrayCompat<Touchable> getHostTouchables() { return mTouchables; } /** * Encapsulates the logic for drawing a set of views and drawables respecting * their drawing order withing the component host i.e. allow interleaved views * and drawables to be drawn with the correct z-index. */ private class InterleavedDispatchDraw { private Canvas mCanvas; private int mDrawIndex; private int mItemsToDraw; private InterleavedDispatchDraw() { } private void start(Canvas canvas) { mCanvas = canvas; mDrawIndex = 0; mItemsToDraw = mMountItems.size(); } private boolean isRunning() { return (mCanvas != null && mDrawIndex < mItemsToDraw); } private void drawNext() { if (mCanvas == null) { return; } for (int i = mDrawIndex, size = mMountItems.size(); i < size; i++) { final MountItem mountItem = mMountItems.valueAt(i); final Object content = mountItem.getDisplayListDrawable() != null ? mountItem.getDisplayListDrawable() : mountItem.getContent(); // During a ViewGroup's dispatchDraw() call with children drawing order enabled, // getChildDrawingOrder() will be called before each child view is drawn. This // method will only draw the drawables "between" the child views and the let // the host draw its children as usual. This is why views are skipped here. if (content instanceof View) { mDrawIndex = i + 1; return; } ComponentsSystrace.beginSection(getTraceName(mountItem)); ((Drawable) content).draw(mCanvas); ComponentsSystrace.endSection(); } mDrawIndex = mItemsToDraw; } private void end() { mCanvas = null; } } private static String getTraceName(MountItem mountItem) { String traceName = "draw: " + mountItem.getComponent().getSimpleName(); final DisplayListDrawable displayListDrawable = mountItem.getDisplayListDrawable(); if (displayListDrawable != null && displayListDrawable.willDrawDisplayList()) { traceName += "DL"; } return traceName; } }
package Math; /** * Holds the information of a System with 3 equations with 3 unknowns. * There are two components: M matrix and C vector. * The system is Mx = C */ public class System3x3 { /** Coefficient matrix */ protected final Matrix3x3 m; /** Constant vector */ protected final Vector3 c; /** Solution */ protected Vector3 s; private final boolean DEBUG = false; /** * Construct a 3x3 system of equations with 3 unknowns * @param m coefficients matrix * @param c c vector */ public System3x3(Matrix3x3 m, Vector3 c) { this.m = m; this.c = c; } /** * Construct the first matrix, replacing the first column with the C vector * @return Mx */ private Matrix3x3 createMx() { Matrix3x3 mx = Matrix3x3.injectVector(m, c, 0); if(DEBUG) System.out.println("mx: " + mx); return mx; } /** * Construct the second matrix, replacing the second column with the C vector * @return My */ private Matrix3x3 createMy() { Matrix3x3 my = Matrix3x3.injectVector(m, c, 1); if(DEBUG) System.out.println("my: " + my); return my; } /** * Construct the third matrix, replacing the third column with the C vector * @return Mz */ public Matrix3x3 createMz() { Matrix3x3 mz = Matrix3x3.injectVector(m, c, 2); if(DEBUG) System.out.println("mz: " + mz); return mz; } /** * Solve the system * @return x1, x2, x3 as a vector. Solution to the system. * @throws java.lang.Exception */ public Vector3 solve() throws Exception { double d = Matrix3x3.determinant(this.m); if(d == 0) throw new Exception("No hay solucion"); double dx = Matrix3x3.determinant(createMx()); double dy = Matrix3x3.determinant(createMy()); double dz = Matrix3x3.determinant(createMz()); if(DEBUG) { System.out.println("dx: " + dx); System.out.println("dy: " + dy); System.out.println("dz: " + dz); } double x = dx / d; double y = dy / d; double z = dz / d; return new Vector3(x, y, z); } /** * Main program to test the program * @param args Not used */ public static void main(String [] args) { //Matrix3x3 m = new Matrix3x3(2, 1, 1, 1, -1, -1, 1, 2, 1); Matrix3x3 m = new Matrix3x3(0, 1, 1, 1, 0, 1, 0, -1, 1); Vector3 c = new Vector3(-1, -1, -1); System3x3 system = new System3x3(m, c); try { Vector3 solution = system.solve(); System.out.println("Coefficients: " + m); System.out.println("Determinant" + Matrix3x3.determinant(m)); System.out.println("Solution: " + solution); } catch (Exception e) { System.out.println(e); } } }
package org.orangepalantir.leastsquares.fitters; import org.orangepalantir.leastsquares.Fitter; import Jama.Matrix; import org.orangepalantir.leastsquares.Function; /** * for solving linear least squares fit of f(x:A) = z with sets of x,z data points. * derivatives are evaluated numerically and the function is assumed to be linear in A. * Then a linear least squares fit is performed. * */ public class LinearFitter implements Fitter { private final double[] working; double[][] X; //values double[] A, //Parameter Set Z; //output vaues Function FUNCTION; double[] ERROR; double[][] DERIVATIVES; double[] BETA; double[][] ALPHA; double DELTA = 0.000001; //used for calculating derivatives public LinearFitter(Function funct){ FUNCTION=funct; working = new double[funct.getNParameters()]; } /** * Sets the values of of the original data points that are going to be fit. * */ public void setData(double[][] xvalues, double[] zvalues){ if(xvalues.length != zvalues.length) throw new IllegalArgumentException("there must be 1 z value for each set of x values"); else if(xvalues[0].length != FUNCTION.getNInputs()) throw new IllegalArgumentException("The length of parameters is longer that the parameters accepted by the function"); X = xvalues; Z = zvalues; } public void setParameters(double[] parameters){ if(parameters.length != FUNCTION.getNParameters()) throw new IllegalArgumentException("the number of parameters must equal the required number for the function: " + FUNCTION.getNParameters()); A = new double[parameters.length]; System.arraycopy(parameters,0,A,0,parameters.length); } /** * returns the cumulative error for current values **/ public double calculateErrors(){ double new_error = 0; for(int i = 0; i<Z.length; i++){ double v = FUNCTION.evaluate(X[i],A); ERROR[i] = Z[i] - v; new_error += Math.pow(ERROR[i],2); } return new_error; } /** * Given a set of parameters, and inputs, calculates the derivative * of the k'th parameter * d/d a_k (F) * * The function is linear in parameters eg: * f(x) = params[0]* f0(x) + params[1]*f1(x) + ... * * So the derivative k is fk(x) or the function evaluated when all of the parameters * are zero except for the k'th parameter which is 1. * * * @param k - index of the parameter that the derivative is being taken of * @param x - set of values to use. * @return derivative of function **/ public double calculateDerivative(int k, double[] x){ for(int i = 0; i<FUNCTION.getNParameters(); i++){ working[i] = i==k?1:0; } return FUNCTION.evaluate(x, working); } /** * Creates an array of derivatives since each one is used 3x's **/ public void calculateDerivatives(){ for(int j = 0; j<A.length; j++){ for(int i = 0; i<Z.length; i++){ DERIVATIVES[i][j] = calculateDerivative(j, X[i]); } } } public void createBetaMatrix(){ BETA = new double[A.length]; for(int k = 0; k<BETA.length; k++){ for(int i = 0; i<X.length; i++){ BETA[k] += ERROR[i]*DERIVATIVES[i][k]; } } } public void createAlphaMatrix(){ ALPHA = new double[A.length][A.length]; int n = A.length; for(int k = 0; k<n; k++){ for(int l = 0; l<n; l++){ for(int i = 0; i<X.length; i++) ALPHA[l][k] += DERIVATIVES[i][k] * DERIVATIVES[i][l]; } } } /** * Takes the current error, and the current parameter set and calculates the * changes, then returns the maximum changed value * */ public void iterateValues(){ calculateErrors(); calculateDerivatives(); createBetaMatrix(); createAlphaMatrix(); Matrix alpha_matrix = new Matrix(ALPHA); Matrix beta = new Matrix(BETA, BETA.length); Matrix out = alpha_matrix.solve(beta); double[][] delta_a = out.getArray(); for(int i = 0; i<A.length; i++) A[i] += delta_a[i][0]; } public void printMatrix(){ for(int i = 0; i<ALPHA.length; i++){ for(int j = 0; j<ALPHA[0].length; j++){ System.out.print(ALPHA[i][j] + "\t"); } System.out.println("| " + BETA[i] ); } } public void initializeWorkspace(){ ERROR = new double[Z.length]; DERIVATIVES = new double[Z.length][A.length]; } /** * Main routine, call this and the Parameters are iterated one time because * the equations are assumed to be linear in parameter space. * */ public void fitData(){ initializeWorkspace(); try{ iterateValues(); } catch(Exception exc){ printMatrix(); exc.printStackTrace(); } } /** * Gets the current set of parameters values. * */ public double[] getParameters(){ return A; } @Override public double[] getUncertainty() { printMatrix(); double sum_a = 0; double sum_b = 0; for(int i = 0;i<DERIVATIVES.length;i++){ sum_a += Math.pow(DERIVATIVES[i][0],2); sum_b += Math.pow(DERIVATIVES[i][1],2); } Matrix a_matrix = new Matrix(ALPHA); Matrix b = a_matrix.inverse(); for(int i = 0; i<b.getColumnDimension(); i++){ for(int j = 0; j<b.getRowDimension(); j++){ System.out.print(b.get(i,j) + "\t"); } System.out.println(); } System.out.println(sum_a/sum_b); double[] residuals = new double[A.length]; double error = calculateErrors(); for(int i = 0; i<A.length; i++){ residuals[i] = error*Math.sqrt(b.get(i,i))/2; } return residuals; } }
package org.apache.geronimo.kernel; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.MBeanNotificationInfo; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MalformedObjectNameException; import javax.management.NotificationBroadcaster; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.geronimo.gbean.GBeanInfo; import org.apache.geronimo.gbean.jmx.GBeanMBean; import org.apache.geronimo.kernel.config.ConfigurationStore; import org.apache.geronimo.kernel.config.InvalidConfigException; import org.apache.geronimo.kernel.config.LocalConfigStore; import org.apache.geronimo.kernel.config.NoSuchConfigException; import org.apache.geronimo.kernel.jmx.JMXUtil; import org.apache.geronimo.kernel.service.DependencyService2; public class Kernel implements Serializable, KernelMBean, NotificationBroadcaster { /** * The JMX name used by a Kernel to register itself when it boots. */ public static final ObjectName KERNEL = JMXUtil.getObjectName("geronimo.boot:role=Kernel"); /** * The JMX name of the DependencyService. */ public static final ObjectName DEPENDENCY_SERVICE = JMXUtil.getObjectName("geronimo.boot:role=DependencyService2"); /** * The JMX name of the ConfigurationStore. */ public static final ObjectName CONFIG_STORE = JMXUtil.getObjectName("geronimo.boot:role=ConfigurationStore"); private final String domainName; private final GBeanInfo storeInfo; private final File configStore; private transient Log log; private transient boolean running; private transient MBeanServer mbServer; private transient GBeanMBean storeGBean; private transient ConfigurationStore store; /** * Construct a Kernel using the specified JMX domain and supply the * information needed to create the ConfigurationStore. * @param domainName the domain name to be used for the JMX MBeanServer * @param storeInfo the info for the GBeanMBean to be used for the ConfigurationStore * @param configStore a local directory to be used by the ConfigurationStore; * this must be present and writable when the kernel is booted */ public Kernel(String domainName, GBeanInfo storeInfo, File configStore) { this.domainName = domainName; this.storeInfo = storeInfo; this.configStore = configStore; } /** * Construct a Kernel which does not have a config store. * @param domainName */ public Kernel(String domainName) { this(domainName, null, null); } /** * Get the MBeanServer used by this kernel * @return the MBeanServer used by this kernel */ public MBeanServer getMBeanServer() { return mbServer; } /** * Load the specified Configuration from the store into this Kernel * @param configID the unique id of the Configuration to load * @return the JMX ObjectName the Kernel registered the Configuration under * @throws org.apache.geronimo.kernel.config.NoSuchConfigException if the store does not contain the specified Configuratoin * @throws java.io.IOException if the Configuration could not be read from the store * @throws org.apache.geronimo.kernel.config.InvalidConfigException if the Configuration is not valid * @throws java.lang.UnsupportedOperationException if this kernel does not have a store */ public ObjectName load(URI configID) throws NoSuchConfigException, IOException, InvalidConfigException { if (!running) { throw new IllegalStateException("Kernel is not running"); } if (store == null) { throw new UnsupportedOperationException("Kernel does not have a ConfigurationStore"); } GBeanMBean config = store.getConfig(configID); URL baseURL = store.getBaseURL(configID); return load(config, baseURL); } /** * Load the supplied Configuration into the Kernel and define its root using the specified URL. * @param config the GBeanMBean representing the Configuration * @param rootURL the URL to be used to resolve relative paths in the configuration * @return the JMX ObjectName the Kernel registered the Configuration under * @throws org.apache.geronimo.kernel.config.InvalidConfigException if the Configuration is not valid */ public ObjectName load(GBeanMBean config, URL rootURL) throws InvalidConfigException { URI configID; try { configID = (URI) config.getAttribute("ID"); } catch (Exception e) { throw new InvalidConfigException("Cannot get config ID", e); } ObjectName configName; try { configName = new ObjectName("geronimo.config:name=" + ObjectName.quote(configID.toString())); } catch (MalformedObjectNameException e) { throw new InvalidConfigException("Cannot convert ID to ObjectName: ", e); } load(config, rootURL, configName); return configName; } /** * Load the supplied Configuration into the Kernel and override the default JMX name. * This method should be used with discretion as it is possible to create * Configurations that cannot be located by management or monitoring tools. * @param config the GBeanMBean representing the Configuration * @param rootURL the URL to be used to resolve relative paths in the configuration * @param configName the JMX ObjectName to register the Configuration under * @throws org.apache.geronimo.kernel.config.InvalidConfigException if the Configuration is not valid */ public void load(GBeanMBean config, URL rootURL, ObjectName configName) throws InvalidConfigException { if (!running) { throw new IllegalStateException("Kernel is not running"); } try { mbServer.registerMBean(config, configName); } catch (Exception e) { throw new InvalidConfigException("Unable to register configuraton", e); } try { config.setAttribute("BaseURL", rootURL); } catch (Exception e) { try { mbServer.unregisterMBean(configName); } catch (Exception e1) { // ignore } throw new InvalidConfigException("Cannot set BaseURL", e); } // @todo replace this with use of the MBeanContext in the Configuration target try { config.setAttribute("MBeanServer", mbServer); config.setAttribute("ObjectName", configName); } catch (Exception e) { try { mbServer.unregisterMBean(configName); } catch (Exception e1) { // ignore } throw new InvalidConfigException("Cannot set MBeanServer info", e); } log.info("Loaded Configuration " + configName); } /** * Unload the specified Configuration from the Kernel * @param configName the JMX name of the Configuration that should be unloaded * @throws org.apache.geronimo.kernel.config.NoSuchConfigException if the specified Configuration is not loaded */ public void unload(ObjectName configName) throws NoSuchConfigException { if (!running) { throw new IllegalStateException("Kernel is not running"); } try { mbServer.unregisterMBean(configName); } catch (InstanceNotFoundException e) { throw new NoSuchConfigException("No config registered: " + configName, e); } catch (MBeanRegistrationException e) { throw (IllegalStateException) new IllegalStateException("Error deregistering configuration " + configName).initCause(e); } log.info("Unloaded Configuration " + configName); } /** * Boot this Kernel, triggering the instanciation of the MBeanServer and * the registration of the DependencyService and ConfigurationStore * @throws java.lang.Exception if the boot fails */ public void boot() throws Exception { if (running) { return; } log = LogFactory.getLog(Kernel.class.getName()); log.info("Starting boot"); mbServer = MBeanServerFactory.createMBeanServer(domainName); mbServer.registerMBean(this, KERNEL); mbServer.registerMBean(new DependencyService2(), DEPENDENCY_SERVICE); if (storeInfo != null) { storeGBean = new GBeanMBean(storeInfo); storeGBean.setAttribute("root", configStore); mbServer.registerMBean(storeGBean, CONFIG_STORE); storeGBean.start(); store = (ConfigurationStore) storeGBean.getTarget(); } running = true; log.info("Booted"); } /** * Shut down this kernel instance, unregistering the MBeans and releasing * the MBeanServer. */ public void shutdown() { if (!running) { return; } running = false; log.info("Starting kernel shutdown"); store = null; try { if (storeGBean != null) { storeGBean.stop(); } } catch (Exception e) { // ignore } try { if (storeGBean != null) { mbServer.unregisterMBean(CONFIG_STORE); } } catch (Exception e) { // ignore } storeGBean = null; try { mbServer.unregisterMBean(DEPENDENCY_SERVICE); } catch (Exception e) { // ignore } try { mbServer.unregisterMBean(KERNEL); } catch (Exception e) { // ignore } MBeanServerFactory.releaseMBeanServer(mbServer); mbServer = null; synchronized (this) { notify(); } log.info("Kernel shutdown complete"); } public boolean isRunning() { return running; } /** * Static entry point allowing a Kernel to be run from the command line. * Arguments are: * <li>the filename of the directory to use for the configuration store. * This will be created if it does not exist.</li> * <li>the id of a configuation to load</li> * Once the Kernel is booted and the configuration is loaded, the process * will remain running until the shutdown() method on the kernel is * invoked or until the JVM exits. * @param args */ public static void main(String[] args) { if (args.length < 2) { System.err.println("usage: " + Kernel.class.getName() + " <config-store-dir> <config-id>"); System.exit(1); } File storeDir = new File(args[0]); URI configID = null; try { configID = new URI(args[1]); } catch (URISyntaxException e) { e.printStackTrace(); System.exit(1); } String domain = "geronimo"; if (storeDir.exists()) { if (!storeDir.isDirectory() || !storeDir.canWrite()) { System.err.println("Store location is not a writable directory: " + storeDir); System.exit(1); } } else { if (!storeDir.mkdirs()) { System.err.println("Could not create store directory: " + storeDir); System.exit(1); } } final Kernel kernel = new Kernel(domain, LocalConfigStore.GBEAN_INFO, storeDir); Runtime.getRuntime().addShutdownHook(new Thread("Shutdown Thread") { public void run() { kernel.shutdown(); } }); try { kernel.boot(); } catch (Exception e) { e.printStackTrace(); System.exit(2); } try { kernel.load(configID); } catch (Exception e) { kernel.shutdown(); e.printStackTrace(); System.exit(2); } while (kernel.isRunning()) { try { synchronized (kernel) { kernel.wait(); } } catch (InterruptedException e) { // continue } } } public MBeanNotificationInfo[] getNotificationInfo() { return new MBeanNotificationInfo[0]; } public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { } }
package io.bitsquare.p2p.network; import com.google.common.util.concurrent.CycleDetectingLockFactory; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.Uninterruptibles; import io.bitsquare.app.Log; import io.bitsquare.app.Version; import io.bitsquare.common.ByteArrayUtils; import io.bitsquare.common.UserThread; import io.bitsquare.common.util.Tuple2; import io.bitsquare.p2p.Message; import io.bitsquare.p2p.NodeAddress; import io.bitsquare.p2p.messaging.PrefixedSealedAndSignedMessage; import io.bitsquare.p2p.network.messages.CloseConnectionMessage; import io.bitsquare.p2p.network.messages.SendersNodeAddressMessage; import io.bitsquare.p2p.peers.keepalive.messages.KeepAliveMessage; import io.bitsquare.p2p.peers.keepalive.messages.Ping; import io.bitsquare.p2p.peers.keepalive.messages.Pong; import io.bitsquare.p2p.storage.messages.RefreshTTLMessage; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleObjectProperty; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.*; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class Connection implements MessageListener { private static final Logger log = LoggerFactory.getLogger(Connection.class); // Enums public enum PeerType { SEED_NODE, PEER, DIRECT_MSG_PEER } // Static private static final int MAX_MSG_SIZE = 100 * 1024; // 100 kb of compressed data //TODO decrease limits again after testing private static final int MSG_THROTTLE_PER_SEC = 50; // With MAX_MSG_SIZE of 100kb results in bandwidth of 5 mbit/sec private static final int MSG_THROTTLE_PER_10_SEC = 500; // With MAX_MSG_SIZE of 100kb results in bandwidth of 50 mbit/sec for 10 sec private static final int SOCKET_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(60); public static int getMaxMsgSize() { return MAX_MSG_SIZE; } private static final CycleDetectingLockFactory cycleDetectingLockFactory = CycleDetectingLockFactory.newInstance(CycleDetectingLockFactory.Policies.THROW); // Class fields private final Socket socket; // private final MessageListener messageListener; private final ConnectionListener connectionListener; private final String portInfo; private final String uid; private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); private final ReentrantLock objectOutputStreamLock = cycleDetectingLockFactory.newReentrantLock("objectOutputStreamLock"); // holder of state shared between InputHandler and Connection private final SharedModel sharedModel; private final Statistic statistic; // set in init private InputHandler inputHandler; private ObjectOutputStream objectOutputStream; // mutable data, set from other threads but not changed internally. private Optional<NodeAddress> peersNodeAddressOptional = Optional.empty(); private volatile boolean stopped; private PeerType peerType; private final ObjectProperty<NodeAddress> peersNodeAddressProperty = new SimpleObjectProperty<>(); private final List<Tuple2<Long, Serializable>> messageTimeStamps = new ArrayList<>(); private final CopyOnWriteArraySet<MessageListener> messageListeners = new CopyOnWriteArraySet<>(); private volatile long lastSendTimeStamp = 0; ; // Constructor Connection(Socket socket, MessageListener messageListener, ConnectionListener connectionListener, @Nullable NodeAddress peersNodeAddress) { this.socket = socket; this.connectionListener = connectionListener; uid = UUID.randomUUID().toString(); statistic = new Statistic(); addMessageListener(messageListener); sharedModel = new SharedModel(this, socket); if (socket.getLocalPort() == 0) portInfo = "port=" + socket.getPort(); else portInfo = "localPort=" + socket.getLocalPort() + "/port=" + socket.getPort(); init(peersNodeAddress); } private void init(@Nullable NodeAddress peersNodeAddress) { try { socket.setSoTimeout(SOCKET_TIMEOUT); // Need to access first the ObjectOutputStream otherwise the ObjectInputStream would block // See: https://stackoverflow.com/questions/5658089/java-creating-a-new-objectinputstream-blocks/5658109#5658109 // When you construct an ObjectInputStream, in the constructor the class attempts to read a header that // the associated ObjectOutputStream on the other end of the connection has written. // It will not return until that header has been read. objectOutputStream = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); // We create a thread for handling inputStream data inputHandler = new InputHandler(sharedModel, objectInputStream, portInfo, this); singleThreadExecutor.submit(inputHandler); } catch (IOException e) { sharedModel.handleConnectionException(e); } // Use Peer as default, in case of other types they will set it as soon as possible. peerType = PeerType.PEER; if (peersNodeAddress != null) setPeersNodeAddress(peersNodeAddress); log.trace("New connection created: " + this.toString()); UserThread.execute(() -> connectionListener.onConnection(this)); } // API // Called form various threads public void sendMessage(Message message) { if (!stopped) { try { Log.traceCall(); // Throttle outbound messages if (System.currentTimeMillis() - lastSendTimeStamp < 20) { log.info("We got 2 sendMessage requests in less then 20 ms. We set the thread to sleep " + "for 50 ms to avoid that we flood our peer. lastSendTimeStamp={}, now={}, elapsed={}", lastSendTimeStamp, System.currentTimeMillis(), (System.currentTimeMillis() - lastSendTimeStamp)); Thread.sleep(50); } lastSendTimeStamp = System.currentTimeMillis(); String peersNodeAddress = peersNodeAddressOptional.isPresent() ? peersNodeAddressOptional.get().toString() : "null"; int size = ByteArrayUtils.objectToByteArray(message).length; if (message instanceof Ping || message instanceof RefreshTTLMessage) { // pings and offer refresh msg we dont want to log in production log.trace("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" + "Sending direct message to peer" + "Write object to outputStream to peer: {} (uid={})\ntruncated message={} / size={}" + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", peersNodeAddress, uid, StringUtils.abbreviate(message.toString(), 100), size); } else if (message instanceof PrefixedSealedAndSignedMessage && peersNodeAddressOptional.isPresent()) { setPeerType(Connection.PeerType.DIRECT_MSG_PEER); log.info("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" + "Sending direct message to peer" + "Write object to outputStream to peer: {} (uid={})\ntruncated message={} / size={}" + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", peersNodeAddress, uid, StringUtils.abbreviate(message.toString(), 100), size); } else { log.info("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" + "Write object to outputStream to peer: {} (uid={})\ntruncated message={} / size={}" + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", peersNodeAddress, uid, StringUtils.abbreviate(message.toString(), 100), size); } if (!stopped) { objectOutputStreamLock.lock(); objectOutputStream.writeObject(message); objectOutputStream.flush(); statistic.addSentBytes(size); statistic.addSentMessage(message); // We don't want to get the activity ts updated by ping/pong msg if (!(message instanceof KeepAliveMessage)) statistic.updateLastActivityTimestamp(); } } catch (IOException e) { // an exception lead to a shutdown sharedModel.handleConnectionException(e); } catch (Throwable t) { log.error(t.getMessage()); t.printStackTrace(); sharedModel.handleConnectionException(t); } finally { if (objectOutputStreamLock.isLocked()) objectOutputStreamLock.unlock(); } } else { log.debug("called sendMessage but was already stopped"); } } public void addMessageListener(MessageListener messageListener) { boolean isNewEntry = messageListeners.add(messageListener); if (!isNewEntry) log.warn("Try to add a messageListener which was already added."); } public void removeMessageListener(MessageListener messageListener) { boolean contained = messageListeners.remove(messageListener); if (!contained) log.debug("Try to remove a messageListener which was never added.\n\t" + "That might happen because of async behaviour of CopyOnWriteArraySet"); } @SuppressWarnings("unused") public boolean reportIllegalRequest(RuleViolation ruleViolation) { return sharedModel.reportInvalidRequest(ruleViolation); } private boolean violatesThrottleLimit(Serializable serializable) { long now = System.currentTimeMillis(); boolean violated = false; //TODO remove serializable storage after network is tested stable if (messageTimeStamps.size() >= MSG_THROTTLE_PER_SEC) { // check if we got more than 10 (MSG_THROTTLE_PER_SEC) msg per sec. long compareValue = messageTimeStamps.get(messageTimeStamps.size() - MSG_THROTTLE_PER_SEC).first; // if duration < 1 sec we received too much messages violated = now - compareValue < TimeUnit.SECONDS.toMillis(1); if (violated) { log.error("violatesThrottleLimit 1 "); log.error("elapsed " + (now - compareValue)); log.error("messageTimeStamps: \n\t" + messageTimeStamps.stream() .map(e -> "\n\tts=" + e.first.toString() + " message=" + e.second.toString()) .collect(Collectors.toList()).toString()); } } if (messageTimeStamps.size() >= MSG_THROTTLE_PER_10_SEC) { if (!violated) { // check if we got more than 50 msg per 10 sec. long compareValue = messageTimeStamps.get(messageTimeStamps.size() - MSG_THROTTLE_PER_10_SEC).first; // if duration < 10 sec we received too much messages violated = now - compareValue < TimeUnit.SECONDS.toMillis(10); if (violated) { log.error("violatesThrottleLimit 2 "); log.error("elapsed " + (now - compareValue)); log.error("messageTimeStamps: \n\t" + messageTimeStamps.stream() .map(e -> "\n\tts=" + e.first.toString() + " message=" + e.second.toString()) .collect(Collectors.toList()).toString()); } } // we limit to max 50 (MSG_THROTTLE_PER_10SEC) entries messageTimeStamps.remove(0); } messageTimeStamps.add(new Tuple2<>(now, serializable)); return violated; } // MessageListener implementation // Only receive non - CloseConnectionMessage messages @Override public void onMessage(Message message, Connection connection) { checkArgument(connection.equals(this)); UserThread.execute(() -> messageListeners.stream().forEach(e -> e.onMessage(message, connection))); } // Setters public void setPeerType(PeerType peerType) { Log.traceCall(peerType.toString()); this.peerType = peerType; } public void setPeersNodeAddress(NodeAddress peerNodeAddress) { checkNotNull(peerNodeAddress, "peerAddress must not be null"); peersNodeAddressOptional = Optional.of(peerNodeAddress); String peersNodeAddress = getPeersNodeAddressOptional().isPresent() ? getPeersNodeAddressOptional().get().getFullAddress() : ""; if (this instanceof InboundConnection) { log.info("\n\n "We got the peers node address set.\n" + "peersNodeAddress= " + peersNodeAddress + "\nconnection.uid=" + getUid() + "\n } peersNodeAddressProperty.set(peerNodeAddress); } // Getters public Optional<NodeAddress> getPeersNodeAddressOptional() { return peersNodeAddressOptional; } public String getUid() { return uid; } public boolean hasPeersNodeAddress() { return peersNodeAddressOptional.isPresent(); } public boolean isStopped() { return stopped; } public PeerType getPeerType() { return peerType; } public ReadOnlyObjectProperty<NodeAddress> peersNodeAddressProperty() { return peersNodeAddressProperty; } public RuleViolation getRuleViolation() { return sharedModel.getRuleViolation(); } public Statistic getStatistic() { return statistic; } // ShutDown public void shutDown(CloseConnectionReason closeConnectionReason) { shutDown(closeConnectionReason, null); } public void shutDown(CloseConnectionReason closeConnectionReason, @Nullable Runnable shutDownCompleteHandler) { Log.traceCall(this.toString()); if (!stopped) { String peersNodeAddress = peersNodeAddressOptional.isPresent() ? peersNodeAddressOptional.get().toString() : "null"; log.info("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + "ShutDown connection:" + "\npeersNodeAddress=" + peersNodeAddress + "\ncloseConnectionReason=" + closeConnectionReason + "\nuid=" + uid + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"); if (closeConnectionReason.sendCloseMessage) { new Thread(() -> { Thread.currentThread().setName("Connection:SendCloseConnectionMessage-" + this.uid); Log.traceCall("sendCloseConnectionMessage"); try { String reason = closeConnectionReason == CloseConnectionReason.RULE_VIOLATION ? sharedModel.getRuleViolation().name() : closeConnectionReason.name(); sendMessage(new CloseConnectionMessage(reason)); setStopFlags(); Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS); } catch (Throwable t) { log.error(t.getMessage()); t.printStackTrace(); } finally { setStopFlags(); UserThread.execute(() -> doShutDown(closeConnectionReason, shutDownCompleteHandler)); } }).start(); } else { setStopFlags(); doShutDown(closeConnectionReason, shutDownCompleteHandler); } } else { //TODO find out why we get called that log.warn("stopped was already true at shutDown call"); UserThread.execute(() -> doShutDown(closeConnectionReason, shutDownCompleteHandler)); } } private void setStopFlags() { stopped = true; sharedModel.stop(); if (inputHandler != null) inputHandler.stop(); } private void doShutDown(CloseConnectionReason closeConnectionReason, @Nullable Runnable shutDownCompleteHandler) { // Use UserThread.execute as its not clear if that is called from a non-UserThread UserThread.execute(() -> connectionListener.onDisconnect(closeConnectionReason, this)); try { sharedModel.getSocket().close(); } catch (SocketException e) { log.trace("SocketException at shutdown might be expected " + e.getMessage()); } catch (IOException e) { log.error("Exception at shutdown. " + e.getMessage()); e.printStackTrace(); } finally { MoreExecutors.shutdownAndAwaitTermination(singleThreadExecutor, 500, TimeUnit.MILLISECONDS); log.debug("Connection shutdown complete " + this.toString()); // Use UserThread.execute as its not clear if that is called from a non-UserThread if (shutDownCompleteHandler != null) UserThread.execute(shutDownCompleteHandler); } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Connection)) return false; Connection that = (Connection) o; return !(uid != null ? !uid.equals(that.uid) : that.uid != null); } @Override public int hashCode() { return uid != null ? uid.hashCode() : 0; } @Override public String toString() { return "Connection{" + "peerAddress=" + peersNodeAddressOptional + ", peerType=" + peerType + ", uid='" + uid + '\'' + '}'; } @SuppressWarnings("unused") public String printDetails() { return "Connection{" + "peerAddress=" + peersNodeAddressOptional + ", peerType=" + peerType + ", portInfo=" + portInfo + ", uid='" + uid + '\'' + ", sharedSpace=" + sharedModel.toString() + ", stopped=" + stopped + '}'; } // SharedSpace /** * Holds all shared data between Connection and InputHandler * Runs in same thread as Connection */ private static class SharedModel { private static final Logger log = LoggerFactory.getLogger(SharedModel.class); private final Connection connection; private final Socket socket; private final ConcurrentHashMap<RuleViolation, Integer> ruleViolations = new ConcurrentHashMap<>(); // mutable private volatile boolean stopped; private CloseConnectionReason closeConnectionReason; private RuleViolation ruleViolation; public SharedModel(Connection connection, Socket socket) { this.connection = connection; this.socket = socket; } public boolean reportInvalidRequest(RuleViolation ruleViolation) { log.warn("We got reported an corrupt request " + ruleViolation + "\n\tconnection=" + this); int numRuleViolations; if (ruleViolations.contains(ruleViolation)) numRuleViolations = ruleViolations.get(ruleViolation); else numRuleViolations = 0; numRuleViolations++; ruleViolations.put(ruleViolation, numRuleViolations); if (numRuleViolations >= ruleViolation.maxTolerance) { log.warn("We close connection as we received too many corrupt requests.\n" + "numRuleViolations={}\n\t" + "corruptRequest={}\n\t" + "corruptRequests={}\n\t" + "connection={}", numRuleViolations, ruleViolation, ruleViolations.toString(), connection); this.ruleViolation = ruleViolation; shutDown(CloseConnectionReason.RULE_VIOLATION); return true; } else { return false; } } public void handleConnectionException(Throwable e) { Log.traceCall(e.toString()); if (e instanceof SocketException) { if (socket.isClosed()) closeConnectionReason = CloseConnectionReason.SOCKET_CLOSED; else closeConnectionReason = CloseConnectionReason.RESET; } else if (e instanceof SocketTimeoutException || e instanceof TimeoutException) { closeConnectionReason = CloseConnectionReason.SOCKET_TIMEOUT; log.warn("SocketTimeoutException at socket " + socket.toString() + "\n\tconnection={}" + this); } else if (e instanceof EOFException || e instanceof StreamCorruptedException) { closeConnectionReason = CloseConnectionReason.TERMINATED; } else { closeConnectionReason = CloseConnectionReason.UNKNOWN_EXCEPTION; String message; if (e.getMessage() != null) message = e.getMessage(); else message = e.toString(); log.warn("Unknown reason for exception at socket {}\n\tconnection={}\n\tException=", socket.toString(), this, message); e.printStackTrace(); } shutDown(closeConnectionReason); } public void shutDown(CloseConnectionReason closeConnectionReason) { if (!stopped) { stopped = true; connection.shutDown(closeConnectionReason); } } public Socket getSocket() { return socket; } public void stop() { this.stopped = true; } public RuleViolation getRuleViolation() { return ruleViolation; } @Override public String toString() { return "SharedSpace{" + ", socket=" + socket + ", ruleViolations=" + ruleViolations + '}'; } } // InputHandler // Runs in same thread as Connection private static class InputHandler implements Runnable { private static final Logger log = LoggerFactory.getLogger(InputHandler.class); private final SharedModel sharedModel; private final ObjectInputStream objectInputStream; private final String portInfo; private final MessageListener messageListener; private volatile boolean stopped; private long lastReadTimeStamp; public InputHandler(SharedModel sharedModel, ObjectInputStream objectInputStream, String portInfo, MessageListener messageListener) { this.sharedModel = sharedModel; this.objectInputStream = objectInputStream; this.portInfo = portInfo; this.messageListener = messageListener; } public void stop() { if (!stopped) { try { objectInputStream.close(); } catch (IOException e) { log.error("IOException at InputHandler.stop\n" + e.getMessage()); e.printStackTrace(); } finally { stopped = true; } } } @Override public void run() { try { Thread.currentThread().setName("InputHandler-" + portInfo); while (!stopped && !Thread.currentThread().isInterrupted()) { try { log.trace("InputHandler waiting for incoming messages.\n\tConnection=" + sharedModel.connection); Object rawInputObject = objectInputStream.readObject(); // Throttle inbound messages if (System.currentTimeMillis() - lastReadTimeStamp < 10) { log.info("We got 2 messages received in less then 10 ms. We set the thread to sleep " + "for 20 ms to avoid that we get flooded by our peer. lastReadTimeStamp={}, now={}, elapsed={}", lastReadTimeStamp, System.currentTimeMillis(), (System.currentTimeMillis() - lastReadTimeStamp)); Thread.sleep(20); } lastReadTimeStamp = System.currentTimeMillis(); int size = ByteArrayUtils.objectToByteArray(rawInputObject).length; if (rawInputObject instanceof Message) { Message message = (Message) rawInputObject; Connection connection = sharedModel.connection; connection.statistic.addReceivedBytes(size); connection.statistic.addReceivedMessage(message); } if (rawInputObject instanceof Pong || rawInputObject instanceof RefreshTTLMessage) { // pongs and offer refresh msg we dont want to log in production log.trace("\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" + "New data arrived at inputHandler of connection {}.\n" + "Received object (truncated)={} / size={}" + "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n", sharedModel.connection, StringUtils.abbreviate(rawInputObject.toString(), 100), size); } else { log.info("\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" + "New data arrived at inputHandler of connection {}.\n" + "Received object (truncated)={} / size={}" + "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n", sharedModel.connection, StringUtils.abbreviate(rawInputObject.toString(), 100), size); } if (size > getMaxMsgSize()) { if (reportInvalidRequest(RuleViolation.MAX_MSG_SIZE_EXCEEDED)) return; } Serializable serializable; if (rawInputObject instanceof Serializable) { serializable = (Serializable) rawInputObject; } else { reportInvalidRequest(RuleViolation.INVALID_DATA_TYPE); return; } if (sharedModel.connection.violatesThrottleLimit(serializable)) { if (reportInvalidRequest(RuleViolation.THROTTLE_LIMIT_EXCEEDED)) return; } if (!(serializable instanceof Message)) { reportInvalidRequest(RuleViolation.INVALID_DATA_TYPE); return; } Message message = (Message) serializable; Connection connection = sharedModel.connection; connection.statistic.addReceivedBytes(size); connection.statistic.addReceivedMessage(message); if (message.getMessageVersion() != Version.getP2PMessageVersion()) { log.warn("message.getMessageVersion()=" + message.getMessageVersion()); log.warn("message=" + message); log.warn("Version.getP2PMessageVersion()=" + Version.getP2PMessageVersion()); reportInvalidRequest(RuleViolation.WRONG_NETWORK_ID); return; } if (message instanceof CloseConnectionMessage) { log.info("CloseConnectionMessage received. Reason={}\n\t" + "connection={}", ((CloseConnectionMessage) message).reason, connection); stop(); sharedModel.shutDown(CloseConnectionReason.CLOSE_REQUESTED_BY_PEER); } else if (!stopped) { // We don't want to get the activity ts updated by ping/pong msg if (!(message instanceof KeepAliveMessage)) connection.statistic.updateLastActivityTimestamp(); // First a seed node gets a message form a peer (PreliminaryDataRequest using // AnonymousMessage interface) which does not has its hidden service // published, so does not know its address. As the IncomingConnection does not has the // peersNodeAddress set that connection cannot be used for outgoing messages until we // get the address set. // At the data update message (DataRequest using SendersNodeAddressMessage interface) // after the HS is published we get the peers address set. // There are only those messages used for new connections to a peer: // 1. PreliminaryDataRequest // 2. DataRequest (implements SendersNodeAddressMessage) // 3. GetPeersRequest (implements SendersNodeAddressMessage) // 4. DirectMessage (implements SendersNodeAddressMessage) if (message instanceof SendersNodeAddressMessage) { NodeAddress senderNodeAddress = ((SendersNodeAddressMessage) message).getSenderNodeAddress(); Optional<NodeAddress> peersNodeAddressOptional = connection.getPeersNodeAddressOptional(); if (peersNodeAddressOptional.isPresent()) { checkArgument(peersNodeAddressOptional.get().equals(senderNodeAddress), "senderNodeAddress not matching connections peer address.\n\t" + "message=" + message); } else { connection.setPeersNodeAddress(senderNodeAddress); } } if (message instanceof PrefixedSealedAndSignedMessage) connection.setPeerType(Connection.PeerType.DIRECT_MSG_PEER); messageListener.onMessage(message, connection); } } catch (ClassNotFoundException | NoClassDefFoundError e) { log.warn(e.getMessage()); e.printStackTrace(); reportInvalidRequest(RuleViolation.INVALID_DATA_TYPE); return; } catch (IOException e) { stop(); sharedModel.handleConnectionException(e); } catch (Throwable t) { t.printStackTrace(); stop(); sharedModel.handleConnectionException(new Exception(t)); } } } catch (Throwable t) { t.printStackTrace(); stop(); sharedModel.handleConnectionException(new Exception(t)); } } private boolean reportInvalidRequest(RuleViolation ruleViolation) { boolean causedShutDown = sharedModel.reportInvalidRequest(ruleViolation); if (causedShutDown) stop(); return causedShutDown; } @Override public String toString() { return "InputHandler{" + "sharedSpace=" + sharedModel + ", port=" + portInfo + ", stopped=" + stopped + '}'; } } }
package th.ac.kmitl.ce.ooad; import org.springframework.web.bind.annotation.*; @RestController public class MainController { @RequestMapping(value = "/addUser/{username}/{name}", params = {"email", "password", "imgLocation"}) @ResponseBody public String addUser(@PathVariable String username,@RequestParam("password") String passphrase, @PathVariable String name, @RequestParam("email") String email, @RequestParam("imgLocation") String imgLoc){ System.out.println("Add " + username); String tmp = UserModel.getInstance().addUser(username, passphrase, name, email, imgLoc); if(tmp != null)System.out.println("Add " + username + " successfully."); else System.out.println("Add " + username + " not successfully."); return tmp; } @RequestMapping(value = "/login/{username}", params = "password") @ResponseBody public boolean loginUser(@PathVariable String username, @RequestParam("password") String passphrase){ return UserModel.getInstance().authenUser(username, passphrase); } @RequestMapping(value = "/login/{username}") @ResponseBody public boolean isUser(@PathVariable String username){ return UserModel.getInstance().isExist(username); } @RequestMapping(value = "/update/name/{username}", params = {"name", "password"}) public boolean updateName(@PathVariable String username, @RequestParam("name") String name, @RequestParam("password") String pwd){ if(UserModel.getInstance().authenUser(username, pwd)){ UserModel.getInstance().updateName(username, name); } return false; } @RequestMapping(value = "/update/password/{username}", params = {"password", "newpassword"}) @ResponseBody public boolean updatePwd(@PathVariable String username, @RequestParam("password") String pwd, @RequestParam("newpassword") String passphrase){ if(UserModel.getInstance().authenUser(username, pwd)){ UserModel.getInstance().updatePwd(username, passphrase); return true; } return false; } @RequestMapping(value = "/plan/{userId}", params = {"password", "cloudProv"}) @ResponseBody public Plan[] requestUserPlan(@PathVariable String userId, @RequestParam("password") String password, @RequestParam("cloudProv") int cloudProv){ return PlanModel.getInstance().getUserPlanByCloud(UserModel.getInstance().getAccountById(userId), cloudProv); } @RequestMapping(value = "/plan", params = "cloudProv") @ResponseBody public Plan[] requestCloudPlan(@RequestParam("cloudProv") int cloudProv){ return PlanModel.getInstance().getAllProviderPlan(cloudProv); } @RequestMapping(value = "/update/plan/{userId}", params = {"password", "ip", "plan", "cloudProv"}) @ResponseBody public boolean updatePlan(@PathVariable String userId, @RequestParam("cloudProv") int cloudProv, @RequestParam ("password") String password, @RequestParam("ip") String ip, @RequestParam("plan") int plan){ return PlanModel.getInstance().updatePlan(UserModel.getInstance().getAccountById(userId), cloudProv, plan); } @RequestMapping(value = "/plan/addCloudAccount/{userId}", params = {"cloudProv", "password", "cloudUsername", "cloudPassword"}) @ResponseBody public boolean addCloudAccount(@PathVariable String userId, @RequestParam("password") String password, @RequestParam("cloudUsername") String cloudUsername, @RequestParam("cloudPassword") String cloudPassword, @RequestParam("cloudProv") int cloudProv){ return false; } }
package org.spoofax.jsglr; import java.io.IOException; import org.spoofax.ArrayDeque; //TODO: keep recovered lines (Testcase: two separated errors) public class RecoveryConnector { private SGLR mySGLR; private IRecoveryParser recoveryParser; private RegionRecovery skipRecovery; private boolean useBridgeParser; private boolean useFineGrained; public void setUseBridgeParser(boolean useBridgeParser) { this.useBridgeParser = useBridgeParser; } public RecoveryConnector(SGLR parser, IRecoveryParser recoveryParser){ mySGLR=parser; skipRecovery = new RegionRecovery(mySGLR); useFineGrained=true; if(recoveryParser!=null){ this.recoveryParser = recoveryParser; useBridgeParser=true; } else useBridgeParser=false; } private ParserHistory getHistory() { return mySGLR.getHistory(); } public void recover() throws IOException { boolean skipSucceeded = skipRecovery.selectErroneousFragment(); //decides whether whitespace parse makes sense mySGLR.acceptingStack=null; mySGLR.activeStacks.clear(); //BRIDGE REPAIR if(useBridgeParser){ String errorFragment = skipRecovery.getErrorFragmentWithLeftMargin(); boolean succeeded = tryBridgeRepair(errorFragment); if(succeeded){ return; } } //FINEGRAINED REPAIR if(useFineGrained){ if(tryFineGrainedRepair()){ //FG succeeded addSkipOption(skipSucceeded); return; } } //WHITESPACE REPAIR if (skipSucceeded) { getHistory().deleteLinesFrom(skipRecovery.getStartIndexErrorFragment());//TODO: integrate with FG and BP getHistory().resetRecoveryIndentHandler(skipRecovery.getStartLineErrorFragment().getIndentValue()); parseErrorFragmentAsWhiteSpace(false); parseRemainingTokens(true); } } private void addSkipOption(boolean skipSucceeded) throws IOException { ArrayDeque<Frame> fgStacks=new ArrayDeque<Frame>(); fgStacks.addAll(mySGLR.activeStacks); if(skipSucceeded && parseErrorFragmentAsWhiteSpace(false) && parseRemainingTokens(false)){ for (Frame frame : mySGLR.activeStacks) { for (Link l : frame.getAllLinks()) { l.recoverCount = 5; } } for (Frame frame : fgStacks) { mySGLR.addStack(frame); } } } private boolean recoverySucceeded() { return (mySGLR.activeStacks.size()>0 || mySGLR.acceptingStack!=null); } private boolean tryFineGrainedRepair() throws IOException { FineGrainedOnRegion fgRepair=new FineGrainedOnRegion(mySGLR); fgRepair.setRegionInfo(skipRecovery.getErroneousRegion(), skipRecovery.getAcceptPosition()); fgRepair.recover(); fgRepair.parseRemainingTokens(); return recoverySucceeded(); } private boolean tryBridgeRepair(String errorFragment) throws IOException { String repairedFragment = repairBridges(errorFragment); mySGLR.activeStacks.addAll(skipRecovery.getStartLineErrorFragment().getStackNodes()); tryParsing(repairedFragment, false); return parseRemainingTokens(true); } private String repairBridges(String errorFragment) { try { IRecoveryResult bpResult = null; bpResult = recoveryParser.recover(errorFragment); return bpResult.getResult(); } catch (TokenExpectedException e) { e.printStackTrace(); } catch (BadTokenException e) { e.printStackTrace(); } catch (SGLRException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return errorFragment; } private void tryParsing(String fragment, boolean asLayout) throws IOException{ // Skip any leading whitespace, since we already parsed up to that point int indexFragment = findFirstNonLayoutToken(fragment); while(indexFragment<fragment.length() && mySGLR.activeStacks.size()>0) { mySGLR.currentToken=fragment.charAt(indexFragment); indexFragment++; if(!asLayout) mySGLR.doParseStep(); else parseAsLayout(); } } public boolean parseErrorFragmentAsWhiteSpace(boolean keepLines) throws IOException{ mySGLR.activeStacks.clear(); mySGLR.activeStacks.addAll(skipRecovery.getStartLineErrorFragment().getStackNodes()); getHistory().setTokenIndex(skipRecovery.getStartPositionErrorFragment()); while((getHistory().getTokenIndex()<skipRecovery.getEndPositionErrorFragment()) && mySGLR.activeStacks.size()>0 && mySGLR.acceptingStack==null){ getHistory().readRecoverToken(mySGLR, keepLines); //System.out.print((char)mySGLR.currentToken); parseAsLayout(); } return recoverySucceeded(); } public boolean parseRemainingTokens(boolean keepHistory) throws IOException{ getHistory().setTokenIndex(skipRecovery.getEndPositionErrorFragment()); while(!getHistory().hasFinishedRecoverTokens() && mySGLR.activeStacks.size()>0 && mySGLR.acceptingStack==null){ getHistory().readRecoverToken(mySGLR, keepHistory); //System.out.print((char)mySGLR.currentToken); mySGLR.doParseStep(); } return recoverySucceeded(); } private void parseAsLayout() throws IOException { if(isLayoutCharacter((char)mySGLR.currentToken) || mySGLR.currentToken==SGLR.EOF) mySGLR.doParseStep(); else{ mySGLR.currentToken=' '; mySGLR.doParseStep(); } } public static boolean isLayoutCharacter(char aChar) { // TODO: Move this to the parse table class; only it truly can now layout characters return aChar==' ' || aChar == '\t' || aChar=='\n'; } private int findFirstNonLayoutToken(String repairedFragment) { int indexFragment=0; while(indexFragment<repairedFragment.length()-1 && isLayoutCharacter(repairedFragment.charAt(indexFragment))) indexFragment++; return indexFragment; } public void setUseFineGrained(boolean useFG) { useFineGrained=useFG; } /* private Map<Integer, char[]> getBPSuggestions(){ Map<Integer, char[]> bpSuggestions = getBridges(); int startPos = skipRecovery.getStartPositionErrorFragment_InclLeftMargin(); Map<Integer, char[]> bpSuggestAbsolute = new HashMap<Integer, char[]>(); for (Integer aKey : bpSuggestions.keySet()) { Integer newKey=new Integer(startPos+aKey.intValue()); char[] newValue=bpSuggestions.get(aKey); bpSuggestAbsolute.put(newKey, newValue); } return bpSuggestAbsolute; } private Map<Integer, char[]> getBridges() { IRecoveryResult bpResult; if (bpResult != null) { return bpResult.getSuggestions(); } return new HashMap<Integer, char[]>(); } */ }
package org.osmdroid.views; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import microsoft.mappoint.TileSystem; import net.wigle.wigleandroid.ZoomButtonsController; import net.wigle.wigleandroid.ZoomButtonsController.OnZoomListener; import org.metalev.multitouch.controller.MultiTouchController; import org.metalev.multitouch.controller.MultiTouchController.MultiTouchObjectCanvas; import org.metalev.multitouch.controller.MultiTouchController.PointInfo; import org.metalev.multitouch.controller.MultiTouchController.PositionAndScale; import org.osmdroid.DefaultResourceProxyImpl; import org.osmdroid.ResourceProxy; import org.osmdroid.api.IGeoPoint; import org.osmdroid.api.IMapView; import org.osmdroid.api.IProjection; import org.osmdroid.events.MapListener; import org.osmdroid.events.ScrollEvent; import org.osmdroid.events.ZoomEvent; import org.osmdroid.tileprovider.MapTileProviderBase; import org.osmdroid.tileprovider.MapTileProviderBasic; import org.osmdroid.tileprovider.tilesource.IStyledTileSource; import org.osmdroid.tileprovider.tilesource.ITileSource; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.tileprovider.util.SimpleInvalidationHandler; import org.osmdroid.util.BoundingBoxE6; import org.osmdroid.util.GeoPoint; import org.osmdroid.util.constants.GeoConstants; import org.osmdroid.views.overlay.Overlay; import org.osmdroid.views.overlay.OverlayManager; import org.osmdroid.views.overlay.TilesOverlay; import org.osmdroid.views.util.constants.MapViewConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.content.Context; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.Rect; import android.os.Handler; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.Scroller; public class MapView extends ViewGroup implements IMapView, MapViewConstants, MultiTouchObjectCanvas<Object> { // Constants private static final Logger logger = LoggerFactory.getLogger(MapView.class); private static final double ZOOM_SENSITIVITY = 1.3; private static final double ZOOM_LOG_BASE_INV = 1.0 / Math.log(2.0 / ZOOM_SENSITIVITY); // Fields /** Current zoom level for map tiles. */ private int mZoomLevel = 0; private final OverlayManager mOverlayManager; private Projection mProjection; private final TilesOverlay mMapOverlay; private final GestureDetector mGestureDetector; /** Handles map scrolling */ private final Scroller mScroller; private final AtomicInteger mTargetZoomLevel = new AtomicInteger(); private final AtomicBoolean mIsAnimating = new AtomicBoolean(false); private final ScaleAnimation mZoomInAnimation; private final ScaleAnimation mZoomOutAnimation; private final MapController mController; // XXX we can use android.widget.ZoomButtonsController if we upgrade the // dependency to Android 1.6 private final ZoomButtonsController mZoomController; private boolean mEnableZoomController = false; private final ResourceProxy mResourceProxy; private MultiTouchController<Object> mMultiTouchController; private float mMultiTouchScale = 1.0f; protected MapListener mListener; // for speed (avoiding allocations) private final Matrix mMatrix = new Matrix(); private final MapTileProviderBase mTileProvider; private final Handler mTileRequestCompleteHandler; /* a point that will be reused to design added views */ private final Point mPoint = new Point(); // Constructors protected MapView(final Context context, final int tileSizePixels, final ResourceProxy resourceProxy, MapTileProviderBase tileProvider, final Handler tileRequestCompleteHandler, final AttributeSet attrs) { super(context, attrs); mResourceProxy = resourceProxy; this.mController = new MapController(this); this.mScroller = new Scroller(context); TileSystem.setTileSize(tileSizePixels); if (tileProvider == null) { final ITileSource tileSource = getTileSourceFromAttributes(attrs); tileProvider = new MapTileProviderBasic(context, tileSource); } mTileRequestCompleteHandler = tileRequestCompleteHandler == null ? new SimpleInvalidationHandler( this) : tileRequestCompleteHandler; mTileProvider = tileProvider; mTileProvider.setTileRequestCompleteHandler(mTileRequestCompleteHandler); this.mMapOverlay = new TilesOverlay(mTileProvider, mResourceProxy); mOverlayManager = new OverlayManager(mMapOverlay); this.mZoomController = new ZoomButtonsController(this); this.mZoomController.setOnZoomListener(new MapViewZoomListener()); mZoomInAnimation = new ScaleAnimation(1, 2, 1, 2, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); mZoomOutAnimation = new ScaleAnimation(1, 0.5f, 1, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); mZoomInAnimation.setDuration(ANIMATION_DURATION_SHORT); mZoomOutAnimation.setDuration(ANIMATION_DURATION_SHORT); mGestureDetector = new GestureDetector(context, new MapViewGestureDetectorListener()); mGestureDetector.setOnDoubleTapListener(new MapViewDoubleClickListener()); } /** * Constructor used by XML layout resource (uses default tile source). */ public MapView(final Context context, final AttributeSet attrs) { this(context, 256, new DefaultResourceProxyImpl(context), null, null, attrs); } /** * Standard Constructor. */ public MapView(final Context context, final int tileSizePixels) { this(context, tileSizePixels, new DefaultResourceProxyImpl(context)); } public MapView(final Context context, final int tileSizePixels, final ResourceProxy resourceProxy) { this(context, tileSizePixels, resourceProxy, null); } public MapView(final Context context, final int tileSizePixels, final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider) { this(context, tileSizePixels, resourceProxy, aTileProvider, null); } public MapView(final Context context, final int tileSizePixels, final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider, final Handler tileRequestCompleteHandler) { this(context, tileSizePixels, resourceProxy, aTileProvider, tileRequestCompleteHandler, null); } // Getter & Setter @Override public MapController getController() { return this.mController; } /** * You can add/remove/reorder your Overlays using the List of {@link Overlay}. The first (index * 0) Overlay gets drawn first, the one with the highest as the last one. */ public List<Overlay> getOverlays() { return this.getOverlayManager(); } public OverlayManager getOverlayManager() { return mOverlayManager; } public MapTileProviderBase getTileProvider() { return mTileProvider; } public Scroller getScroller() { return mScroller; } public Handler getTileRequestCompleteHandler() { return mTileRequestCompleteHandler; } @Override public int getLatitudeSpan() { return this.getBoundingBox().getLatitudeSpanE6(); } @Override public int getLongitudeSpan() { return this.getBoundingBox().getLongitudeSpanE6(); } public BoundingBoxE6 getBoundingBox() { return getBoundingBox(getWidth(), getHeight()); } public BoundingBoxE6 getBoundingBox(final int pViewWidth, final int pViewHeight) { final int world_2 = TileSystem.MapSize(mZoomLevel) / 2; final Rect screenRect = getScreenRect(null); screenRect.offset(world_2, world_2); final IGeoPoint neGeoPoint = TileSystem.PixelXYToLatLong(screenRect.right, screenRect.top, mZoomLevel, null); final IGeoPoint swGeoPoint = TileSystem.PixelXYToLatLong(screenRect.left, screenRect.bottom, mZoomLevel, null); return new BoundingBoxE6(neGeoPoint.getLatitudeE6(), neGeoPoint.getLongitudeE6(), swGeoPoint.getLatitudeE6(), swGeoPoint.getLongitudeE6()); } /** * Gets the current bounds of the screen in <I>screen coordinates</I>. */ public Rect getScreenRect(final Rect reuse) { final Rect out = reuse == null ? new Rect() : reuse; out.set(getScrollX() - getWidth() / 2, getScrollY() - getHeight() / 2, getScrollX() + getWidth() / 2, getScrollY() + getHeight() / 2); return out; } /** * Get a projection for converting between screen-pixel coordinates and latitude/longitude * coordinates. You should not hold on to this object for more than one draw, since the * projection of the map could change. * * @return The Projection of the map in its current state. You should not hold on to this object * for more than one draw, since the projection of the map could change. */ @Override public Projection getProjection() { if (mProjection == null) { mProjection = new Projection(); } return mProjection; } void setMapCenter(final IGeoPoint aCenter) { this.setMapCenter(aCenter.getLatitudeE6(), aCenter.getLongitudeE6()); } void setMapCenter(final int aLatitudeE6, final int aLongitudeE6) { final Point coords = TileSystem.LatLongToPixelXY(aLatitudeE6 / 1E6, aLongitudeE6 / 1E6, getZoomLevel(), null); final int worldSize_2 = TileSystem.MapSize(this.getZoomLevel(false)) / 2; if (getAnimation() == null || getAnimation().hasEnded()) { logger.debug("StartScroll"); mScroller.startScroll(getScrollX(), getScrollY(), coords.x - worldSize_2 - getScrollX(), coords.y - worldSize_2 - getScrollY(), 500); postInvalidate(); } } public void setTileSource(final ITileSource aTileSource) { mTileProvider.setTileSource(aTileSource); TileSystem.setTileSize(aTileSource.getTileSizePixels()); this.checkZoomButtons(); this.setZoomLevel(mZoomLevel); // revalidate zoom level postInvalidate(); } /** * @param aZoomLevel * the zoom level bound by the tile source */ int setZoomLevel(final int aZoomLevel) { final int minZoomLevel = getMinZoomLevel(); final int maxZoomLevel = getMaxZoomLevel(); final int newZoomLevel = Math.max(minZoomLevel, Math.min(maxZoomLevel, aZoomLevel)); final int curZoomLevel = this.mZoomLevel; if (newZoomLevel != curZoomLevel) { mScroller.forceFinished(true); } this.mZoomLevel = newZoomLevel; this.checkZoomButtons(); if (newZoomLevel > curZoomLevel) { // We are going from a lower-resolution plane to a higher-resolution plane, so we have // to do it the hard way. final int worldSize_current_2 = TileSystem.MapSize(curZoomLevel) / 2; final int worldSize_new_2 = TileSystem.MapSize(newZoomLevel) / 2; final IGeoPoint centerGeoPoint = TileSystem.PixelXYToLatLong(getScrollX() + worldSize_current_2, getScrollY() + worldSize_current_2, curZoomLevel, null); final Point centerPoint = TileSystem.LatLongToPixelXY( centerGeoPoint.getLatitudeE6() / 1E6, centerGeoPoint.getLongitudeE6() / 1E6, newZoomLevel, null); scrollTo(centerPoint.x - worldSize_new_2, centerPoint.y - worldSize_new_2); } else if (newZoomLevel < curZoomLevel) { // We are going from a higher-resolution plane to a lower-resolution plane, so we can do // it the easy way. scrollTo(getScrollX() >> curZoomLevel - newZoomLevel, getScrollY() >> curZoomLevel - newZoomLevel); } // snap for all snappables final Point snapPoint = new Point(); mProjection = new Projection(); if (this.getOverlayManager().onSnapToItem(getScrollX(), getScrollY(), snapPoint, this)) { scrollTo(snapPoint.x, snapPoint.y); } mTileProvider.rescaleCache(newZoomLevel, curZoomLevel, getScreenRect(null)); // do callback on listener if (newZoomLevel != curZoomLevel && mListener != null) { final ZoomEvent event = new ZoomEvent(this, newZoomLevel); mListener.onZoom(event); } // Allows any views fixed to a Location in the MapView to adjust this.requestLayout(); return this.mZoomLevel; } /** * Zoom the map to enclose the specified bounding box, as closely as possible. * Must be called after display layout is complete, or screen dimensions are not known, and * will always zoom to center of zoom level 0. * Suggestion: Check getScreenRect(null).getHeight() > 0 */ public void zoomToBoundingBox(final BoundingBoxE6 boundingBox) { final BoundingBoxE6 currentBox = getBoundingBox(); // Calculated required zoom based on latitude span final double maxZoomLatitudeSpan = mZoomLevel == getMaxZoomLevel() ? currentBox.getLatitudeSpanE6() : currentBox.getLatitudeSpanE6() / Math.pow(2, getMaxZoomLevel() - mZoomLevel); final double requiredLatitudeZoom = getMaxZoomLevel() - Math.ceil(Math.log(boundingBox.getLatitudeSpanE6() / maxZoomLatitudeSpan) / Math.log(2)); // Calculated required zoom based on longitude span final double maxZoomLongitudeSpan = mZoomLevel == getMaxZoomLevel() ? currentBox.getLongitudeSpanE6() : currentBox.getLongitudeSpanE6() / Math.pow(2, getMaxZoomLevel() - mZoomLevel); final double requiredLongitudeZoom = getMaxZoomLevel() - Math.ceil(Math.log(boundingBox.getLongitudeSpanE6() / maxZoomLongitudeSpan) / Math.log(2)); // Zoom to boundingBox center, at calculated maximum allowed zoom level getController().setZoom((int)( requiredLatitudeZoom < requiredLongitudeZoom ? requiredLatitudeZoom : requiredLongitudeZoom)); getController().setCenter( new GeoPoint( boundingBox.getCenter().getLatitudeE6()/1000000.0, boundingBox.getCenter().getLongitudeE6()/1000000.0 )); } /** * Get the current ZoomLevel for the map tiles. * * @return the current ZoomLevel between 0 (equator) and 18/19(closest), depending on the tile * source chosen. */ @Override public int getZoomLevel() { return getZoomLevel(true); } /** * Get the current ZoomLevel for the map tiles. * * @param aPending * if true and we're animating then return the zoom level that we're animating * towards, otherwise return the current zoom level * @return the zoom level */ public int getZoomLevel(final boolean aPending) { if (aPending && isAnimating()) { return mTargetZoomLevel.get(); } else { return mZoomLevel; } } /** * Returns the minimum zoom level for the point currently at the center. * * @return The minimum zoom level for the map's current center. */ public int getMinZoomLevel() { return mMapOverlay.getMinimumZoomLevel(); } /** * Returns the maximum zoom level for the point currently at the center. * * @return The maximum zoom level for the map's current center. */ @Override public int getMaxZoomLevel() { return mMapOverlay.getMaximumZoomLevel(); } public boolean canZoomIn() { final int maxZoomLevel = getMaxZoomLevel(); if (mZoomLevel >= maxZoomLevel) { return false; } if (mIsAnimating.get() & mTargetZoomLevel.get() >= maxZoomLevel) { return false; } return true; } public boolean canZoomOut() { final int minZoomLevel = getMinZoomLevel(); if (mZoomLevel <= minZoomLevel) { return false; } if (mIsAnimating.get() && mTargetZoomLevel.get() <= minZoomLevel) { return false; } return true; } /** * Zoom in by one zoom level. */ boolean zoomIn() { if (canZoomIn()) { if (mIsAnimating.get()) { // TODO extend zoom (and return true) return false; } else { mTargetZoomLevel.set(mZoomLevel + 1); mIsAnimating.set(true); startAnimation(mZoomInAnimation); return true; } } else { return false; } } boolean zoomInFixing(final IGeoPoint point) { setMapCenter(point); // TODO should fix on point, not center on it return zoomIn(); } boolean zoomInFixing(final int xPixel, final int yPixel) { setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it return zoomIn(); } /** * Zoom out by one zoom level. */ boolean zoomOut() { if (canZoomOut()) { if (mIsAnimating.get()) { // TODO extend zoom (and return true) return false; } else { mTargetZoomLevel.set(mZoomLevel - 1); mIsAnimating.set(true); startAnimation(mZoomOutAnimation); return true; } } else { return false; } } boolean zoomOutFixing(final IGeoPoint point) { setMapCenter(point); // TODO should fix on point, not center on it return zoomOut(); } boolean zoomOutFixing(final int xPixel, final int yPixel) { setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it return zoomOut(); } /** * Returns the current center-point position of the map, as a GeoPoint (latitude and longitude). * * @return A GeoPoint of the map's center-point. */ @Override public IGeoPoint getMapCenter() { final int world_2 = TileSystem.MapSize(mZoomLevel) / 2; final Rect screenRect = getScreenRect(null); screenRect.offset(world_2, world_2); return TileSystem.PixelXYToLatLong(screenRect.centerX(), screenRect.centerY(), mZoomLevel, null); } public ResourceProxy getResourceProxy() { return mResourceProxy; } /** * Whether to use the network connection if it's available. */ public boolean useDataConnection() { return mMapOverlay.useDataConnection(); } /** * Set whether to use the network connection if it's available. * * @param aMode * if true use the network connection if it's available. if false don't use the * network connection even if it's available. */ public void setUseDataConnection(final boolean aMode) { mMapOverlay.setUseDataConnection(aMode); } // Methods from SuperClass/Interfaces /** * Returns a set of layout parameters with a width of * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, a height of * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} at the {@link GeoPoint} (0, 0) align * with {@link MapView.LayoutParams#BOTTOM_CENTER}. */ @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, null, MapView.LayoutParams.BOTTOM_CENTER, 0, 0); } @Override public ViewGroup.LayoutParams generateLayoutParams(final AttributeSet attrs) { return new MapView.LayoutParams(getContext(), attrs); } // Override to allow type-checking of LayoutParams. @Override protected boolean checkLayoutParams(final ViewGroup.LayoutParams p) { return p instanceof MapView.LayoutParams; } @Override protected ViewGroup.LayoutParams generateLayoutParams(final ViewGroup.LayoutParams p) { return new MapView.LayoutParams(p); } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { final int count = getChildCount(); int maxHeight = 0; int maxWidth = 0; // Find out how big everyone wants to be measureChildren(widthMeasureSpec, heightMeasureSpec); // Find rightmost and bottom-most child for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams(); final int childHeight = child.getMeasuredHeight(); final int childWidth = child.getMeasuredWidth(); getProjection().toMapPixels(lp.geoPoint, mPoint); final int x = mPoint.x + getWidth() / 2; final int y = mPoint.y + getHeight() / 2; int childRight = x; int childBottom = y; switch (lp.alignment) { case MapView.LayoutParams.TOP_LEFT: childRight = x + childWidth; childBottom = y; break; case MapView.LayoutParams.TOP_CENTER: childRight = x + childWidth / 2; childBottom = y; break; case MapView.LayoutParams.TOP_RIGHT: childRight = x; childBottom = y; break; case MapView.LayoutParams.CENTER_LEFT: childRight = x + childWidth; childBottom = y + childHeight / 2; break; case MapView.LayoutParams.CENTER: childRight = x + childWidth / 2; childBottom = y + childHeight / 2; break; case MapView.LayoutParams.CENTER_RIGHT: childRight = x; childBottom = y + childHeight / 2; break; case MapView.LayoutParams.BOTTOM_LEFT: childRight = x + childWidth; childBottom = y + childHeight; break; case MapView.LayoutParams.BOTTOM_CENTER: childRight = x + childWidth / 2; childBottom = y + childHeight; break; case MapView.LayoutParams.BOTTOM_RIGHT: childRight = x; childBottom = y + childHeight; break; } childRight += lp.offsetX; childBottom += lp.offsetY; maxWidth = Math.max(maxWidth, childRight); maxHeight = Math.max(maxHeight, childBottom); } } // Account for padding too maxWidth += getPaddingLeft() + getPaddingRight(); maxHeight += getPaddingTop() + getPaddingBottom(); // Check against minimum height and width maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec), resolveSize(maxHeight, heightMeasureSpec)); } @Override protected void onLayout(final boolean changed, final int l, final int t, final int r, final int b) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams(); final int childHeight = child.getMeasuredHeight(); final int childWidth = child.getMeasuredWidth(); getProjection().toMapPixels(lp.geoPoint, mPoint); final int x = mPoint.x + getWidth() / 2; final int y = mPoint.y + getHeight() / 2; int childLeft = x; int childTop = y; switch (lp.alignment) { case MapView.LayoutParams.TOP_LEFT: childLeft = getPaddingLeft() + x; childTop = getPaddingTop() + y; break; case MapView.LayoutParams.TOP_CENTER: childLeft = getPaddingLeft() + x - childWidth / 2; childTop = getPaddingTop() + y; break; case MapView.LayoutParams.TOP_RIGHT: childLeft = getPaddingLeft() + x - childWidth; childTop = getPaddingTop() + y; break; case MapView.LayoutParams.CENTER_LEFT: childLeft = getPaddingLeft() + x; childTop = getPaddingTop() + y - childHeight / 2; break; case MapView.LayoutParams.CENTER: childLeft = getPaddingLeft() + x - childWidth / 2; childTop = getPaddingTop() + y - childHeight / 2; break; case MapView.LayoutParams.CENTER_RIGHT: childLeft = getPaddingLeft() + x - childWidth; childTop = getPaddingTop() + y - childHeight / 2; break; case MapView.LayoutParams.BOTTOM_LEFT: childLeft = getPaddingLeft() + x; childTop = getPaddingTop() + y - childHeight; break; case MapView.LayoutParams.BOTTOM_CENTER: childLeft = getPaddingLeft() + x - childWidth / 2; childTop = getPaddingTop() + y - childHeight; break; case MapView.LayoutParams.BOTTOM_RIGHT: childLeft = getPaddingLeft() + x - childWidth; childTop = getPaddingTop() + y - childHeight; break; } childLeft += lp.offsetX; childTop += lp.offsetY; child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); } } } public void onDetach() { this.getOverlayManager().onDetach(this); } @Override public boolean onKeyDown(final int keyCode, final KeyEvent event) { final boolean result = this.getOverlayManager().onKeyDown(keyCode, event, this); return result || super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(final int keyCode, final KeyEvent event) { final boolean result = this.getOverlayManager().onKeyUp(keyCode, event, this); return result || super.onKeyUp(keyCode, event); } @Override public boolean onTrackballEvent(final MotionEvent event) { if (this.getOverlayManager().onTrackballEvent(event, this)) { return true; } scrollBy((int) (event.getX() * 25), (int) (event.getY() * 25)); return super.onTrackballEvent(event); } @Override public boolean dispatchTouchEvent(final MotionEvent event) { if (DEBUGMODE) { logger.debug("dispatchTouchEvent(" + event + ")"); } if (mZoomController.isVisible() && mZoomController.onTouch(this, event)) { return true; } if (this.getOverlayManager().onTouchEvent(event, this)) { return true; } if (mMultiTouchController != null && mMultiTouchController.onTouchEvent(event)) { if (DEBUGMODE) { logger.debug("mMultiTouchController handled onTouchEvent"); } return true; } final boolean r = super.dispatchTouchEvent(event); if (mGestureDetector.onTouchEvent(event)) { if (DEBUGMODE) { logger.debug("mGestureDetector handled onTouchEvent"); } return true; } if (r) { if (DEBUGMODE) { logger.debug("super handled onTouchEvent"); } } else { if (DEBUGMODE) { logger.debug("no-one handled onTouchEvent"); } } return r; } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { if (mScroller.isFinished()) { // This will facilitate snapping-to any Snappable points. setZoomLevel(mZoomLevel); } else { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); } postInvalidate(); // Keep on drawing until the animation has // finished. } } @Override public void scrollTo(int x, int y) { final int worldSize_2 = TileSystem.MapSize(this.getZoomLevel(false)) / 2; while (x < -worldSize_2) { x += worldSize_2 * 2; } while (x > worldSize_2) { x -= worldSize_2 * 2; } while (y < -worldSize_2) { y += worldSize_2 * 2; } while (y > worldSize_2) { y -= worldSize_2 * 2; } super.scrollTo(x, y); // do callback on listener if (mListener != null) { final ScrollEvent event = new ScrollEvent(this, x, y); mListener.onScroll(event); } } @Override public void setBackgroundColor(final int pColor) { mMapOverlay.setLoadingBackgroundColor(pColor); invalidate(); } @Override protected void dispatchDraw(final Canvas c) { final long startMs = System.currentTimeMillis(); mProjection = new Projection(); // Save the current canvas matrix c.save(); if (mMultiTouchScale == 1.0f) { c.translate(getWidth() / 2, getHeight() / 2); } else { c.getMatrix(mMatrix); mMatrix.postTranslate(getWidth() / 2, getHeight() / 2); mMatrix.preScale(mMultiTouchScale, mMultiTouchScale, getScrollX(), getScrollY()); c.setMatrix(mMatrix); } /* Draw background */ // c.drawColor(mBackgroundColor); /* Draw all Overlays. */ this.getOverlayManager().onDraw(c, this); // Restore the canvas matrix c.restore(); super.dispatchDraw(c); if (DEBUGMODE) { final long endMs = System.currentTimeMillis(); logger.debug("Rendering overall: " + (endMs - startMs) + "ms"); } } @Override protected void onDetachedFromWindow() { this.mZoomController.setVisible(false); this.onDetach(); super.onDetachedFromWindow(); } // Animation @Override protected void onAnimationStart() { mIsAnimating.set(true); super.onAnimationStart(); } @Override protected void onAnimationEnd() { mIsAnimating.set(false); clearAnimation(); setZoomLevel(mTargetZoomLevel.get()); super.onAnimationEnd(); } /** * Check mAnimationListener.isAnimating() to determine if view is animating. Useful for overlays * to avoid recalculating during an animation sequence. * * @return boolean indicating whether view is animating. */ public boolean isAnimating() { return mIsAnimating.get(); } // Implementation of MultiTouchObjectCanvas @Override public Object getDraggableObjectAtPoint(final PointInfo pt) { return this; } @Override public void getPositionAndScale(final Object obj, final PositionAndScale objPosAndScaleOut) { objPosAndScaleOut.set(0, 0, true, mMultiTouchScale, false, 0, 0, false, 0); } @Override public void selectObject(final Object obj, final PointInfo pt) { // if obj is null it means we released the pointers // if scale is not 1 it means we pinched if (obj == null && mMultiTouchScale != 1.0f) { final float scaleDiffFloat = (float) (Math.log(mMultiTouchScale) * ZOOM_LOG_BASE_INV); final int scaleDiffInt = Math.round(scaleDiffFloat); setZoomLevel(mZoomLevel + scaleDiffInt); // XXX maybe zoom in/out instead of zooming direct to zoom level // - probably not a good idea because you'll repeat the animation } // reset scale mMultiTouchScale = 1.0f; } @Override public boolean setPositionAndScale(final Object obj, final PositionAndScale aNewObjPosAndScale, final PointInfo aTouchPoint) { float multiTouchScale = aNewObjPosAndScale.getScale(); // If we are at the first or last zoom level, prevent pinching/expanding if (multiTouchScale > 1 && !canZoomIn()) { multiTouchScale = 1; } if (multiTouchScale < 1 && !canZoomOut()) { multiTouchScale = 1; } mMultiTouchScale = multiTouchScale; invalidate(); // redraw return true; } /* * Set the MapListener for this view */ public void setMapListener(final MapListener ml) { mListener = ml; } // Methods private void checkZoomButtons() { this.mZoomController.setZoomInEnabled(canZoomIn()); this.mZoomController.setZoomOutEnabled(canZoomOut()); } public void setBuiltInZoomControls(final boolean on) { this.mEnableZoomController = on; this.checkZoomButtons(); } public void setMultiTouchControls(final boolean on) { mMultiTouchController = on ? new MultiTouchController<Object>(this, false) : null; } private ITileSource getTileSourceFromAttributes(final AttributeSet aAttributeSet) { ITileSource tileSource = TileSourceFactory.DEFAULT_TILE_SOURCE; if (aAttributeSet != null) { final String tileSourceAttr = aAttributeSet.getAttributeValue(null, "tilesource"); if (tileSourceAttr != null) { try { final ITileSource r = TileSourceFactory.getTileSource(tileSourceAttr); logger.info("Using tile source specified in layout attributes: " + r); tileSource = r; } catch (final IllegalArgumentException e) { logger.warn("Invalid tile souce specified in layout attributes: " + tileSource); } } } if (aAttributeSet != null && tileSource instanceof IStyledTileSource) { final String style = aAttributeSet.getAttributeValue(null, "style"); if (style == null) { logger.info("Using default style: 1"); } else { logger.info("Using style specified in layout attributes: " + style); ((IStyledTileSource<?>) tileSource).setStyle(style); } } logger.info("Using tile source: " + tileSource); return tileSource; } // Inner and Anonymous Classes /** * A Projection serves to translate between the coordinate system of x/y on-screen pixel * coordinates and that of latitude/longitude points on the surface of the earth. You obtain a * Projection from MapView.getProjection(). You should not hold on to this object for more than * one draw, since the projection of the map could change. <br /> * <br /> * <I>Screen coordinates</I> are in the coordinate system of the screen's Canvas. The origin is * in the center of the plane. <I>Screen coordinates</I> are appropriate for using to draw to * the screen.<br /> * <br /> * <I>Map coordinates</I> are in the coordinate system of the standard Mercator projection. The * origin is in the upper-left corner of the plane. <I>Map coordinates</I> are appropriate for * use in the TileSystem class.<br /> * <br /> * <I>Intermediate coordinates</I> are used to cache the computationally heavy part of the * projection. They aren't suitable for use until translated into <I>screen coordinates</I> or * <I>map coordinates</I>. * * @author Nicolas Gramlich * @author Manuel Stahl */ public class Projection implements IProjection, GeoConstants { private final int viewWidth_2 = getWidth() / 2; private final int viewHeight_2 = getHeight() / 2; private final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2; private final int offsetX = -worldSize_2; private final int offsetY = -worldSize_2; private final BoundingBoxE6 mBoundingBoxProjection; private final int mZoomLevelProjection; private final Rect mScreenRectProjection; private Projection() { /* * Do some calculations and drag attributes to local variables to save some performance. */ mZoomLevelProjection = MapView.this.mZoomLevel; mBoundingBoxProjection = MapView.this.getBoundingBox(); mScreenRectProjection = MapView.this.getScreenRect(null); } public int getZoomLevel() { return mZoomLevelProjection; } public BoundingBoxE6 getBoundingBox() { return mBoundingBoxProjection; } public Rect getScreenRect() { return mScreenRectProjection; } /** * @deprecated Use TileSystem.getTileSize() instead. */ @Deprecated public int getTileSizePixels() { return TileSystem.getTileSize(); } /** * @deprecated Use * <code>Point out = TileSystem.PixelXYToTileXY(screenRect.centerX(), screenRect.centerY(), null);</code> * instead. */ @Deprecated public Point getCenterMapTileCoords() { final Rect rect = getScreenRect(); return TileSystem.PixelXYToTileXY(rect.centerX(), rect.centerY(), null); } /** * @deprecated Use * <code>final Point out = TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null);</code> * instead. */ @Deprecated public Point getUpperLeftCornerOfCenterMapTile() { final Point centerMapTileCoords = getCenterMapTileCoords(); return TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null); } /** * Converts <I>screen coordinates</I> to the underlying GeoPoint. * * @param x * @param y * @return GeoPoint under x/y. */ public IGeoPoint fromPixels(final float x, final float y) { final Rect screenRect = getScreenRect(); return TileSystem.PixelXYToLatLong(screenRect.left + (int) x + worldSize_2, screenRect.top + (int) y + worldSize_2, mZoomLevelProjection, null); } public Point fromMapPixels(final int x, final int y, final Point reuse) { final Point out = reuse != null ? reuse : new Point(); out.set(x - viewWidth_2, y - viewHeight_2); out.offset(getScrollX(), getScrollY()); return out; } /** * Converts a GeoPoint to its <I>screen coordinates</I>. * * @param in * the GeoPoint you want the <I>screen coordinates</I> of * @param reuse * just pass null if you do not have a Point to be 'recycled'. * @return the Point containing the <I>screen coordinates</I> of the GeoPoint passed. */ public Point toMapPixels(final IGeoPoint in, final Point reuse) { final Point out = reuse != null ? reuse : new Point(); TileSystem.LatLongToPixelXY( in.getLatitudeE6() / 1E6, in.getLongitudeE6() / 1E6, getZoomLevel(), out); out.offset(offsetX, offsetY); if (Math.abs(out.x - getScrollX()) > Math.abs(out.x - TileSystem.MapSize(getZoomLevel()) - getScrollX())) { out.x -= TileSystem.MapSize(getZoomLevel()); } if (Math.abs(out.y - getScrollY()) > Math.abs(out.y - TileSystem.MapSize(getZoomLevel()) - getScrollY())) { out.y -= TileSystem.MapSize(getZoomLevel()); } return out; } /** * Performs only the first computationally heavy part of the projection. Call * toMapPixelsTranslated to get the final position. * * @param latituteE6 * the latitute of the point * @param longitudeE6 * the longitude of the point * @param reuse * just pass null if you do not have a Point to be 'recycled'. * @return intermediate value to be stored and passed to toMapPixelsTranslated. */ public Point toMapPixelsProjected(final int latituteE6, final int longitudeE6, final Point reuse) { final Point out = reuse != null ? reuse : new Point(); TileSystem .LatLongToPixelXY(latituteE6 / 1E6, longitudeE6 / 1E6, MAXIMUM_ZOOMLEVEL, out); return out; } /** * Performs the second computationally light part of the projection. Returns results in * <I>screen coordinates</I>. * * @param in * the Point calculated by the toMapPixelsProjected * @param reuse * just pass null if you do not have a Point to be 'recycled'. * @return the Point containing the <I>Screen coordinates</I> of the initial GeoPoint passed * to the toMapPixelsProjected. */ public Point toMapPixelsTranslated(final Point in, final Point reuse) { final Point out = reuse != null ? reuse : new Point(); final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel(); out.set((in.x >> zoomDifference) + offsetX, (in.y >> zoomDifference) + offsetY); return out; } /** * Translates a rectangle from <I>screen coordinates</I> to <I>intermediate coordinates</I>. * * @param in * the rectangle in <I>screen coordinates</I> * @return a rectangle in </I>intermediate coordindates</I>. */ public Rect fromPixelsToProjected(final Rect in) { final Rect result = new Rect(); final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel(); final int x0 = in.left - offsetX << zoomDifference; final int x1 = in.right - offsetX << zoomDifference; final int y0 = in.bottom - offsetY << zoomDifference; final int y1 = in.top - offsetY << zoomDifference; result.set(Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1)); return result; } /** * @deprecated Use TileSystem.TileXYToPixelXY */ @Deprecated public Point toPixels(final Point tileCoords, final Point reuse) { return toPixels(tileCoords.x, tileCoords.y, reuse); } /** * @deprecated Use TileSystem.TileXYToPixelXY */ @Deprecated public Point toPixels(final int tileX, final int tileY, final Point reuse) { return TileSystem.TileXYToPixelXY(tileX, tileY, reuse); } // not presently used public Rect toPixels(final BoundingBoxE6 pBoundingBoxE6) { final Rect rect = new Rect(); final Point reuse = new Point(); toMapPixels( new GeoPoint(pBoundingBoxE6.getLatNorthE6(), pBoundingBoxE6.getLonWestE6()), reuse); rect.left = reuse.x; rect.top = reuse.y; toMapPixels( new GeoPoint(pBoundingBoxE6.getLatSouthE6(), pBoundingBoxE6.getLonEastE6()), reuse); rect.right = reuse.x; rect.bottom = reuse.y; return rect; } @Override public float metersToEquatorPixels(final float meters) { return meters / (float) TileSystem.GroundResolution(0, mZoomLevelProjection); } @Override public Point toPixels(final IGeoPoint in, final Point out) { return toMapPixels(in, out); } @Override public IGeoPoint fromPixels(final int x, final int y) { return fromPixels((float) x, (float) y); } } private class MapViewGestureDetectorListener implements OnGestureListener { @Override public boolean onDown(final MotionEvent e) { if (MapView.this.getOverlayManager().onDown(e, MapView.this)) { return true; } mZoomController.setVisible(mEnableZoomController); return true; } @Override public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX, final float velocityY) { if (MapView.this.getOverlayManager() .onFling(e1, e2, velocityX, velocityY, MapView.this)) { return true; } final int worldSize = TileSystem.MapSize(MapView.this.getZoomLevel(false)); mScroller.fling(getScrollX(), getScrollY(), (int) -velocityX, (int) -velocityY, -worldSize, worldSize, -worldSize, worldSize); return true; } @Override public void onLongPress(final MotionEvent e) { if (mMultiTouchController != null && mMultiTouchController.isPinching()) { return; } MapView.this.getOverlayManager().onLongPress(e, MapView.this); } @Override public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX, final float distanceY) { if (MapView.this.getOverlayManager().onScroll(e1, e2, distanceX, distanceY, MapView.this)) { return true; } scrollBy((int) distanceX, (int) distanceY); return true; } @Override public void onShowPress(final MotionEvent e) { MapView.this.getOverlayManager().onShowPress(e, MapView.this); } @Override public boolean onSingleTapUp(final MotionEvent e) { if (MapView.this.getOverlayManager().onSingleTapUp(e, MapView.this)) { return true; } return false; } } private class MapViewDoubleClickListener implements GestureDetector.OnDoubleTapListener { @Override public boolean onDoubleTap(final MotionEvent e) { if (MapView.this.getOverlayManager().onDoubleTap(e, MapView.this)) { return true; } final IGeoPoint center = getProjection().fromPixels(e.getX(), e.getY()); return zoomInFixing(center); } @Override public boolean onDoubleTapEvent(final MotionEvent e) { if (MapView.this.getOverlayManager().onDoubleTapEvent(e, MapView.this)) { return true; } return false; } @Override public boolean onSingleTapConfirmed(final MotionEvent e) { if (MapView.this.getOverlayManager().onSingleTapConfirmed(e, MapView.this)) { return true; } return false; } } private class MapViewZoomListener implements OnZoomListener { @Override public void onZoom(final boolean zoomIn) { if (zoomIn) { getController().zoomIn(); } else { getController().zoomOut(); } } @Override public void onVisibilityChanged(final boolean visible) { } } // Public Classes /** * Per-child layout information associated with OpenStreetMapView. */ public static class LayoutParams extends ViewGroup.LayoutParams { /** * Special value for the alignment requested by a View. TOP_LEFT means that the location * will at the top left the View. */ public static final int TOP_LEFT = 1; /** * Special value for the alignment requested by a View. TOP_RIGHT means that the location * will be centered at the top of the View. */ public static final int TOP_CENTER = 2; /** * Special value for the alignment requested by a View. TOP_RIGHT means that the location * will at the top right the View. */ public static final int TOP_RIGHT = 3; /** * Special value for the alignment requested by a View. CENTER_LEFT means that the location * will at the center left the View. */ public static final int CENTER_LEFT = 4; /** * Special value for the alignment requested by a View. CENTER means that the location will * be centered at the center of the View. */ public static final int CENTER = 5; /** * Special value for the alignment requested by a View. CENTER_RIGHT means that the location * will at the center right the View. */ public static final int CENTER_RIGHT = 6; /** * Special value for the alignment requested by a View. BOTTOM_LEFT means that the location * will be at the bottom left of the View. */ public static final int BOTTOM_LEFT = 7; /** * Special value for the alignment requested by a View. BOTTOM_CENTER means that the * location will be centered at the bottom of the view. */ public static final int BOTTOM_CENTER = 8; /** * Special value for the alignment requested by a View. BOTTOM_RIGHT means that the location * will be at the bottom right of the View. */ public static final int BOTTOM_RIGHT = 9; /** * The location of the child within the map view. */ public IGeoPoint geoPoint; /** * The alignment the alignment of the view compared to the location. */ public int alignment; public int offsetX; public int offsetY; /** * Creates a new set of layout parameters with the specified width, height and location. * * @param width * the width, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size * in pixels * @param height * the height, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size * in pixels * @param geoPoint * the location of the child within the map view * @param alignment * the alignment of the view compared to the location {@link #BOTTOM_CENTER}, * {@link #BOTTOM_LEFT}, {@link #BOTTOM_RIGHT} {@link #TOP_CENTER}, * {@link #TOP_LEFT}, {@link #TOP_RIGHT} * @param offsetX * the additional X offset from the alignment location to draw the child within * the map view * @param offsetY * the additional Y offset from the alignment location to draw the child within * the map view */ public LayoutParams(final int width, final int height, final IGeoPoint geoPoint, final int alignment, final int offsetX, final int offsetY) { super(width, height); if (geoPoint != null) { this.geoPoint = geoPoint; } else { this.geoPoint = new GeoPoint(0, 0); } this.alignment = alignment; this.offsetX = offsetX; this.offsetY = offsetY; } /** * Since we cannot use XML files in this project this constructor is useless. Creates a new * set of layout parameters. The values are extracted from the supplied attributes set and * context. * * @param c * the application environment * @param attrs * the set of attributes fom which to extract the layout parameters values */ public LayoutParams(final Context c, final AttributeSet attrs) { super(c, attrs); this.geoPoint = new GeoPoint(0, 0); this.alignment = BOTTOM_CENTER; } /** * {@inheritDoc} */ public LayoutParams(final ViewGroup.LayoutParams source) { super(source); } } }
package com.intellij.usages; import com.intellij.injected.editor.DocumentWindow; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.lexer.Lexer; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.PlainSyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Segment; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import com.intellij.reference.SoftReference; import com.intellij.usageView.UsageTreeColors; import com.intellij.usageView.UsageTreeColorsScheme; import com.intellij.usages.impl.SyntaxHighlighterOverEditorHighlighter; import com.intellij.usages.impl.rules.UsageType; import com.intellij.util.containers.FactoryMap; import com.intellij.util.text.CharArrayUtil; import com.intellij.util.text.StringFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author peter */ public final class ChunkExtractor { private static final Logger LOG = Logger.getInstance(ChunkExtractor.class); static final int MAX_LINE_LENGTH_TO_SHOW = 200; static final int OFFSET_BEFORE_TO_SHOW_WHEN_LONG_LINE = 40; static final int OFFSET_AFTER_TO_SHOW_WHEN_LONG_LINE = 100; private final EditorColorsScheme myColorsScheme; private final Document myDocument; private long myDocumentStamp; private final SyntaxHighlighterOverEditorHighlighter myHighlighter; private abstract static class WeakFactory<T> { private WeakReference<T> myRef; @NotNull protected abstract T create(); @NotNull public T getValue() { final T cur = SoftReference.dereference(myRef); if (cur != null) return cur; final T result = create(); myRef = new WeakReference<>(result); return result; } } private static final ThreadLocal<WeakFactory<Map<PsiFile, ChunkExtractor>>> ourExtractors = ThreadLocal.withInitial( () -> new WeakFactory<Map<PsiFile, ChunkExtractor>>() { @NotNull @Override protected Map<PsiFile, ChunkExtractor> create() { return FactoryMap.create(psiFile -> new ChunkExtractor(psiFile)); } }); static TextChunk @NotNull [] extractChunks(@NotNull PsiFile file, @NotNull UsageInfo2UsageAdapter usageAdapter) { return getExtractor(file).extractChunks(usageAdapter, file); } @NotNull public static ChunkExtractor getExtractor(@NotNull PsiFile file) { return ourExtractors.get().getValue().get(file); } private ChunkExtractor(@NotNull PsiFile file) { myColorsScheme = UsageTreeColorsScheme.getInstance().getScheme(); Project project = file.getProject(); myDocument = PsiDocumentManager.getInstance(project).getDocument(file); LOG.assertTrue(myDocument != null); final FileType fileType = file.getFileType(); SyntaxHighlighter highlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, file.getVirtualFile()); highlighter = highlighter == null ? new PlainSyntaxHighlighter() : highlighter; myHighlighter = new SyntaxHighlighterOverEditorHighlighter(highlighter, file.getVirtualFile(), project); myDocumentStamp = -1; } public static int getStartOffset(final List<? extends RangeMarker> rangeMarkers) { LOG.assertTrue(!rangeMarkers.isEmpty()); int minStart = Integer.MAX_VALUE; for (RangeMarker rangeMarker : rangeMarkers) { if (!rangeMarker.isValid()) continue; final int startOffset = rangeMarker.getStartOffset(); if (startOffset < minStart) minStart = startOffset; } return minStart == Integer.MAX_VALUE ? -1 : minStart; } private TextChunk @NotNull [] extractChunks(@NotNull UsageInfo2UsageAdapter usageInfo2UsageAdapter, @NotNull PsiFile file) { int absoluteStartOffset = usageInfo2UsageAdapter.getNavigationOffset(); if (absoluteStartOffset == -1) return TextChunk.EMPTY_ARRAY; Document visibleDocument = myDocument instanceof DocumentWindow ? ((DocumentWindow)myDocument).getDelegate() : myDocument; int visibleStartOffset = myDocument instanceof DocumentWindow ? ((DocumentWindow)myDocument).injectedToHost(absoluteStartOffset) : absoluteStartOffset; int lineNumber = myDocument.getLineNumber(absoluteStartOffset); int visibleLineNumber = visibleDocument.getLineNumber(visibleStartOffset); List<TextChunk> result = new ArrayList<>(); appendPrefix(result, visibleLineNumber); int fragmentToShowStart = myDocument.getLineStartOffset(lineNumber); int fragmentToShowEnd = fragmentToShowStart < myDocument.getTextLength() ? myDocument.getLineEndOffset(lineNumber) : 0; if (fragmentToShowStart > fragmentToShowEnd) return TextChunk.EMPTY_ARRAY; final CharSequence chars = myDocument.getCharsSequence(); if (fragmentToShowEnd - fragmentToShowStart > MAX_LINE_LENGTH_TO_SHOW) { final int lineStartOffset = fragmentToShowStart; fragmentToShowStart = Math.max(lineStartOffset, absoluteStartOffset - OFFSET_BEFORE_TO_SHOW_WHEN_LONG_LINE); final int lineEndOffset = fragmentToShowEnd; Segment segment = usageInfo2UsageAdapter.getUsageInfo().getSegment(); int usage_length = segment != null ? segment.getEndOffset() - segment.getStartOffset():0; fragmentToShowEnd = Math.min(lineEndOffset, absoluteStartOffset + usage_length + OFFSET_AFTER_TO_SHOW_WHEN_LONG_LINE); // if we search something like a word, then expand shown context from one symbol before / after at least for word boundary // this should not cause restarts of the lexer as the tokens are usually words if (usage_length > 0 && StringUtil.isJavaIdentifierStart(chars.charAt(absoluteStartOffset)) && StringUtil.isJavaIdentifierStart(chars.charAt(absoluteStartOffset + usage_length - 1))) { while(fragmentToShowEnd < lineEndOffset && StringUtil.isJavaIdentifierStart(chars.charAt(fragmentToShowEnd - 1))) ++fragmentToShowEnd; while(fragmentToShowStart > lineStartOffset && StringUtil.isJavaIdentifierStart(chars.charAt(fragmentToShowStart))) --fragmentToShowStart; if (fragmentToShowStart != lineStartOffset) ++fragmentToShowStart; if (fragmentToShowEnd != lineEndOffset) --fragmentToShowEnd; } } if (myDocument instanceof DocumentWindow) { List<TextRange> editable = InjectedLanguageManager.getInstance(file.getProject()) .intersectWithAllEditableFragments(file, new TextRange(fragmentToShowStart, fragmentToShowEnd)); for (TextRange range : editable) { createTextChunks(usageInfo2UsageAdapter, chars, range.getStartOffset(), range.getEndOffset(), true, result); } return result.toArray(TextChunk.EMPTY_ARRAY); } return createTextChunks(usageInfo2UsageAdapter, chars, fragmentToShowStart, fragmentToShowEnd, true, result); } public TextChunk @NotNull [] createTextChunks(@NotNull UsageInfo2UsageAdapter usageInfo2UsageAdapter, @NotNull CharSequence chars, int start, int end, boolean selectUsageWithBold, @NotNull List<? super TextChunk> result) { final Lexer lexer = myHighlighter.getHighlightingLexer(); final SyntaxHighlighterOverEditorHighlighter highlighter = myHighlighter; LOG.assertTrue(start <= end); int i = StringUtil.indexOf(chars, '\n', start, end); if (i != -1) end = i; if (myDocumentStamp != myDocument.getModificationStamp()) { highlighter.restart(chars); myDocumentStamp = myDocument.getModificationStamp(); } else if(lexer.getTokenType() == null || lexer.getTokenStart() > start) { highlighter.resetPosition(0); // todo restart from nearest position with initial state } boolean isBeginning = true; for(;lexer.getTokenType() != null; lexer.advance()) { int hiStart = lexer.getTokenStart(); int hiEnd = lexer.getTokenEnd(); if (hiStart >= end) break; hiStart = Math.max(hiStart, start); hiEnd = Math.min(hiEnd, end); if (hiStart >= hiEnd) { continue; } if (isBeginning) { String text = chars.subSequence(hiStart, hiEnd).toString(); if(text.trim().isEmpty()) continue; } isBeginning = false; IElementType tokenType = lexer.getTokenType(); TextAttributesKey[] tokenHighlights = highlighter.getTokenHighlights(tokenType); processIntersectingRange(usageInfo2UsageAdapter, chars, hiStart, hiEnd, tokenHighlights, selectUsageWithBold, result); } return result.toArray(TextChunk.EMPTY_ARRAY); } private void processIntersectingRange(@NotNull UsageInfo2UsageAdapter usageInfo2UsageAdapter, @NotNull final CharSequence chars, int hiStart, final int hiEnd, final TextAttributesKey @NotNull [] tokenHighlights, final boolean selectUsageWithBold, @NotNull final List<? super TextChunk> result) { final TextAttributes originalAttrs = convertAttributes(tokenHighlights); if (selectUsageWithBold) { originalAttrs.setFontType(Font.PLAIN); } final int[] lastOffset = {hiStart}; usageInfo2UsageAdapter.processRangeMarkers(segment -> { int usageStart = segment.getStartOffset(); int usageEnd = segment.getEndOffset(); if (rangeIntersect(lastOffset[0], hiEnd, usageStart, usageEnd)) { addChunk(chars, lastOffset[0], Math.max(lastOffset[0], usageStart), originalAttrs, false, null, result); UsageType usageType = isHighlightedAsString(tokenHighlights) ? UsageType.LITERAL_USAGE : isHighlightedAsComment(tokenHighlights) ? UsageType.COMMENT_USAGE : null; addChunk(chars, Math.max(lastOffset[0], usageStart), Math.min(hiEnd, usageEnd), originalAttrs, selectUsageWithBold, usageType, result); lastOffset[0] = usageEnd; if (usageEnd > hiEnd) { return false; } } return true; }); if (lastOffset[0] < hiEnd) { addChunk(chars, lastOffset[0], hiEnd, originalAttrs, false, null, result); } } public static boolean isHighlightedAsComment(TextAttributesKey... keys) { for (TextAttributesKey key : keys) { if (key == DefaultLanguageHighlighterColors.DOC_COMMENT || key == DefaultLanguageHighlighterColors.LINE_COMMENT || key == DefaultLanguageHighlighterColors.BLOCK_COMMENT ) { return true; } if (key == null) continue; final TextAttributesKey fallbackAttributeKey = key.getFallbackAttributeKey(); if (fallbackAttributeKey != null && isHighlightedAsComment(fallbackAttributeKey)) { return true; } } return false; } public static boolean isHighlightedAsString(TextAttributesKey... keys) { for (TextAttributesKey key : keys) { if (key == DefaultLanguageHighlighterColors.STRING) { return true; } if (key == null) continue; final TextAttributesKey fallbackAttributeKey = key.getFallbackAttributeKey(); if (fallbackAttributeKey != null && isHighlightedAsString(fallbackAttributeKey)) { return true; } } return false; } private static void addChunk(@NotNull CharSequence chars, int start, int end, @NotNull TextAttributes originalAttrs, boolean bold, @Nullable UsageType usageType, @NotNull List<? super TextChunk> result) { if (start >= end) return; TextAttributes attrs = bold ? TextAttributes.merge(originalAttrs, new TextAttributes(null, null, null, null, Font.BOLD)) : originalAttrs; result.add(new TextChunk(attrs, StringFactory.createShared(CharArrayUtil.fromSequence(chars, start, end)), usageType)); } private static boolean rangeIntersect(int s1, int e1, int s2, int e2) { return s2 < s1 && s1 < e2 || s2 < e1 && e1 < e2 || s1 < s2 && s2 < e1 || s1 < e2 && e2 < e1 || s1 == s2 && e1 == e2; } @NotNull private TextAttributes convertAttributes(TextAttributesKey @NotNull [] keys) { TextAttributes attrs = myColorsScheme.getAttributes(HighlighterColors.TEXT); for (TextAttributesKey key : keys) { TextAttributes attrs2 = myColorsScheme.getAttributes(key); if (attrs2 != null) { attrs = TextAttributes.merge(attrs, attrs2); } } attrs = attrs.clone(); return attrs; } private void appendPrefix(@NotNull List<? super TextChunk> result, int lineNumber) { result.add(new TextChunk(myColorsScheme.getAttributes(UsageTreeColors.USAGE_LOCATION), String.valueOf(lineNumber + 1))); } }
package com.google.sps.data; import com.google.sps.data.Query; import com.google.sps.data.SentimentTools; import com.google.sps.data.Video; // Represents a video analysis, holds the results from an analysis and can also analyze a video that is passed in. public class VideoAnalysis { private float sentimentScore; private float sentimentMagnitude; private String query; private static int QUERY_SIZE = 7; //If given a video we will run analysis on it !!THIS IS SLOWER THAN JUST PASSING IN THE VALUES IF YOU HAVE THEM!! public VideoAnalysis(Video video) { SentimentTools sentimentAnalysis = new SentimentTools(video); Query queryAnalysis = new Query(video, QUERY_SIZE); this.sentimentScore = sentimentAnalysis.getScore(); this.sentimentMagnitude = sentimentAnalysis.getMagnitude(); this.query = queryAnalysis.toString(); } //Pass in the results from a Video analysis to create this object public VideoAnalysis(float _sentimentScore, float _sentimentMagnitude, String _query) { this.sentimentScore = _sentimentScore; this.sentimentMagnitude = _sentimentMagnitude; this.query = _query; } public void setSentimentScore(float score){ this.sentimentScore = score; } public float getSentimentScore(){ return this.sentimentScore; } public void setSentimentMagnitude(float magnitude) { this.sentimentMagnitude = magnitude; } public float getSentimentMagnitude() { return this.sentimentMagnitude; } public void setQuery(String query){ this.query = query; } public String getQuery(){ return this.query; } }
package snake; import java.awt.AWTException; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Robot; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import javax.imageio.ImageIO; import javax.swing.JPanel; import javax.swing.Timer; import utilityClasses.*; public class SnakePanel extends JPanel implements ActionListener, KeyListener { private boolean startGame = true; private boolean playing = false; private boolean paused = false; private boolean endGame = false; private boolean nameEnter = false; private boolean highScores = false; private boolean autoPlay = false; private ScoreInfo scores = new ScoreInfo("snake"); private String pName = ""; private Character letter; private ArrayList<Point> snakeBody = new ArrayList<Point>(); private ArrayList<Color> snakeColor = new ArrayList<Color>(); private Color[] Colors = { Color.CYAN, Color.RED, Color.GREEN, Color.YELLOW, Color.ORANGE, Color.WHITE }; private int bodySize = 10; private Point head = new Point(250, 250); private int numOfFruits = 4; // private int fruitX = 300; // private int fruitY = 200; private ArrayList<Integer> fruitX = new ArrayList<Integer>(); private ArrayList<Integer> fruitY = new ArrayList<Integer>(); // private Color fruitColor = Color.WHITE; private ArrayList<Color> fruitColor = new ArrayList<Color>(); private int deltaX = 0; private int deltaY = -bodySize; private int prevLoseKey = KeyEvent.VK_DOWN; private int upKey = KeyEvent.VK_UP; private int downKey = KeyEvent.VK_DOWN; private int leftKey = KeyEvent.VK_LEFT; private int rightKey = KeyEvent.VK_RIGHT; private int[] keyMap = { KeyEvent.VK_UP, KeyEvent.VK_RIGHT, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT }; private int keyIndex = 0; private Timer timer; private int origSpeed = 10; private double speed = origSpeed; private int score = 0; public SnakePanel() { // for (Point x : snakeBody) { // // System.out.print(x.x + " " + x.y); // // System.out.println(); setBackground(Color.BLACK); setFocusable(true); addKeyListener(this); randFruitSetup(); timer = new Timer((int) (1000 / speed), this); resetBody(); timer.start(); } public void actionPerformed(ActionEvent e) { moves(); } public void moves() { if (playing) { head.x += deltaX; head.y += deltaY; for (int i = snakeBody.size() - 1; i > 0; i if (head.x == snakeBody.get(i).x && head.y == snakeBody.get(i).y) { playing = false; nameEnter = true; } snakeBody.set(i, snakeBody.get(i - 1)); } snakeBody.set(0, new Point(head.x, head.y)); int nextHeadX = head.x + deltaX; int nextHeadY = head.y + deltaY; for (int i = 0; i < fruitX.size(); i++) { int fx = fruitX.get(i); int fy = fruitY.get(i); if (Math.abs(head.x - fx) < 5 && Math.abs(head.y - fy) < 5) { addBodySquare(i); } } if (autoPlay) { autonomous(); } if (head.x < 1 || head.x > 485 || head.y < 8 || head.y > 465) { playing = false; nameEnter = true; } } repaint(); } public void autonomous() { int nextHeadX = head.x + deltaX; int nextHeadY = head.y + deltaY; // if (Math.abs(head.x - fruitX) < 5 || Math.abs(head.y - fruitY) < 5) { if ((head.x < 1 + bodySize || head.x > 485 - bodySize) && deltaX != 0) { deltaX = 0; deltaY = (head.y - fruitY.get(0) > 0) ? -bodySize : bodySize; } if ((head.y < 8 + bodySize || head.y > 465 - bodySize) && deltaY != 0) { deltaY = 0; deltaX = (head.x - fruitX.get(0) > 0) ? -bodySize : bodySize; } // if ((head.y < 8 + bodySize || head.y > 465 - bodySize) && (head.x < 1 // + bodySize || head.x > 485 - bodySize)) { for (int i = 0; i < fruitX.size(); i++) { int fruitXx = fruitX.get(i); int fruitYy = fruitY.get(i); if (Math.abs(head.x - fruitX.get(0)) < 5) { deltaX = 0; deltaY = (head.y - fruitY.get(0) > 0) ? -bodySize : bodySize; // deltaY = (head.y - fruitY == 0) ? deltaY : (head.y - fruitY > // ? -bodySize : bodySize; // addBodySquare(); } if (Math.abs(head.y - fruitY.get(0)) < 5) { deltaY = 0; deltaX = (head.x - fruitX.get(0) > 0) ? -bodySize : bodySize; // deltaX = (head.x - fruitX == 0) ? deltaX : (head.x - fruitX > // ? -bodySize : bodySize; // addBodySquare(); } } } public void addBodySquare(int fruitIndex) { int lastBodyX = snakeBody.get(snakeBody.size() - 1).x; int lastBodyY = snakeBody.get(snakeBody.size() - 1).y; int secondLastBodyX = snakeBody.get(snakeBody.size() - 2).x; int secondLastBodyY = snakeBody.get(snakeBody.size() - 2).y; int changeX = lastBodyX - secondLastBodyX; int changeY = lastBodyY - secondLastBodyY; snakeBody.add(new Point(lastBodyX + changeX, lastBodyY + changeY)); snakeColor.add(fruitColor.get(fruitIndex)); fruitX.set(fruitIndex, randNum()); fruitY.set(fruitIndex, randNum()); fruitColor.set(fruitIndex, randColor()); speed += .5; // System.out.println(speed); // System.out.println((int) (1000.0 / speed)); timer.setDelay((int) (1000.0 / speed)); score++; } public void resetBody() { snakeBody.clear(); snakeColor.clear(); snakeBody.add(new Point(250, 250)); snakeBody.add(new Point(250, 260)); snakeBody.add(new Point(250, 270)); snakeBody.add(new Point(250, 280)); for (int i = 0; i < snakeBody.size(); i++) { // Whoop // snakeColor.add(randColor()); snakeColor.add(Color.WHITE); } head.x = 250; head.y = 250; deltaY = -bodySize; deltaX = 0; prevLoseKey = KeyEvent.VK_DOWN; speed = origSpeed; timer.setDelay((int) (1000.0 / speed)); // timer = new Timer((int) (1000 / speed), this); // timer.start(); } public void setKeys() { upKey = keyMap[0]; rightKey = keyMap[1]; downKey = keyMap[2]; leftKey = keyMap[3]; } public int randNum() { return ((int) (Math.random() * 45)) * 10 + 10; } public Color randColor() { return Colors[(int) (Math.random() * Colors.length)]; } public void randFruitSetup() { fruitX.clear(); fruitY.clear(); for (int i = 0; i < numOfFruits; i++) { fruitX.add(randNum()); fruitY.add(randNum()); fruitColor.add(randColor()); } } public int randFruitNum() { return (int) (Math.random() * fruitColor.size()); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.WHITE); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(15)); g2.drawRect(0, 0, 499, 477); g2.setStroke(new BasicStroke(2)); if (startGame) { g.setFont(new Font("Joystix", Font.BOLD, 80)); CenteredText title1 = new CenteredText("SNAKE!!", 500, 500, g, true, 180); drawColorOptions(g, 415); g.setFont(new Font("Joystix", Font.BOLD, 20)); CenteredText start1 = new CenteredText("Press Enter to", 500, 500, g, true, 300); CenteredText start2 = new CenteredText("Start", 500, 500, g, true, 330); g.setFont(new Font("Joystix", Font.BOLD, 12)); CenteredText keyMapInstruct = new CenteredText( "Press keys Up, Right, Down, Left to map new keys", 500, 500, g, true, 30); } else if (playing || paused) { g.setFont(new Font("Joystix", Font.BOLD, 40)); g.setColor(Color.WHITE); CenteredText score1 = new CenteredText(String.valueOf(score), 500, 500, g, true, 450); int i = 0; for (Point body : snakeBody) { g.setColor(snakeColor.get(i)); i++; g.fillRect(body.x, body.y, bodySize, bodySize); g.setColor(Color.BLACK); g.drawRect(body.x, body.y, bodySize, bodySize); } for (i = 0; i < fruitX.size(); i++) { g.setColor(Color.BLACK); int fx = fruitX.get(i); int fy = fruitY.get(i); g.drawRect(fx, fy, bodySize, bodySize); // g.setColor(Color.WHITE); g.setColor(fruitColor.get(i)); g.fillRect(fx + 1, fy + 1, bodySize - 2, bodySize - 2); } if (paused) { g.setFont(new Font("Joystix", Font.BOLD, 60)); g.setColor(Color.WHITE); CenteredText pause = new CenteredText("Paused", 500, 500, g, true, 200); drawColorOptions(g, 300); } } else if (endGame) { g.setFont(new Font("Joystix", Font.BOLD, 40)); g.setColor(Color.WHITE); CenteredText score1 = new CenteredText(String.valueOf(score), 500, 500, g, true, 450); g.setFont(new Font("Joystix", Font.BOLD, 60)); CenteredText lose = new CenteredText("You Lose!", 500, 500, g, true, 170); g.setFont(new Font("Joystix", Font.BOLD, 26)); CenteredText restart = new CenteredText("Enter to Restart", 500, 500, g, true, 320); } else if (nameEnter) { scores.enterName(g, 500, 500, snakeBody.size(), pName); } else if (highScores) { // scores.setScores(timeSeconds, pName); scores.drawScores(g); } } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub if (startGame && e.getKeyCode() != KeyEvent.VK_ENTER) { keyMap[keyIndex] = e.getKeyCode(); keyIndex++; if (keyIndex > 3) keyIndex = 0; } else if (e.getKeyCode() == prevLoseKey) { // playing = false; // nameEnter = true; } else if (e.getKeyCode() == upKey) { deltaX = 0; deltaY = -bodySize; prevLoseKey = downKey; } else if (e.getKeyCode() == downKey) { deltaX = 0; deltaY = bodySize; prevLoseKey = upKey; } else if (e.getKeyCode() == leftKey) { deltaY = 0; deltaX = -bodySize; prevLoseKey = rightKey; } else if (e.getKeyCode() == rightKey) { deltaY = 0; deltaX = bodySize; prevLoseKey = leftKey; } else if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (startGame) { playing = true; startGame = false; setKeys(); } else if (endGame) { resetBody(); startGame = false; playing = true; nameEnter = false; highScores = false; endGame = false; pName = ""; randFruitSetup(); speed = 10; score = 0; } else if (nameEnter) { nameEnter = false; highScores = true; scores.setScores(score, pName); } else if (highScores) { highScores = false; endGame = true; } else { startGame = false; playing = true; } } else if (e.getKeyCode() == KeyEvent.VK_SPACE && !nameEnter) { playing = !playing; paused = !paused; } else if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_STANDARD && nameEnter) { if (pName.length() < 10) { letter = e.getKeyChar(); letter = Character.toUpperCase(letter); pName = pName.concat(letter.toString()); } } else if (e.getKeyCode() == KeyEvent.VK_M && playing) { autoPlay = !autoPlay; } else { // if (startGame || endGame) { switch (e.getKeyCode()) { case KeyEvent.VK_R: fruitColor.set(randFruitNum(), Color.RED); break; case KeyEvent.VK_G: fruitColor.set(randFruitNum(), Color.GREEN); break; case KeyEvent.VK_B: fruitColor.set(randFruitNum(), Color.CYAN); break; case KeyEvent.VK_Y: fruitColor.set(randFruitNum(), Color.YELLOW); break; case KeyEvent.VK_O: fruitColor.set(randFruitNum(), Color.ORANGE); break; case KeyEvent.VK_W: // VK_W - White is default case fruitColor.set(randFruitNum(), Color.WHITE); break; } } } public void drawColorOptions(Graphics g, int colorY) { g.setFont(new Font(Font.DIALOG, Font.BOLD, 45)); g.setColor(Color.RED); g.drawString("R", 50, colorY); g.setColor(Color.GREEN); g.drawString("G", 140, colorY); g.setColor(Color.CYAN); g.drawString("B", 230, colorY); g.setColor(Color.YELLOW); g.drawString("Y", 315, colorY); g.setColor(Color.ORANGE); g.drawString("O", 410, colorY); // g.setColor(Color.BLACK); // g.drawString("W", 500, colorY); g.setColor(Color.WHITE); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } }
package is.mpg.ruglan; import java.util.Calendar; import java.util.Date; import java.lang.IllegalArgumentException; /** * Class representing Calendar Event for the project. * @author Siggi */ public class CalEvent { private String name, description, location; private Date start, end; /** * CalEvent has the following attributes: * - name: * A string holding the name of the event. * - location: * A string holding the location of the event. * - description: * A string holding the description of the event. * - start: * A Date object holding start date and time of the event. * - end: * A Date object holding end date and time of the event. */ /** * @use CalEvent e = new CalEvent("A", "B", "C", s, e); * @pre s and e have the same date and s < e. * @post e is a new instance of type CalEvent. e has the name * * @param name Name of the event. * @param description Description of the event. * @param location Location of the event. * @param start Start date of the event. * @param end End date of the event. * @return A object of type CalEvent */ public CalEvent(String name, String description, String location, Date start, Date end) { Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(start); cal2.setTime(end); boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR); if (!sameDay) { throw new IllegalArgumentException("start date and end date need to be on the same day."); } if (start.compareTo(end) >= 0) { throw new IllegalArgumentException("end date needs to be after start date."); } this.name = name; this.description = description; this.location = location; this.start = start; this.end = end; } /** * @use String s = e.getName(); * @pre e is an instance of CalEvent. * @post s is the name of the CalEvent e. * * @return Name of the event. */ public String getName() { return this.name; } /** * @use String s = e.getDescription(); * @pre e is an instance of CalEvent. * @post s is the description of the CalEvent e. * * @return Description of the event. */ public String getDescription() { return this.description; } /** * @use String s = e.getLocation(); * @pre e is an instance of CalEvent. * @post s is the location of the CalEvent e. * * @return Location of the event. */ public String getLocation() { return this.location; } /** * @use Date d = e.getStart(); * @pre e is an instance of CalEvent. * @post d is the start time of the CalEvent e. * * @return Start date of the event. */ public Date getStart() { return this.start; } /** * @use Date d = e.getEnd(); * @pre e is an instance of CalEvent. * @post d is the end time of the CalEvent e. * * @return End date of the event. */ public Date getEnd() { return this.end; } /** * @use s = e.toString(); * @pre Nothing; * @post s is a string that represents this event * * @return A string representation of the event. */ public String toString(){ return this.getName() + " " + this.getDescription() + " " + this.getLocation() + " " + this.getStart() + " " + this.getEnd(); } }
package com.markelintl.pq.data; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class AddressTest { @Test public void compareTo_should_fail_on_mismatch() throws IOException { final String[][] testData = new String[][]{ {"Toront", "Canada", "200 Wellington Street West", "Suite 400", "Ontario", "M5V 3C7"}, {"Toronto", "Canad", "200 Wellington Street West", "Suite 400", "Ontario", "M5V 3C7"}, {"Toronto", "Canada", "200 Wellington Street Wes", "Suite 400", "Ontario", "M5V 3C7"}, {"Toronto", "Canada", "200 Wellington Street West", "Suite 40", "Ontario", "M5V 3C7"}, {"Toronto", "Canada", "200 Wellington Street West", "Suite 400", "Ontari", "M5V 3C7"}, {"Toronto", "Canada", "200 Wellington Street West", "Suite 400", "Ontario", "M5V 3C"}, }; final Address actual = DataFixtures.addressFixture(); for (int i = 0; i < testData.length; i++) { final String[] d = testData[i]; final Address expected = new Address(d[0], d[1], new String[]{d[2], d[3]}, d[4], d[5]); assertThat("expected " + i + " to not equal fixture but did", actual.compareTo(expected), is(not(0))); } } @Test public void compareTo_should_fail_on_line_mismatch() { final Address expected = new Address("Toronto", "Canada", new String[]{"200 Wellington Street West", "Suite 40"}, "Ontario", "M5V 3C7"); final Address actual = new Address("Toronto", "Canada", new String[]{"200 Wellington Street West"}, "Ontario", "M5V 3C7"); assertThat(actual.compareTo(expected), is(1)); } @Test public void compareTo_should_succeed_with_valid_address() throws IOException { final Address expected = new Address("Toronto", "Canada", new String[]{"200 Wellington Street West", "Suite 400"}, "Ontario", "M5V 3C7"); final Address actual = DataFixtures.addressFixture(); assertThat(actual.compareTo(expected), is(0)); } @Test public void toString_should_concatenate_fields_in_ascending_order() { final Address address = new Address("A", "B", new String[]{"C", "D"}, "E", "F"); assertThat(address.toString(), is("ABCDEF")); } @Test public void mapper_should_serialise_empty_json() throws IOException { final ObjectMapper om = new ObjectMapper(); final Address address = om.readValue("{}", Address.class); assertThat(address.toString(), is("")); } }
package com.zwenexsys.reverse; import com.squareup.okhttp.OkHttpClient; import com.zwenexsys.reverse.models.AddressComponent; import com.zwenexsys.reverse.models.Maps; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.OkClient; import retrofit.client.Response; public class ReverseGeo { // There are more attributes depends on location public static final String ROUTE = "route"; public static final String NEIGHBORHOOD = "neighborhood"; public static final String SUBLOCALITY = "sublocality"; public static final String LOCALITY = "locality"; public static final String COUNTRY = "country"; private static final String BASE_URL = "http://maps.googleapis.com/maps/api/geocode/"; private final OkHttpClient client = new OkHttpClient(); private String shortName; private String latLng; private String type; /** * Accept the already concatenated string as param * @param latLng the concatenated lat/lng string */ public ReverseGeo(String latLng) { this.latLng = latLng; } /** * Accept two double latitude and longitude as param * * @param lat - latitude * @param lng - longitude */ public ReverseGeo(double lat, double lng) { this.latLng = String.valueOf(lat) + "," + String.valueOf(lng); } /** * Return the type of location * * @return type of location */ public String getType() { return this.type; } public void setType(String type) { if (type == null) { throw new NullPointerException("Type may not be null."); } else if (type.equals(ROUTE)) { this.type = ROUTE; } else if (type.equals(NEIGHBORHOOD)) { this.type = NEIGHBORHOOD; } else if (type.equals(SUBLOCALITY)) { this.type = SUBLOCALITY; } else if (type.equals(LOCALITY)) { this.type = LOCALITY; } else if (type.equals(COUNTRY)) { this.type = COUNTRY; } else { this.type = LOCALITY; } } public String getShortNameAsync() { RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(BASE_URL) .setClient(new OkClient(client)) .setLogLevel(RestAdapter.LogLevel.BASIC) .build(); MapServiceAsync service = restAdapter.create(MapServiceAsync.class); service.getResult(latLng, new Callback<Maps>() { @Override public void success(Maps maps, Response response) { List<AddressComponent> components = maps.getResults().get(0).getAddressComponents(); for (AddressComponent component : components) { List<String> types = component.getTypes(); for (String s : types) { if (type.equalsIgnoreCase(ROUTE) && s.equalsIgnoreCase(ROUTE)) { shortName = component.getShortName(); } else if (type.equalsIgnoreCase(NEIGHBORHOOD) && s.equalsIgnoreCase(NEIGHBORHOOD)) { shortName = component.getShortName(); } else if (type.equalsIgnoreCase(LOCALITY) && s.equalsIgnoreCase(LOCALITY)) { shortName = component.getShortName(); } else if (type.equalsIgnoreCase(COUNTRY) && s.equalsIgnoreCase(COUNTRY)) { shortName = component.getShortName(); } } } } @Override public void failure(RetrofitError error) { error.printStackTrace(); } }); return shortName; } public String getShortNameSync() { RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(BASE_URL) .setClient(new OkClient(client)) .setLogLevel(RestAdapter.LogLevel.BASIC) .build(); MapServiceSync service = restAdapter.create(MapServiceSync.class); Maps maps = service.getResult(latLng); List<AddressComponent> components = maps.getResults().get(0).getAddressComponents(); for (AddressComponent component : components) { List<String> types = component.getTypes(); for (String s : types) { if (type.equalsIgnoreCase(ROUTE) && s.equalsIgnoreCase(ROUTE)) { shortName = component.getShortName(); } else if (type.equalsIgnoreCase(NEIGHBORHOOD) && s.equalsIgnoreCase(NEIGHBORHOOD)) { shortName = component.getShortName(); } else if (type.equalsIgnoreCase(LOCALITY) && s.equalsIgnoreCase(LOCALITY)) { shortName = component.getShortName(); } else if (type.equalsIgnoreCase(COUNTRY) && s.equalsIgnoreCase(COUNTRY)) { shortName = component.getShortName(); } } } return shortName; } }
package net.i2p.router.transport.tcp; import java.net.Socket; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import net.i2p.data.DataHelper; import net.i2p.data.Hash; import net.i2p.data.RouterAddress; import net.i2p.data.RouterIdentity; import net.i2p.data.RouterInfo; import net.i2p.data.SigningPrivateKey; import net.i2p.router.JobImpl; import net.i2p.router.OutNetMessage; import net.i2p.router.RouterContext; import net.i2p.router.transport.TransportBid; import net.i2p.router.transport.TransportImpl; import net.i2p.util.I2PThread; import net.i2p.util.Log; /** * Defines a way to send a message to another peer and start listening for messages * */ public class TCPTransport extends TransportImpl { private Log _log; public final static String STYLE = "TCP"; private List _listeners; private Map _connections; // routerIdentity --> List of TCPConnection private String _listenHost; private int _listenPort; private RouterAddress _address; private boolean _listenAddressIsValid; private Map _msgs; // H(ident) --> PendingMessages for unestablished connections private boolean _running; private int _numConnectionEstablishers; private final static String PROP_ESTABLISHERS = "i2np.tcp.concurrentEstablishers"; private final static int DEFAULT_ESTABLISHERS = 3; public static String PROP_LISTEN_IS_VALID = "i2np.tcp.listenAddressIsValid"; /** * pre 1.4 java doesn't have a way to timeout the creation of sockets (which * can take up to 3 minutes), so we do it on a seperate thread and wait for * either that thread to complete, or for this timeout to be reached. */ final static long SOCKET_CREATE_TIMEOUT = 10*1000; public TCPTransport(RouterContext context, RouterAddress address) { super(context); _log = context.logManager().getLog(TCPTransport.class); if (_context == null) throw new RuntimeException("Context is null"); if (_context.statManager() == null) throw new RuntimeException("Stat manager is null"); _context.statManager().createFrequencyStat("tcp.attemptFailureFrequency", "How often do we attempt to contact someone, and fail?", "TCP Transport", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l }); _context.statManager().createFrequencyStat("tcp.attemptSuccessFrequency", "How often do we attempt to contact someone, and succeed?", "TCP Transport", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l }); _context.statManager().createFrequencyStat("tcp.acceptFailureFrequency", "How often do we reject someone who contacts us?", "TCP Transport", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l }); _context.statManager().createFrequencyStat("tcp.acceptSuccessFrequency", "How often do we accept someone who contacts us?", "TCP Transport", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l }); _context.statManager().createRateStat("tcp.connectionLifetime", "How long do connections last (measured when they close)?", "TCP Transport", new long[] { 60*1000l, 60*60*1000l, 24*60*60*1000l }); _listeners = new ArrayList(); _connections = new HashMap(); _msgs = new HashMap(); _address = address; if (address != null) { _listenHost = address.getOptions().getProperty(TCPAddress.PROP_HOST); String portStr = address.getOptions().getProperty(TCPAddress.PROP_PORT); try { _listenPort = Integer.parseInt(portStr); } catch (NumberFormatException nfe) { _log.error("Invalid port: " + portStr + " Address: \n" + address, nfe); } } _listenAddressIsValid = false; try { String setting = _context.router().getConfigSetting(PROP_LISTEN_IS_VALID); _listenAddressIsValid = Boolean.TRUE.toString().equalsIgnoreCase(setting); } catch (Throwable t) { _listenAddressIsValid = false; if (_log.shouldLog(Log.WARN)) _log.warn("Unable to determine whether TCP listening address is valid, so we're assuming it isn't. Set " + PROP_LISTEN_IS_VALID + " otherwise"); } _running = false; } boolean getListenAddressIsValid() { return _listenAddressIsValid; } SigningPrivateKey getMySigningKey() { return _context.keyManager().getSigningPrivateKey(); } int getListenPort() { return _listenPort; } /** fetch all of our TCP listening addresses */ TCPAddress[] getMyAddresses() { if (_address != null) { TCPAddress rv[] = new TCPAddress[1]; rv[0] = new TCPAddress(_listenHost, _listenPort); return rv; } else { return new TCPAddress[0]; } } /** * This message is called whenever a new message is added to the send pool, * and it should not block */ protected void outboundMessageReady() { //_context.jobQueue().addJob(new NextJob()); NextJob j = new NextJob(); j.runJob(); } private class NextJob extends JobImpl { public NextJob() { super(TCPTransport.this._context); } public void runJob() { OutNetMessage msg = getNextMessage(); if (msg != null) { handleOutbound(msg); // this just adds to either the establish thread's queue or the conn's queue } else { if (_log.shouldLog(Log.DEBUG)) _log.debug("OutboundMessageReady called, but none were available"); } } public String getName() { return "TCP Message Ready to send"; } } /** * Return a random connection to the peer from the set of known connections * */ private TCPConnection getConnection(RouterIdentity peer) { synchronized (_connections) { if (!_connections.containsKey(peer)) return null; List cons = (List)_connections.get(peer); if (cons.size() <= 0) return null; TCPConnection first = (TCPConnection)cons.get(0); return first; } } protected void handleOutbound(OutNetMessage msg) { msg.timestamp("TCPTransport.handleOutbound before handleConnection"); TCPConnection con = getConnection(msg.getTarget().getIdentity()); if (con == null) { if (_log.shouldLog(Log.DEBUG)) _log.debug("Handling outbound message to an unestablished peer"); msg.timestamp("TCPTransport.handleOutbound to addPending"); addPending(msg); } else { if (_log.shouldLog(Log.DEBUG)) _log.debug("Toss the message onto an established peer's connection"); msg.timestamp("TCPTransport.handleOutbound to con.addMessage"); con.addMessage(msg); } } protected boolean establishConnection(RouterInfo target) { long startEstablish = 0; long socketCreated = 0; long conCreated = 0; long conEstablished = 0; try { for (Iterator iter = target.getAddresses().iterator(); iter.hasNext(); ) { RouterAddress addr = (RouterAddress)iter.next(); startEstablish = _context.clock().now(); if (getStyle().equals(addr.getTransportStyle())) { if (_log.shouldLog(Log.DEBUG)) _log.debug("Establishing a connection with address " + addr); Socket s = createSocket(addr); socketCreated = _context.clock().now(); if (s == null) { if (_log.shouldLog(Log.WARN)) _log.warn("Unable to establish a socket in time to " + addr); _context.profileManager().commErrorOccurred(target.getIdentity().getHash()); _context.shitlist().shitlistRouter(target.getIdentity().getHash(), "Unable to contact host"); return false; } if (_log.shouldLog(Log.DEBUG)) _log.debug("Socket created"); TCPConnection con = new RestrictiveTCPConnection(_context, s, true); conCreated = _context.clock().now(); if (_log.shouldLog(Log.DEBUG)) _log.debug("TCPConnection created"); boolean established = handleConnection(con, target); conEstablished = _context.clock().now(); if (_log.shouldLog(Log.DEBUG)) _log.debug("connection handled"); return established; } } _context.shitlist().shitlistRouter(target.getIdentity().getHash(), "No addresses we can handle"); return false; } catch (Throwable t) { if (_log.shouldLog(Log.WARN)) _log.warn("Unexpected error establishing the connection", t); _context.shitlist().shitlistRouter(target.getIdentity().getHash(), "Internal error connecting"); return false; } finally { long diff = conEstablished - startEstablish; if ( ( (diff > 6000) || (conEstablished == 0) ) && (_log.shouldLog(Log.WARN)) ) { _log.warn("establishConnection took too long: socketCreate: " + (socketCreated-startEstablish) + "ms conCreated: " + (conCreated-socketCreated) + "ms conEstablished: " + (conEstablished - conCreated) + "ms overall: " + diff); } } } protected Socket createSocket(RouterAddress addr) { String host = addr.getOptions().getProperty(TCPAddress.PROP_HOST); String portStr = addr.getOptions().getProperty(TCPAddress.PROP_PORT); int port = -1; try { port = Integer.parseInt(portStr); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.ERROR)) _log.error("Invalid port number in router address: " + portStr, nfe); return null; } long start = _context.clock().now(); SocketCreator creator = new SocketCreator(host, port); I2PThread sockCreator = new I2PThread(creator); sockCreator.setDaemon(true); sockCreator.setName("SocketCreator_:" + _listenPort); //sockCreator.setPriority(I2PThread.MIN_PRIORITY); sockCreator.start(); try { synchronized (creator) { creator.wait(SOCKET_CREATE_TIMEOUT); } } catch (InterruptedException ie) {} long finish = _context.clock().now(); long diff = finish - start; if (diff > 6000) { if (_log.shouldLog(Log.WARN)) _log.warn("Creating a new socket took too long? wtf?! " + diff + "ms for " + host + ':' + port); } return creator.getSocket(); } private boolean isConnected(RouterInfo info) { return (null != getConnection(info.getIdentity())); } public TransportBid bid(RouterInfo toAddress, long dataSize) { TCPConnection con = getConnection(toAddress.getIdentity()); int latencyStartup = 0; if (con == null) latencyStartup = 2000; else latencyStartup = 0; int sendTime = (int)((dataSize)/(16*1024)); // 16K/sec int bytes = (int)dataSize+8; if (con != null) sendTime += 50000 * con.getPendingMessageCount(); // try to avoid backed up (throttled) connections TransportBid bid = new TransportBid(); bid.setBandwidthBytes(bytes); bid.setExpiration(new Date(_context.clock().now()+1000*60)); // 1 minute bid.setLatencyMs(latencyStartup + sendTime); bid.setMessageSize((int)dataSize); bid.setRouter(toAddress); bid.setTransport(this); RouterAddress addr = getTargetAddress(toAddress); if (addr == null) { if (con == null) { if (_log.shouldLog(Log.INFO)) _log.info("No address or connection to " + toAddress.getIdentity().getHash().toBase64()); // don't bid if we can't send them a message return null; } else { if (_log.shouldLog(Log.DEBUG)) _log.debug("No address, but we're connected to " + toAddress.getIdentity().getHash().toBase64()); } } return bid; } public void rotateAddresses() { // noop } public void addAddressInfo(Properties infoForNewAddress) { // noop } public RouterAddress startListening() { RouterAddress address = new RouterAddress(); address.setTransportStyle(getStyle()); address.setCost(10); address.setExpiration(null); Properties options = new Properties(); if (_address != null) { options.setProperty(TCPAddress.PROP_HOST, _listenHost); options.setProperty(TCPAddress.PROP_PORT, _listenPort+""); } address.setOptions(options); if (_address != null) { try { TCPAddress addr = new TCPAddress(); addr.setHost(_listenHost); addr.setPort(_listenPort); TCPListener listener = new TCPListener(_context, this); listener.setAddress(addr); _listeners.add(listener); listener.startListening(); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.ERROR)) _log.error("Error parsing port number", nfe); } addCurrentAddress(address); } String str = _context.router().getConfigSetting(PROP_ESTABLISHERS); if (str != null) { try { _numConnectionEstablishers = Integer.parseInt(str); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.ERROR)) _log.error("Invalid number of connection establishers [" + str + "]"); _numConnectionEstablishers = DEFAULT_ESTABLISHERS; } } else { _numConnectionEstablishers = DEFAULT_ESTABLISHERS; } _running = true; for (int i = 0; i < _numConnectionEstablishers; i++) { Thread t = new I2PThread(new ConnEstablisher(i)); t.setDaemon(true); t.start(); } return address; } public void stopListening() { if (_log.shouldLog(Log.ERROR)) _log.error("Stop listening called! No more TCP", new Exception("Die tcp, die")); _running = false; for (int i = 0; i < _listeners.size(); i++) { TCPListener lsnr = (TCPListener)_listeners.get(i); lsnr.stopListening(); } Set allCons = new HashSet(); synchronized (_connections) { for (Iterator iter = _connections.values().iterator(); iter.hasNext(); ) { List cons = (List)iter.next(); for (Iterator citer = cons.iterator(); citer.hasNext(); ) { TCPConnection con = (TCPConnection)citer.next(); allCons.add(con); } } } for (Iterator iter = allCons.iterator(); iter.hasNext(); ) { TCPConnection con = (TCPConnection)iter.next(); con.closeConnection(); } } public RouterIdentity getMyIdentity() { return _context.router().getRouterInfo().getIdentity(); } void connectionClosed(TCPConnection con) { if (_log.shouldLog(Log.INFO)) _log.info("Connection closed with " + con.getRemoteRouterIdentity()); StringBuffer buf = new StringBuffer(256); buf.append("Still connected to: "); synchronized (_connections) { List cons = (List)_connections.get(con.getRemoteRouterIdentity()); if ( (cons != null) && (cons.size() > 0) ) { cons.remove(con); long lifetime = con.getLifetime(); if (_log.shouldLog(Log.INFO)) _log.info("Connection closed (with remaining) after lifetime " + lifetime); _context.statManager().addRateData("tcp.connectionLifetime", lifetime, 0); } Set toRemove = new HashSet(); for (Iterator iter = _connections.keySet().iterator(); iter.hasNext();) { RouterIdentity ident = (RouterIdentity)iter.next(); List all = (List)_connections.get(ident); if (all.size() > 0) buf.append(ident.getHash().toBase64()).append(" "); else toRemove.add(ident); } for (Iterator iter = toRemove.iterator(); iter.hasNext(); ) { _connections.remove(iter.next()); } } if (_log.shouldLog(Log.INFO)) _log.info(buf.toString()); //if (con.getRemoteRouterIdentity() != null) } boolean handleConnection(TCPConnection con, RouterInfo target) { con.setTransport(this); if (_log.shouldLog(Log.DEBUG)) _log.debug("Before establishing connection"); long start = _context.clock().now(); RouterIdentity ident = con.establishConnection(); long afterEstablish = _context.clock().now(); long startRunning = 0; if (ident == null) { _context.statManager().updateFrequency("tcp.acceptFailureFrequency"); con.closeConnection(); return false; } if (_log.shouldLog(Log.INFO)) _log.info("Connection established with " + ident + " after " + (afterEstablish-start) + "ms"); if (target != null) { if (!target.getIdentity().equals(ident)) { _context.statManager().updateFrequency("tcp.acceptFailureFrequency"); if (_log.shouldLog(Log.ERROR)) _log.error("Target changed identities!!! was " + target.getIdentity().getHash().toBase64() + ", now is " + ident.getHash().toBase64() + "! DROPPING CONNECTION"); con.closeConnection(); // remove the old ref, since they likely just created a new identity _context.netDb().fail(target.getIdentity().getHash()); _context.shitlist().shitlistRouter(target.getIdentity().getHash(), "Peer changed identities"); return false; } else { if (_log.shouldLog(Log.DEBUG)) _log.debug("Target is the same as who we connected with"); } } if (ident != null) { Set toClose = new HashSet(4); List toAdd = new LinkedList(); synchronized (_connections) { if (!_connections.containsKey(ident)) _connections.put(ident, new ArrayList(2)); List cons = (List)_connections.get(ident); if (cons.size() > 0) { if (_log.shouldLog(Log.WARN)) _log.warn("Attempted to open additional connections with " + ident.getHash() + ": closing older connections", new Exception("multiple cons")); while (cons.size() > 0) { TCPConnection oldCon = (TCPConnection)cons.remove(0); toAdd.addAll(oldCon.getPendingMessages()); toClose.add(oldCon); } } cons.add(con); Set toRemove = new HashSet(); for (Iterator iter = _connections.keySet().iterator(); iter.hasNext();) { RouterIdentity cur = (RouterIdentity)iter.next(); List all = (List)_connections.get(cur); if (all.size() <= 0) toRemove.add(ident); } for (Iterator iter = toRemove.iterator(); iter.hasNext(); ) { _connections.remove(iter.next()); } } if (toAdd.size() > 0) { for (Iterator iter = toAdd.iterator(); iter.hasNext(); ) { OutNetMessage msg = (OutNetMessage)iter.next(); con.addMessage(msg); } if (_log.shouldLog(Log.INFO)) _log.info("Transferring " + toAdd.size() + " messages from old cons to the newly established con"); } _context.shitlist().unshitlistRouter(ident.getHash()); con.runConnection(); startRunning = _context.clock().now(); if (toClose.size() > 0) { for (Iterator iter = toClose.iterator(); iter.hasNext(); ) { TCPConnection oldCon = (TCPConnection)iter.next(); if (_log.shouldLog(Log.INFO)) _log.info("Closing old duplicate connection " + oldCon.toString(), new Exception("Closing old con")); oldCon.closeConnection(); _context.statManager().addRateData("tcp.connectionLifetime", oldCon.getLifetime(), 0); } } long done = _context.clock().now(); long diff = done - start; if ( (diff > 3*1000) && (_log.shouldLog(Log.WARN)) ) { _log.warn("handleConnection took too long: " + diff + "ms with " + (afterEstablish-start) + "ms to establish " + (startRunning-afterEstablish) + "ms to start running " + (done-startRunning) + "ms to cleanup"); } if (_log.shouldLog(Log.DEBUG)) _log.debug("runConnection called on the con"); } _context.statManager().updateFrequency("tcp.acceptSuccessFrequency"); return true; } public String getStyle() { return STYLE; } public String renderStatusHTML() { StringBuffer buf = new StringBuffer(); Map cons = new HashMap(); synchronized (_connections) { cons.putAll(_connections); } int established = 0; buf.append("<b>TCP Transport</b> <i>(").append(cons.size()).append(" connections)</i><br />\n"); buf.append("<ul>"); for (Iterator iter = cons.keySet().iterator(); iter.hasNext(); ) { buf.append("<li>"); RouterIdentity ident = (RouterIdentity)iter.next(); List curCons = (List)cons.get(ident); buf.append("Connection to ").append(ident.getHash().toBase64()).append(": "); String lifetime = null; for (int i = 0; i < curCons.size(); i++) { TCPConnection con = (TCPConnection)curCons.get(i); if (con.getLifetime() > 30*1000) { established++; lifetime = DataHelper.formatDuration(con.getLifetime()); } } if (lifetime != null) buf.append(lifetime); else buf.append("[pending]"); buf.append("</li>\n"); } buf.append("</ul>\n"); if (established == 0) { buf.append("<b><font color=\"red\">No TCP connections</font></b><ul>"); buf.append("<li>Is your publicly reachable IP address / hostname <b>").append(_listenHost).append("</b>?</li>\n"); buf.append("<li>Is your firewall / NAT open to receive connections on port <b>").append(_listenPort).append("</b>?</li>\n"); buf.append("<li>Do you have any reachable peer references (see down below for \"Routers\", "); buf.append(" or check your netDb directory - you want at least two routers, since one of them is your own)</li>\n"); buf.append("</ul>\n"); } return buf.toString(); } /** * only establish one connection at a time, and if multiple requests are pooled * for the same one, once one is established send all the messages through * */ private class ConnEstablisher implements Runnable { private int _id; public ConnEstablisher(int id) { _id = id; } public int getId() { return _id; } public void run() { Thread.currentThread().setName("Conn Establisher" + _id + ':' + _listenPort); while (_running) { try { PendingMessages pending = nextPeer(this); long start = _context.clock().now(); if (_log.shouldLog(Log.INFO)) _log.info("Beginning establishment with " + pending.getPeer().toBase64() + " [not error]"); TCPConnection con = getConnection(pending.getPeerInfo().getIdentity()); long conFetched = _context.clock().now(); long sentPending = 0; long establishedCon = 0; long refetchedCon = 0; long sentRefetched = 0; long failedPending = 0; if (con != null) { sendPending(con, pending); sentPending = _context.clock().now(); } else { boolean established = establishConnection(pending.getPeerInfo()); establishedCon = _context.clock().now(); if (established) { _context.statManager().updateFrequency("tcp.attemptSuccessFrequency"); if (_log.shouldLog(Log.DEBUG)) _log.debug("Connection established"); con = getConnection(pending.getPeerInfo().getIdentity()); refetchedCon = _context.clock().now(); if (con == null) { if (_log.shouldLog(Log.ERROR)) _log.error("Connection established but we can't find the connection? wtf! peer = " + pending.getPeer()); } else { _context.shitlist().unshitlistRouter(pending.getPeer()); sendPending(con, pending); sentRefetched = _context.clock().now(); } } else { _context.statManager().updateFrequency("tcp.attemptFailureFrequency"); if (_log.shouldLog(Log.INFO)) _log.info("Unable to establish a connection to " + pending.getPeer()); failPending(pending); // shitlisted by establishConnection with a more detailed reason //_context.shitlist().shitlistRouter(pending.getPeer(), "Unable to contact host"); //ProfileManager.getInstance().commErrorOccurred(pending.getPeer()); failedPending = _context.clock().now(); } } long end = _context.clock().now(); long diff = end - start; StringBuffer buf = new StringBuffer(128); buf.append("Time to establish with ").append(pending.getPeer().toBase64()).append(": ").append(diff).append("ms"); buf.append(" fetched: ").append(conFetched-start).append(" ms"); if (sentPending != 0) buf.append(" sendPending: ").append(sentPending - conFetched).append("ms"); if (establishedCon != 0) { buf.append(" established: ").append(establishedCon - conFetched).append("ms"); if (refetchedCon != 0) { buf.append(" refetched: ").append(refetchedCon - establishedCon).append("ms"); if (sentRefetched != 0) { buf.append(" sentRefetched: ").append(sentRefetched - refetchedCon).append("ms"); } } else { buf.append(" failedPending: ").append(failedPending - establishedCon).append("ms"); } } if (diff > 6000) { if (_log.shouldLog(Log.WARN)) _log.warn(buf.toString()); } else { if (_log.shouldLog(Log.INFO)) _log.info(buf.toString()); } } catch (Throwable t) { if (_log.shouldLog(Log.CRIT)) _log.log(Log.CRIT, "Error in connection establisher thread - NO MORE CONNECTIONS", t); } } } } /** * Add a new message to the outbound pool to be established asap (may be sent * along existing connections if they appear later) * */ public void addPending(OutNetMessage msg) { synchronized (_msgs) { Hash target = msg.getTarget().getIdentity().getHash(); PendingMessages msgs = (PendingMessages)_msgs.get(target); if (msgs == null) { msgs = new PendingMessages(msg.getTarget()); msgs.addPending(msg); _msgs.put(target, msgs); if (_log.shouldLog(Log.DEBUG)) _log.debug("Adding a pending to new " + target.toBase64()); } else { msgs.addPending(msg); if (_log.shouldLog(Log.DEBUG)) _log.debug("Adding a pending to existing " + target.toBase64()); } int level = Log.INFO; if (msgs.getMessageCount() > 1) level = Log.WARN; if (_log.shouldLog(level)) _log.log(level, "Add message to " + target.toBase64() + ", making a total of " + msgs.getMessageCount() + " for them, with another " + (_msgs.size() -1) + " peers pending establishment"); _msgs.notifyAll(); } msg.timestamp("TCPTransport.addPending finished and notified"); } /** * blocking call to claim the next available targeted peer. does a wait on * the _msgs pool which should be notified from addPending. * */ private PendingMessages nextPeer(ConnEstablisher establisher) { PendingMessages rv = null; while (true) { synchronized (_msgs) { if (_msgs.size() <= 0) { try { _msgs.wait(); } catch (InterruptedException ie) {} } if (_msgs.size() > 0) { for (Iterator iter = _msgs.keySet().iterator(); iter.hasNext(); ) { Object key = iter.next(); rv = (PendingMessages)_msgs.get(key); if (!rv.setEstablisher(establisher)) { // unable to claim this peer if (_log.shouldLog(Log.INFO)) _log.info("Peer is still in process: " + rv.getPeer() + " on establisher " + rv.getEstablisher().getId()); rv = null; } else { if (_log.shouldLog(Log.INFO)) _log.info("Returning next peer " + rv.getPeer().toBase64()); return rv; } } // all of the messages refer to a connection being established try { _msgs.wait(); } catch (InterruptedException ie) {} } } } } /** * Send all the messages targetting the given location * over the established connection * */ private void sendPending(TCPConnection con, PendingMessages pending) { if (con == null) { if (_log.shouldLog(Log.ERROR)) _log.error("Send pending to null con?", new Exception("Hmm")); return; } if (pending == null) { if (_log.shouldLog(Log.ERROR)) _log.error("Null pending, 'eh?", new Exception("Hmm..")); return; } if (_log.shouldLog(Log.INFO)) _log.info("Connection established, now queueing up " + pending.getMessageCount() + " messages to be sent"); synchronized (_msgs) { _msgs.remove(pending.getPeer()); OutNetMessage msg = null; while ( (msg = pending.getNextMessage()) != null) { msg.timestamp("TCPTransport.sendPending to con.addMessage"); con.addMessage(msg); } } } /** * Fail out all messages pending to the specified peer */ private void failPending(PendingMessages pending) { if (pending != null) { synchronized (_msgs) { _msgs.remove(pending.getPeer()); } OutNetMessage msg = null; while ( (msg = pending.getNextMessage()) != null) { afterSend(msg, false); } } } /** * Coordinate messages for a particular peer that hasn't been established yet * */ private static class PendingMessages { private List _messages; private Hash _peer; private RouterInfo _peerInfo; private ConnEstablisher _establisher; public PendingMessages(RouterInfo peer) { _messages = new LinkedList(); _peerInfo = peer; _peer = peer.getIdentity().getHash(); _establisher = null; } /** * Claim a peer for a specific establisher * * @return true if the claim was successful, false if someone beat us to it */ public boolean setEstablisher(ConnEstablisher establisher) { synchronized (PendingMessages.this) { if (_establisher == null) { _establisher = establisher; return true; } else { return false; } } } public ConnEstablisher getEstablisher() { return _establisher; } /** * Add a new message to this to-be-established connection */ public void addPending(OutNetMessage msg) { synchronized (_messages) { _messages.add(msg); } } /** * Get the next message queued up for delivery on this connection being established * */ public OutNetMessage getNextMessage() { synchronized (_messages) { if (_messages.size() <= 0) return null; else return (OutNetMessage)_messages.remove(0); } } /** * Get the number of messages queued up for this to be established connection * */ public int getMessageCount() { synchronized (_messages) { return _messages.size(); } } /** who are we going to establish with? */ public Hash getPeer() { return _peer; } /** who are we going to establish with? */ public RouterInfo getPeerInfo() { return _peerInfo; } } }
package uk.org.ponder.rsf.processor; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import uk.org.ponder.rsf.renderer.RenderSystemDecoder; import uk.org.ponder.rsf.request.EarlyRequestParser; import uk.org.ponder.rsf.request.FossilizedConverter; import uk.org.ponder.rsf.request.RequestSubmittedValueCache; import uk.org.ponder.rsf.request.SVESorter; import uk.org.ponder.rsf.request.SubmittedValueEntry; import uk.org.ponder.util.Logger; /** * A request-scope bean whose job is to determine the (topologically sorted) set * of submitted request submitted values for this POST request. If this is a * RENDER request, returns an empty list. * * @author Antranig Basman (antranig@caret.cam.ac.uk) * */ public class PostDecoder { private FossilizedConverter fossilizedconverter; private RenderSystemDecoder rendersystemdecoder; private Map requestparams; private String requesttype; private Map normalizedrequest; private RequestSubmittedValueCache requestrsvc; public void setFossilizedConverter(FossilizedConverter fossilizedconverter) { this.fossilizedconverter = fossilizedconverter; } public void setRenderSystemDecoder(RenderSystemDecoder rendersystemdecoder) { this.rendersystemdecoder = rendersystemdecoder; } public void setRequestMap(Map requestparams) { this.requestparams = requestparams; } public void setRequestType(String requesttype) { this.requesttype = requesttype; } public void init() { normalizedrequest = new HashMap(); normalizedrequest.putAll(requestparams); rendersystemdecoder.normalizeRequestMap(normalizedrequest); } // This method is expected to be called by accreteRSVC public void parseRequest(RequestSubmittedValueCache rsvc) { // Firstly acquire all non-component ("pure") bindings for (Iterator keyit = normalizedrequest.keySet().iterator(); keyit .hasNext();) { String key = (String) keyit.next(); String[] values = (String[]) normalizedrequest.get(key); Logger.log.info("PostInit: key " + key + " value " + values[0]); if (fossilizedconverter.isNonComponentBinding(key)) { for (int i = 0; i < values.length; ++ i) { // EL binding key is fixed, there may be many values SubmittedValueEntry sve = fossilizedconverter.parseBinding(key, values[i]); rsvc.addEntry(sve); Logger.log.info("Discovered noncomponent binding for " + sve.valuebinding + " rvalue " + sve.newvalue); } } // Secondly assess whether this was a component fossilised binding. else if (fossilizedconverter.isFossilisedBinding(key) && values.length > 0) { SubmittedValueEntry sve = fossilizedconverter.parseFossil(key, values[0]); // Grab dependent values which we can now deduce may be in the request String[] newvalue = (String[]) normalizedrequest.get(sve.componentid); sve.newvalue = newvalue; fossilizedconverter.fixupNewValue(sve, rendersystemdecoder, key, values[0]); String[] reshaper = (String[]) normalizedrequest.get(fossilizedconverter.getReshaperKey(sve.componentid)); if (reshaper != null) { sve.reshaperbinding = reshaper[0]; } Logger.log.info("Discovered fossilised binding for " + sve.valuebinding + " for component " + sve.componentid + " with old value " + sve.oldvalue); rsvc.addEntry(sve); } } } public RequestSubmittedValueCache getRequestRSVC() { if (requestrsvc == null) { requestrsvc = new RequestSubmittedValueCache(); if (requesttype.equals(EarlyRequestParser.ACTION_REQUEST)) { RequestSubmittedValueCache newvalues = new RequestSubmittedValueCache(); parseRequest(newvalues); // Topologically sort the fresh values (which may be arbitrarily // disordered through passing the request) in order of intrinsic // dependency. SVESorter sorter = new SVESorter(newvalues); List sorted = sorter.getSortedRSVC(); for (int i = 0; i < sorted.size(); ++i) { requestrsvc.addEntry((SubmittedValueEntry) sorted.get(i)); } } } return requestrsvc; } public Map getNormalizedRequest() { return normalizedrequest; } public static String decodeAction(Map normalizedrequest) { String[] actionmethods = (String[]) normalizedrequest .get(SubmittedValueEntry.FAST_TRACK_ACTION); if (actionmethods != null) { String actionmethod = actionmethods[0]; //actionmethod = BeanUtil.stripEL(actionmethod); return actionmethod; } return null; } public static String decodeSubmittingControl(Map normalized) { // This SHOULD be set if an RSF submitting response is required String[] array = (String[]) normalized .get(SubmittedValueEntry.SUBMITTING_CONTROL); return array == null? null : array[0]; } }
package com.s3auth.hosts; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.DeleteItemRequest; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import com.amazonaws.services.dynamodbv2.model.ScanRequest; import com.amazonaws.services.dynamodbv2.model.ScanResult; import com.google.common.collect.ImmutableMap; import com.jcabi.aspects.Cacheable; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.manifests.Manifests; import com.jcabi.urn.URN; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Abstraction on top of DynamoDB SDK. * * <p>The class is mutable and thread-safe. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 0.0.1 * @checkstyle ClassDataAbstractionCoupling (500 lines) * @todo #1 Would be nice to migrate to jcabi-dynamo */ @Immutable @ToString @EqualsAndHashCode(of = { "client", "table" }) @Loggable(Loggable.INFO) final class DefaultDynamo implements Dynamo { /** * Dynamo DB key, URN of a user. */ public static final String USER = "user.urn"; /** * Dynamo DB key, name of domain. */ public static final String NAME = "domain.name"; /** * Dynamo DB key, AWS key of bucket. */ public static final String KEY = "domain.key"; /** * Dynamo DB key, AWS secret of bucket. */ public static final String SECRET = "domain.secret"; /** * Dynamo DB key, AWS S3 region of bucket. */ public static final String REGION = "domain.region"; /** * Dynamo DB key, Syslog host and port of domain. */ public static final String SYSLOG = "domain.syslog"; /** * Lifetime of registry in memory, in minutes. */ private static final int LIFETIME = 5; /** * Client. */ private final transient Dynamo.Client client; /** * Table name. */ private final transient String table; /** * Public ctor. */ DefaultDynamo() { this( new Dynamo.Client() { @Override public AmazonDynamoDB get() { final AmazonDynamoDB aws = new AmazonDynamoDBClient( new BasicAWSCredentials( Manifests.read("S3Auth-AwsDynamoKey"), Manifests.read("S3Auth-AwsDynamoSecret") ) ); // @checkstyle MultipleStringLiterals (1 line) if (Manifests.exists("S3Auth-AwsDynamoEntryPoint")) { aws.setEndpoint( Manifests.read("S3Auth-AwsDynamoEntryPoint") ); } return aws; } }, Manifests.read("S3Auth-AwsDynamoTable") ); } /** * Ctor for unit tests. * @param clnt The client to Dynamo DB * @param tbl Table name */ DefaultDynamo(@NotNull final Dynamo.Client clnt, @NotNull final String tbl) { this.client = clnt; this.table = tbl; } @Override public void close() { // nothing to do } @Override @NotNull @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") @Cacheable(lifetime = DefaultDynamo.LIFETIME, unit = TimeUnit.MINUTES) public ConcurrentMap<URN, Domains> load() throws IOException { final ConcurrentMap<URN, Domains> domains = new ConcurrentHashMap<URN, Domains>(0); final AmazonDynamoDB amazon = this.client.get(); final ScanResult result = amazon.scan(new ScanRequest(this.table)); for (final Map<String, AttributeValue> item : result.getItems()) { final String syslog; if (item.containsKey(DefaultDynamo.SYSLOG)) { syslog = item.get(DefaultDynamo.SYSLOG).getS(); } else { syslog = ""; } final URN user = URN.create(item.get(DefaultDynamo.USER).getS()); domains.putIfAbsent(user, new Domains()); domains.get(user).add( new DefaultDomain( item.get(DefaultDynamo.NAME).getS(), item.get(DefaultDynamo.KEY).getS(), item.get(DefaultDynamo.SECRET).getS(), item.get(DefaultDynamo.REGION).getS(), syslog ) ); } amazon.shutdown(); return domains; } @Override @Cacheable.FlushBefore public boolean add(@NotNull final URN user, @NotNull final Domain domain) throws IOException { final ConcurrentMap<String, AttributeValue> attrs = new ConcurrentHashMap<String, AttributeValue>(0); attrs.put(DefaultDynamo.USER, new AttributeValue(user.toString())); attrs.put(DefaultDynamo.NAME, new AttributeValue(domain.name())); attrs.put(DefaultDynamo.KEY, new AttributeValue(domain.key())); attrs.put(DefaultDynamo.SECRET, new AttributeValue(domain.secret())); attrs.put(DefaultDynamo.REGION, new AttributeValue(domain.region())); attrs.put(DefaultDynamo.SYSLOG, new AttributeValue(domain.syslog())); final AmazonDynamoDB amazon = this.client.get(); amazon.putItem(new PutItemRequest(this.table, attrs)); amazon.shutdown(); return true; } @Override @Cacheable.FlushBefore public boolean remove(@NotNull final Domain domain) throws IOException { final AmazonDynamoDB amazon = this.client.get(); amazon.deleteItem( new DeleteItemRequest( this.table, new ImmutableMap.Builder<String, AttributeValue>() .put(DefaultDynamo.NAME, new AttributeValue(domain.name())) .build() ) ); amazon.shutdown(); return true; } }
package br.com.softctrl.utils; import java.util.Comparator; import java.util.List; import java.util.Map; /** * This class consists of {@code static} utility methods for operating * on objects. These utilities include {@code null}-safe or {@code * null}-tolerant methods for computing the hash code of an object, * returning a string for an object, and comparing two objects. * * @since 1.7 */ public final class Objects { private Objects() { throw new AssertionError("No br.com.softctrl.utils.Objects instances for you!"); } /** * * @author carlostimoshenkorodrigueslopes@gmail.com * */ public static class StringHelper { private StringBuilder mDescription = new StringBuilder(); private java.util.HashMap<String, Object> mFields = new java.util.HashMap<String, Object>(); /** * * @param clazz */ private StringHelper(final Class<?> clazz) { this.mDescription.append("Class<").append(clazz.getSimpleName()).append('>').append(':').append(' '); } public StringHelper add(String name, Object value) { this.mFields.put(name, value); return this; } @Override public String toString() { StringBuilder result = new StringBuilder('{'); for (Map.Entry<String, Object> field : this.mFields.entrySet()) { result.append(field.getKey()).append(':').append(' ').append(field.getValue()).append(' '); } return this.mDescription.append(result).append('}').toString(); } } /** * * @param clazz * @return */ public static StringHelper toStringHelper(final Class<?> clazz) { return new StringHelper(clazz); } /** * Returns {@code true} if the arguments are equal to each other * and {@code false} otherwise. * Consequently, if both arguments are {@code null}, {@code true} * is returned and if exactly one argument is {@code null}, {@code * false} is returned. Otherwise, equality is determined by using * the {@link Object#equals equals} method of the first * argument. * * @param a an object * @param b an object to be compared with {@code a} for equality * @return {@code true} if the arguments are equal to each other * and {@code false} otherwise * @see Object#equals(Object) */ public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); } /** * Returns {@code true} if the arguments are deeply equal to each other * and {@code false} otherwise. * * Two {@code null} values are deeply equal. If both arguments are * arrays, the algorithm in {@link Arrays#deepEquals(Object[], * Object[]) Arrays.deepEquals} is used to determine equality. * Otherwise, equality is determined by using the {@link * Object#equals equals} method of the first argument. * * @param a an object * @param b an object to be compared with {@code a} for deep equality * @return {@code true} if the arguments are deeply equal to each other * and {@code false} otherwise * @see Arrays#deepEquals(Object[], Object[]) * @see Objects#equals(Object, Object) */ public static boolean deepEquals(Object a, Object b) { if (a == b) return true; else if (a == null || b == null) return false; else return Arrays.deepEquals0(a, b); } /** * Returns the hash code of a non-{@code null} argument and 0 for * a {@code null} argument. * * @param o an object * @return the hash code of a non-{@code null} argument and 0 for * a {@code null} argument * @see Object#hashCode */ public static int hashCode(Object o) { return o != null ? o.hashCode() : 0; } /** * Generates a hash code for a sequence of input values. The hash * code is generated as if all the input values were placed into an * array, and that array were hashed by calling {@link * Arrays#hashCode(Object[])}. * * <p>This method is useful for implementing {@link * Object#hashCode()} on objects containing multiple fields. For * example, if an object that has three fields, {@code x}, {@code * y}, and {@code z}, one could write: * * <blockquote><pre> * &#064;Override public int hashCode() { * return Objects.hash(x, y, z); * } * </pre></blockquote> * * <b>Warning: When a single object reference is supplied, the returned * value does not equal the hash code of that object reference.</b> This * value can be computed by calling {@link #hashCode(Object)}. * * @param values the values to be hashed * @return a hash value of the sequence of input values * @see Arrays#hashCode(Object[]) * @see List#hashCode */ public static int hash(Object... values) { return Arrays.hashCode(values); } /** * Returns the result of calling {@code toString} for a non-{@code * null} argument and {@code "null"} for a {@code null} argument. * * @param o an object * @return the result of calling {@code toString} for a non-{@code * null} argument and {@code "null"} for a {@code null} argument * @see Object#toString * @see String#valueOf(Object) */ public static String toString(Object o) { return String.valueOf(o); } public static <T> String toString(T o) { return String.valueOf(o); } /** * Returns the result of calling {@code toString} on the first * argument if the first argument is not {@code null} and returns * the second argument otherwise. * * @param o an object * @param nullDefault string to return if the first argument is * {@code null} * @return the result of calling {@code toString} on the first * argument if it is not {@code null} and the second argument * otherwise. * @see Objects#toString(Object) */ public static String toString(Object o, String nullDefault) { return (o != null) ? o.toString() : nullDefault; } /** * Returns 0 if the arguments are identical and {@code * c.compare(a, b)} otherwise. * Consequently, if both arguments are {@code null} 0 * is returned. * * <p>Note that if one of the arguments is {@code null}, a {@code * NullPointerException} may or may not be thrown depending on * what ordering policy, if any, the {@link Comparator Comparator} * chooses to have for {@code null} values. * * @param <T> the type of the objects being compared * @param a an object * @param b an object to be compared with {@code a} * @param c the {@code Comparator} to compare the first two arguments * @return 0 if the arguments are identical and {@code * c.compare(a, b)} otherwise. * @see Comparable * @see Comparator */ public static <T> int compare(T a, T b, Comparator<? super T> c) { return (a == b) ? 0 : c.compare(a, b); } /** * Checks that the specified object reference is not {@code null}. This * method is designed primarily for doing parameter validation in methods * and constructors, as demonstrated below: * <blockquote><pre> * public Foo(Bar bar) { * this.bar = Objects.requireNonNull(bar); * } * </pre></blockquote> * * @param obj the object reference to check for nullity * @param <T> the type of the reference * @return {@code obj} if not {@code null} * @throws NullPointerException if {@code obj} is {@code null} */ public static <T> T requireNonNull(T obj) { if (obj == null) throw new NullPointerException(); return obj; } /** * Checks that the specified object reference is not {@code null} and * throws a customized {@link NullPointerException} if it is. This method * is designed primarily for doing parameter validation in methods and * constructors with multiple parameters, as demonstrated below: * <blockquote><pre> * public Foo(Bar bar, Baz baz) { * this.bar = Objects.requireNonNull(bar, "bar must not be null"); * this.baz = Objects.requireNonNull(baz, "baz must not be null"); * } * </pre></blockquote> * * @param obj the object reference to check for nullity * @param message detail message to be used in the event that a {@code * NullPointerException} is thrown * @param <T> the type of the reference * @return {@code obj} if not {@code null} * @throws NullPointerException if {@code obj} is {@code null} */ public static <T> T requireNonNull(T obj, String message) { if (obj == null) throw new NullPointerException(message); return obj; } /** * Returns {@code true} if the provided reference is {@code null} otherwise * returns {@code false}. * * @apiNote This method exists to be used as a * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)} * * @param obj a reference to be checked against {@code null} * @return {@code true} if the provided reference is {@code null} otherwise * {@code false} * * @see java.util.function.Predicate * @since 1.8 */ public static boolean isNull(Object obj) { return obj == null; } /** * * @param obj * @return */ public static <T> boolean isNull(T obj) { return (obj == null); } /** * * @param value * @return */ public static boolean isNullOrEmpty(String value) { return ((value + "").trim().length() == 0); } /** * * @param items * @return */ public static boolean isNullOrEmpty(Object[] items) { return (isNull(items) ? true : (items.length == 0)); } /** * * @param items * @return */ public static <T> boolean isNullOrEmpty(T[] items) { return (isNull(items) ? true : (items.length == 0)); } /** * * @param items * @return */ public static <T> boolean isNullOrEmpty(List<T> items) { return (isNull(items) ? true : (items.size() == 0)); } /** * Returns {@code true} if the provided reference is non-{@code null} * otherwise returns {@code false}. * * @apiNote This method exists to be used as a * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)} * * @param obj a reference to be checked against {@code null} * @return {@code true} if the provided reference is non-{@code null} * otherwise {@code false} * * @see java.util.function.Predicate * @since 1.8 */ public static <T> boolean nonNull(T obj) { return obj != null; } /** * * @param value * @return */ public static boolean nonNullOrEmpty(String value) { return (value != null && value.trim().length() > 0); } /** * * @param tArray * @return */ public static <T> boolean nonNullOrEmpty(T[] tArray) { return (tArray != null && tArray.length > 0); } /** * * @param map * @return */ public static <K, V> boolean nonNullOrEmpty(Map<K, V> map) { return (map != null && map.size() > 0); } /** * * @param tArray * @return */ public static <T> boolean nonNullOrEmpty(List<T> tList) { return (tList != null && tList.size() > 0); } /** * * @param value * @param defaultValue * @return */ public static <T> T thisOrDefault(T value, T defaultValue) { return (T) (value == null ? requireNonNull(defaultValue, "Seriously!!"): value); } /** * * @author carlostimoshenkorodrigueslopes@gmail.com * */ public static class ToString { private static final String FORM = "[%s = %s]"; private StringBuilder toString; ToString(){ this.toString = new StringBuilder(); } ToString(Class<?> clazz){ this.toString = new StringBuilder(clazz.getSimpleName()); } public ToString append(Object value, String description){ this.toString.append(String.format(FORM, description, Objects.toString(value))); return this; } @Override public String toString() { return this.toString.toString(); } } /** * * @return */ public ToString ToString(){ return new ToString(); } /** * * @param clazz * @return */ public ToString ToString(Class<?> clazz){ return new ToString(clazz); } }
package com.cloud.network.firewall; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.api.commands.ListFirewallRulesCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventVO; import com.cloud.event.dao.EventDao; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IPAddressVO; import com.cloud.network.IpAddress; import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.dao.FirewallRulesCidrsDao; import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.rules.FirewallManager; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.FirewallRuleType; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRule.State; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.PortForwardingRuleVO; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.DomainManager; import com.cloud.user.UserContext; import com.cloud.utils.Pair; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.vm.UserVmVO; import com.cloud.vm.dao.UserVmDao; @Local(value = { FirewallService.class, FirewallManager.class }) public class FirewallManagerImpl implements FirewallService, FirewallManager, Manager{ private static final Logger s_logger = Logger.getLogger(FirewallManagerImpl.class); String _name; @Inject FirewallRulesDao _firewallDao; @Inject IPAddressDao _ipAddressDao; @Inject EventDao _eventDao; @Inject DomainDao _domainDao; @Inject FirewallRulesCidrsDao _firewallCidrsDao; @Inject AccountManager _accountMgr; @Inject NetworkManager _networkMgr; @Inject UsageEventDao _usageEventDao; @Inject ConfigurationDao _configDao; @Inject DomainManager _domainMgr; @Inject PortForwardingRulesDao _pfRulesDao; @Inject UserVmDao _vmDao; private boolean _elbEnabled=false; @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public String getName() { return _name; } @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; String elbEnabledString = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key()); _elbEnabled = Boolean.parseBoolean(elbEnabledString); return true; } @Override public FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException { Account caller = UserContext.current().getCaller(); return createFirewallRule(rule.getSourceIpAddressId(), caller, rule.getXid(), rule.getSourcePortStart() ,rule.getSourcePortEnd(), rule.getProtocol(), rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), null, rule.getType()); } @DB @Override @ActionEvent(eventType = EventTypes.EVENT_FIREWALL_OPEN, eventDescription = "creating firewall rule", create = true) public FirewallRule createFirewallRule(long ipAddrId, Account caller, String xId, Integer portStart,Integer portEnd, String protocol, List<String> sourceCidrList, Integer icmpCode, Integer icmpType, Long relatedRuleId, FirewallRule.FirewallRuleType type) throws NetworkRuleConflictException{ IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId); // Validate ip address if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) { throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system"); } validateFirewallRule(caller, ipAddress, portStart, portEnd, protocol, Purpose.Firewall, type); //icmp code and icmp type can't be passed in for any other protocol rather than icmp if (!protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (icmpCode != null || icmpType != null)) { throw new InvalidParameterValueException("Can specify icmpCode and icmpType for ICMP protocol only"); } if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (portStart != null || portEnd != null)) { throw new InvalidParameterValueException("Can't specify start/end port when protocol is ICMP"); } Long networkId = null; Long accountId = null; Long domainId = null; if (ipAddress != null) { networkId = ipAddress.getAssociatedWithNetworkId(); accountId = ipAddress.getAccountId(); domainId = ipAddress.getDomainId(); } Transaction txn = Transaction.currentTxn(); txn.start(); FirewallRuleVO newRule = new FirewallRuleVO (xId, ipAddrId, portStart, portEnd, protocol.toLowerCase(), networkId, accountId, domainId, Purpose.Firewall, sourceCidrList, icmpCode, icmpType, relatedRuleId); newRule.setType(type); newRule = _firewallDao.persist(newRule); if (type == FirewallRuleType.User) detectRulesConflict(newRule, ipAddress); if (!_firewallDao.setStateToAdd(newRule)) { throw new CloudRuntimeException("Unable to update the state to add for " + newRule); } UserContext.current().setEventDetails("Rule Id: " + newRule.getId()); txn.commit(); return newRule; } @Override public List<? extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd) { Account caller = UserContext.current().getCaller(); Long ipId = cmd.getIpAddressId(); Long id = cmd.getId(); String path = null; Pair<List<Long>, Long> accountDomainPair = _accountMgr.finalizeAccountDomainForList(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId()); List<Long> permittedAccounts = accountDomainPair.first(); Long domainId = accountDomainPair.second(); if (ipId != null) { IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId); if (ipAddressVO == null || !ipAddressVO.readyToUse()) { throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for firewall rules yet"); } _accountMgr.checkAccess(caller, null, ipAddressVO); } if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { Domain domain = _domainMgr.getDomain(caller.getDomainId()); path = domain.getPath(); } Filter filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder(); sb.and("id", sb.entity().getId(), Op.EQ); sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ); sb.and("accountId", sb.entity().getAccountId(), Op.IN); sb.and("domainId", sb.entity().getDomainId(), Op.EQ); sb.and("purpose", sb.entity().getPurpose(), Op.EQ); if (path != null) { // for domain admin we should show only subdomains information SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } SearchCriteria<FirewallRuleVO> sc = sb.create(); if (id != null) { sc.setParameters("id", id); } if (ipId != null) { sc.setParameters("ip", ipId); } if (domainId != null) { sc.setParameters("domainId", domainId); } if (!permittedAccounts.isEmpty()) { sc.setParameters("accountId", permittedAccounts.toArray()); } sc.setParameters("purpose", Purpose.Firewall); if (path != null) { sc.setJoinParameters("domainSearch", "path", path + "%"); } return _firewallDao.search(sc, filter); } @Override public void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException { assert newRule.getSourceIpAddressId() == ipAddress.getId() : "You passed in an ip address that doesn't match the address in the new rule"; List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurposeAndNotRevoked(newRule.getSourceIpAddressId(), null); assert (rules.size() >= 1) : "For network rules, we now always first persist the rule and then check for network conflicts so we should at least have one rule at this point."; for (FirewallRuleVO rule : rules) { if (rule.getId() == newRule.getId()) { continue; // Skips my own rule. } boolean oneOfRulesIsFirewall = ((rule.getPurpose() == Purpose.Firewall || newRule.getPurpose() == Purpose.Firewall) && ((newRule.getPurpose() != rule.getPurpose()) || (!newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())))); //if both rules are firewall and their cidrs are different, we can skip port ranges verification boolean bothRulesFirewall = (rule.getPurpose() == newRule.getPurpose() && rule.getPurpose() == Purpose.Firewall); boolean duplicatedCidrs = false; if (bothRulesFirewall) { //Verify that the rules have different cidrs List<String> ruleCidrList = rule.getSourceCidrList(); List<String> newRuleCidrList = newRule.getSourceCidrList(); if (ruleCidrList == null || newRuleCidrList == null) { continue; } Collection<String> similar = new HashSet<String>(ruleCidrList); similar.retainAll(newRuleCidrList); if (similar.size() > 0) { duplicatedCidrs = true; } } if (!oneOfRulesIsFirewall) { if (rule.getPurpose() == Purpose.StaticNat && newRule.getPurpose() != Purpose.StaticNat) { throw new NetworkRuleConflictException("There is 1 to 1 Nat rule specified for the ip address id=" + newRule.getSourceIpAddressId()); } else if (rule.getPurpose() != Purpose.StaticNat && newRule.getPurpose() == Purpose.StaticNat) { throw new NetworkRuleConflictException("There is already firewall rule specified for the ip address id=" + newRule.getSourceIpAddressId()); } } if (rule.getNetworkId() != newRule.getNetworkId() && rule.getState() != State.Revoke) { throw new NetworkRuleConflictException("New rule is for a different network than what's specified in rule " + rule.getXid()); } if (newRule.getProtocol().equalsIgnoreCase(NetUtils.ICMP_PROTO) && newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())) { if (newRule.getIcmpCode().longValue() == rule.getIcmpCode().longValue() && newRule.getIcmpType().longValue() == rule.getIcmpType().longValue() && newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())) { throw new InvalidParameterValueException("New rule conflicts with existing rule id=" + rule.getId()); } } boolean notNullPorts = (newRule.getSourcePortStart() != null && newRule.getSourcePortEnd() != null && rule.getSourcePortStart() != null && rule.getSourcePortEnd() != null) ; if (!notNullPorts) { continue; } else if (!oneOfRulesIsFirewall && !(bothRulesFirewall && !duplicatedCidrs) && ((rule.getSourcePortStart().intValue() <= newRule.getSourcePortStart().intValue() && rule.getSourcePortEnd().intValue() >= newRule.getSourcePortStart().intValue()) || (rule.getSourcePortStart().intValue() <= newRule.getSourcePortEnd().intValue() && rule.getSourcePortEnd().intValue() >= newRule.getSourcePortEnd().intValue()) || (newRule.getSourcePortStart().intValue() <= rule.getSourcePortStart().intValue() && newRule.getSourcePortEnd().intValue() >= rule.getSourcePortStart().intValue()) || (newRule.getSourcePortStart().intValue() <= rule.getSourcePortEnd().intValue() && newRule.getSourcePortEnd().intValue() >= rule.getSourcePortEnd().intValue()))) { // we allow port forwarding rules with the same parameters but different protocols boolean allowPf = (rule.getPurpose() == Purpose.PortForwarding && newRule.getPurpose() == Purpose.PortForwarding && !newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())); boolean allowStaticNat = (rule.getPurpose() == Purpose.StaticNat && newRule.getPurpose() == Purpose.StaticNat && !newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())); if (!(allowPf || allowStaticNat || oneOfRulesIsFirewall)) { throw new NetworkRuleConflictException("The range specified, " + newRule.getSourcePortStart() + "-" + newRule.getSourcePortEnd() + ", conflicts with rule " + rule.getId() + " which has " + rule.getSourcePortStart() + "-" + rule.getSourcePortEnd()); } } } if (s_logger.isDebugEnabled()) { s_logger.debug("No network rule conflicts detected for " + newRule + " against " + (rules.size() - 1) + " existing rules"); } } @Override public void validateFirewallRule(Account caller, IPAddressVO ipAddress, Integer portStart, Integer portEnd, String proto, Purpose purpose, FirewallRuleType type) { if (portStart != null && !NetUtils.isValidPort(portStart)) { throw new InvalidParameterValueException("publicPort is an invalid value: " + portStart); } if (portEnd != null && !NetUtils.isValidPort(portEnd)) { throw new InvalidParameterValueException("Public port range is an invalid value: " + portEnd); } // start port can't be bigger than end port if (portStart != null && portEnd != null && portStart > portEnd) { throw new InvalidParameterValueException("Start port can't be bigger than end port"); } if (ipAddress == null && type == FirewallRuleType.System) { return; } // Validate ip address _accountMgr.checkAccess(caller, null, ipAddress); Long networkId = ipAddress.getAssociatedWithNetworkId(); if (networkId == null) { throw new InvalidParameterValueException("Unable to create port forwarding rule ; ip id=" + ipAddress.getId() + " is not associated with any network"); } Network network = _networkMgr.getNetwork(networkId); assert network != null : "Can't create port forwarding rule as network associated with public ip address is null?"; // Verify that the network guru supports the protocol specified Map<Network.Capability, String> protocolCapabilities = null; if (purpose == Purpose.LoadBalancing) { if (!_elbEnabled) { protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.Lb); } } else if (purpose == Purpose.Firewall){ protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.Firewall); } else if (purpose == Purpose.PortForwarding) { protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.PortForwarding); } if (protocolCapabilities != null) { String supportedProtocols = protocolCapabilities.get(Capability.SupportedProtocols).toLowerCase(); if (!supportedProtocols.contains(proto.toLowerCase())) { throw new InvalidParameterValueException("Protocol " + proto + " is not supported in zone " + network.getDataCenterId()); } else if (proto.equalsIgnoreCase(NetUtils.ICMP_PROTO) && purpose != Purpose.Firewall) { throw new InvalidParameterValueException("Protocol " + proto + " is currently supported only for rules with purpose " + Purpose.Firewall); } } } @Override public boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException { boolean success = true; if (!_networkMgr.applyRules(rules, continueOnError)) { s_logger.warn("Rules are not completely applied"); return false; } else { if (updateRulesInDB) { for (FirewallRule rule : rules) { if (rule.getState() == FirewallRule.State.Revoke) { FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(rule.getId()); if (relatedRule != null) { s_logger.warn("Can't remove the firewall rule id=" + rule.getId() + " as it has related firewall rule id=" + relatedRule.getId() + "; leaving it in Revoke state"); success = false; } else { _firewallDao.remove(rule.getId()); } } else if (rule.getState() == FirewallRule.State.Add) { FirewallRuleVO ruleVO = _firewallDao.findById(rule.getId()); ruleVO.setState(FirewallRule.State.Active); _firewallDao.update(ruleVO.getId(), ruleVO); } } } } return success; } @Override public boolean applyFirewallRules(long ipId, Account caller) throws ResourceUnavailableException { List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(ipId, Purpose.Firewall); return applyFirewallRules(rules, false, caller); } @Override public boolean applyFirewallRules(List<FirewallRuleVO> rules, boolean continueOnError, Account caller) { if (rules.size() == 0) { s_logger.debug("There are no firewall rules to apply for ip id=" + rules); return true; } for (FirewallRuleVO rule: rules){ // load cidrs if any rule.setSourceCidrList(_firewallCidrsDao.getSourceCidrs(rule.getId())); } if (caller != null) { _accountMgr.checkAccess(caller, null, rules.toArray(new FirewallRuleVO[rules.size()])); } try { if (!applyRules(rules, continueOnError, true)) { return false; } } catch (ResourceUnavailableException ex) { s_logger.warn("Failed to apply firewall rules due to ", ex); return false; } return true; } @Override @ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true) public boolean revokeFirewallRule(long ruleId, boolean apply, Account caller, long userId) { FirewallRuleVO rule = _firewallDao.findById(ruleId); if (rule == null || rule.getPurpose() != Purpose.Firewall) { throw new InvalidParameterValueException("Unable to find " + ruleId + " having purpose " + Purpose.Firewall); } if (rule.getType() == FirewallRuleType.System && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { throw new InvalidParameterValueException("Only root admin can delete the system wide firewall rule"); } _accountMgr.checkAccess(caller, null, rule); revokeRule(rule, caller, userId, false); boolean success = false; if (apply) { List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(rule.getSourceIpAddressId(), Purpose.Firewall); return applyFirewallRules(rules, false, caller); } else { success = true; } return success; } @Override public boolean revokeFirewallRule(long ruleId, boolean apply) { Account caller = UserContext.current().getCaller(); long userId = UserContext.current().getCallerUserId(); return revokeFirewallRule(ruleId, apply, caller, userId); } @Override @DB public void revokeRule(FirewallRuleVO rule, Account caller, long userId, boolean needUsageEvent) { if (caller != null) { _accountMgr.checkAccess(caller, null, rule); } Transaction txn = Transaction.currentTxn(); boolean generateUsageEvent = false; txn.start(); if (rule.getState() == State.Staged) { if (s_logger.isDebugEnabled()) { s_logger.debug("Found a rule that is still in stage state so just removing it: " + rule); } _firewallDao.remove(rule.getId()); generateUsageEvent = true; } else if (rule.getState() == State.Add || rule.getState() == State.Active) { rule.setState(State.Revoke); _firewallDao.update(rule.getId(), rule); generateUsageEvent = true; } if (generateUsageEvent && needUsageEvent) { UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_DELETE, rule.getAccountId(), 0, rule.getId(), null); _usageEventDao.persist(usageEvent); } txn.commit(); } @Override public FirewallRule getFirewallRule(long ruleId) { return _firewallDao.findById(ruleId); } @Override public boolean revokeFirewallRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException { List<FirewallRule> rules = new ArrayList<FirewallRule>(); List<FirewallRuleVO> fwRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.Firewall); if (s_logger.isDebugEnabled()) { s_logger.debug("Releasing " + fwRules.size() + " firewall rules for ip id=" + ipId); } for (FirewallRuleVO rule : fwRules) { // Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no need to send them one by one revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM); } // now send everything to the backend List<FirewallRuleVO> rulesToApply = _firewallDao.listByIpAndPurpose(ipId, Purpose.Firewall); applyFirewallRules(rulesToApply, true, caller); // Now we check again in case more rules have been inserted. rules.addAll(_firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.Firewall)); if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully released firewall rules for ip id=" + ipId + " and # of rules now = " + rules.size()); } return rules.size() == 0; } @Override public FirewallRule createRuleForAllCidrs(long ipAddrId, Account caller, Integer startPort, Integer endPort, String protocol, Integer icmpCode, Integer icmpType, Long relatedRuleId) throws NetworkRuleConflictException{ //If firwallRule for this port range already exists, return it List<FirewallRuleVO> rules = _firewallDao.listByIpPurposeAndProtocolAndNotRevoked(ipAddrId, startPort, endPort, protocol, Purpose.Firewall); if (!rules.isEmpty()) { return rules.get(0); } List<String> oneCidr = new ArrayList<String>(); oneCidr.add(NetUtils.ALL_CIDRS); return createFirewallRule(ipAddrId, caller, null, startPort, endPort, protocol, oneCidr, icmpCode, icmpType, relatedRuleId, FirewallRule.FirewallRuleType.User); } @Override public boolean revokeAllFirewallRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException { List<FirewallRule> rules = new ArrayList<FirewallRule>(); List<FirewallRuleVO> fwRules = _firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.Firewall); if (s_logger.isDebugEnabled()) { s_logger.debug("Releasing " + fwRules.size() + " firewall rules for network id=" + networkId); } for (FirewallRuleVO rule : fwRules) { // Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no need to send them one by one revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM); } // now send everything to the backend List<FirewallRuleVO> rulesToApply = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.Firewall); boolean success = applyFirewallRules(rulesToApply, true, caller); // Now we check again in case more rules have been inserted. rules.addAll(_firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.Firewall)); if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully released firewall rules for network id=" + networkId + " and # of rules now = " + rules.size()); } return success && rules.size() == 0; } @Override public boolean revokeRelatedFirewallRule(long ruleId, boolean apply) { FirewallRule fwRule = _firewallDao.findByRelatedId(ruleId); if (fwRule == null) { s_logger.trace("No related firewall rule exists for rule id=" + ruleId + " so returning true here"); return true; } s_logger.debug("Revoking Firewall rule id=" + fwRule.getId() + " as a part of rule delete id=" + ruleId + " with apply=" + apply); return revokeFirewallRule(fwRule.getId(), apply); } @Override public boolean revokeFirewallRulesForVm(long vmId) { boolean success = true; UserVmVO vm = _vmDao.findByIdIncludingRemoved(vmId); if (vm == null) { return false; } List<PortForwardingRuleVO> pfRules = _pfRulesDao.listByVm(vmId); List<FirewallRuleVO> staticNatRules = _firewallDao.listStaticNatByVmId(vm.getId()); List<FirewallRuleVO> firewallRules = new ArrayList<FirewallRuleVO>(); //Make a list of firewall rules to reprogram for (PortForwardingRuleVO pfRule : pfRules) { FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(pfRule.getId()); if (relatedRule != null) { firewallRules.add(relatedRule); } } for (FirewallRuleVO staticNatRule : staticNatRules) { FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(staticNatRule.getId()); if (relatedRule != null) { firewallRules.add(relatedRule); } } Set<Long> ipsToReprogram = new HashSet<Long>(); if (firewallRules.isEmpty()) { s_logger.debug("No firewall rules are found for vm id=" + vmId); return true; } else { s_logger.debug("Found " + firewallRules.size() + " to cleanup for vm id=" + vmId); } for (FirewallRuleVO rule : firewallRules) { // Mark firewall rules as Revoked, but don't revoke it yet (apply=false) revokeFirewallRule(rule.getId(), false, _accountMgr.getSystemAccount(), Account.ACCOUNT_ID_SYSTEM); ipsToReprogram.add(rule.getSourceIpAddressId()); } // apply rules for all ip addresses for (Long ipId : ipsToReprogram) { s_logger.debug("Applying firewall rules for ip address id=" + ipId + " as a part of vm expunge"); try { success = success && applyFirewallRules(ipId,_accountMgr.getSystemAccount()); } catch (ResourceUnavailableException ex) { s_logger.warn("Failed to apply port forwarding rules for ip id=" + ipId); success = false; } } return success; } @Override public boolean addSystemFirewallRules(IPAddressVO ip, Account acct) { List<FirewallRuleVO> systemRules = _firewallDao.listSystemRules(); for (FirewallRuleVO rule : systemRules) { try { this.createFirewallRule(ip.getId(), acct, rule.getXid(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), rule.getRelated(), FirewallRuleType.System); } catch (Exception e) { s_logger.debug("Failed to add system wide firewall rule, due to:" + e.toString()); } } return true; } }
package com.devicehive.service; import com.devicehive.auth.CheckPermissionsHelper; import com.devicehive.auth.HivePrincipal; import com.devicehive.auth.HiveRoles; import com.devicehive.configuration.Messages; import com.devicehive.dao.DeviceDAO; import com.devicehive.exceptions.HiveException; import com.devicehive.messages.bus.Create; import com.devicehive.messages.bus.GlobalMessage; import com.devicehive.messages.bus.LocalMessage; import com.devicehive.model.AccessKey; import com.devicehive.model.Device; import com.devicehive.model.DeviceClass; import com.devicehive.model.DeviceNotification; import com.devicehive.model.Equipment; import com.devicehive.model.Network; import com.devicehive.model.SpecialNotifications; import com.devicehive.model.User; import com.devicehive.model.updates.DeviceUpdate; import com.devicehive.util.HiveValidator; import com.devicehive.util.LogExecutionTime; import com.devicehive.util.ServerResponsesFactory; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.enterprise.event.Event; import javax.inject.Inject; import javax.validation.constraints.NotNull; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.UNAUTHORIZED; @Stateless @LogExecutionTime @EJB(beanInterface = DeviceService.class, name = "DeviceService") public class DeviceService { private static final Logger logger = LoggerFactory.getLogger(DeviceService.class); @EJB private DeviceNotificationService deviceNotificationService; @EJB private DeviceDAO deviceDAO; @EJB private NetworkService networkService; @EJB private UserService userService; @EJB private DeviceClassService deviceClassService; @EJB private DeviceActivityService deviceActivityService; @EJB private AccessKeyService accessKeyService; @EJB private HiveValidator hiveValidator; @Inject @Create @LocalMessage private Event<DeviceNotification> eventLocal; @Inject @Create @GlobalMessage private Event<DeviceNotification> eventGlobal; public void deviceSaveAndNotify(DeviceUpdate device, Set<Equipment> equipmentSet, HivePrincipal principal) { logger.debug("Device: {}. Current role: {}.", device.getGuid(), principal == null ? null : principal.getRole()); validateDevice(device); DeviceNotification dn; if (principal != null && principal.isAuthenticated()) { switch (principal.getRole()) { case HiveRoles.ADMIN: dn = deviceSaveByUser(device, equipmentSet, principal.getUser()); break; case HiveRoles.CLIENT: dn = deviceSaveByUser(device, equipmentSet, principal.getUser()); break; case HiveRoles.DEVICE: dn = deviceUpdateByDevice(device, equipmentSet, principal.getDevice()); break; case HiveRoles.KEY: dn = deviceSaveByKey(device, equipmentSet, principal.getKey()); break; default: dn = deviceSave(device, equipmentSet); break; } } else { dn = deviceSave(device, equipmentSet); } eventLocal.fire(dn); eventGlobal.fire(dn); deviceActivityService.update(dn.getDevice().getId()); } public DeviceNotification deviceSaveByUser(DeviceUpdate deviceUpdate, Set<Equipment> equipmentSet, User user) { logger.debug("Device save executed for device: id {}, user: {}", deviceUpdate.getGuid(), user.getId()); Network network = networkService.createOrUpdateNetworkByUser(deviceUpdate.getNetwork(), user); DeviceClass deviceClass = deviceClassService .createOrUpdateDeviceClass(deviceUpdate.getDeviceClass(), equipmentSet); Device existingDevice = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceUpdate.getGuid().getValue()); if (existingDevice == null) { Device device = deviceUpdate.convertTo(); if (deviceClass != null) { device.setDeviceClass(deviceClass); } if (network != null) { device.setNetwork(network); } existingDevice = deviceDAO.createDevice(device); final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_ADD); List<DeviceNotification> resultList = deviceNotificationService.saveDeviceNotification(Arrays.asList(addDeviceNotification)); return resultList.get(0); } else { if (!userService.hasAccessToDevice(user, existingDevice)) { throw new HiveException(Messages.UNAUTHORIZED_REASON_PHRASE, UNAUTHORIZED.getStatusCode()); } if (deviceUpdate.getDeviceClass() != null) { existingDevice.setDeviceClass(deviceClass); } if (deviceUpdate.getStatus() != null) { existingDevice.setStatus(deviceUpdate.getStatus().getValue()); } if (deviceUpdate.getData() != null) { existingDevice.setData(deviceUpdate.getData().getValue()); } if (deviceUpdate.getNetwork() != null) { existingDevice.setNetwork(network); } if (deviceUpdate.getName() != null) { existingDevice.setName(deviceUpdate.getName().getValue()); } if (deviceUpdate.getKey() != null) { existingDevice.setKey(deviceUpdate.getKey().getValue()); } final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_UPDATE); List<DeviceNotification> resultList = deviceNotificationService.saveDeviceNotification(Arrays.asList(addDeviceNotification)); return resultList.get(0); } } public DeviceNotification deviceSaveByKey(DeviceUpdate deviceUpdate, Set<Equipment> equipmentSet, AccessKey key) { logger.debug("Device save executed for device: id {}, user: {}", deviceUpdate.getGuid(), key.getKey()); Device existingDevice = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceUpdate.getGuid().getValue()); if (existingDevice != null && !accessKeyService.hasAccessToNetwork(key, existingDevice.getNetwork())) { throw new HiveException( String.format(Messages.DEVICE_NOT_FOUND, deviceUpdate.getGuid().getValue()), UNAUTHORIZED.getStatusCode()); } Network network = networkService.createOrVeriryNetworkByKey(deviceUpdate.getNetwork(), key); DeviceClass deviceClass = deviceClassService .createOrUpdateDeviceClass(deviceUpdate.getDeviceClass(), equipmentSet); if (existingDevice == null) { Device device = deviceUpdate.convertTo(); device.setDeviceClass(deviceClass); device.setNetwork(network); existingDevice = deviceDAO.createDevice(device); final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_ADD); List<DeviceNotification> resultList = deviceNotificationService.saveDeviceNotification(Arrays.asList(addDeviceNotification)); return resultList.get(0); } else { if (!accessKeyService.hasAccessToDevice(key, deviceUpdate.getGuid().getValue())) { throw new HiveException( String.format(Messages.DEVICE_NOT_FOUND, deviceUpdate.getGuid().getValue()), UNAUTHORIZED.getStatusCode()); } if (deviceUpdate.getDeviceClass() != null && !existingDevice.getDeviceClass().getPermanent()) { existingDevice.setDeviceClass(deviceClass); } if (deviceUpdate.getStatus() != null) { existingDevice.setStatus(deviceUpdate.getStatus().getValue()); } if (deviceUpdate.getData() != null) { existingDevice.setData(deviceUpdate.getData().getValue()); } if (deviceUpdate.getNetwork() != null) { existingDevice.setNetwork(network); } if (deviceUpdate.getName() != null) { existingDevice.setName(deviceUpdate.getName().getValue()); } if (deviceUpdate.getKey() != null) { existingDevice.setKey(deviceUpdate.getKey().getValue()); } final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_UPDATE); List<DeviceNotification> resultList = deviceNotificationService.saveDeviceNotification(Arrays.asList(addDeviceNotification)); return resultList.get(0); } } public DeviceNotification deviceUpdateByDevice(DeviceUpdate deviceUpdate, Set<Equipment> equipmentSet, Device device) { logger.debug("Device update executed for device update: id {}, device: {}", deviceUpdate.getGuid(), device.getId()); if (deviceUpdate.getGuid() == null) { throw new HiveException(Messages.INVALID_REQUEST_PARAMETERS, BAD_REQUEST.getStatusCode()); } if (!device.getGuid().equals(deviceUpdate.getGuid().getValue())) { throw new HiveException(String.format(Messages.DEVICE_NOT_FOUND, deviceUpdate.getGuid().getValue()), UNAUTHORIZED.getStatusCode()); } if (deviceUpdate.getKey() != null && !device.getKey().equals(deviceUpdate.getKey().getValue())) { throw new HiveException(Messages.INCORRECT_CREDENTIALS, UNAUTHORIZED.getStatusCode()); } DeviceClass deviceClass = deviceClassService .createOrUpdateDeviceClass(deviceUpdate.getDeviceClass(), equipmentSet); Device existingDevice = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceUpdate.getGuid().getValue()); if (deviceUpdate.getDeviceClass() != null && !existingDevice.getDeviceClass().getPermanent()) { existingDevice.setDeviceClass(deviceClass); } if (deviceUpdate.getNetwork() != null) { Network network = networkService.createOrVeriryNetwork(deviceUpdate.getNetwork()); existingDevice.setNetwork(network); } if (deviceUpdate.getStatus() != null) { existingDevice.setStatus(deviceUpdate.getStatus().getValue()); } if (deviceUpdate.getData() != null) { existingDevice.setData(deviceUpdate.getData().getValue()); } if (deviceUpdate.getName() != null) { existingDevice.setName(deviceUpdate.getName().getValue()); } if (deviceUpdate.getKey() != null) { existingDevice.setKey(deviceUpdate.getKey().getValue()); } final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_UPDATE); List<DeviceNotification> resultList = deviceNotificationService.saveDeviceNotification(Arrays.asList(addDeviceNotification)); return resultList.get(0); } public DeviceNotification deviceSave(DeviceUpdate deviceUpdate, Set<Equipment> equipmentSet) { logger.debug("Device save executed for device update: id {}", deviceUpdate.getGuid()); Network network = networkService.createOrVeriryNetwork(deviceUpdate.getNetwork()); DeviceClass deviceClass = deviceClassService .createOrUpdateDeviceClass(deviceUpdate.getDeviceClass(), equipmentSet); Device existingDevice = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceUpdate.getGuid().getValue()); if (existingDevice == null) { Device device = deviceUpdate.convertTo(); if (deviceClass != null) { device.setDeviceClass(deviceClass); } if (network != null) { device.setNetwork(network); } existingDevice = deviceDAO.createDevice(device); final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_ADD); List<DeviceNotification> resultList = deviceNotificationService.saveDeviceNotification(Arrays.asList(addDeviceNotification)); return resultList.get(0); } else { if (deviceUpdate.getKey() == null || !existingDevice.getKey().equals(deviceUpdate.getKey().getValue())) { throw new HiveException(Messages.INCORRECT_CREDENTIALS, UNAUTHORIZED.getStatusCode()); } if (deviceUpdate.getDeviceClass() != null) { existingDevice.setDeviceClass(deviceClass); } if (deviceUpdate.getStatus() != null) { existingDevice.setStatus(deviceUpdate.getStatus().getValue()); } if (deviceUpdate.getData() != null) { existingDevice.setData(deviceUpdate.getData().getValue()); } if (deviceUpdate.getNetwork() != null) { existingDevice.setNetwork(network); } final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice (existingDevice, SpecialNotifications.DEVICE_UPDATE); List<DeviceNotification> resultList = deviceNotificationService.saveDeviceNotification(Arrays.asList(addDeviceNotification)); return resultList.get(0); } } @TransactionAttribute(TransactionAttributeType.SUPPORTS) public Device findByGuidWithPermissionsCheck(String guid, HivePrincipal principal) { List<Device> result = findByGuidWithPermissionsCheck(Arrays.asList(guid), principal); return result.isEmpty() ? null : result.get(0); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Device> findByGuidWithPermissionsCheck(Collection<String> guids, HivePrincipal principal) { return deviceDAO.getDeviceList(principal, guids); } /** * Implementation for model: if field exists and null - error if field does not exists - use field from database * * @param device device to check */ @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public void validateDevice(DeviceUpdate device) throws HiveException { if (device == null) { throw new HiveException(Messages.EMPTY_DEVICE); } if (device.getName() != null && device.getName() == null) { throw new HiveException(Messages.EMPTY_DEVICE_NAME); } if (device.getKey() != null && device.getKey() == null) { throw new HiveException(Messages.EMPTY_DEVICE_KEY); } if (device.getDeviceClass() != null && device.getDeviceClass().getValue() == null) { throw new HiveException(Messages.EMPTY_DEVICE_CLASS); } hiveValidator.validate(device); } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Device getDeviceWithNetworkAndDeviceClass(String deviceId, HivePrincipal principal) { if (getAllowedDevicesCount(principal, Arrays.asList(deviceId)) == 0) { throw new HiveException(String.format(Messages.DEVICE_NOT_FOUND, deviceId), NOT_FOUND.getStatusCode()); } Device device = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceId); if (device == null) { throw new HiveException(String.format(Messages.DEVICE_NOT_FOUND, deviceId), NOT_FOUND.getStatusCode()); } return device; } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Device authenticate(String uuid, String key) { Device device = deviceDAO.findByUUIDAndKey(uuid, key); if (device != null) { deviceActivityService.update(device.getId()); } return device; } public boolean deleteDevice(@NotNull String guid, HivePrincipal principal) { List<Device> existing = deviceDAO.getDeviceList(principal, Arrays.asList(guid)); return existing.isEmpty() || deviceDAO.deleteDevice(guid); } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public List<Device> getList(String name, String namePattern, String status, Long networkId, String networkName, Long deviceClassId, String deviceClassName, String deviceClassVersion, String sortField, Boolean sortOrderAsc, Integer take, Integer skip, HivePrincipal principal) { return deviceDAO.getList(name, namePattern, status, networkId, networkName, deviceClassId, deviceClassName, deviceClassVersion, sortField, sortOrderAsc, take, skip, principal); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Device> getList(Long networkId, HivePrincipal principal) { return deviceDAO .getList(null, null, null, networkId, null, null, null, null, null, null, null, null, principal); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) public long getAllowedDevicesCount(HivePrincipal principal, List<String> guids) { return deviceDAO.getNumberOfAvailableDevices(principal, guids); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) public Map<Device, Set<String>> createFilterMap(@NotNull Map<String, Set<String>> requested, HivePrincipal principal) { List<Device> allowedDevices = findByGuidWithPermissionsCheck(requested.keySet(), principal); Map<String, Device> uuidToDevice = new HashMap<>(); for (Device device : allowedDevices) { uuidToDevice.put(device.getGuid(), device); } Set<String> noAccessUuid = new HashSet<>(); Map<Device, Set<String>> result = new HashMap<>(); for (Map.Entry<String, Set<String>> entry : requested.entrySet()) { String uuid = entry.getKey(); if (uuidToDevice.containsKey(uuid)) { result.put(uuidToDevice.get(uuid), entry.getValue()); } else { noAccessUuid.add(uuid); } } if (!noAccessUuid.isEmpty()) { String message = String.format(Messages.DEVICES_NOT_FOUND, StringUtils.join(noAccessUuid, ",")); throw new HiveException(message, Response.Status.NOT_FOUND.getStatusCode()); } return result; } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public boolean hasAccessTo(@NotNull HivePrincipal filtered, @NotNull Device device) { if (filtered.getDevice() != null) { return filtered.getDevice().getId().equals(device.getId()); } if (filtered.getUser() != null) { return userService.hasAccessToDevice(filtered.getUser(), device); } if (filtered.getKey() != null) { if (!userService.hasAccessToDevice(filtered.getKey().getUser(), device)) { return false; } return CheckPermissionsHelper.checkFilteredPermissions(filtered.getKey().getPermissions(), device); } return false; } }
package org.jboss.as.server.deployment; /** * An enumeration of the phases of a deployment unit's processing cycle. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public enum Phase { /* == TEMPLATE == * Upon entry, this phase performs the following actions: * <ul> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ /** * This phase creates the initial root structure. Depending on the service for this phase will ensure that the * deployment unit's initial root structure is available and accessible. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li> * <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments: * <ul> * <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * </ul> * <p> */ STRUCTURE(null), /** * This phase assembles information from the root structure to prepare for adding and processing additional external * structure, such as from class path entries and other similar mechanisms. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li> * <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li> * <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li> * </ul> * <p> */ PARSE(null), /** * In this phase parsing of deployment metadata is complete and the component may be registered with the subsystem. * This is prior to working out the components dependency and equivalent to the OSGi INSTALL life cycle. */ REGISTER(null), /** * In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>Any additional external structure is mounted during {@link #XXX}</li> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ DEPENDENCIES(null), CONFIGURE_MODULE(null), /** * Processors that need to start/complete before the deployment classloader is used to load application classes, * belong in the FIRST_MODULE_USE phase. */ FIRST_MODULE_USE(null), POST_MODULE(null), INSTALL(null), CLEANUP(null), ; /** * This is the key for the attachment to use as the phase's "value". The attachment is taken from * the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified. */ private final AttachmentKey<?> phaseKey; private Phase(final AttachmentKey<?> key) { phaseKey = key; } /** * Get the next phase, or {@code null} if none. * * @return the next phase, or {@code null} if there is none */ public Phase next() { final int ord = ordinal() + 1; final Phase[] phases = Phase.values(); return ord == phases.length ? null : phases[ord]; } /** * Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value * of this phase. * * @return the key */ public AttachmentKey<?> getPhaseKey() { return phaseKey; } // STRUCTURE public static final int STRUCTURE_EXPLODED_MOUNT = 0x0100; public static final int STRUCTURE_MOUNT = 0x0200; public static final int STRUCTURE_MANIFEST = 0x0300; public static final int STRUCTURE_OSGI_MANIFEST = 0x0400; public static final int STRUCTURE_REMOUNT_EXPLODED = 0x0450; public static final int STRUCTURE_EE_SPEC_DESC_PROPERTY_REPLACEMENT = 0x0500; public static final int STRUCTURE_EE_JBOSS_DESC_PROPERTY_REPLACEMENT= 0x0550; public static final int STRUCTURE_JDBC_DRIVER = 0x0600; public static final int STRUCTURE_RAR = 0x0700; public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0800; public static final int STRUCTURE_WAR = 0x0900; public static final int STRUCTURE_CONTENT_OVERRIDE = 0x0950; public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0A00; public static final int STRUCTURE_REGISTER_JBOSS_ALL_XML_PARSER = 0x0A10; public static final int STRUCTURE_PARSE_JBOSS_ALL_XML = 0x0A20; public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0B00; public static final int STRUCTURE_JBOSS_EJB_CLIENT_XML_PARSE = 0x0C00; public static final int STRUCTURE_EJB_EAR_APPLICATION_NAME = 0x0D00; public static final int STRUCTURE_EAR = 0x0E00; public static final int STRUCTURE_APP_CLIENT = 0x0F00; public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x1000; public static final int STRUCTURE_ANNOTATION_INDEX = 0x1100; public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x1200; public static final int STRUCTURE_APPLICATION_CLIENT_IN_EAR = 0x1300; public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x1400; public static final int STRUCTURE_BUNDLE_SUB_DEPLOYMENT = 0x1450; public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x1500; public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x1600; public static final int STRUCTURE_SUB_DEPLOYMENT = 0x1700; public static final int STRUCTURE_JBOSS_DEPLOYMENT_STRUCTURE = 0x1800; public static final int STRUCTURE_CLASS_PATH = 0x1900; public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1A00; public static final int STRUCTURE_EE_MODULE_INIT = 0x1B00; public static final int STRUCTURE_EE_RESOURCE_INJECTION_REGISTRY = 0x1C00; public static final int STRUCTURE_DEPLOYMENT_DEPENDENCIES = 0x1D00; // PARSE public static final int PARSE_EE_DEPLOYMENT_PROPERTIES = 0x0001; public static final int PARSE_EE_DEPLOYMENT_PROPERTY_RESOLVER = 0x0002; public static final int PARSE_EE_VAULT_PROPERTY_RESOLVER = 0x0003; public static final int PARSE_EE_SYSTEM_PROPERTY_RESOLVER = 0x0004; public static final int PARSE_EE_PROPERTY_RESOLVER = 0x0005; public static final int PARSE_EE_MODULE_NAME = 0x0100; public static final int PARSE_EJB_DEFAULT_DISTINCT_NAME = 0x0110; public static final int PARSE_EAR_SUBDEPLOYMENTS_ISOLATION_DEFAULT = 0x0200; public static final int PARSE_DEPENDENCIES_MANIFEST = 0x0300; public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0301; public static final int PARSE_EXTENSION_LIST = 0x0700; public static final int PARSE_EXTENSION_NAME = 0x0800; public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900; public static final int PARSE_OSGI_PROPERTIES = 0x0A00; public static final int PARSE_WEB_DEPLOYMENT = 0x0B00; public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00; public static final int PARSE_JSF_VERSION = 0x0C50; public static final int PARSE_JSF_SHARED_TLDS = 0x0C51; public static final int PARSE_ANNOTATION_WAR = 0x0D00; public static final int PARSE_ANNOTATION_EJB = 0x0D10; public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00; public static final int PARSE_TLD_DEPLOYMENT = 0x0F00; public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000; // create and attach EJB metadata for EJB deployments public static final int PARSE_EJB_DEPLOYMENT = 0x1100; public static final int PARSE_APP_CLIENT_XML = 0x1101; public static final int PARSE_CREATE_COMPONENT_DESCRIPTIONS = 0x1150; // described EJBs must be created after annotated EJBs public static final int PARSE_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1152; public static final int PARSE_CMP_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1153; public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200; // create and attach the component description out of EJB annotations public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901; public static final int PARSE_WEB_COMPONENTS = 0x1F00; public static final int PARSE_WEB_MERGE_METADATA = 0x2000; public static final int PARSE_OSGI_COMPONENTS = 0x2010; public static final int PARSE_WEBSERVICES_CONTEXT_INJECTION = 0x2040; public static final int PARSE_WEBSERVICES_XML = 0x2050; public static final int PARSE_JBOSS_WEBSERVICES_XML = 0x2051; public static final int PARSE_JAXWS_EJB_INTEGRATION = 0x2052; public static final int PARSE_JAXRPC_POJO_INTEGRATION = 0x2053; public static final int PARSE_JAXRPC_EJB_INTEGRATION = 0x2054; public static final int PARSE_JAXWS_HANDLER_CHAIN_ANNOTATION = 0x2055; public static final int PARSE_WS_JMS_INTEGRATION = 0x2056; public static final int PARSE_JAXWS_ENDPOINT_CREATE_COMPONENT_DESCRIPTIONS = 0x2057; public static final int PARSE_JAXWS_HANDLER_CREATE_COMPONENT_DESCRIPTIONS = 0x2058; public static final int PARSE_RA_DEPLOYMENT = 0x2100; public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200; public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300; public static final int PARSE_POJO_DEPLOYMENT = 0x2400; public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500; public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900; public static final int PARSE_EE_ANNOTATIONS = 0x2901; public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00; public static final int PARSE_CDI_ANNOTATIONS = 0x2A10; public static final int PARSE_WELD_DEPLOYMENT = 0x2B00; public static final int PARSE_DATA_SOURCE_DEFINITION_ANNOTATION = 0x2D00; public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00; public static final int PARSE_EJB_TIMERSERVICE_BINDING = 0x2E01; public static final int PARSE_EJB_DEFAULT_SECURITY_DOMAIN = 0x2E02; public static final int PARSE_PERSISTENCE_UNIT = 0x2F00; public static final int PARSE_LIFECYCLE_ANNOTATION = 0x3200; public static final int PARSE_PASSIVATION_ANNOTATION = 0x3250; public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300; public static final int PARSE_AROUNDTIMEOUT_ANNOTATION = 0x3400; public static final int PARSE_TIMEOUT_ANNOTATION = 0x3401; public static final int PARSE_EJB_DD_INTERCEPTORS = 0x3500; public static final int PARSE_EJB_SECURITY_ROLE_REF_DD = 0x3501; public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x3600; public static final int PARSE_DISTINCT_NAME = 0x3601; public static final int PARSE_OSGI_DEPLOYMENT = 0x3700; public static final int PARSE_OSGI_SUBSYSTEM_ACTIVATOR = 0x3800; // should be after all components are known public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x4000; public static final int PARSE_JACORB = 0x4100; public static final int PARSE_TRANSACTION_ROLLBACK_ACTION = 0x4200; public static final int PARSE_EAR_MESSAGE_DESTINATIONS = 0x4400; public static final int PARSE_DSXML_DEPLOYMENT = 0x4500; public static final int PARSE_MESSAGING_XML_RESOURCES = 0x4600; public static final int PARSE_DESCRIPTOR_LIFECYCLE_METHOD_RESOLUTION = 0x4700; // REGISTER public static final int REGISTER_BUNDLE_INSTALL = 0x0100; // DEPENDENCIES public static final int DEPENDENCIES_EJB = 0x0200; public static final int DEPENDENCIES_MODULE = 0x0300; public static final int DEPENDENCIES_RAR_CONFIG = 0x0400; public static final int DEPENDENCIES_MANAGED_BEAN = 0x0500; public static final int DEPENDENCIES_SAR_MODULE = 0x0600; public static final int DEPENDENCIES_WAR_MODULE = 0x0700; public static final int DEPENDENCIES_CLASS_PATH = 0x0800; public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900; public static final int DEPENDENCIES_WELD = 0x0A00; public static final int DEPENDENCIES_SEAM = 0x0A01; public static final int DEPENDENCIES_WS = 0x0C00; public static final int DEPENDENCIES_SECURITY = 0x0C50; public static final int DEPENDENCIES_JAXRS = 0x0D00; public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00; public static final int DEPENDENCIES_PERSISTENCE_ANNOTATION = 0x0F00; public static final int DEPENDENCIES_JPA = 0x1000; public static final int DEPENDENCIES_GLOBAL_MODULES = 0x1100; public static final int DEPENDENCIES_JDK = 0x1200; public static final int DEPENDENCIES_JACORB = 0x1300; public static final int DEPENDENCIES_CMP = 0x1500; public static final int DEPENDENCIES_JAXR = 0x1600; public static final int DEPENDENCIES_DRIVERS = 0x1700; public static final int DEPENDENCIES_JSF = 0x1800; public static final int DEPENDENCIES_BUNDLE_CONTEXT_BINDING = 0x1900; //these must be last, and in this specific order public static final int DEPENDENCIES_APPLICATION_CLIENT = 0x2000; public static final int DEPENDENCIES_VISIBLE_MODULES = 0x2100; public static final int DEPENDENCIES_EE_CLASS_DESCRIPTIONS = 0x2200; // CONFIGURE_MODULE public static final int CONFIGURE_RESOLVE_BUNDLE = 0x0100; public static final int CONFIGURE_MODULE_SPEC = 0x0200; // FIRST_MODULE_USE public static final int FIRST_MODULE_USE_PERSISTENCE_CLASS_FILE_TRANSFORMER = 0x0100; // need to be before POST_MODULE_REFLECTION_INDEX // and anything that could load class definitions public static final int FIRST_MODULE_USE_INTERCEPTORS = 0x0200; public static final int FIRST_MODULE_USE_PERSISTENCE_PREPARE = 0x0300; public static final int FIRST_MODULE_USE_DSXML_DEPLOYMENT = 0x0400; public static final int FIRST_MODULE_USE_TRANSFORMER = 0x0500; // POST_MODULE public static final int POST_MODULE_INJECTION_ANNOTATION = 0x0100; public static final int POST_MODULE_REFLECTION_INDEX = 0x0200; public static final int POST_MODULE_JSF_MANAGED_BEANS = 0x0300; public static final int POST_MODULE_INTERCEPTOR_ANNOTATIONS = 0x0301; public static final int POST_MODULE_EJB_BUSINESS_VIEW_ANNOTATION = 0x0400; public static final int POST_MODULE_EJB_HOME_MERGE = 0x0401; public static final int POST_MODULE_EJB_DD_METHOD_RESOLUTION = 0x0402; public static final int POST_MODULE_EJB_TIMER_METADATA_MERGE = 0x0506; public static final int POST_MODULE_EJB_SLSB_POOL_NAME_MERGE = 0x0507; public static final int POST_MODULE_EJB_MDB_POOL_NAME_MERGE = 0x0508; public static final int POST_MODULE_EJB_ENTITY_POOL_NAME_MERGE = 0x0509; public static final int POST_MODULE_EJB_DD_INTERCEPTORS = 0x0600; public static final int POST_MODULE_EJB_TIMER_SERVICE = 0x0601; public static final int POST_MODULE_EJB_TRANSACTION_MANAGEMENT = 0x0602; public static final int POST_MODULE_EJB_TX_ATTR_MERGE = 0x0603; public static final int POST_MODULE_EJB_CONCURRENCY_MANAGEMENT_MERGE= 0x0604; public static final int POST_MODULE_EJB_CONCURRENCY_MERGE = 0x0605; public static final int POST_MODULE_EJB_RUN_AS_MERGE = 0x0606; public static final int POST_MODULE_EJB_RESOURCE_ADAPTER_MERGE = 0x0607; public static final int POST_MODULE_EJB_REMOVE_METHOD = 0x0608; public static final int POST_MODULE_EJB_STARTUP_MERGE = 0x0609; public static final int POST_MODULE_EJB_SECURITY_DOMAIN = 0x060A; public static final int POST_MODULE_EJB_ROLES = 0x060B; public static final int POST_MODULE_METHOD_PERMISSIONS = 0x060C; public static final int POST_MODULE_EJB_STATEFUL_TIMEOUT = 0x060D; public static final int POST_MODULE_EJB_ASYNCHRONOUS_MERGE = 0x060E; public static final int POST_MODULE_EJB_SESSION_SYNCHRONIZATION = 0x060F; public static final int POST_MODULE_EJB_INIT_METHOD = 0x0610; public static final int POST_MODULE_EJB_SESSION_BEAN = 0x0611; public static final int POST_MODULE_EJB_SECURITY_PRINCIPAL_ROLE_MAPPING_MERGE = 0x0612; public static final int POST_MODULE_EJB_CACHE = 0x0614; public static final int POST_MODULE_EJB_CLUSTERED = 0x0615; public static final int POST_MODULE_WELD_WEB_INTEGRATION = 0x0700; public static final int POST_MODULE_WELD_COMPONENT_INTEGRATION = 0x0800; public static final int POST_MODULE_INSTALL_EXTENSION = 0x0A00; public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0B00; public static final int POST_MODULE_EAR_DEPENDENCY = 0x0C00; public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0D00; public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0E00; // should come before ejb jndi bindings processor public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x1000; public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x1100; public static final int POST_MODULE_EJB_CLIENT_METADATA = 0x1102; public static final int POST_MODULE_EJB_APPLICATION_EXCEPTIONS = 0x1200; public static final int POST_INITIALIZE_IN_ORDER = 0x1300; public static final int POST_MODULE_ENV_ENTRY = 0x1400; public static final int POST_MODULE_EJB_REF = 0x1500; public static final int POST_MODULE_PERSISTENCE_REF = 0x1600; public static final int POST_MODULE_DATASOURCE_REF = 0x1700; public static final int POST_MODULE_WS_REF_DESCRIPTOR = 0x1800; public static final int POST_MODULE_WS_REF_ANNOTATION = 0x1801; public static final int POST_MODULE_JAXRS_SCANNING = 0x1A00; public static final int POST_MODULE_JAXRS_COMPONENT = 0x1B00; public static final int POST_MODULE_JAXRS_CDI_INTEGRATION = 0x1C00; public static final int POST_MODULE_LOCAL_HOME = 0x1E00; public static final int POST_MODULE_APPLICATION_CLIENT_MANIFEST = 0x1F00; public static final int POST_MODULE_APPLICATION_CLIENT_ACTIVE = 0x2000; public static final int POST_MODULE_EJB_ORB_BIND = 0x2100; public static final int POST_MODULE_CMP_PARSE = 0x2300; public static final int POST_MODULE_CMP_ENTITY_METADATA = 0x2400; public static final int POST_MODULE_CMP_STORE_MANAGER = 0x2500; public static final int POST_MODULE_EJB_IIOP = 0x2600; public static final int POST_MODULE_POJO = 0x2700; public static final int POST_MODULE_NAMING_CONTEXT = 0x2800; public static final int POST_MODULE_APP_NAMING_CONTEXT = 0x2900; public static final int POST_MODULE_CACHED_CONNECTION_MANAGER = 0x2A00; public static final int POST_MODULE_LOGGING_CONFIG = 0x2B00; public static final int POST_MODULE_EL_EXPRESSION_FACTORY = 0x2C00; public static final int POST_MODULE_SAR_SERVICE_COMPONENT = 0x2D00; // INSTALL public static final int INSTALL_JACC_POLICY = 0x0350; public static final int INSTALL_COMPONENT_AGGREGATION = 0x0400; public static final int INSTALL_RESOLVE_MESSAGE_DESTINATIONS = 0x0403; public static final int INSTALL_EJB_CLIENT_CONTEXT = 0x0404; public static final int INSTALL_EJB_JACC_PROCESSING = 0x0405; public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500; public static final int INSTALL_RESOLVER_MODULE = 0x0600; public static final int INSTALL_RA_NATIVE = 0x0800; public static final int INSTALL_RA_DEPLOYMENT = 0x0801; public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900; public static final int INSTALL_POJO_DEPLOYMENT = 0x0A00; public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00; public static final int INSTALL_EE_MODULE_CONFIG = 0x1101; public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200; public static final int INSTALL_DEPENDS_ON_ANNOTATION = 0x1210; public static final int INSTALL_PERSISTENTUNIT = 0x1220; public static final int INSTALL_EE_COMPONENT = 0x1230; public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300; public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500; public static final int INSTALL_JSF_ANNOTATIONS = 0x1600; public static final int INSTALL_JDBC_DRIVER = 0x1800; public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900; public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00; public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00; public static final int INSTALL_JNDI_DEPENDENCIES = 0x1C01; public static final int INSTALL_WS_UNIVERSAL_META_DATA_MODEL = 0x1C10; public static final int INSTALL_WS_DEPLOYMENT_ASPECTS = 0x1C11; // IMPORTANT: WS integration installs deployment aspects dynamically // so consider INSTALL 0x1C10 - 0x1CFF reserved for WS subsystem! public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00; public static final int INSTALL_WAB_DEPLOYMENT = 0x1E00; public static final int INSTALL_DEPLOYMENT_REPOSITORY = 0x1F00; public static final int INSTALL_EJB_MANAGEMENT_RESOURCES = 0x2000; public static final int INSTALL_APPLICATION_CLIENT = 0x2010; public static final int INSTALL_MESSAGING_XML_RESOURCES = 0x2030; public static final int INSTALL_BUNDLE_ACTIVATE = 0x2040; public static final int INSTALL_WAB_SERVLETCONTEXT_SERVICE = 0x2050; public static final int INSTALL_PERSISTENCE_SERVICES = 0x2060; public static final int INSTALL_DEPLOYMENT_COMPLETE_SERVICE = 0x2100; // CLEANUP public static final int CLEANUP_REFLECTION_INDEX = 0x0100; public static final int CLEANUP_EE = 0x0200; public static final int CLEANUP_EJB = 0x0300; public static final int CLEANUP_ANNOTATION_INDEX = 0x0400; }