answer
stringlengths
17
10.2M
package com.streamdata.apps.cryptochat.utils; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Network { public static final String NETWORK_LOG_TAG = "Network"; public static final int DEFAULT_TIMEOUT = 5000; public static String getJSON(String url, int timeout) { HttpURLConnection connection = null; try { // setup and process connection URL u = new URL(url); connection = (HttpURLConnection) u.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-length", "0"); connection.setUseCaches(false); connection.setAllowUserInteraction(false); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.connect(); // receive data from input stream on successful response int status = connection.getResponseCode(); switch (status) { case 200: case 201: BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line).append("\n"); } reader.close(); return stringBuilder.toString(); } } catch (IOException ex) { Log.d(NETWORK_LOG_TAG, null, ex); } finally { // close connection if necessary if (connection != null) { try { connection.disconnect(); } catch (Exception ex) { Log.d(NETWORK_LOG_TAG, null, ex); } } } return null; } }
package de.cs.fau.mad.quickshop.android.common; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable(tableName = "group") public class Group { @DatabaseField(generatedId = true) private int id; @DatabaseField(canBeNull = false) private String name; @DatabaseField(canBeNull = true) private String displayNameResourceName; public Group() { // Default no-arg constructor for generating Groups, required for ORMLite } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplayNameResourceName() { return displayNameResourceName; } public void setDisplayNameResourceName(String value) { this.displayNameResourceName = value; } @Override public int hashCode() { return getName().hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other instanceof Group) { return equals((Group) other); } else { return false; } } public boolean equals(Group other) { if (other == null) { return false; } return other.getId() == this.getId() && other.getName().equals(this.getName()); } }
package de.fau.cs.mad.fablab.android.ui; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import de.fau.cs.mad.fablab.android.FabButton; import de.fau.cs.mad.fablab.android.R; import de.fau.cs.mad.fablab.android.cart.CartSingleton; import de.fau.cs.mad.fablab.android.navdrawer.AppbarDrawerInclude; import de.fau.cs.mad.fablab.android.productsearch.AutoCompleteHelper; import de.fau.cs.mad.fablab.rest.NewsApiClient; import de.fau.cs.mad.fablab.rest.core.ICal; import de.fau.cs.mad.fablab.rest.core.News; import de.fau.cs.mad.fablab.rest.myapi.NewsApi; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; import roboguice.activity.RoboActionBarActivity; import roboguice.inject.ContentView; import roboguice.inject.InjectView; @ContentView(R.layout.activity_news) public class NewsActivity extends RoboActionBarActivity { @InjectView(R.id.cart_recycler_view) RecyclerView cart_rv; @InjectView(R.id.news) RecyclerView news_rv; @InjectView(R.id.dates_view_pager) ViewPager datesViewPager; private DatesSlidePagerAdapter datesSlidePagerAdapter; private RecyclerView.LayoutManager newsLayoutManager; private NewsAdapter newsAdapter; private UiUtils uiUtils; private List<News> newsList; private NewsApi newsApi; private AppbarDrawerInclude appbarDrawer; static final String IMAGE = "IMAGE"; static final String TITLE = "TITLE"; static final String TEXT = "TEXT"; static final String ICAL1 = "ICAL1"; static final String ICAL2 = "ICAL2"; //This callback is used for product Search. private Callback<List<News>> newsCallback = new Callback<List<News>>() { @Override public void success(List<News> news, Response response) { if (news.isEmpty()) { Toast.makeText(getBaseContext(), R.string.product_not_found, Toast.LENGTH_LONG).show(); } newsList.clear(); for (News singleNews : news) { singleNews.setDescription(uiUtils.processNewsText(singleNews.getDescription())); newsList.add(singleNews); } newsAdapter = new NewsAdapter(newsList); news_rv.setAdapter(newsAdapter); } @Override public void failure(RetrofitError error) { Toast.makeText(getBaseContext(), R.string.retrofit_callback_failure, Toast.LENGTH_LONG).show(); newsAdapter = new NewsAdapter(newsList); news_rv.setAdapter(newsAdapter); } }; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiUtils = new UiUtils(); appbarDrawer = AppbarDrawerInclude.getInstance(this); appbarDrawer.create(); if (savedInstanceState == null) { // init db and cart - always do this on app start CartSingleton.MYCART.init(getApplication()); } // init cart panel CartSingleton.MYCART.setSlidingUpPanel(this, findViewById(android.R.id.content), true); // init Floating Action Menu FabButton.MYFABUTTON.init(findViewById(android.R.id.content), this); //get news and set them newsLayoutManager = new LinearLayoutManager(getApplicationContext()); news_rv.setLayoutManager(newsLayoutManager); newsList = new ArrayList<>(); newsApi = new NewsApiClient(this).get(); newsApi.findAll(newsCallback); List<ICal> listDates = new ArrayList<>(); ICal date1 = new ICal(); date1.setLocation("Fablab"); date1.setSummery("OpenLab"); listDates.add(date1); ICal date2 = new ICal(); date2.setLocation("Fablab"); date2.setSummery("SelfLab"); listDates.add(date2); ICal date3 = new ICal(); date3.setLocation("Cafete"); date3.setSummery("Kaffeetrinken"); listDates.add(date3); ICal date4 = new ICal(); date4.setLocation("ziemlich lange location"); date4.setSummery("ziemlich langer Veranstaltungstitel"); listDates.add(date4); ICal date5 = new ICal(); date5.setLocation("CIP"); date5.setSummery("Test ungerade"); listDates.add(date5); datesSlidePagerAdapter = new DatesSlidePagerAdapter(getSupportFragmentManager(), listDates); datesViewPager.setAdapter(datesSlidePagerAdapter); //Load Autocompleteionwords AutoCompleteHelper.getInstance().loadProductNames(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { appbarDrawer.createMenu(menu); appbarDrawer.startTimer(); return true; } @Override public void onPause() { super.onPause(); appbarDrawer.stopTimer(); } @Override public void onResume() { super.onResume(); CartSingleton.MYCART.setSlidingUpPanel(this, findViewById(android.R.id.content), true); appbarDrawer.startTimer(); //Load Autocompleteionwords AutoCompleteHelper.getInstance().loadProductNames(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_opened) { appbarDrawer.updateOpenState(item); Toast appbar_opened_toast = Toast.makeText(this, appbarDrawer.openedMessage, Toast.LENGTH_SHORT); appbar_opened_toast.show(); return true; } return super.onOptionsItemSelected(item); } public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> { private List<News> news = new ArrayList<>(); @Override public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_entry, parent, false); return new NewsViewHolder(view); } @Override public void onBindViewHolder(NewsViewHolder holder, int position) { holder.setNews(news.get(position)); } @Override public int getItemCount() { return news.size(); } public NewsAdapter(List<News> newsList) { this.news = newsList; } public class NewsViewHolder extends RecyclerView.ViewHolder { private final View view; private final TextView titleView, subTitleView; private final ImageView iconView; private String description; public NewsViewHolder(View view) { super(view); this.view = view; this.titleView = (TextView) view.findViewById(R.id.title_news_entry); this.subTitleView = (TextView) view.findViewById(R.id.text_news_entry); this.iconView = (ImageView) view.findViewById(R.id.icon_news_entry); } public void setNews(News news) { description = news.getDescription(); this.titleView.setText(news.getTitle()); this.subTitleView.setText(Html.fromHtml(description)); if(news.getLinkToPreviewImage() != null) { new DownloadImageTask(iconView) .execute(news.getLinkToPreviewImage()); } view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView title = (TextView) v.findViewById(R.id.title_news_entry); TextView text = (TextView) v.findViewById(R.id.text_news_entry); ImageView image = (ImageView) v.findViewById(R.id.icon_news_entry); Bundle args = new Bundle(); args.putString(TITLE, title.getText().toString()); args.putString(TEXT, description); args.putParcelable(IMAGE, ((BitmapDrawable) image.getDrawable()).getBitmap()); NewsDialog dialog = new NewsDialog(); dialog.setArguments(args); dialog.show(getSupportFragmentManager(), "news dialog"); } }); } } } private class DatesSlidePagerAdapter extends FragmentStatePagerAdapter { List<ICal> dates = new ArrayList<>(); public DatesSlidePagerAdapter(FragmentManager fm) { super(fm); } public DatesSlidePagerAdapter(FragmentManager fm, List<ICal> dates) { super(fm); this.dates = dates; } @Override public Fragment getItem(int position) { int arrayPosition = position *2; Bundle args = new Bundle(); args.putSerializable(ICAL1, dates.get(arrayPosition)); if(arrayPosition+1 < dates.size()) { args.putSerializable(ICAL2, dates.get(arrayPosition+1)); } DatesFragment datesFragment = new DatesFragment(); datesFragment.setArguments(args); return datesFragment; } @Override public int getCount() { return (dates.size()+1)/2; } } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } }
package fr.free.nrw.commons.nearby; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.annotations.MarkerOptions; import com.mapbox.mapboxsdk.annotations.PolygonOptions; import com.mapbox.mapboxsdk.camera.CameraPosition; import com.mapbox.mapboxsdk.constants.Style; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.MapboxMapOptions; import com.mapbox.services.android.telemetry.MapboxTelemetry; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import fr.free.nrw.commons.R; import fr.free.nrw.commons.utils.UriDeserializer; public class NearbyMapFragment extends android.support.v4.app.Fragment { private MapView mapView; private List<NearbyBaseMarker> baseMarkerOptions; private fr.free.nrw.commons.location.LatLng curLatLng; private View bottomSheetList; private View bottomSheetDetails; private BottomSheetBehavior bottomSheetListBehavior; private BottomSheetBehavior bottomSheetDetailsBehavior; private FloatingActionButton fabList; private FloatingActionButton fabPlus; private FloatingActionButton fabCamera; private FloatingActionButton fabGallery; private View transparentView; private boolean isFabOpen=false; private Animation rotate_backward; private Animation fab_close; private Animation fab_open; private Animation rotate_forward; public NearbyMapFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = this.getArguments(); initViews(); setListeners(); Gson gson = new GsonBuilder() .registerTypeAdapter(Uri.class, new UriDeserializer()) .create(); if (bundle != null) { String gsonPlaceList = bundle.getString("PlaceList"); String gsonLatLng = bundle.getString("CurLatLng"); Type listType = new TypeToken<List<Place>>() {}.getType(); List<Place> placeList = gson.fromJson(gsonPlaceList, listType); Type curLatLngType = new TypeToken<fr.free.nrw.commons.location.LatLng>() {}.getType(); curLatLng = gson.fromJson(gsonLatLng, curLatLngType); baseMarkerOptions = NearbyController .loadAttractionsFromLocationToBaseMarkerOptions(curLatLng, placeList, getActivity()); } Mapbox.getInstance(getActivity(), getString(R.string.mapbox_commons_app_token)); MapboxTelemetry.getInstance().setTelemetryEnabled(false); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (curLatLng != null) { setupMapView(savedInstanceState); } setHasOptionsMenu(false); return mapView; } private void initViews() { bottomSheetList = getActivity().findViewById(R.id.bottom_sheet); bottomSheetListBehavior = BottomSheetBehavior.from(bottomSheetList); bottomSheetDetails = getActivity().findViewById(R.id.bottom_sheet_details); bottomSheetDetailsBehavior = BottomSheetBehavior.from(bottomSheetDetails); bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); fabList = getActivity().findViewById(R.id.fab_list); fabPlus = getActivity().findViewById(R.id.fab_plus); fabCamera = getActivity().findViewById(R.id.fab_camera); fabGallery = getActivity().findViewById(R.id.fab_galery); fab_open = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_open); fab_close = AnimationUtils.loadAnimation(getActivity(),R.anim.fab_close); rotate_forward = AnimationUtils.loadAnimation(getActivity(),R.anim.rotate_forward); rotate_backward = AnimationUtils.loadAnimation(getActivity(),R.anim.rotate_backward); transparentView = getActivity().findViewById(R.id.transparentView); } private void setListeners() { fabPlus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { animateFAB(isFabOpen); } }); bottomSheetDetails.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(bottomSheetDetailsBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } else{ bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } } }); bottomSheetDetailsBehavior.setBottomSheetCallback(new BottomSheetBehavior .BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { prepareViewsForSheetPosition(newState); } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { if(slideOffset>=0){ transparentView.setAlpha(slideOffset); } } }); bottomSheetListBehavior.setBottomSheetCallback(new BottomSheetBehavior .BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { if (newState == BottomSheetBehavior.STATE_EXPANDED){ bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { } }); } private void setupMapView(Bundle savedInstanceState) { MapboxMapOptions options = new MapboxMapOptions() .styleUrl(Style.OUTDOORS) .logoEnabled(false) .attributionEnabled(false) .camera(new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())) .zoom(11) .build()); // create map mapView = new MapView(getActivity(), options); mapView.onCreate(savedInstanceState); mapView.getMapAsync(mapboxMap -> { mapboxMap.addMarkers(baseMarkerOptions); mapboxMap.setOnMarkerClickListener(marker -> { if (marker instanceof NearbyMarker) { NearbyMarker nearbyMarker = (NearbyMarker) marker; Place place = nearbyMarker.getNearbyBaseMarker().getPlace(); passInfoToSheet(place); bottomSheetListBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); //NearbyInfoDialog.showYourself(getActivity(), place); } return false; }); addCurrentLocationMarker(mapboxMap); }); mapView.setStyleUrl("asset://mapstyle.json"); } /** * Adds a marker for the user's current position. Adds a * circle which uses the accuracy * 2, to draw a circle * which represents the user's position with an accuracy * of 95%. */ private void addCurrentLocationMarker(MapboxMap mapboxMap) { MarkerOptions currentLocationMarker = new MarkerOptions() .position(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())); mapboxMap.addMarker(currentLocationMarker); List<LatLng> circle = createCircleArray(curLatLng.getLatitude(), curLatLng.getLongitude(), curLatLng.getAccuracy() * 2, 100); mapboxMap.addPolygon( new PolygonOptions() .addAll(circle) .strokeColor(Color.parseColor("#55000000")) .fillColor(Color.parseColor("#11000000")) ); } /** * Creates a series of points that create a circle on the map. * Takes the center latitude, center longitude of the circle, * the radius in meter and the number of nodes of the circle. * * @return List List of LatLng points of the circle. */ private List<LatLng> createCircleArray( double centerLat, double centerLong, float radius, int nodes) { List<LatLng> circle = new ArrayList<>(); float radiusKilometer = radius / 1000; double radiusLong = radiusKilometer / (111.320 * Math.cos(centerLat * Math.PI / 180)); double radiusLat = radiusKilometer / 110.574; for (int i = 0; i < nodes; i++) { double theta = ((double) i / (double) nodes) * (2 * Math.PI); double nodeLongitude = centerLong + radiusLong * Math.cos(theta); double nodeLatitude = centerLat + radiusLat * Math.sin(theta); circle.add(new LatLng(nodeLatitude, nodeLongitude)); } return circle; } public void prepareViewsForSheetPosition(int bottomSheetState) { if(bottomSheetState==BottomSheetBehavior.STATE_COLLAPSED){ if(!fabList.isShown()) fabList.show(); closeFabs(isFabOpen); if(!fabPlus.isShown()){ CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fabPlus.getLayoutParams(); p.setAnchorId(getActivity().findViewById(R.id.bottom_sheet_details).getId()); fabPlus.setLayoutParams(p); fabPlus.show(); } this.getView().requestFocus(); //moreInfo.setVisibility(View.VISIBLE); //NearbyActivity.bottomSheetStatus = NearbyActivity.BottomSheetStatus.DISPLAY_DETAILS_SHEET_COLLAPSED; } else if(bottomSheetState==BottomSheetBehavior.STATE_EXPANDED){ if(fabList.isShown()) fabList.hide(); this.getView().requestFocus(); //moreInfo.setVisibility(View.GONE); //NearbyActivity.bottomSheetStatus = NearbyActivity.BottomSheetStatus.DISPLAY_DETAILS_SHEET_EXPANDED; } else if(bottomSheetState==BottomSheetBehavior.STATE_HIDDEN){ closeFabs(isFabOpen); //get rid of anchors CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fabPlus.getLayoutParams(); p.setAnchorId(View.NO_ID); fabPlus.setLayoutParams(p); fabPlus.hide(); //moreInfo.setVisibility(View.GONE); } //currBottomSheetState = bottomSheetState; } private void passInfoToSheet(Place place) { } private void animateFAB(boolean isFabOpen) { if (isFabOpen) { fabPlus.startAnimation(rotate_backward); fabCamera.startAnimation(fab_close); fabGallery.startAnimation(fab_close); fabCamera.setClickable(false); fabGallery.setClickable(false); } else { fabPlus.startAnimation(rotate_forward); fabCamera.startAnimation(fab_open); fabGallery.startAnimation(fab_open); fabCamera.setClickable(true); fabGallery.setClickable(true); } this.isFabOpen=!isFabOpen; } private void closeFabs(boolean isFabOpen){ if(isFabOpen){ fabPlus.startAnimation(rotate_backward); fabCamera.startAnimation(fab_close); fabGallery.startAnimation(fab_close); fabCamera.setClickable(false); fabGallery.setClickable(false); this.isFabOpen=!isFabOpen; } } @Override public void onStart() { if (mapView != null) { mapView.onStart(); } super.onStart(); } @Override public void onPause() { if (mapView != null) { mapView.onPause(); } super.onPause(); } @Override public void onResume() { if (mapView != null) { mapView.onResume(); } super.onResume(); } @Override public void onStop() { if (mapView != null) { mapView.onStop(); } super.onStop(); } @Override public void onDestroyView() { if (mapView != null) { mapView.onDestroy(); } super.onDestroyView(); } }
package fr.free.nrw.commons.nearby; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.annotations.MarkerOptions; import com.mapbox.mapboxsdk.annotations.PolygonOptions; import com.mapbox.mapboxsdk.camera.CameraPosition; import com.mapbox.mapboxsdk.constants.Style; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.MapboxMapOptions; import com.mapbox.services.android.telemetry.MapboxTelemetry; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import fr.free.nrw.commons.R; import fr.free.nrw.commons.utils.UriDeserializer; import timber.log.Timber; public class NearbyMapFragment extends android.support.v4.app.Fragment { private MapView mapView; private List<NearbyBaseMarker> baseMarkerOptions; private fr.free.nrw.commons.location.LatLng curLatLng; private View bottomSheetList; private View bottomSheetDetails; private BottomSheetBehavior bottomSheetListBehavior; private BottomSheetBehavior bottomSheetDetailsBehavior; private LinearLayout wikipediaButton; private LinearLayout wikidataButton; private LinearLayout directionsButton; private LinearLayout commonsButton; private FloatingActionButton fabPlus; private FloatingActionButton fabCamera; private FloatingActionButton fabGallery; private View transparentView; private TextView description; private TextView title; private TextView distance; private ImageView icon; private TextView wikipediaButtonText; private TextView wikidataButtonText; private TextView commonsButtonText; private TextView directionsButtonText; private boolean isFabOpen=false; private Animation rotate_backward; private Animation fab_close; private Animation fab_open; private Animation rotate_forward; private Place place; public NearbyMapFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = this.getArguments(); initViews(); setListeners(); Gson gson = new GsonBuilder() .registerTypeAdapter(Uri.class, new UriDeserializer()) .create(); if (bundle != null) { String gsonPlaceList = bundle.getString("PlaceList"); String gsonLatLng = bundle.getString("CurLatLng"); Type listType = new TypeToken<List<Place>>() {}.getType(); List<Place> placeList = gson.fromJson(gsonPlaceList, listType); Type curLatLngType = new TypeToken<fr.free.nrw.commons.location.LatLng>() {}.getType(); curLatLng = gson.fromJson(gsonLatLng, curLatLngType); baseMarkerOptions = NearbyController .loadAttractionsFromLocationToBaseMarkerOptions(curLatLng, placeList, getActivity()); } Mapbox.getInstance(getActivity(), getString(R.string.mapbox_commons_app_token)); MapboxTelemetry.getInstance().setTelemetryEnabled(false); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (curLatLng != null) { setupMapView(savedInstanceState); } setHasOptionsMenu(false); return mapView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.getView().setFocusableInTouchMode(true); this.getView().requestFocus(); this.getView().setOnKeyListener( new View.OnKeyListener() { @Override public boolean onKey( View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if(bottomSheetDetailsBehavior.getState() == BottomSheetBehavior .STATE_EXPANDED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); return true; } else if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior .STATE_COLLAPSED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); return true; } } return false; } } ); } private void initViews() { bottomSheetList = getActivity().findViewById(R.id.bottom_sheet); bottomSheetListBehavior = BottomSheetBehavior.from(bottomSheetList); bottomSheetDetails = getActivity().findViewById(R.id.bottom_sheet_details); bottomSheetDetailsBehavior = BottomSheetBehavior.from(bottomSheetDetails); bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); fabPlus = getActivity().findViewById(R.id.fab_plus); fabCamera = getActivity().findViewById(R.id.fab_camera); fabGallery = getActivity().findViewById(R.id.fab_galery); fab_open = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_open); fab_close = AnimationUtils.loadAnimation(getActivity(),R.anim.fab_close); rotate_forward = AnimationUtils.loadAnimation(getActivity(),R.anim.rotate_forward); rotate_backward = AnimationUtils.loadAnimation(getActivity(),R.anim.rotate_backward); transparentView = getActivity().findViewById(R.id.transparentView); description = getActivity().findViewById(R.id.description); title = getActivity().findViewById(R.id.title); distance = getActivity().findViewById(R.id.category); icon = getActivity().findViewById(R.id.icon); wikidataButton = getActivity().findViewById(R.id.wikidataButton); wikipediaButton = getActivity().findViewById(R.id.wikipediaButton); directionsButton = getActivity().findViewById(R.id.directionsButton); commonsButton = getActivity().findViewById(R.id.commonsButton); wikidataButtonText = getActivity().findViewById(R.id.wikidataButtonText); wikipediaButtonText = getActivity().findViewById(R.id.wikipediaButtonText); directionsButtonText = getActivity().findViewById(R.id.directionsButtonText); commonsButtonText = getActivity().findViewById(R.id.commonsButtonText); } private void setListeners() { fabPlus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { animateFAB(isFabOpen); } }); bottomSheetDetails.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(bottomSheetDetailsBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } else{ bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } } }); bottomSheetDetailsBehavior.setBottomSheetCallback(new BottomSheetBehavior .BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { prepareViewsForSheetPosition(newState); } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { if (slideOffset >= 0) { transparentView.setAlpha(slideOffset); if (slideOffset == 1) { transparentView.setClickable(true); } else if (slideOffset == 0){ transparentView.setClickable(false); } } } }); bottomSheetListBehavior.setBottomSheetCallback(new BottomSheetBehavior .BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { if (newState == BottomSheetBehavior.STATE_EXPANDED){ bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { } }); // Remove texts if it doesnt fit if (wikipediaButtonText.getLineCount() > 1 || wikidataButtonText.getLineCount() > 1 || commonsButtonText.getLineCount() > 1 || directionsButtonText.getLineCount() > 1) { wikipediaButtonText.setVisibility(View.GONE); wikidataButtonText.setVisibility(View.GONE); commonsButtonText.setVisibility(View.GONE); directionsButtonText.setVisibility(View.GONE); } } private void setupMapView(Bundle savedInstanceState) { MapboxMapOptions options = new MapboxMapOptions() .styleUrl(Style.OUTDOORS) .camera(new CameraPosition.Builder() .target(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())) .zoom(11) .build()); // create map mapView = new MapView(getActivity(), options); mapView.onCreate(savedInstanceState); mapView.getMapAsync(mapboxMap -> { mapboxMap.addMarkers(baseMarkerOptions); mapboxMap.setOnMarkerClickListener(marker -> { if (marker instanceof NearbyMarker) { NearbyMarker nearbyMarker = (NearbyMarker) marker; Place place = nearbyMarker.getNearbyBaseMarker().getPlace(); passInfoToSheet(place); bottomSheetListBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } return false; }); addCurrentLocationMarker(mapboxMap); }); mapView.setStyleUrl("asset://mapstyle.json"); } /** * Adds a marker for the user's current position. Adds a * circle which uses the accuracy * 2, to draw a circle * which represents the user's position with an accuracy * of 95%. */ private void addCurrentLocationMarker(MapboxMap mapboxMap) { MarkerOptions currentLocationMarker = new MarkerOptions() .position(new LatLng(curLatLng.getLatitude(), curLatLng.getLongitude())); mapboxMap.addMarker(currentLocationMarker); List<LatLng> circle = createCircleArray(curLatLng.getLatitude(), curLatLng.getLongitude(), curLatLng.getAccuracy() * 2, 100); mapboxMap.addPolygon( new PolygonOptions() .addAll(circle) .strokeColor(Color.parseColor("#55000000")) .fillColor(Color.parseColor("#11000000")) ); } /** * Creates a series of points that create a circle on the map. * Takes the center latitude, center longitude of the circle, * the radius in meter and the number of nodes of the circle. * * @return List List of LatLng points of the circle. */ private List<LatLng> createCircleArray( double centerLat, double centerLong, float radius, int nodes) { List<LatLng> circle = new ArrayList<>(); float radiusKilometer = radius / 1000; double radiusLong = radiusKilometer / (111.320 * Math.cos(centerLat * Math.PI / 180)); double radiusLat = radiusKilometer / 110.574; for (int i = 0; i < nodes; i++) { double theta = ((double) i / (double) nodes) * (2 * Math.PI); double nodeLongitude = centerLong + radiusLong * Math.cos(theta); double nodeLatitude = centerLat + radiusLat * Math.sin(theta); circle.add(new LatLng(nodeLatitude, nodeLongitude)); } return circle; } public void prepareViewsForSheetPosition(int bottomSheetState) { switch (bottomSheetState) { case (BottomSheetBehavior.STATE_COLLAPSED): closeFabs(isFabOpen); if (!fabPlus.isShown()) showFAB(); this.getView().requestFocus(); break; case (BottomSheetBehavior.STATE_EXPANDED): this.getView().requestFocus(); break; case (BottomSheetBehavior.STATE_HIDDEN): transparentView.setClickable(false); transparentView.setAlpha(0); closeFabs(isFabOpen); hideFAB(); this.getView().requestFocus(); break; } } private void hideFAB() { //get rid of anchors CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fabPlus .getLayoutParams(); p.setAnchorId(View.NO_ID); fabPlus.setLayoutParams(p); fabPlus.hide(); fabCamera.hide(); fabGallery.hide(); } private void showFAB() { CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fabPlus.getLayoutParams(); p.setAnchorId(getActivity().findViewById(R.id.bottom_sheet_details).getId()); fabPlus.setLayoutParams(p); fabPlus.show(); } private void passInfoToSheet(Place place) { this.place = place; wikipediaButton.setEnabled( !(place.siteLinks == null || Uri.EMPTY.equals(place.siteLinks.getWikipediaLink()))); wikipediaButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openWebView(place.siteLinks.getWikipediaLink()); } }); wikidataButton.setEnabled( !(place.siteLinks == null || Uri.EMPTY.equals(place.siteLinks.getWikidataLink()))); wikidataButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openWebView(place.siteLinks.getWikidataLink()); } }); directionsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { LatLng location = new LatLng(place.location.getLatitude() , place.location.getLongitude(), 0); //Open map app at given position Uri gmmIntentUri = Uri.parse( "geo:0,0?q=" + location.getLatitude() + "," + location.getLongitude()); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); if (mapIntent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(mapIntent); } } }); commonsButton.setEnabled( !(place.siteLinks == null || Uri.EMPTY.equals(place.siteLinks.getCommonsLink()))); commonsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openWebView(place.siteLinks.getCommonsLink()); } }); icon.setImageResource(place.getDescription().getIcon()); description.setText(place.getLongDescription()); title.setText(place.name.toString()); distance.setText(place.distance.toString()); fabCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //TODO: Change this to activate camera upload (see ContributionsListFragment). Insert shared preference. Timber.d("Image title: " + place.getName() + "Image desc: " + place.getLongDescription()); openWebView(place.siteLinks.getWikidataLink()); } }); fabGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //TODO: Change this to activate gallery upload (see ContributionsListFragment). Insert shared preference. Timber.d("Image title: " + place.getName() + "Image desc: " + place.getLongDescription()); openWebView(place.siteLinks.getWikidataLink()); } }); } private void openWebView(Uri link) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, link); startActivity(browserIntent); } private void animateFAB(boolean isFabOpen) { if (isFabOpen) { fabPlus.startAnimation(rotate_backward); fabCamera.startAnimation(fab_close); fabGallery.startAnimation(fab_close); fabCamera.hide(); fabGallery.hide(); } else { fabPlus.startAnimation(rotate_forward); fabCamera.startAnimation(fab_open); fabGallery.startAnimation(fab_open); fabCamera.show(); fabGallery.show(); } this.isFabOpen=!isFabOpen; } private void closeFabs(boolean isFabOpen){ if (isFabOpen) { fabPlus.startAnimation(rotate_backward); fabCamera.startAnimation(fab_close); fabGallery.startAnimation(fab_close); fabCamera.hide(); fabGallery.hide(); this.isFabOpen=!isFabOpen; } } @Override public void onStart() { if (mapView != null) { mapView.onStart(); } super.onStart(); } @Override public void onPause() { if (mapView != null) { mapView.onPause(); } super.onPause(); } @Override public void onResume() { if (mapView != null) { mapView.onResume(); } super.onResume(); } @Override public void onStop() { if (mapView != null) { mapView.onStop(); } super.onStop(); } @Override public void onDestroyView() { if (mapView != null) { mapView.onDestroy(); } super.onDestroyView(); } }
package me.shkschneider.app.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.google.gson.JsonObject; import me.shkschneider.app.R; import me.shkschneider.skeleton.SkeletonFragment; import me.shkschneider.skeleton.WebServiceIon; import me.shkschneider.skeleton.helper.ActivityHelper; import me.shkschneider.skeleton.helper.GsonParser; import me.shkschneider.skeleton.helper.LogHelper; import me.shkschneider.skeleton.helper.StringHelper; public class NetworkFragment extends SkeletonFragment { private ArrayAdapter<String> mAdapter; public NetworkFragment() { title("Network"); } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final LayoutInflater layoutInflater = LayoutInflater.from(skeletonActivity()); mAdapter = new ArrayAdapter<String>(skeletonActivity(), R.layout.listview_iconitem2) { @Override public View getView(final int position, View convertView, final ViewGroup parent) { if (convertView == null) { convertView = layoutInflater.inflate(R.layout.listview_iconitem2, parent, false); } ((ImageView) convertView.findViewById(R.id.imageview)).setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher)); final String string = getItem(position); final String string1 = string.substring(0, string.indexOf(" ")); final String string2 = string.substring(string.indexOf(" ") + 1, string.length()); ((TextView) convertView.findViewById(android.R.id.text1)).setText(string1); ((TextView) convertView.findViewById(android.R.id.text2)).setText(string2); return convertView; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(final int position) { return false; } }; } @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_listview, container, false); } @Override public void onViewCreated(final View view, final @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ListView listView = (ListView) view.findViewById(R.id.listview); listView.setAdapter(mAdapter); } @Override public void onResume() { super.onResume(); refresh(); } public void refresh() { mAdapter.clear(); skeletonActivity().loading(+1); final long start1 = System.currentTimeMillis(); new WebServiceIon().getString("http://ipecho.net/plain", new WebServiceIon.Callback() { @Override public void webServiceCallback(final WebServiceIon.WebServiceException e, final Object result) { LogHelper.info("time:" + (System.currentTimeMillis() - start1)); skeletonActivity().loading(-1); if (e != null) { ActivityHelper.croutonRed(skeletonActivity(), e.getMessage()); return; } final String string = (String) result; mAdapter.add("ip " + string); mAdapter.notifyDataSetChanged(); } }); skeletonActivity().loading(+1); final long start2 = System.currentTimeMillis(); new WebServiceIon().getJsonObject("http://ifconfig.me/all.json", new WebServiceIon.Callback() { @Override public void webServiceCallback(final WebServiceIon.WebServiceException e, final Object result) { skeletonActivity().loading(-1); LogHelper.info("time:" + (System.currentTimeMillis() - start2)); if (e != null) { ActivityHelper.croutonRed(skeletonActivity(), e.getMessage()); return ; } final JsonObject jsonObject = (JsonObject) result; for (final String key : GsonParser.keys(jsonObject)) { final String value = GsonParser.string(jsonObject, key); if (!StringHelper.nullOrEmpty(value)) { final String string = String.format("%s %s", key, value); mAdapter.add(string); } } mAdapter.notifyDataSetChanged(); } }); } }
package org.cnodejs.android.md.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.CheckedTextView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.melnykov.fab.FloatingActionButton; import com.squareup.picasso.Picasso; import org.cnodejs.android.md.R; import org.cnodejs.android.md.adapter.MainAdapter; import org.cnodejs.android.md.listener.NavigationOpenClickListener; import org.cnodejs.android.md.listener.RecyclerViewLoadMoreListener; import org.cnodejs.android.md.model.api.ApiClient; import org.cnodejs.android.md.model.api.CallbackAdapter; import org.cnodejs.android.md.model.entity.Result; import org.cnodejs.android.md.model.entity.TabType; import org.cnodejs.android.md.model.entity.Topic; import org.cnodejs.android.md.model.entity.User; import org.cnodejs.android.md.storage.LoginShared; import org.cnodejs.android.md.util.HandlerUtils; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, RecyclerViewLoadMoreListener.OnLoadMoreListener { private static final int REQUEST_LOGIN = 1024; @Bind(R.id.main_drawer_layout) protected DrawerLayout drawerLayout; @Bind(R.id.main_left_img_avatar) protected ImageView imgAvatar; @Bind(R.id.main_left_tv_login_name) protected TextView tvLoginName; @Bind(R.id.main_left_tv_score) protected TextView tvScore; @Bind(R.id.main_left_tv_badger_notification) protected TextView tvBadgerNotification; @Bind(R.id.main_left_btn_logout) protected View btnLogout; @Bind({ R.id.main_left_btn_all, R.id.main_left_btn_good, R.id.main_left_btn_share, R.id.main_left_btn_ask, R.id.main_left_btn_job }) protected List<CheckedTextView> navMainItemList; @Bind(R.id.main_toolbar) protected Toolbar toolbar; @Bind(R.id.main_refresh_layout) protected SwipeRefreshLayout refreshLayout; @Bind(R.id.main_recycler_view) protected RecyclerView recyclerView; @Bind(R.id.main_fab_new_topic) protected FloatingActionButton fabNewTopic; @Bind(R.id.main_layout_no_data) protected ViewGroup layoutNoData; // all private TabType currentTab = TabType.all; private int currentPage = 0; private List<Topic> topicList = new ArrayList<>(); private MainAdapter adapter; private long firstBackPressedTime = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); drawerLayout.setDrawerShadow(R.drawable.navigation_drawer_shadow, GravityCompat.START); drawerLayout.setDrawerListener(openDrawerListener); toolbar.setNavigationOnClickListener(new NavigationOpenClickListener(drawerLayout)); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(linearLayoutManager); adapter = new MainAdapter(this, topicList); recyclerView.setAdapter(adapter); recyclerView.addOnScrollListener(new RecyclerViewLoadMoreListener(linearLayoutManager, this, 20)); fabNewTopic.attachToRecyclerView(recyclerView); refreshLayout.setColorSchemeResources(R.color.red_light, R.color.green_light, R.color.blue_light, R.color.orange_light); refreshLayout.setOnRefreshListener(this); HandlerUtils.postDelayed(new Runnable() { @Override public void run() { refreshLayout.setRefreshing(true); onRefresh(); } }, 100); // refreshLayoutonCreate updateUserInfoViews(); } @Override protected void onResume() { super.onResume(); getMessageCountAsyncTask(); } private void getMessageCountAsyncTask() { if (!TextUtils.isEmpty(LoginShared.getAccessToken(this))) { ApiClient.service.getMessageCount(LoginShared.getAccessToken(this), new Callback<Result<Integer>>() { @Override public void success(Result<Integer> result, Response response) { if (result.getData() <= 0) { tvBadgerNotification.setText(null); } else if (result.getData() > 99) { tvBadgerNotification.setText("99+"); } else { tvBadgerNotification.setText(String.valueOf(result.getData())); } } @Override public void failure(RetrofitError error) { if (error.getResponse() != null && error.getResponse().getStatus() == 403) { tvBadgerNotification.setText(null); } } }); } } private DrawerLayout.DrawerListener openDrawerListener = new DrawerLayout.SimpleDrawerListener() { @Override public void onDrawerOpened(View drawerView) { updateUserInfoViews(); getUserAsyncTask(); getMessageCountAsyncTask(); } }; private void updateUserInfoViews() { if (TextUtils.isEmpty(LoginShared.getAccessToken(this))) { Picasso.with(this).load(R.drawable.image_default).into(imgAvatar); tvLoginName.setText(R.string.click_avatar_to_login); tvScore.setText(null); btnLogout.setVisibility(View.GONE); } else { Picasso.with(this).load(ApiClient.ROOT_HOST + LoginShared.getAvatarUrl(this)).error(R.drawable.image_default).into(imgAvatar); tvLoginName.setText(LoginShared.getLoginName(this)); tvScore.setText(getString(R.string.score_$) + LoginShared.getScore(this)); btnLogout.setVisibility(View.VISIBLE); } } private void getUserAsyncTask() { if (!TextUtils.isEmpty(LoginShared.getAccessToken(this))) { ApiClient.service.getUser(LoginShared.getLoginName(this), new CallbackAdapter<Result<User>>() { @Override public void success(Result<User> result, Response response) { LoginShared.update(MainActivity.this, result.getData()); updateUserInfoViews(); } }); } } @Override public void onRefresh() { final TabType tab = currentTab; ApiClient.service.getTopics(tab, 1, 20, false, new Callback<Result<List<Topic>>>() { @Override public void success(Result<List<Topic>> result, Response response) { if (currentTab == tab && result.getData() != null) { topicList.clear(); topicList.addAll(result.getData()); notifyDataSetChanged(); refreshLayout.setRefreshing(false); currentPage = 1; } } @Override public void failure(RetrofitError error) { if (currentTab == tab) { Toast.makeText(MainActivity.this, R.string.data_load_faild, Toast.LENGTH_SHORT).show(); refreshLayout.setRefreshing(false); } } }); } @Override public void onLoadMore() { if (adapter.canLoadMore()) { adapter.setLoading(true); adapter.notifyItemChanged(adapter.getItemCount() - 1); final TabType tab = currentTab; final int page = currentPage; ApiClient.service.getTopics(tab, page + 1, 20, false, new Callback<Result<List<Topic>>>() { @Override public void success(Result<List<Topic>> result, Response response) { if (currentTab == tab && currentPage == page) { if (result.getData().size() > 0) { topicList.addAll(result.getData()); adapter.setLoading(false); adapter.notifyItemRangeInserted(topicList.size() - result.getData().size(), result.getData().size()); currentPage++; } else { Toast.makeText(MainActivity.this, R.string.have_no_more_data, Toast.LENGTH_SHORT).show(); adapter.setLoading(false); adapter.notifyItemChanged(adapter.getItemCount() - 1); } } } @Override public void failure(RetrofitError error) { if (currentTab == tab && currentPage == page) { Toast.makeText(MainActivity.this, R.string.data_load_faild, Toast.LENGTH_SHORT).show(); adapter.setLoading(false); adapter.notifyItemChanged(adapter.getItemCount() - 1); } } }); } } private void notifyDataSetChanged() { if (topicList.size() < 20) { adapter.setLoading(false); } adapter.notifyDataSetChanged(); layoutNoData.setVisibility(topicList.size() == 0 ? View.VISIBLE : View.GONE); } @OnClick({ R.id.main_left_btn_all, R.id.main_left_btn_good, R.id.main_left_btn_share, R.id.main_left_btn_ask, R.id.main_left_btn_job }) public void onNavigationMainItemClick(CheckedTextView itemView) { switch (itemView.getId()) { case R.id.main_left_btn_all: drawerLayout.setDrawerListener(tabAllDrawerListener); break; case R.id.main_left_btn_good: drawerLayout.setDrawerListener(tabGoodDrawerListener); break; case R.id.main_left_btn_share: drawerLayout.setDrawerListener(tabShareDrawerListener); break; case R.id.main_left_btn_ask: drawerLayout.setDrawerListener(tabAskDrawerListener); break; case R.id.main_left_btn_job: drawerLayout.setDrawerListener(tabJobDrawerListener); break; default: drawerLayout.setDrawerListener(openDrawerListener); break; } for (CheckedTextView navItem : navMainItemList) { navItem.setChecked(navItem.getId() == itemView.getId()); } drawerLayout.closeDrawers(); } private class MainItemDrawerListener extends DrawerLayout.SimpleDrawerListener { private TabType tabType; protected MainItemDrawerListener(TabType tabType) { this.tabType = tabType; } @Override public void onDrawerClosed(View drawerView) { if (tabType != currentTab) { currentTab = tabType; currentPage = 0; toolbar.setTitle(currentTab.getNameId()); topicList.clear(); notifyDataSetChanged(); refreshLayout.setRefreshing(true); onRefresh(); fabNewTopic.show(true); } drawerLayout.setDrawerListener(openDrawerListener); } } private DrawerLayout.DrawerListener tabAllDrawerListener = new MainItemDrawerListener(TabType.all); private DrawerLayout.DrawerListener tabGoodDrawerListener = new MainItemDrawerListener(TabType.good); private DrawerLayout.DrawerListener tabShareDrawerListener = new MainItemDrawerListener(TabType.share); private DrawerLayout.DrawerListener tabAskDrawerListener = new MainItemDrawerListener(TabType.ask); private DrawerLayout.DrawerListener tabJobDrawerListener = new MainItemDrawerListener(TabType.job); @OnClick({ R.id.main_left_btn_notification, R.id.main_left_btn_setting, R.id.main_left_btn_about }) public void onNavigationItemOtherClick(View itemView) { switch (itemView.getId()) { case R.id.main_left_btn_notification: if (TextUtils.isEmpty(LoginShared.getAccessToken(this))) { showNeedLoginDialog(); } else { drawerLayout.setDrawerListener(notificationDrawerListener); drawerLayout.closeDrawers(); } break; case R.id.main_left_btn_setting: drawerLayout.setDrawerListener(settingDrawerListener); drawerLayout.closeDrawers(); break; case R.id.main_left_btn_about: drawerLayout.setDrawerListener(aboutDrawerListener); drawerLayout.closeDrawers(); break; default: drawerLayout.setDrawerListener(openDrawerListener); drawerLayout.closeDrawers(); break; } } private class OtherItemDrawerListener extends DrawerLayout.SimpleDrawerListener { private Class gotoClz; protected OtherItemDrawerListener(Class gotoClz) { this.gotoClz = gotoClz; } @Override public void onDrawerClosed(View drawerView) { startActivity(new Intent(MainActivity.this, gotoClz)); drawerLayout.setDrawerListener(openDrawerListener); } } private DrawerLayout.DrawerListener notificationDrawerListener = new OtherItemDrawerListener(NotificationActivity.class); private DrawerLayout.DrawerListener settingDrawerListener = new OtherItemDrawerListener(SettingActivity.class); private DrawerLayout.DrawerListener aboutDrawerListener = new OtherItemDrawerListener(AboutActivity.class); @OnClick(R.id.main_left_btn_logout) protected void onBtnLogoutClick() { new MaterialDialog.Builder(this) .content(R.string.logout_tip) .positiveText(R.string.logout) .negativeText(R.string.cancel) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { LoginShared.logout(MainActivity.this); tvBadgerNotification.setText(null); updateUserInfoViews(); } }) .show(); } @OnClick(R.id.main_left_layout_info) protected void onBtnInfoClick() { if (TextUtils.isEmpty(LoginShared.getAccessToken(this))) { startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_LOGIN); } else { Intent intent = new Intent(this, UserDetailActivity.class); intent.putExtra("loginName", LoginShared.getLoginName(this)); startActivity(intent); } } @OnClick(R.id.main_fab_new_topic) protected void onBtnNewTopicClick() { if (TextUtils.isEmpty(LoginShared.getAccessToken(this))) { showNeedLoginDialog(); } else { startActivity(new Intent(this, NewTopicActivity.class)); } } private void showNeedLoginDialog() { new MaterialDialog.Builder(this) .content(R.string.need_login_tip) .positiveText(R.string.login) .negativeText(R.string.cancel) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), REQUEST_LOGIN); } }) .show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_LOGIN && resultCode == RESULT_OK) { updateUserInfoViews(); getUserAsyncTask(); } } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START); } else { long secondBackPressedTime = System.currentTimeMillis(); if (secondBackPressedTime - firstBackPressedTime > 2000) { Toast.makeText(this, R.string.press_back_again_to_exit, Toast.LENGTH_SHORT).show(); firstBackPressedTime = secondBackPressedTime; } else { finish(); } } } }
package org.wikipedia.analytics; import com.google.gson.annotations.SerializedName; import org.json.JSONObject; import org.wikipedia.Constants.InvokeSource; import org.wikipedia.WikipediaApp; import org.wikipedia.json.GsonUtil; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import static org.wikipedia.Constants.InvokeSource.EDIT_FEED_TITLE_DESC; import static org.wikipedia.Constants.InvokeSource.EDIT_FEED_TRANSLATE_TITLE_DESC; import static org.wikipedia.Constants.InvokeSource.NAV_MENU; import static org.wikipedia.Constants.InvokeSource.NOTIFICATION; import static org.wikipedia.Constants.InvokeSource.ONBOARDING_DIALOG; public final class SuggestedEditsFunnel extends TimedFunnel { private static SuggestedEditsFunnel INSTANCE; private static final String SCHEMA_NAME = "MobileWikiAppSuggestedEdits"; private static final int REV_ID = 18949003; private static final String SUGGESTED_EDITS_UI_VERSION = "1.0"; private static final String SUGGESTED_EDITS_API_VERSION = "1.0"; public static final String SUGGESTED_EDITS_ADD_COMMENT = "#suggestededit-add " + SUGGESTED_EDITS_UI_VERSION; public static final String SUGGESTED_EDITS_TRANSLATE_COMMENT = "#suggestededit-translate " + SUGGESTED_EDITS_UI_VERSION; private InvokeSource invokeSource; private String parentSessionToken; private int helpOpenedCount = 0; private int contributionsOpenedCount = 0; private SuggestedEditStatsCollection statsCollection = new SuggestedEditStatsCollection(); private List<String> uniqueTitles = new ArrayList<>(); private SuggestedEditsFunnel(WikipediaApp app, InvokeSource invokeSource) { super(app, SCHEMA_NAME, REV_ID, Funnel.SAMPLE_LOG_ALL); this.invokeSource = invokeSource; this.parentSessionToken = app.getSessionFunnel().getSessionToken(); } public static SuggestedEditsFunnel get(InvokeSource invokeSource) { if (INSTANCE == null) { INSTANCE = new SuggestedEditsFunnel(WikipediaApp.getInstance(), invokeSource); } return INSTANCE; } public static SuggestedEditsFunnel get() { return get(NAV_MENU); } public static void reset() { INSTANCE = null; } @Override protected void preprocessSessionToken(@NonNull JSONObject eventData) { preprocessData(eventData, "session_token", parentSessionToken); } public void impression(InvokeSource source) { if (source == EDIT_FEED_TITLE_DESC) { statsCollection.addDescriptionStats.impressions++; } else if (source == EDIT_FEED_TRANSLATE_TITLE_DESC) { statsCollection.translateDescriptionStats.impressions++; } } public void click(String title, InvokeSource source) { SuggestedEditStats stats; if (source == InvokeSource.EDIT_FEED_TITLE_DESC) { stats = statsCollection.addDescriptionStats; } else if (source == InvokeSource.EDIT_FEED_TRANSLATE_TITLE_DESC) { stats = statsCollection.translateDescriptionStats; } else { return; } stats.clicks++; if (!uniqueTitles.contains(title)) { uniqueTitles.add(title); final int maxItems = 100; if (uniqueTitles.size() > maxItems) { uniqueTitles.remove(0); } stats.suggestionsClicked++; } } public void cancel(InvokeSource source) { if (source == EDIT_FEED_TITLE_DESC) { statsCollection.addDescriptionStats.cancels++; } else if (source == EDIT_FEED_TRANSLATE_TITLE_DESC) { statsCollection.translateDescriptionStats.cancels++; } } public void success(InvokeSource source) { if (source == EDIT_FEED_TITLE_DESC) { statsCollection.addDescriptionStats.successes++; } else if (source == EDIT_FEED_TRANSLATE_TITLE_DESC) { statsCollection.translateDescriptionStats.successes++; } } public void failure(InvokeSource source) { if (source == EDIT_FEED_TITLE_DESC) { statsCollection.addDescriptionStats.failures++; } else if (source == EDIT_FEED_TRANSLATE_TITLE_DESC) { statsCollection.translateDescriptionStats.failures++; } } public void helpOpened() { helpOpenedCount++; } public void contributionsOpened() { contributionsOpenedCount++; } public void log() { log( "edit_tasks", GsonUtil.getDefaultGson().toJson(statsCollection), "help_opened", helpOpenedCount, "scorecard_opened", contributionsOpenedCount, "source", (invokeSource == ONBOARDING_DIALOG ? "dialog" : invokeSource == NOTIFICATION ? "notification" : "menu") ); } private static class SuggestedEditStatsCollection { @SerializedName("add-description") private SuggestedEditStats addDescriptionStats = new SuggestedEditStats(); @SerializedName("translate-description") private SuggestedEditStats translateDescriptionStats = new SuggestedEditStats(); } @SuppressWarnings("unused") private static class SuggestedEditStats { private int impressions; private int clicks; @SerializedName("suggestions_clicked") private int suggestionsClicked; private int cancels; private int successes; private int failures; } }
package tech.salroid.filmy.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.SwitchPreference; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import tech.salroid.filmy.R; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getFragmentManager().beginTransaction(). replace(R.id.container, new MyPreferenceFragment()).commit(); } public static class MyPreferenceFragment extends PreferenceFragment { private SwitchPreference imagePref; private CheckBoxPreference cache_pref; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference); final SharedPreferences.Editor my_prefrence = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit(); imagePref = (SwitchPreference) findPreference("imagequality"); imagePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { String quality; SwitchPreference switchPreference = (SwitchPreference) preference; if (switchPreference.isChecked()) { quality = "medium"; } else { quality = "thumb"; } my_prefrence.putString("image_quality", quality); my_prefrence.commit(); return true; } }); cache_pref = (CheckBoxPreference) findPreference("pref_sync"); cache_pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { CheckBoxPreference checkBoxPreference = (CheckBoxPreference) preference; if (!checkBoxPreference.isChecked()) { my_prefrence.putBoolean("cache",true); my_prefrence.commit(); } return true; } }); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } }
package weave.servlets; import static weave.config.WeaveConfig.getConnectionConfig; import static weave.config.WeaveConfig.getDataConfig; import static weave.config.WeaveConfig.initWeaveConfig; import java.rmi.RemoteException; import java.security.InvalidParameterException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Vector; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import org.postgis.Geometry; import org.postgis.PGgeometry; import org.postgis.Point; import weave.beans.AttributeColumnData; import weave.beans.GeometryStreamMetadata; import weave.beans.PGGeom; import weave.beans.WeaveJsonDataSet; import weave.beans.WeaveRecordList; import weave.config.ConnectionConfig.ConnectionInfo; import weave.config.DataConfig; import weave.config.DataConfig.DataEntity; import weave.config.DataConfig.DataEntityMetadata; import weave.config.DataConfig.DataEntityWithRelationships; import weave.config.DataConfig.DataType; import weave.config.DataConfig.EntityHierarchyInfo; import weave.config.DataConfig.PrivateMetadata; import weave.config.DataConfig.PublicMetadata; import weave.config.WeaveContextParams; import weave.geometrystream.SQLGeometryStreamReader; import weave.utils.CSVParser; import weave.utils.ListUtils; import weave.utils.SQLResult; import weave.utils.SQLUtils; import weave.utils.SQLUtils.WhereClause; import weave.utils.SQLUtils.WhereClause.ColumnFilter; import weave.utils.Strings; /** * This class connects to a database and gets data * uses xml configuration file to get connection/query info * * @author Andy Dufilie */ public class DataService extends GenericServlet { private static final long serialVersionUID = 1L; public DataService() { } public void init(ServletConfig config) throws ServletException { super.init(config); initWeaveConfig(WeaveContextParams.getInstance(config.getServletContext())); } // helper functions private DataEntity getColumnEntity(int columnId) throws RemoteException { DataEntity entity = getDataConfig().getEntity(columnId); if (entity == null || entity.type != DataEntity.TYPE_COLUMN) throw new RemoteException("No column with id " + columnId); return entity; } private void assertColumnHasPrivateMetadata(DataEntity columnEntity, String ... fields) throws RemoteException { for (String field : fields) { if (Strings.isEmpty(columnEntity.privateMetadata.get(field))) { String dataType = columnEntity.publicMetadata.get(PublicMetadata.DATATYPE); String description = (dataType != null && dataType.equals(DataType.GEOMETRY)) ? "Geometry column" : "Column"; throw new RemoteException(String.format("%s %s is missing private metadata %s", description, columnEntity.id, field)); } } } private boolean assertStreamingGeometryColumn(DataEntity entity, boolean throwException) throws RemoteException { try { String dataType = entity.publicMetadata.get(PublicMetadata.DATATYPE); if (dataType == null || !dataType.equals(DataType.GEOMETRY)) throw new RemoteException(String.format("Column %s dataType is %s, not %s", entity.id, dataType, DataType.GEOMETRY)); assertColumnHasPrivateMetadata(entity, PrivateMetadata.CONNECTION, PrivateMetadata.SQLSCHEMA, PrivateMetadata.SQLTABLEPREFIX); return true; } catch (RemoteException e) { if (throwException) throw e; return false; } } // DataEntity info public EntityHierarchyInfo[] getDataTableList() throws RemoteException { return getDataConfig().getEntityHierarchyInfo(DataEntity.TYPE_DATATABLE); } public int[] getEntityChildIds(int parentId) throws RemoteException { return ListUtils.toIntArray( getDataConfig().getChildIds(parentId) ); } public int[] getEntityIdsByMetadata(Map<String,String> publicMetadata, int entityType) throws RemoteException { DataEntityMetadata dem = new DataEntityMetadata(); dem.publicMetadata = publicMetadata; int[] ids = ListUtils.toIntArray( getDataConfig().getEntityIdsByMetadata(dem, entityType) ); Arrays.sort(ids); return ids; } public DataEntity[] getEntitiesById(int[] ids) throws RemoteException { DataConfig config = getDataConfig(); Set<Integer> idSet = new HashSet<Integer>(); for (int id : ids) idSet.add(id); DataEntity[] result = config.getEntitiesById(idSet).toArray(new DataEntity[0]); for (int i = 0; i < result.length; i++) { int id = result[i].id; int[] parentIds = ListUtils.toIntArray( config.getParentIds(Arrays.asList(id)) ); int[] childIds = ListUtils.toIntArray( config.getChildIds(id) ); result[i] = new DataEntityWithRelationships(result[i], parentIds, childIds); // prevent user from receiving private metadata result[i].privateMetadata = null; } return result; } public int[] getParents(int childId) throws RemoteException { int[] ids = ListUtils.toIntArray( getDataConfig().getParentIds(Arrays.asList(childId)) ); Arrays.sort(ids); return ids; } // Columns private static ConnectionInfo getColumnConnectionInfo(DataEntity entity) throws RemoteException { String connName = entity.privateMetadata.get(PrivateMetadata.CONNECTION); ConnectionInfo connInfo = getConnectionConfig().getConnectionInfo(connName); if (connInfo == null) { String title = entity.publicMetadata.get(PublicMetadata.TITLE); throw new RemoteException(String.format("Connection named '%s' associated with column #%s (%s) no longer exists", connName, entity.id, title)); } return connInfo; } /** * This retrieves the data and the public metadata for a single attribute column. * @param columnId Either an entity ID (int) or a Map specifying public metadata values that uniquely identify a column. * @param minParam Used for filtering numeric data * @param maxParam Used for filtering numeric data * @param sqlParams Specifies parameters to be used in place of '?' placeholders that appear in the SQL query for the column. * @return The column data. * @throws RemoteException */ public AttributeColumnData getColumn(Object columnId, double minParam, double maxParam, String[] sqlParams) throws RemoteException { DataEntity entity = null; if (columnId instanceof Number) { entity = getColumnEntity(((Number)columnId).intValue()); } else if (columnId instanceof Map) { @SuppressWarnings({ "unchecked", "rawtypes" }) int[] ids = getEntityIdsByMetadata((Map)columnId, DataEntity.TYPE_COLUMN); if (ids.length == 0) throw new RemoteException("No column with id " + columnId); if (ids.length > 1) throw new RemoteException(String.format( "The specified metadata does not uniquely identify a column (%s matching columns found): %s", ids.length, columnId )); entity = getColumnEntity(ids[0]); } else throw new RemoteException("columnId must either be an Integer or a Map of public metadata values."); // if it's a geometry column, just return the metadata if (assertStreamingGeometryColumn(entity, false)) { GeometryStreamMetadata gsm = (GeometryStreamMetadata) getGeometryData(entity, GeomStreamComponent.TILE_DESCRIPTORS, null); AttributeColumnData result = new AttributeColumnData(); result.id = entity.id; result.metadata = entity.publicMetadata; result.metadataTileDescriptors = gsm.metadataTileDescriptors; result.geometryTileDescriptors = gsm.geometryTileDescriptors; return result; } String query = entity.privateMetadata.get(PrivateMetadata.SQLQUERY); String dataType = entity.publicMetadata.get(PublicMetadata.DATATYPE); ConnectionInfo connInfo = getColumnConnectionInfo(entity); List<String> keys = new ArrayList<String>(); List<Double> numericData = null; List<String> stringData = null; List<Object> thirdColumn = null; // hack for dimension slider format List<PGGeom> geometricData = null; // use config min,max or param min,max to filter the data double minValue = Double.NaN; double maxValue = Double.NaN; // override config min,max with param values if given if (!Double.isNaN(minParam)) { minValue = minParam; } else { try { minValue = Double.parseDouble(entity.publicMetadata.get(PublicMetadata.MIN)); } catch (Exception e) { } } if (!Double.isNaN(maxParam)) { maxValue = maxParam; } else { try { maxValue = Double.parseDouble(entity.publicMetadata.get(PublicMetadata.MAX)); } catch (Exception e) { } } if (Double.isNaN(minValue)) minValue = Double.NEGATIVE_INFINITY; if (Double.isNaN(maxValue)) maxValue = Double.POSITIVE_INFINITY; try { Connection conn = connInfo.getStaticReadOnlyConnection(); // use default sqlParams if not specified by query params if (sqlParams == null || sqlParams.length == 0) { String sqlParamsString = entity.privateMetadata.get(PrivateMetadata.SQLPARAMS); sqlParams = CSVParser.defaultParser.parseCSVRow(sqlParamsString, true); } SQLResult result = SQLUtils.getResultFromQuery(conn, query, sqlParams, false); // if dataType is defined in the config file, use that value. // otherwise, derive it from the sql result. if (Strings.isEmpty(dataType)) { dataType = DataType.fromSQLType(result.columnTypes[1]); entity.publicMetadata.put(PublicMetadata.DATATYPE, dataType); // fill in missing metadata for the client } if (dataType.equalsIgnoreCase(DataType.NUMBER)) // special case: "number" => Double { numericData = new LinkedList<Double>(); } else if (dataType.equalsIgnoreCase(DataType.GEOMETRY)) { geometricData = new LinkedList<PGGeom>(); } else { stringData = new LinkedList<String>(); } // hack for dimension slider format if (result.columnTypes.length == 3) thirdColumn = new LinkedList<Object>(); Object keyObj, dataObj; double value; for (int i = 0; i < result.rows.length; i++) { keyObj = result.rows[i][0]; if (keyObj == null) continue; dataObj = result.rows[i][1]; if (dataObj == null) continue; if (numericData != null) { try { if (dataObj instanceof String) dataObj = Double.parseDouble((String)dataObj); value = ((Number)dataObj).doubleValue(); } catch (Exception e) { continue; } // filter the data based on the min,max values if (minValue <= value && value <= maxValue) numericData.add(value); else continue; } else if (geometricData != null) { // The dataObj must be cast to PGgeometry before an individual Geometry can be extracted. if (!(dataObj instanceof PGgeometry)) continue; Geometry geom = ((PGgeometry) dataObj).getGeometry(); int numPoints = geom.numPoints(); // Create PGGeom Bean here and fill it up! PGGeom bean = new PGGeom(); bean.type = geom.getType(); bean.xyCoords = new double[numPoints * 2]; for (int j = 0; j < numPoints; j++) { Point pt = geom.getPoint(j); bean.xyCoords[j * 2] = pt.x; bean.xyCoords[j * 2 + 1] = pt.y; } geometricData.add(bean); } else { stringData.add(dataObj.toString()); } // if we got here, it means a data value was added, so add the corresponding key keys.add(keyObj.toString()); // hack for dimension slider format if (thirdColumn != null) thirdColumn.add(result.rows[i][2]); } } catch (SQLException e) { System.err.println(query); e.printStackTrace(); throw new RemoteException(String.format("Unable to retrieve data for column %s", columnId)); } catch (NullPointerException e) { e.printStackTrace(); throw(new RemoteException(e.getMessage())); } AttributeColumnData result = new AttributeColumnData(); result.id = entity.id; result.metadata = entity.publicMetadata; result.keys = keys.toArray(new String[keys.size()]); if (numericData != null) result.data = numericData.toArray(); else if (geometricData != null) result.data = geometricData.toArray(); else result.data = stringData.toArray(); // hack for dimension slider if (thirdColumn != null) result.thirdColumn = thirdColumn.toArray(); return result; } /** * This function is intended for use with JsonRPC calls. * @param columnIds A list of column IDs. * @return A WeaveJsonDataSet containing all the data from the columns. * @throws RemoteException */ public WeaveJsonDataSet getDataSet(int[] columnIds) throws RemoteException { WeaveJsonDataSet result = new WeaveJsonDataSet(); for (Integer columnId : columnIds) { try { AttributeColumnData columnData = getColumn(columnId, Double.NaN, Double.NaN, null); result.addColumnData(columnData); } catch (RemoteException e) { e.printStackTrace(); } } return result; } // geometry columns public byte[] getGeometryStreamMetadataTiles(int columnId, int[] tileIDs) throws RemoteException { DataEntity entity = getColumnEntity(columnId); if (tileIDs == null || tileIDs.length == 0) throw new RemoteException("At least one tileID must be specified."); return (byte[]) getGeometryData(entity, GeomStreamComponent.METADATA_TILES, tileIDs); } public byte[] getGeometryStreamGeometryTiles(int columnId, int[] tileIDs) throws RemoteException { DataEntity entity = getColumnEntity(columnId); if (tileIDs == null || tileIDs.length == 0) throw new RemoteException("At least one tileID must be specified."); return (byte[]) getGeometryData(entity, GeomStreamComponent.GEOMETRY_TILES, tileIDs); } private static enum GeomStreamComponent { TILE_DESCRIPTORS, METADATA_TILES, GEOMETRY_TILES }; private Object getGeometryData(DataEntity entity, GeomStreamComponent component, int[] tileIDs) throws RemoteException { assertStreamingGeometryColumn(entity, true); Connection conn = getColumnConnectionInfo(entity).getStaticReadOnlyConnection(); String schema = entity.privateMetadata.get(PrivateMetadata.SQLSCHEMA); String tablePrefix = entity.privateMetadata.get(PrivateMetadata.SQLTABLEPREFIX); try { switch (component) { case TILE_DESCRIPTORS: GeometryStreamMetadata result = new GeometryStreamMetadata(); result.metadataTileDescriptors = SQLGeometryStreamReader.getMetadataTileDescriptors(conn, schema, tablePrefix); result.geometryTileDescriptors = SQLGeometryStreamReader.getGeometryTileDescriptors(conn, schema, tablePrefix); return result; case METADATA_TILES: return SQLGeometryStreamReader.getMetadataTiles(conn, schema, tablePrefix, tileIDs); case GEOMETRY_TILES: return SQLGeometryStreamReader.getGeometryTiles(conn, schema, tablePrefix, tileIDs); default: throw new InvalidParameterException("Invalid GeometryStreamComponent param."); } } catch (Exception e) { e.printStackTrace(); throw new RemoteException(String.format("Unable to read geometry data (id=%s)", entity.id)); } } // Row query public WeaveRecordList getRows(String keyType, String[] keysArray) throws RemoteException { DataConfig dataConfig = getDataConfig(); DataEntityMetadata params = new DataEntityMetadata(); params.publicMetadata.put(PublicMetadata.KEYTYPE,keyType); List<Integer> columnIds = new ArrayList<Integer>( dataConfig.getEntityIdsByMetadata(params, DataEntity.TYPE_COLUMN) ); if (columnIds.size() > 100) columnIds = columnIds.subList(0, 100); FilteredColumnRequest[] requestedColumns = new FilteredColumnRequest[columnIds.size()]; for (int i = 0; i < requestedColumns.length; i++) { FilteredColumnRequest fcr = new FilteredColumnRequest(); fcr.id = columnIds.get(i); requestedColumns[i] = fcr; } return DataService.getFilteredRows(requestedColumns, keysArray); } public static class FilteredColumnRequest { public int id; public boolean getData; /** * Either [[min,max],[min2,max2],...] for numeric values or ["a","b",...] for string values. */ public Object[] filters; } private static SQLResult getFilteredRowsFromSQL(Connection conn, String schema, String table, FilteredColumnRequest[] columns, DataEntity[] entities) throws SQLException { ColumnFilter[] cfArray = new ColumnFilter[columns.length]; List<String> quotedFields = new LinkedList<String>(); for (int i = 0; i < columns.length; i++) { cfArray[i] = new ColumnFilter(); cfArray[i].field = entities[i].privateMetadata.get(PrivateMetadata.SQLCOLUMN); cfArray[i].filters = columns[i].filters; if (columns[i].getData) quotedFields.add(SQLUtils.quoteSymbol(conn, cfArray[i].field)); } WhereClause<Object> where = WhereClause.fromFilters(conn, cfArray); String query = String.format( "SELECT %s FROM %s %s", Strings.join(",", quotedFields), SQLUtils.quoteSchemaTable(conn, schema, table), where.clause ); return SQLUtils.getResultFromQuery(conn, query, where.params.toArray(), false); } /* [ {id: 1, getData: true, filters: ["a","b"]}, {id: 2, getData: true, filters: [[min,max],[min2,max2]]} ] */ @SuppressWarnings("unchecked") public static WeaveRecordList getFilteredRows(FilteredColumnRequest[] columns, String[] keysArray) throws RemoteException { List<Integer> columnIds = new Vector<Integer>(); for (FilteredColumnRequest fcr : columns) columnIds.add(fcr.id); DataConfig dataConfig = getDataConfig(); DataEntity[] entities; Map<String,String>[] metadataList; { Collection<DataEntity> unordered = dataConfig.getEntitiesById(columnIds); Map<Integer, DataEntity> lookup = new HashMap<Integer, DataEntity>(); for (DataEntity de : unordered) lookup.put(de.id, de); int n = columnIds.size(); entities = new DataEntity[n]; metadataList = new Map[n]; for (int i = 0; i < n; i++) { entities[i] = lookup.get(columnIds.get(i)); metadataList[i] = entities[i].publicMetadata; } } if (entities.length < 1) throw new RemoteException("No columns found matching specified ids: "+columnIds); String keyType = entities[0].publicMetadata.get(PublicMetadata.KEYTYPE); for (DataEntity entity : entities) { String keyType2 = entity.publicMetadata.get(PublicMetadata.KEYTYPE); if (keyType != keyType2 && (keyType == null || keyType2 == null || !keyType.equals(keyType2))) throw new RemoteException("Specified columns must all have same keyType."); } WeaveRecordList result = new WeaveRecordList(); if (keysArray == null) { boolean canGenerateSQL = true; // check to see if all the columns are from the same SQL table. String connection = null; String sqlSchema = null; String sqlTable = null; for (DataEntity entity : entities) { String c = entity.privateMetadata.get(PrivateMetadata.CONNECTION); String s = entity.privateMetadata.get(PrivateMetadata.SQLSCHEMA); String t = entity.privateMetadata.get(PrivateMetadata.SQLTABLE); if (connection == null) connection = c; if (sqlSchema == null) sqlSchema = s; if (sqlTable == null) sqlTable = t; if (!Strings.equal(connection, c) || !Strings.equal(sqlSchema, s) || !Strings.equal(sqlTable, t)) { canGenerateSQL = false; break; } } if (canGenerateSQL) { Connection conn = getColumnConnectionInfo(entities[0]).getStaticReadOnlyConnection(); try { result.recordData = getFilteredRowsFromSQL(conn, sqlSchema, sqlTable, columns, entities).rows; } catch (SQLException e) { throw new RemoteException("getFilteredRows() failed.", e); } } } if (result.recordData == null) { HashMap<String,Object[]> data = new HashMap<String,Object[]>(); if (keysArray != null) for (String key : keysArray) data.put(key, new Object[entities.length]); for (int colIndex = 0; colIndex < entities.length; colIndex++) { Object[] filters = columns[colIndex].filters; DataEntity info = entities[colIndex]; String sqlQuery = info.privateMetadata.get(PrivateMetadata.SQLQUERY); String sqlParams = info.privateMetadata.get(PrivateMetadata.SQLPARAMS); //if (dataWithKeysQuery.length() == 0) // throw new RemoteException(String.format("No SQL query is associated with column \"%s\" in dataTable \"%s\"", attributeColumnName, dataTableName)); String dataType = info.publicMetadata.get(PublicMetadata.DATATYPE); // use config min,max or param min,max to filter the data String infoMinStr = info.publicMetadata.get(PublicMetadata.MIN); String infoMaxStr = info.publicMetadata.get(PublicMetadata.MAX); double minValue = Double.NEGATIVE_INFINITY; double maxValue = Double.POSITIVE_INFINITY; // first try parsing config min,max values try { minValue = Double.parseDouble(infoMinStr); } catch (Exception e) { } try { maxValue = Double.parseDouble(infoMaxStr); } catch (Exception e) { } // override config min,max with param values if given /** * columnInfoArray = config.getDataEntity(params); * for each info in columnInfoArray * get sql data * for each row in sql data * if key is in keys array, * add this value to the result * return result */ try { //timer.start(); boolean errorReported = false; Connection conn = getColumnConnectionInfo(info).getStaticReadOnlyConnection(); String[] sqlParamsArray = null; if (sqlParams != null && sqlParams.length() > 0) sqlParamsArray = CSVParser.defaultParser.parseCSV(sqlParams, true)[0]; SQLResult sqlResult = SQLUtils.getResultFromQuery(conn, sqlQuery, sqlParamsArray, false); //timer.lap("get row set"); // if dataType is defined in the config file, use that value. // otherwise, derive it from the sql result. if (Strings.isEmpty(dataType)) dataType = DataType.fromSQLType(sqlResult.columnTypes[1]); boolean isNumeric = dataType != null && dataType.equalsIgnoreCase(DataType.NUMBER); Object keyObj, dataObj; for (int iRow = 0; iRow < sqlResult.rows.length; iRow++) { keyObj = sqlResult.rows[iRow][0]; dataObj = sqlResult.rows[iRow][1]; if (keyObj == null || dataObj == null) continue; keyObj = keyObj.toString(); if (data.containsKey(keyObj)) { // if row has been set to null, skip if (data.get(keyObj) == null) continue; } else { // if keys are specified and row is not present, skip if (keysArray != null) continue; } try { boolean passedFilters = true; // convert the data to the appropriate type, then filter by value if (isNumeric) { if (dataObj instanceof Number) // TEMPORARY SOLUTION - FIX ME { double doubleValue = ((Number)dataObj).doubleValue(); // filter the data based on the min,max values if (minValue <= doubleValue && doubleValue <= maxValue) { // filter the value if (filters != null) { passedFilters = false; for (Object range : filters) { Number min = (Number)((Object[])range)[0]; Number max = (Number)((Object[])range)[1]; if (min.doubleValue() <= doubleValue && doubleValue <= max.doubleValue()) { passedFilters = true; break; } } } } else passedFilters = false; } else passedFilters = false; } else { String stringValue = dataObj.toString(); dataObj = stringValue; // filter the value if (filters != null) { passedFilters = false; for (Object filter : filters) { if (filter.equals(stringValue)) { passedFilters = true; break; } } } } Object[] row = data.get(keyObj); if (passedFilters) { // add existing row if it has not been added yet if (!data.containsKey(keyObj)) { for (int i = 0; i < colIndex; i++) { Object[] prevFilters = columns[i].filters; if (prevFilters != null) { passedFilters = false; break; } } if (passedFilters) row = new Object[entities.length]; data.put((String)keyObj, row); } if (row != null) row[colIndex] = dataObj; } else { // remove existing row if value did not pass filters if (row != null || !data.containsKey(keyObj)) data.put((String)keyObj, null); } } catch (Exception e) { if (!errorReported) { errorReported = true; e.printStackTrace(); } } } } catch (SQLException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); throw new RemoteException(e.getMessage()); } } if (keysArray == null) { LinkedList<String> keys = new LinkedList<String>(); for (Entry<String,Object[]> entry : data.entrySet()) if (entry.getValue() != null) keys.add(entry.getKey()); keysArray = keys.toArray(new String[keys.size()]); } Object[][] rows = new Object[keysArray.length][]; for (int iKey = 0; iKey < keysArray.length; iKey++) rows[iKey] = data.get(keysArray[iKey]); result.recordData = rows; } result.keyType = keyType; result.recordKeys = keysArray; result.attributeColumnMetadata = metadataList; return result; } // backwards compatibility /** * @param metadata The metadata query. * @return The id of the matching column. * @throws RemoteException Thrown if the metadata query does not match exactly one column. */ @Deprecated public AttributeColumnData getColumnFromMetadata(Map<String, String> metadata) throws RemoteException { if (metadata == null || metadata.size() == 0) throw new RemoteException("No metadata query parameters specified."); DataEntityMetadata query = new DataEntityMetadata(); query.publicMetadata = metadata; final String DATATABLE = "dataTable"; final String NAME = "name"; // exclude these parameters from the query if (metadata.containsKey(NAME)) metadata.remove(PublicMetadata.TITLE); String minStr = metadata.remove(PublicMetadata.MIN); String maxStr = metadata.remove(PublicMetadata.MAX); String paramsStr = metadata.remove(PrivateMetadata.SQLPARAMS); DataConfig dataConfig = getDataConfig(); Collection<Integer> ids = dataConfig.getEntityIdsByMetadata(query, DataEntity.TYPE_COLUMN); // attempt recovery for backwards compatibility if (ids.size() == 0) { String dataType = metadata.get(PublicMetadata.DATATYPE); if (metadata.containsKey(DATATABLE) && metadata.containsKey(NAME)) { // try to find columns sqlTable==dataTable and sqlColumn=name DataEntityMetadata sqlInfoQuery = new DataEntityMetadata(); String sqlTable = metadata.get(DATATABLE); String sqlColumn = metadata.get(NAME); for (int i = 0; i < 2; i++) { if (i == 1) sqlTable = sqlTable.toLowerCase(); sqlInfoQuery.setPrivateMetadata( PrivateMetadata.SQLTABLE, sqlTable, PrivateMetadata.SQLCOLUMN, sqlColumn ); ids = dataConfig.getEntityIdsByMetadata(sqlInfoQuery, DataEntity.TYPE_COLUMN); if (ids.size() > 0) break; } } else if (metadata.containsKey(NAME) && dataType != null && dataType.equals(DataType.GEOMETRY)) { metadata.put(PublicMetadata.TITLE, metadata.remove(NAME)); ids = dataConfig.getEntityIdsByMetadata(query, DataEntity.TYPE_COLUMN); } if (ids.size() == 0) throw new RemoteException("No column matches metadata query: " + metadata); } // warning if more than one column if (ids.size() > 1) { String message = String.format( "WARNING: Multiple columns (%s) match metadata query: %s", ids.size(), metadata ); System.err.println(message); //throw new RemoteException(message); } // return first column int id = ListUtils.getFirstSortedItem(ids, DataConfig.NULL); double min = Double.NaN, max = Double.NaN; try { min = (Double)cast(minStr, double.class); } catch (Throwable t) { } try { max = (Double)cast(maxStr, double.class); } catch (Throwable t) { } String[] sqlParams = CSVParser.defaultParser.parseCSVRow(paramsStr, true); return getColumn(id, min, max, sqlParams); } }
package railo.runtime.tag; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.servlet.jsp.tagext.Tag; import railo.commons.io.res.Resource; import railo.commons.io.res.util.ResourceUtil; import railo.commons.lang.StringUtil; import railo.runtime.Component; import railo.runtime.ComponentPro; import railo.runtime.Mapping; import railo.runtime.MappingImpl; import railo.runtime.PageContext; import railo.runtime.PageContextImpl; import railo.runtime.PageSource; import railo.runtime.component.ComponentLoader; import railo.runtime.component.Member; import railo.runtime.config.Config; import railo.runtime.config.ConfigWeb; import railo.runtime.exp.ApplicationException; import railo.runtime.exp.CasterException; import railo.runtime.exp.ExpressionException; import railo.runtime.exp.PageException; import railo.runtime.exp.PageRuntimeException; import railo.runtime.exp.PageServletException; import railo.runtime.ext.tag.AppendixTag; import railo.runtime.ext.tag.BodyTagTryCatchFinallyImpl; import railo.runtime.ext.tag.DynamicAttributes; import railo.runtime.op.Caster; import railo.runtime.op.Decision; import railo.runtime.type.Collection; import railo.runtime.type.KeyImpl; import railo.runtime.type.List; import railo.runtime.type.Struct; import railo.runtime.type.StructImpl; import railo.runtime.type.scope.Caller; import railo.runtime.type.scope.CallerImpl; import railo.runtime.type.scope.Undefined; import railo.runtime.type.scope.Variables; import railo.runtime.type.scope.VariablesImpl; import railo.runtime.type.util.ArrayUtil; import railo.runtime.type.util.ComponentUtil; import railo.runtime.type.util.Type; import railo.runtime.util.QueryStack; import railo.runtime.util.QueryStackImpl; import railo.transformer.library.tag.TagLibTag; import railo.transformer.library.tag.TagLibTagAttr; /** * Creates a ColdFusion Custom Tag **/ public class CFTag extends BodyTagTryCatchFinallyImpl implements DynamicAttributes,AppendixTag { private static Collection.Key GENERATED_CONTENT=KeyImpl.getInstance("GENERATEDCONTENT"); private static Collection.Key EXECUTION_MODE=KeyImpl.getInstance("EXECUTIONMODE"); private static Collection.Key EXECUTE_BODY=KeyImpl.getInstance("EXECUTEBODY"); private static Collection.Key HAS_END_TAG=KeyImpl.getInstance("HASENDTAG"); private static Collection.Key PARENT=KeyImpl.getInstance("PARENT"); private static Collection.Key CFCATCH=KeyImpl.getInstance("CFCATCH"); private static Collection.Key SOURCE=KeyImpl.getInstance("SOURCE"); private static Collection.Key ATTRIBUTES=KeyImpl.getInstance("ATTRIBUTES"); private static Collection.Key ATTRIBUTE=KeyImpl.getInstance("ATTRIBUTE"); private static Collection.Key CALLER=KeyImpl.getInstance("CALLER"); private static Collection.Key THIS_TAG=KeyImpl.getInstance("THISTAG"); private static final Collection.Key ON_ERROR = KeyImpl.getInstance("onError"); private static final Collection.Key ON_FINALLY = KeyImpl.getInstance("onFinally"); private static final Collection.Key ON_START_TAG = KeyImpl.getInstance("onStartTag"); private static final Collection.Key ON_END_TAG = KeyImpl.getInstance("onEndTag"); private static final Collection.Key INIT = KeyImpl.getInstance("init"); private static final Collection.Key ATTRIBUTE_TYPE = KeyImpl.getInstance("attributetype"); private static final Collection.Key TYPE = KeyImpl.getInstance("type"); private static final Collection.Key HINT = KeyImpl.getInstance("hint"); private static final Collection.Key DESCRIPTION = KeyImpl.getInstance("description"); private static final Collection.Key RT_EXPR_VALUE = KeyImpl.getInstance("rtexprvalue"); private static final Collection.Key PARSE_BODY = KeyImpl.getInstance("parsebody"); private static final Collection.Key EVALUATE_BODY = KeyImpl.getInstance("evaluatebody"); private static final Collection.Key REQUIRED = KeyImpl.getInstance("required"); private static final Collection.Key DEFAULT = KeyImpl.getInstance("default"); private static final Collection.Key METADATA = KeyImpl.getInstance("metadata"); /** * Field <code>attributesScope</code> */ // new scopes protected StructImpl attributesScope; private Caller callerScope; private StructImpl thistagScope; private Variables ctVariablesScope; private boolean hasBody; /** * Field <code>filename</code> */ //protected String filename; /** * Field <code>source</code> */ protected InitFile source; private String appendix; //private boolean doCustomTagDeepSearch; private ComponentPro cfc; private boolean isEndTag; /** * constructor for the tag class **/ public CFTag() { attributesScope = new StructImpl(); callerScope = new CallerImpl(); //thistagScope = new StructImpl(); } /** * @see railo.runtime.ext.tag.DynamicAttributes#setDynamicAttribute(java.lang.String, java.lang.String, java.lang.Object) */ public void setDynamicAttribute(String uri, String name, Object value) { TagUtil.setDynamicAttribute(attributesScope,name,value); } /** * @see javax.servlet.jsp.tagext.Tag#release() */ public void release() { super.release(); hasBody=false; //filename=null; attributesScope=new StructImpl();//.clear(); callerScope = new CallerImpl(); if(thistagScope!=null)thistagScope=null; if(ctVariablesScope!=null)ctVariablesScope=null; isEndTag=false; //cfc=null; source=null; } /** * sets the appendix of the class * @param appendix */ public void setAppendix(String appendix) { this.appendix=appendix; //filename = appendix+'.'+pageContext.getConfig().getCFMLExtension(); } /** * @see javax.servlet.jsp.tagext.Tag#doStartTag() */ public int doStartTag() throws PageException { PageContextImpl pci=(PageContextImpl) pageContext; boolean old=pci.useSpecialMappings(true); try{ initFile(); callerScope.initialize(pageContext); if(source.isCFC)return cfcStartTag(); return cfmlStartTag(); } finally{ pci.useSpecialMappings(old); } } /** * @see javax.servlet.jsp.tagext.Tag#doEndTag() */ public int doEndTag() { PageContextImpl pci=(PageContextImpl) pageContext; boolean old=pci.useSpecialMappings(true); try{ if(source.isCFC)_doCFCFinally(); return EVAL_PAGE; } finally{ pci.useSpecialMappings(old); } } /** * @see javax.servlet.jsp.tagext.BodyTag#doInitBody() */ public void doInitBody() { } /** * @see javax.servlet.jsp.tagext.BodyTag#doAfterBody() */ public int doAfterBody() throws PageException { if(source.isCFC)return cfcEndTag(); return cfmlEndTag(); } /** * @see railo.runtime.ext.tag.BodyTagTryCatchFinallyImpl#doCatch(java.lang.Throwable) */ public void doCatch(Throwable t) throws Throwable { if(source.isCFC){ String source=isEndTag?"end":"body"; isEndTag=false; _doCFCCatch(t,source); } else super.doCatch(t); } void initFile() throws PageException { source=initFile(pageContext); } public InitFile initFile(PageContext pageContext) throws PageException { ConfigWeb config = pageContext.getConfig(); // filenames String[] filenames=getFileNames(config,appendix); // search local PageSource source=null; if(config.doLocalCustomTag()){ for(int i=0;i<filenames.length;i++){ source=pageContext.getRelativePageSource(filenames[i]); if(MappingImpl.isOK(source)) return new InitFile(source,filenames[i],filenames[i].endsWith('.'+config.getCFCExtension())); } } // search in custom tag directory boolean doCustomTagDeepSearch = config.doCustomTagDeepSearch(); // local mappings Mapping[] ctms = pageContext.getApplicationContext().getCustomTagMappings(); if(ctms!=null){ for(int i=0;i<filenames.length;i++){ source=getMapping(ctms, filenames[i],doCustomTagDeepSearch); if(source!=null) return new InitFile(source,filenames[i],filenames[i].endsWith('.'+config.getCFCExtension())); } } // config mappings ctms = config.getCustomTagMappings(); for(int i=0;i<filenames.length;i++){ source=getMapping(ctms, filenames[i], doCustomTagDeepSearch); if(source!=null) return new InitFile(source,filenames[i],filenames[i].endsWith('.'+config.getCFCExtension())); } // EXCEPTION // message StringBuffer msg=new StringBuffer("custom tag \""); msg.append(getDisplayName(config,appendix)); msg.append("\" is not defined in directory \""); msg.append(ResourceUtil.getResource(pageContext, pageContext.getCurrentPageSource()).getParent()); msg.append('"'); if(!ArrayUtil.isEmpty(ctms)){ if(ctms.length==1)msg.append(" and directory "); else msg.append(" and directories "); msg.append("\""); msg.append(toString(ctms)); msg.append("\""); } throw new ExpressionException(msg.toString(),getDetail(config)); } public static String getDetail(Config config) { boolean hasCFC=false,hasCFML=false; String[] extensions=config.getCustomTagExtensions(); for(int i =0;i<extensions.length;i++){ if(extensions[i].equalsIgnoreCase(config.getCFCExtension())) hasCFC=true; else hasCFML=true; } StringBuffer sb=new StringBuffer(); if(!hasCFC)sb.append("Component based Custom Tags are not enabled;"); if(!hasCFML)sb.append("CFML based Custom Tags are not enabled;"); return sb.toString(); } public static String getDisplayName(Config config,String name) { String[] extensions=config.getCustomTagExtensions(); if(extensions.length==0) return name; return name+".["+List.arrayToList(extensions, "|")+"]"; } public static String[] getFileNames(Config config, String name) throws ExpressionException { String[] extensions=config.getCustomTagExtensions(); if(extensions.length==0) throw new ExpressionException("Custom Tags are disabled"); String[] fileNames=new String[extensions.length]; for(int i =0;i<fileNames.length;i++){ fileNames[i]=name+'.'+extensions[i]; } return fileNames; } private static PageSource getMapping(Mapping[] ctms, String filename, boolean doCustomTagDeepSearch) { //print.o("filename:"+filename); //MappingImpl ctm; PageSource ps; // first check for cached pathes for(int i=0;i<ctms.length;i++){ //ctm=(MappingImpl) ctms[i]; ps = ((MappingImpl) ctms[i]).getCustomTagPath(filename, doCustomTagDeepSearch); if(ps!=null) return ps; } return null; } static String toString(Mapping[] ctms) { if(ctms==null) return ""; StringBuffer sb=new StringBuffer(); Resource p; for(int i=0;i<ctms.length;i++){ if(sb.length()!=0)sb.append("; "); p = ctms[i].getPhysical(); if(p!=null) sb.append(p.toString()); } return sb.toString(); } private int cfmlStartTag() throws PageException { callerScope.initialize(pageContext); // thistag if(thistagScope==null)thistagScope=new StructImpl(StructImpl.TYPE_LINKED); thistagScope.set(GENERATED_CONTENT,""); thistagScope.set(EXECUTION_MODE,"start"); thistagScope.set(EXECUTE_BODY,Boolean.TRUE); thistagScope.set(HAS_END_TAG,Caster.toBoolean(hasBody)); ctVariablesScope=new VariablesImpl(); ctVariablesScope.setEL(ATTRIBUTES,attributesScope); ctVariablesScope.setEL(CALLER,callerScope); ctVariablesScope.setEL(THIS_TAG,thistagScope); // include doInclude(); return Caster.toBooleanValue(thistagScope.get(EXECUTE_BODY))?EVAL_BODY_BUFFERED:SKIP_BODY; } private int cfmlEndTag() throws PageException { // thistag thistagScope.set(GENERATED_CONTENT,bodyContent.getString()); bodyContent.clearBody(); thistagScope.set(EXECUTION_MODE,"end"); thistagScope.set(EXECUTE_BODY,Boolean.FALSE); // include doInclude(); String output = bodyContent.getString(); try { bodyContent.clearBody(); bodyContent.getEnclosingWriter().write(Caster.toString(thistagScope.get(GENERATED_CONTENT))+output); } catch (IOException e) {} return Caster.toBooleanValue(thistagScope.get(EXECUTE_BODY))?EVAL_BODY_BUFFERED:SKIP_BODY; } void doInclude() throws PageException { Variables var=pageContext.variablesScope(); pageContext.setVariablesScope(ctVariablesScope); QueryStack cs=null; Undefined undefined=pageContext.undefinedScope(); int oldMode=undefined.setMode(Undefined.MODE_NO_LOCAL_AND_ARGUMENTS); if(oldMode!=Undefined.MODE_NO_LOCAL_AND_ARGUMENTS) callerScope.setScope(var,pageContext.localScope(),pageContext.argumentsScope(),true); else callerScope.setScope(var,null,null,false); if(pageContext.getConfig().allowImplicidQueryCall()) { cs=undefined.getQueryStack(); undefined.setQueryStack(new QueryStackImpl()); } try { pageContext.doInclude(source.ps); } catch (Throwable t) { throw Caster.toPageException(t); } finally { undefined.setMode(oldMode); //varScopeData=variablesScope.getMap(); pageContext.setVariablesScope(var); if(pageContext.getConfig().allowImplicidQueryCall()) { undefined.setQueryStack(cs); } } } // CFC private int cfcStartTag() throws PageException { callerScope.initialize(pageContext); cfc = ComponentLoader.loadComponentImpl(pageContext,null,source.ps, source.filename.substring(0,source.filename.length()-(pageContext.getConfig().getCFCExtension().length()+1)), false,true); validateAttributes(cfc,attributesScope,StringUtil.ucFirst(List.last(source.ps.getComponentName(),'.'))); boolean exeBody = false; try { Object rtn=Boolean.TRUE; if(cfc.contains(pageContext, INIT)){ Tag parent=getParent(); while(parent!=null && !(parent instanceof CFTag && ((CFTag)parent).isCFCBasedCustomTag())) { parent=parent.getParent(); } Struct args=new StructImpl(StructImpl.TYPE_LINKED); args.set(HAS_END_TAG, Caster.toBoolean(hasBody)); if(parent instanceof CFTag) { args.set(PARENT, ((CFTag)parent).getComponent()); } rtn=cfc.callWithNamedValues(pageContext, INIT, args); } if(cfc.contains(pageContext, ON_START_TAG)){ Struct args=new StructImpl(); args.set(ATTRIBUTES, attributesScope); args.set(CALLER, pageContext.variablesScope()); rtn=cfc.callWithNamedValues(pageContext, ON_START_TAG, args); } exeBody=Caster.toBooleanValue(rtn,true); } catch(Throwable t){ _doCFCCatch(t,"start"); } return exeBody?EVAL_BODY_BUFFERED:SKIP_BODY; } private static void validateAttributes(ComponentPro cfc,StructImpl attributesScope,String tagName) throws ApplicationException, ExpressionException { TagLibTag tag=getAttributeRequirments(cfc,false); if(tag==null) return; if(tag.getAttributeType()==TagLibTag.ATTRIBUTE_TYPE_FIXED || tag.getAttributeType()==TagLibTag.ATTRIBUTE_TYPE_MIXED){ Iterator it = tag.getAttributes().entrySet().iterator(); Map.Entry entry; int count=0; Collection.Key key; TagLibTagAttr attr; Object value; // check existing attributes while(it.hasNext()){ entry = (Entry) it.next(); count++; key=KeyImpl.toKey(entry.getKey(),null); attr=(TagLibTagAttr) entry.getValue(); value=attributesScope.get(key,null); if(value==null){ if(attr.getDefaultValue()!=null){ value=attr.getDefaultValue(); attributesScope.setEL(key, value); } else if(attr.isRequired()) throw new ApplicationException("attribute ["+key.getString()+"] is required for tag ["+tagName+"]"); } if(value!=null) { if(!Decision.isCastableTo(attr.getType(),value,true)) throw new CasterException(createMessage(attr.getType(), value)); } } // check if there are attributes not supported if(tag.getAttributeType()==TagLibTag.ATTRIBUTE_TYPE_FIXED && count<attributesScope.size()){ Collection.Key[] keys = attributesScope.keys(); for(int i=0;i<keys.length;i++){ if(tag.getAttribute(keys[i].getLowerString())==null) throw new ApplicationException("attribute ["+keys[i].getString()+"] is not supported for tag ["+tagName+"]"); } //Attribute susi is not allowed for tag cfmail } } } private static String createMessage(String type, Object value) { if(value instanceof String) return "can't cast String ["+value+"] to a value of type ["+type+"]"; else if(value!=null) return "can't cast Object type ["+Type.getName(value)+"] to a value of type ["+type+"]"; else return "can't cast Null value to value of type ["+type+"]"; } private static TagLibTag getAttributeRequirments(ComponentPro cfc, boolean runtime) throws ExpressionException { Struct meta=null; //try { //meta = Caster.toStruct(cfc.get(Component.ACCESS_PRIVATE, METADATA),null,false); Member mem = ComponentUtil.toComponentImpl(cfc).getMember(Component.ACCESS_PRIVATE, METADATA,true,false); if(mem!=null)meta = Caster.toStruct(mem.getValue(),null,false); //}catch (PageException e) {e.printStackTrace();} if(meta==null) return null; TagLibTag tag=new TagLibTag(null); // TAG // type String type=Caster.toString(meta.get(ATTRIBUTE_TYPE,"dynamic"),"dynamic"); if("fixed".equalsIgnoreCase(type))tag.setAttributeType(TagLibTag.ATTRIBUTE_TYPE_FIXED); //else if("mixed".equalsIgnoreCase(type))tag.setAttributeType(TagLibTag.ATTRIBUTE_TYPE_MIXED); //else if("noname".equalsIgnoreCase(type))tag.setAttributeType(TagLibTag.ATTRIBUTE_TYPE_NONAME); else tag.setAttributeType(TagLibTag.ATTRIBUTE_TYPE_DYNAMIC); if(!runtime){ // hint String hint=Caster.toString(meta.get(HINT,null),null); if(!StringUtil.isEmpty(hint))tag.setDescription(hint); // parseBody boolean rtexprvalue=Caster.toBooleanValue(meta.get(PARSE_BODY,Boolean.FALSE),false); tag.setParseBody(rtexprvalue); } // ATTRIBUTES Struct attributes=Caster.toStruct(meta.get(ATTRIBUTES,null),null,false); if(attributes!=null) { Iterator it = attributes.entrySet().iterator(); Map.Entry entry; TagLibTagAttr attr; Struct sct; String name,defaultValue; Object o; while(it.hasNext()){ entry=(Entry) it.next(); name=Caster.toString(entry.getKey(),null); if(StringUtil.isEmpty(name)) continue; attr=new TagLibTagAttr(tag); attr.setName(name); sct=Caster.toStruct(entry.getValue(),null,false); if(sct!=null){ attr.setRequired(Caster.toBooleanValue(sct.get(REQUIRED,Boolean.FALSE),false)); attr.setType(Caster.toString(sct.get(TYPE,"any"),"any")); o= sct.get(DEFAULT,null); if(o!=null){ defaultValue=Caster.toString(o,null); if(defaultValue!=null) attr.setDefaultValue(defaultValue); } if(!runtime){ attr.setDescription(Caster.toString(sct.get(HINT,null),null)); attr.setRtexpr(Caster.toBooleanValue(sct.get(RT_EXPR_VALUE,Boolean.TRUE),true)); } } tag.setAttribute(attr); } } return tag; } private int cfcEndTag() throws PageException { boolean exeAgain = false; try{ String output=null; Object rtn=Boolean.FALSE; if(cfc.contains(pageContext, ON_END_TAG)){ try { output=bodyContent.getString(); bodyContent.clearBody(); //rtn=cfc.call(pageContext, ON_END_TAG, new Object[]{attributesScope,pageContext.variablesScope(),output}); Struct args=new StructImpl(StructImpl.TYPE_LINKED); args.set(ATTRIBUTES, attributesScope); args.set(CALLER, pageContext.variablesScope()); args.set(GENERATED_CONTENT, output); rtn=cfc.callWithNamedValues(pageContext, ON_END_TAG, args); } finally { writeEnclosingWriter(); } } else writeEnclosingWriter(); exeAgain= Caster.toBooleanValue(rtn,false); } catch(Throwable t){ isEndTag=true; throw Caster.toPageException(t); } return exeAgain?EVAL_BODY_BUFFERED:SKIP_BODY; } public void _doCFCCatch(Throwable t, String source) throws PageException { writeEnclosingWriter(); // remove PageServletException wrap if(t instanceof PageServletException) { PageServletException pse=(PageServletException)t; t=pse.getPageException(); } // abort try { if(t instanceof railo.runtime.exp.Abort){ if(bodyContent!=null){ bodyContent.writeOut(bodyContent.getEnclosingWriter()); bodyContent.clearBuffer(); } throw Caster.toPageException(t); } } catch(IOException ioe){ throw Caster.toPageException(ioe); } try { if(cfc.contains(pageContext, ON_ERROR)){ PageException pe = Caster.toPageException(t); //Object rtn=cfc.call(pageContext, ON_ERROR, new Object[]{pe.getCatchBlock(pageContext),source}); Struct args=new StructImpl(StructImpl.TYPE_LINKED); args.set(CFCATCH, pe.getCatchBlock(pageContext)); args.set(SOURCE, source); Object rtn=cfc.callWithNamedValues(pageContext, ON_ERROR, args); if(Caster.toBooleanValue(rtn,false)) throw t; } else throw t; } catch(Throwable th) { writeEnclosingWriter(); _doCFCFinally(); throw Caster.toPageException(th); } writeEnclosingWriter(); } private void _doCFCFinally() { if(cfc.contains(pageContext, ON_FINALLY)){ try { cfc.call(pageContext, ON_FINALLY, ArrayUtil.OBJECT_EMPTY); } catch (PageException pe) { throw new PageRuntimeException(pe); } finally{ writeEnclosingWriter(); } } } private void writeEnclosingWriter() { if(bodyContent!=null){ try { String output = bodyContent.getString(); bodyContent.clearBody(); bodyContent.getEnclosingWriter().write(output); } catch (IOException e) { //throw Caster.toPageException(e); } } } /** * sets if tag has a body or not * @param hasBody */ public void hasBody(boolean hasBody) { this.hasBody=hasBody; } /** * @return Returns the appendix. */ public String getAppendix() { return appendix; } /** * @return return thistag */ public Struct getThis() { if(isCFCBasedCustomTag()){ return cfc; } return thistagScope; } /** * @return return thistag */ public Struct getCallerScope() { return callerScope; } /** * @return return thistag */ public Struct getAttributesScope() { return attributesScope; } /** * @return the ctVariablesScope */ public Struct getVariablesScope() { if(isCFCBasedCustomTag()) { return cfc.getComponentScope(); } return ctVariablesScope; } /** * @return the cfc */ public Component getComponent() { return cfc; } public boolean isCFCBasedCustomTag() { return getSource().isCFC; } private InitFile getSource() { if(source==null){ try { source=initFile(pageContext); } catch (PageException e) { e.printStackTrace(); } } return source; } class InitFile { PageSource ps; String filename; boolean isCFC; public InitFile(PageSource ps,String filename,boolean isCFC){ this.ps=ps; this.filename=filename; this.isCFC=isCFC; } } }
package com.afollestad.silk.http; import android.os.Handler; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.client.HttpClient; import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest; import ch.boye.httpclientandroidlib.conn.ClientConnectionManager; import ch.boye.httpclientandroidlib.conn.scheme.PlainSocketFactory; import ch.boye.httpclientandroidlib.conn.scheme.Scheme; import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry; import ch.boye.httpclientandroidlib.conn.ssl.SSLSocketFactory; import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; import ch.boye.httpclientandroidlib.impl.conn.PoolingClientConnectionManager; import java.util.ArrayList; import java.util.List; /** * @author Aidan Follestad (afollestad) */ class SilkHttpBase { public SilkHttpBase(Handler handler) { mHeaders = new ArrayList<SilkHttpHeader>(); mHandler = handler; init(); } public SilkHttpBase() { this(new Handler()); } private void init() { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); ClientConnectionManager cm = new PoolingClientConnectionManager(registry); mClient = new DefaultHttpClient(cm); } private HttpClient mClient; protected final List<SilkHttpHeader> mHeaders; private final Handler mHandler; protected void reset() { mHeaders.clear(); } protected Handler getHandler() { return mHandler; } protected void runOnPriorityThread(Runnable runnable) { Thread t = new Thread(runnable); t.setPriority(Thread.MAX_PRIORITY); t.start(); } protected SilkHttpResponse performRequest(final HttpUriRequest request) throws SilkHttpException { if (mHeaders.size() > 0) { for (SilkHttpHeader header : mHeaders) request.setHeader(header.getName(), header.getValue()); } HttpResponse response; try { response = mClient.execute(request); } catch (Exception e) { reset(); throw new SilkHttpException(e); } int status = response.getStatusLine().getStatusCode(); if (status != 200) { reset(); throw new SilkHttpException(response); } reset(); return new SilkHttpResponse(response); } public final void release() { mClient.getConnectionManager().shutdown(); } }
package com.anthonycr.base47; import org.jetbrains.annotations.NotNull; import java.util.concurrent.atomic.AtomicInteger; public final class Base47 { private static final int BASE_2 = 2; private static final int BASE_47 = 47; private static final String[] CHARACTERS_2_ARRAY = { "0", "1" }; private static final String[] CHARACTERS_ARRAY = { "\uD83D\uDC36", "\uD83D\uDC31", "\uD83D\uDC2D", "\uD83D\uDC39", "\uD83D\uDC30", "\uD83D\uDC3B", "\uD83D\uDC3C", "\uD83D\uDC28", "\uD83D\uDC2F", "\uD83E\uDD81", "\uD83D\uDC2E", "\uD83D\uDC37", "\uD83D\uDC38", "\uD83D\uDC19", "\uD83D\uDC35", "\uD83D\uDE48", "\uD83D\uDE49", "\uD83D\uDE4A", "\uD83D\uDC12", "\uD83D\uDC14", "\uD83D\uDC27", "\uD83D\uDC26", "\uD83D\uDC24", "\uD83D\uDC23", "\uD83D\uDC25", "\uD83D\uDC3A", "\uD83D\uDC17", "\uD83D\uDC34", "\uD83E\uDD84", "\uD83D\uDC1D", "\uD83D\uDC1B", "\uD83D\uDC0C", "\uD83D\uDC1E", "\uD83E\uDD80", "\uD83D\uDC0D", "\uD83D\uDC22", "\uD83D\uDC20", "\uD83D\uDC1F", "\uD83D\uDC21", "\uD83D\uDC2C", "\uD83D\uDC33", "\uD83D\uDC18", "\uD83D\uDC16", "\uD83D\uDD4A", "\uD83D\uDC3F", "\uD83E\uDD8D", "\uD83E\uDD8C" }; private Base47() { throw new UnsupportedOperationException("Class is not instantiable"); } @NotNull private static String byteToString(byte bite) { return Integer.toBinaryString((bite & 0xFF) + 0x100).substring(1); } @NotNull private static String byteArrayToString(@NotNull byte[] bytes) { StringBuilder stringBuilder = new StringBuilder(bytes.length * 8); for (byte bite : bytes) { stringBuilder.append(byteToString(bite)); } return stringBuilder.toString(); } @NotNull private static byte[] bitStringToByteArray(@NotNull String bytes) { if (bytes.length() % 8 != 0) { throw new RuntimeException("Unsupported string length"); } byte[] newBytes = new byte[bytes.length() / 8]; int index = 0; for (int n = 0; n <= bytes.length() - 8; n += 8) { StringBuilder inner = new StringBuilder(8); for (int i = 0; i < 8; i++) { inner.append(bytes.charAt(n + i)); } newBytes[index] = (byte) Integer.parseInt(inner.toString(), 2); index++; } if (index != newBytes.length) { throw new UnsupportedOperationException( "Byte array was not completely filled, length was " + newBytes.length + ", last filled index was " + (index - 1)); } return newBytes; } /** * Encodes a byte array as a string of emojis. * * @param bytes the bytes to encode in base 47. * @return the encoded string of emojis. */ @NotNull public static String encode(@NotNull byte[] bytes) { Preconditions.checkNotNull(bytes); return convertNumber(byteArrayToString(bytes), BASE_2, BASE_47); } /** * Decodes a string of previously encoded emojis * back into the original byte array. * * @param string the base 47 emoji string to decode. * @return the original decoded bytes. */ @NotNull public static byte[] decode(@NotNull String string) { Preconditions.checkNotNull(string); String preConversion = convertNumber(string, BASE_47, BASE_2); int prependZero = 8 - (preConversion.length() % 8); if (prependZero == 8) { prependZero = 0; } StringBuilder postConversion = new StringBuilder(preConversion.length() + prependZero); for (int n = 0; n < prependZero; n++) { postConversion.append('0'); } postConversion.append(preConversion); return bitStringToByteArray(postConversion.toString()); } @NotNull private static String zeroAsBase(int base) { return valueToDigit(0, base); } @NotNull private static String convertNumber(@NotNull String number, int oldBase, int newBase) { // Calculating the character length of the new number using int size = (int) Math.round(number.length() * Math.log(oldBase) / Math.log(newBase) + 1); StringBuilder newNumber = new StringBuilder(size); AtomicInteger remainder = new AtomicInteger(); StringBuilder reusableResultBuilder = new StringBuilder(number.length()); StringBuilder reusableValueBuilder = new StringBuilder(2); while (!zeroAsBase(oldBase).equals(number)) { remainder.set(0); number = divideNumber(number, oldBase, newBase, remainder, reusableResultBuilder, reusableValueBuilder); String newDigit = valueToDigit(remainder.get(), newBase); newNumber.insert(0, newDigit); } if (newNumber.length() == 0) { return zeroAsBase(newBase); } return newNumber.toString(); } @NotNull private static String divideNumber(@NotNull String number, int base, int divisor, @NotNull AtomicInteger remainder, @NotNull StringBuilder resultBuilder, @NotNull StringBuilder valueBuilder) { remainder.set(0); resultBuilder.setLength(0); boolean hasCharacters = false; for (int n = 0; n < number.length(); ) { int digitValue; final int codePoint = number.codePointAt(n); int codePointCount = Character.charCount(codePoint); valueBuilder.setLength(0); for (int i = n; i < (n + codePointCount); i++) { valueBuilder.append(number.charAt(i)); } n += codePointCount; digitValue = digitToValue(base, valueBuilder.toString()); remainder.set(base * remainder.get() + digitValue); int newDigitValue = remainder.get() / divisor; remainder.set(remainder.get() % divisor); if (newDigitValue > 0 || hasCharacters) { String newDigits = valueToDigit(newDigitValue, base); hasCharacters = true; resultBuilder.append(newDigits); } } String resultString = resultBuilder.toString(); if (resultString.isEmpty()) { return zeroAsBase(base); } return resultString; } private static int digitToValue(int base, @NotNull String digit) { int index; if (base == BASE_2) { index = indexOf(CHARACTERS_2_ARRAY, digit); } else if (base == BASE_47) { index = indexOf(CHARACTERS_ARRAY, digit); } else { throw new RuntimeException("Unsupported base: " + base); } if (index < 0) { throw new UnsupportedOperationException( "Unable to find string charset for base " + digit + ": " + digit); } else { return index; } } @NotNull private static String valueToDigit(int value, int base) { if (value >= base) { throw new IndexOutOfBoundsException("Index was " + value + ", must not be greater than " + base); } if (base == BASE_2) { return CHARACTERS_2_ARRAY[value]; } else if (base == BASE_47) { return CHARACTERS_ARRAY[value]; } throw new RuntimeException("Unsupported base: " + base); } private static int indexOf(@NotNull String[] array, @NotNull String string) { for (int n = 0; n < array.length; n++) { if (string.equals(array[n])) { return n; } } return -1; } }
package org.holoeverywhere.widget; import java.util.ArrayList; import org.holoeverywhere.R; import org.holoeverywhere.util.Pool; import org.holoeverywhere.util.Poolable; import org.holoeverywhere.util.PoolableManager; import org.holoeverywhere.util.Pools; import org.holoeverywhere.util.ReflectHelper; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.Animatable; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ClipDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.RotateDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.graphics.drawable.shapes.Shape; import android.os.Build.VERSION; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.Gravity; import android.view.ViewDebug; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.view.animation.Transformation; public class ProgressBar extends View { private class AccessibilityEventSender implements Runnable { @Override public void run() { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } } private static class RefreshData implements Poolable<RefreshData> { private static final int POOL_MAX = 24; private static final Pool<RefreshData> sPool = Pools .synchronizedPool(Pools.finitePool( new PoolableManager<RefreshData>() { @Override public RefreshData newInstance() { return new RefreshData(); } @Override public void onAcquired(RefreshData element) { } @Override public void onReleased(RefreshData element) { } }, RefreshData.POOL_MAX)); public static RefreshData obtain(int id, int progress, boolean fromUser) { RefreshData rd = RefreshData.sPool.acquire(); rd.id = id; rd.progress = progress; rd.fromUser = fromUser; return rd; } public boolean fromUser; public int id; private boolean mIsPooled; private RefreshData mNext; public int progress; @Override public RefreshData getNextPoolable() { return mNext; } @Override public boolean isPooled() { return mIsPooled; } public void recycle() { RefreshData.sPool.release(this); } @Override public void setNextPoolable(RefreshData element) { mNext = element; } @Override public void setPooled(boolean isPooled) { mIsPooled = isPooled; } } private class RefreshProgressRunnable implements Runnable { @Override public void run() { synchronized (ProgressBar.this) { final int count = mRefreshData.size(); for (int i = 0; i < count; i++) { final RefreshData rd = mRefreshData.get(i); doRefreshProgress(rd.id, rd.progress, rd.fromUser, true); rd.recycle(); } mRefreshData.clear(); mRefreshIsPosted = false; } } } protected static class SavedState extends BaseSavedState { public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; int progress; int secondaryProgress; protected SavedState(Parcel in) { super(in); progress = in.readInt(); secondaryProgress = in.readInt(); } protected SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(progress); out.writeInt(secondaryProgress); } } private static final int MAX_LEVEL = 10000; private static final int TIMEOUT_SEND_ACCESSIBILITY_EVENT = 200; private AccessibilityEventSender mAccessibilityEventSender; private AlphaAnimation mAnimation; private boolean mAttached; private int mBehavior; private Drawable mCurrentDrawable; private int mDuration; private boolean mHasAnimation; private boolean mIndeterminate; private Drawable mIndeterminateDrawable; private boolean mInDrawing; private Interpolator mInterpolator; private int mMax; protected int mMinWidth, mMaxWidth, mMinHeight, mMaxHeight; private boolean mNoInvalidate; private boolean mOnlyIndeterminate; private int mProgress; private Drawable mProgressDrawable; private final ArrayList<RefreshData> mRefreshData = new ArrayList<RefreshData>(); private boolean mRefreshIsPosted; private RefreshProgressRunnable mRefreshProgressRunnable; private Bitmap mSampleTile; private int mSecondaryProgress; private boolean mShouldStartAnimationDrawable; private Transformation mTransformation; private long mUiThreadId; public ProgressBar(Context context) { this(context, null); } public ProgressBar(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.progressBarStyle); } public ProgressBar(Context context, AttributeSet attrs, int defStyle) { this(context, attrs, defStyle, R.style.Holo_ProgressBar); } public ProgressBar(Context context, AttributeSet attrs, int defStyle, int styleRes) { super(context, attrs, defStyle); mUiThreadId = Thread.currentThread().getId(); initProgressBar(); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ProgressBar, defStyle, styleRes); mNoInvalidate = true; Drawable drawable = getDrawable(a, R.styleable.ProgressBar_android_progressDrawable); if (drawable != null) { drawable = tileify(drawable, false); setProgressDrawable(drawable); } mDuration = a.getInt( R.styleable.ProgressBar_android_indeterminateDuration, mDuration); mMinWidth = a.getDimensionPixelSize( R.styleable.ProgressBar_android_minWidth, mMinWidth); mMaxWidth = a.getDimensionPixelSize( R.styleable.ProgressBar_android_maxWidth, mMaxWidth); mMinHeight = a.getDimensionPixelSize( R.styleable.ProgressBar_android_minHeight, mMinHeight); mMaxHeight = a.getDimensionPixelSize( R.styleable.ProgressBar_android_maxHeight, mMaxHeight); mBehavior = a.getInt( R.styleable.ProgressBar_android_indeterminateBehavior, mBehavior); final int resID = a.getResourceId( R.styleable.ProgressBar_android_interpolator, android.R.anim.linear_interpolator); if (resID > 0) { setInterpolator(context, resID); } setMax(a.getInt(R.styleable.ProgressBar_android_max, mMax)); setProgress(a.getInt(R.styleable.ProgressBar_android_progress, mProgress)); setSecondaryProgress(a.getInt( R.styleable.ProgressBar_android_secondaryProgress, mSecondaryProgress)); drawable = getDrawable(a, R.styleable.ProgressBar_android_indeterminateDrawable); if (drawable != null) { drawable = tileifyIndeterminate(drawable); setIndeterminateDrawable(drawable); } mOnlyIndeterminate = a.getBoolean( R.styleable.ProgressBar_android_indeterminateOnly, mOnlyIndeterminate); mNoInvalidate = false; setIndeterminate(mOnlyIndeterminate || a.getBoolean(R.styleable.ProgressBar_android_indeterminate, mIndeterminate)); a.recycle(); } private synchronized void doRefreshProgress(int id, int progress, boolean fromUser, boolean callBackToApp) { float scale = mMax > 0 ? (float) progress / (float) mMax : 0; final Drawable d = mCurrentDrawable; if (d != null) { Drawable progressDrawable = null; if (d instanceof LayerDrawable) { progressDrawable = ((LayerDrawable) d) .findDrawableByLayerId(id); } final int level = (int) (scale * ProgressBar.MAX_LEVEL); (progressDrawable != null ? progressDrawable : d).setLevel(level); } else { invalidate(); } if (callBackToApp && id == R.id.progress) { onProgressRefresh(scale, fromUser); } } @Override protected void drawableStateChanged() { super.drawableStateChanged(); updateDrawableState(); } protected Drawable getCurrentDrawable() { return mCurrentDrawable; } // Very funny change android.RotateDrawable on custom RotateDrawable, // ported from JB private Drawable getDrawable(TypedArray a, int attr) { Drawable d = a.getDrawable(attr); try { int id = a.getResourceId(attr, 0); if ((id == R.drawable.progress_small_holo || id == R.drawable.progress_medium_holo || id == R.drawable.progress_large_holo) && VERSION.SDK_INT < 14) { LayerDrawable layers = (LayerDrawable) d; int layersCount = layers.getNumberOfLayers(); Drawable[] newLayers = new Drawable[layersCount]; for (int i = 0; i < layersCount; i++) { Drawable layer = layers.getDrawable(i); if (layer instanceof RotateDrawable && (i == 0 || i == 1)) { org.holoeverywhere.drawable.RotateDrawable r = new org.holoeverywhere.drawable.RotateDrawable(); Drawable rotatedDrawable = ((RotateDrawable) layer) .getDrawable(); if (i == 0) { r.setState(rotatedDrawable, true, true, 0.5f, 0.5f, 0f, 1080f); } else if (i == 1) { r.setState(rotatedDrawable, true, true, 0.5f, 0.5f, 720f, 0f); } layer = r; } newLayers[i] = layer; } return new LayerDrawable(newLayers); } } catch (Exception e) { e.printStackTrace(); } return d; } private Shape getDrawableShape() { final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 }; return new RoundRectShape(roundedCorners, null, null); } public Drawable getIndeterminateDrawable() { return mIndeterminateDrawable; } public Interpolator getInterpolator() { return mInterpolator; } @ViewDebug.ExportedProperty(category = "progress") public synchronized int getMax() { return mMax; } @ViewDebug.ExportedProperty(category = "progress") public synchronized int getProgress() { return mIndeterminate ? 0 : mProgress; } public Drawable getProgressDrawable() { return mProgressDrawable; } public int getResolvedLayoutDirection() { return 0; } public int getResolvedLayoutDirection(Drawable who) { return who == mProgressDrawable || who == mIndeterminateDrawable ? getResolvedLayoutDirection() : 0; } @ViewDebug.ExportedProperty(category = "progress") public synchronized int getSecondaryProgress() { return mIndeterminate ? 0 : mSecondaryProgress; } public synchronized final void incrementProgressBy(int diff) { setProgress(mProgress + diff); } public synchronized final void incrementSecondaryProgressBy(int diff) { setSecondaryProgress(mSecondaryProgress + diff); } private void initProgressBar() { mMax = 100; mProgress = 0; mSecondaryProgress = 0; mIndeterminate = false; mOnlyIndeterminate = false; mDuration = 4000; mBehavior = Animation.RESTART; mMinWidth = 24; mMaxWidth = 48; mMinHeight = 24; mMaxHeight = 48; } @Override public void invalidateDrawable(Drawable dr) { if (!mInDrawing) { if (verifyDrawable(dr)) { final Rect dirty = dr.getBounds(); final int scrollX = getScrollX() + getPaddingLeft(); final int scrollY = getScrollY() + getPaddingTop(); invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY); } else { super.invalidateDrawable(dr); } } } @ViewDebug.ExportedProperty(category = "progress") public synchronized boolean isIndeterminate() { return mIndeterminate; } @SuppressLint("NewApi") @Override public void jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState(); if (mProgressDrawable != null) { mProgressDrawable.jumpToCurrentState(); } if (mIndeterminateDrawable != null) { mIndeterminateDrawable.jumpToCurrentState(); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mIndeterminate) { startAnimation(); } if (mRefreshData != null) { synchronized (this) { final int count = mRefreshData.size(); for (int i = 0; i < count; i++) { final RefreshData rd = mRefreshData.get(i); doRefreshProgress(rd.id, rd.progress, rd.fromUser, true); rd.recycle(); } mRefreshData.clear(); } } mAttached = true; } @Override protected void onDetachedFromWindow() { if (mIndeterminate) { stopAnimation(); } if (mRefreshProgressRunnable != null) { removeCallbacks(mRefreshProgressRunnable); } if (mRefreshProgressRunnable != null && mRefreshIsPosted) { removeCallbacks(mRefreshProgressRunnable); } if (mAccessibilityEventSender != null) { removeCallbacks(mAccessibilityEventSender); } super.onDetachedFromWindow(); mAttached = false; } @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); Drawable d = mCurrentDrawable; if (d != null) { canvas.save(); canvas.translate(getPaddingLeft(), getPaddingTop()); long time = getDrawingTime(); if (mHasAnimation) { mAnimation.getTransformation(time, mTransformation); float scale = mTransformation.getAlpha(); try { mInDrawing = true; d.setLevel((int) (scale * ProgressBar.MAX_LEVEL)); } finally { mInDrawing = false; } postInvalidate(); } d.draw(canvas); canvas.restore(); if (mShouldStartAnimationDrawable && d instanceof Animatable) { ((Animatable) d).start(); mShouldStartAnimationDrawable = false; } } } @SuppressLint("NewApi") @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(ProgressBar.class.getName()); event.setItemCount(mMax); event.setCurrentItemIndex(mProgress); } @Override @SuppressLint("NewApi") public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(ProgressBar.class.getName()); } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Drawable d = mCurrentDrawable; int dw = 0; int dh = 0; if (d != null) { dw = Math .max(mMinWidth, Math.min(mMaxWidth, d.getIntrinsicWidth())); dh = Math.max(mMinHeight, Math.min(mMaxHeight, d.getIntrinsicHeight())); } updateDrawableState(); dw += getPaddingLeft() + getPaddingRight(); dh += getPaddingTop() + getPaddingBottom(); setMeasuredDimension( View.supportResolveSizeAndState(dw, widthMeasureSpec, 0), View.supportResolveSizeAndState(dh, heightMeasureSpec, 0)); } protected void onProgressRefresh(float scale, boolean fromUser) { try { if (((AccessibilityManager) AccessibilityManager.class.getMethod( "getInstance", Context.class).invoke(null, getContext())) .isEnabled()) { scheduleAccessibilityEventSender(); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setProgress(ss.progress); setSecondaryProgress(ss.secondaryProgress); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.progress = mProgress; ss.secondaryProgress = mSecondaryProgress; return ss; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { updateDrawableBounds(w, h); } @Override public void onVisibilityChanged(View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (mIndeterminate) { if (visibility == android.view.View.GONE || visibility == android.view.View.INVISIBLE) { stopAnimation(); } else { startAnimation(); } } } @Override public void postInvalidate() { if (!mNoInvalidate) { super.postInvalidate(); } } private synchronized void refreshProgress(int id, int progress, boolean fromUser) { if (mUiThreadId == Thread.currentThread().getId()) { doRefreshProgress(id, progress, fromUser, true); } else { if (mRefreshProgressRunnable == null) { mRefreshProgressRunnable = new RefreshProgressRunnable(); } final RefreshData rd = RefreshData.obtain(id, progress, fromUser); mRefreshData.add(rd); if (mAttached && !mRefreshIsPosted) { post(mRefreshProgressRunnable); mRefreshIsPosted = true; } } } private void scheduleAccessibilityEventSender() { if (mAccessibilityEventSender == null) { mAccessibilityEventSender = new AccessibilityEventSender(); } else { removeCallbacks(mAccessibilityEventSender); } postDelayed(mAccessibilityEventSender, ProgressBar.TIMEOUT_SEND_ACCESSIBILITY_EVENT); } public synchronized void setIndeterminate(boolean indeterminate) { if ((!mOnlyIndeterminate || !mIndeterminate) && indeterminate != mIndeterminate) { mIndeterminate = indeterminate; if (indeterminate) { // swap between indeterminate and regular backgrounds mCurrentDrawable = mIndeterminateDrawable; startAnimation(); } else { mCurrentDrawable = mProgressDrawable; stopAnimation(); } } } public void setIndeterminateDrawable(Drawable d) { if (d != null) { d.setCallback(this); } mIndeterminateDrawable = d; if (mIndeterminate) { mCurrentDrawable = d; postInvalidate(); } } public void setInterpolator(Context context, int resID) { setInterpolator(AnimationUtils.loadInterpolator(context, resID)); } public void setInterpolator(Interpolator interpolator) { mInterpolator = interpolator; } public synchronized void setMax(int max) { if (max < 0) { max = 0; } if (max != mMax) { mMax = max; postInvalidate(); if (mProgress > max) { mProgress = max; } refreshProgress(R.id.progress, mProgress, false); } } public synchronized void setProgress(int progress) { setProgress(progress, false); } synchronized void setProgress(int progress, boolean fromUser) { if (mIndeterminate) { return; } if (progress < 0) { progress = 0; } if (progress > mMax) { progress = mMax; } if (progress != mProgress) { mProgress = progress; refreshProgress(R.id.progress, mProgress, fromUser); } } public void setProgressDrawable(Drawable d) { boolean needUpdate; if (mProgressDrawable != null && d != mProgressDrawable) { mProgressDrawable.setCallback(null); needUpdate = true; } else { needUpdate = false; } if (d != null) { d.setCallback(this); int drawableHeight = d.getMinimumHeight(); if (mMaxHeight < drawableHeight) { mMaxHeight = drawableHeight; requestLayout(); } } mProgressDrawable = d; if (!mIndeterminate) { mCurrentDrawable = d; postInvalidate(); } if (needUpdate) { updateDrawableBounds(getWidth(), getHeight()); updateDrawableState(); doRefreshProgress(R.id.progress, mProgress, false, false); doRefreshProgress(R.id.secondaryProgress, mSecondaryProgress, false, false); } } public synchronized void setSecondaryProgress(int secondaryProgress) { if (mIndeterminate) { return; } if (secondaryProgress < 0) { secondaryProgress = 0; } if (secondaryProgress > mMax) { secondaryProgress = mMax; } if (secondaryProgress != mSecondaryProgress) { mSecondaryProgress = secondaryProgress; refreshProgress(R.id.secondaryProgress, mSecondaryProgress, false); } } @Override public void setVisibility(int v) { if (getVisibility() != v) { super.setVisibility(v); if (mIndeterminate) { if (v == android.view.View.GONE || v == android.view.View.INVISIBLE) { stopAnimation(); } else { startAnimation(); } } } } void startAnimation() { if (getVisibility() != android.view.View.VISIBLE) { return; } if (mIndeterminateDrawable instanceof Animatable) { mShouldStartAnimationDrawable = true; mHasAnimation = false; } else { mHasAnimation = true; if (mInterpolator == null) { mInterpolator = new LinearInterpolator(); } if (mTransformation == null) { mTransformation = new Transformation(); } else { mTransformation.clear(); } if (mAnimation == null) { mAnimation = new AlphaAnimation(0.0f, 1.0f); } else { mAnimation.reset(); } mAnimation.setRepeatMode(mBehavior); mAnimation.setRepeatCount(Animation.INFINITE); mAnimation.setDuration(mDuration); mAnimation.setInterpolator(mInterpolator); mAnimation.setStartTime(Animation.START_ON_FIRST_FRAME); } postInvalidate(); } void stopAnimation() { mHasAnimation = false; if (mIndeterminateDrawable instanceof Animatable) { ((Animatable) mIndeterminateDrawable).stop(); mShouldStartAnimationDrawable = false; } postInvalidate(); } private Drawable tileify(Drawable drawable, boolean clip) { if (drawable instanceof LayerDrawable) { LayerDrawable background = (LayerDrawable) drawable; final int N = background.getNumberOfLayers(); Drawable[] outDrawables = new Drawable[N]; for (int i = 0; i < N; i++) { int id = background.getId(i); outDrawables[i] = tileify(background.getDrawable(i), id == R.id.progress || id == R.id.secondaryProgress); } LayerDrawable newBg = new LayerDrawable(outDrawables); for (int i = 0; i < N; i++) { newBg.setId(i, background.getId(i)); } return newBg; } else if (drawable instanceof StateListDrawable) { StateListDrawable in = (StateListDrawable) drawable; StateListDrawable out = new StateListDrawable(); int numStates = ReflectHelper .invoke(in, "getStateCount", int.class); for (int i = 0; i < numStates; i++) { out.addState( ReflectHelper.invoke(in, "getStateSet", int[].class, i), tileify(ReflectHelper.invoke(in, "getStateDrawable", Drawable.class, i), clip)); } return out; } else if (drawable instanceof BitmapDrawable) { final Bitmap tileBitmap = ((BitmapDrawable) drawable).getBitmap(); if (mSampleTile == null) { mSampleTile = tileBitmap; } final ShapeDrawable shapeDrawable = new ShapeDrawable( getDrawableShape()); final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP); shapeDrawable.getPaint().setShader(bitmapShader); return clip ? new ClipDrawable(shapeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL) : shapeDrawable; } return drawable; } private Drawable tileifyIndeterminate(Drawable drawable) { if (drawable instanceof AnimationDrawable) { AnimationDrawable background = (AnimationDrawable) drawable; final int N = background.getNumberOfFrames(); AnimationDrawable newBg = new AnimationDrawable(); newBg.setOneShot(background.isOneShot()); for (int i = 0; i < N; i++) { Drawable frame = tileify(background.getFrame(i), true); frame.setLevel(10000); newBg.addFrame(frame, background.getDuration(i)); } newBg.setLevel(10000); drawable = newBg; } return drawable; } private void updateDrawableBounds(int w, int h) { int right = w - getPaddingRight() - getPaddingLeft(); int bottom = h - getPaddingBottom() - getPaddingTop(); int top = 0; int left = 0; if (mIndeterminateDrawable != null) { if (mOnlyIndeterminate && !(mIndeterminateDrawable instanceof AnimationDrawable)) { final int intrinsicWidth = mIndeterminateDrawable .getIntrinsicWidth(); final int intrinsicHeight = mIndeterminateDrawable .getIntrinsicHeight(); final float intrinsicAspect = (float) intrinsicWidth / intrinsicHeight; final float boundAspect = (float) w / h; if (intrinsicAspect != boundAspect) { if (boundAspect > intrinsicAspect) { final int width = (int) (h * intrinsicAspect); left = (w - width) / 2; right = left + width; } else { final int height = (int) (w * (1 / intrinsicAspect)); top = (h - height) / 2; bottom = top + height; } } } mIndeterminateDrawable.setBounds(left, top, right, bottom); } if (mProgressDrawable != null) { mProgressDrawable.setBounds(0, 0, right, bottom); } } private void updateDrawableState() { int[] state = getDrawableState(); if (mProgressDrawable != null && mProgressDrawable.isStateful()) { mProgressDrawable.setState(state); } if (mIndeterminateDrawable != null && mIndeterminateDrawable.isStateful()) { mIndeterminateDrawable.setState(state); } } @Override protected boolean verifyDrawable(Drawable who) { return who == mProgressDrawable || who == mIndeterminateDrawable || super.verifyDrawable(who); } }
package adf.sample.algorithm.pathplanning; import adf.agent.info.AgentInfo; import adf.agent.info.ScenarioInfo; import adf.agent.info.WorldInfo; import adf.component.algorithm.PathPlanning; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import rescuecore2.misc.collections.LazyMap; import rescuecore2.standard.entities.Area; import rescuecore2.worldmodel.Entity; import rescuecore2.worldmodel.EntityID; import java.util.*; public class SamplePathPlanning extends PathPlanning { private Map<EntityID, Set<EntityID>> graph; private EntityID from; private List<EntityID> result; public SamplePathPlanning(AgentInfo ai, WorldInfo wi, ScenarioInfo si) { super(ai, wi, si); this.init(); } private void init() { Map<EntityID, Set<EntityID>> neighbours = new LazyMap<EntityID, Set<EntityID>>() { @Override public Set<EntityID> createValue() { return new HashSet<>(); } }; for (Entity next : this.worldInfo) { if (next instanceof Area) { Collection<EntityID> areaNeighbours = ((Area) next).getNeighbours(); neighbours.get(next.getID()).addAll(areaNeighbours); } } this.graph = neighbours; } @Override public List<EntityID> getResult() { return this.result; } @Override public void setFrom(EntityID id) { this.from = id; } @Override public PathPlanning setDestination(Collection<EntityID> targets) { List<EntityID> open = new LinkedList<>(); Map<EntityID, EntityID> ancestors = new HashMap<>(); open.add(this.from); EntityID next; boolean found = false; ancestors.put(this.from, this.from); do { next = open.remove(0); if (isGoal(next, targets)) { found = true; break; } Collection<EntityID> neighbours = graph.get(next); if (neighbours.isEmpty()) { continue; } for (EntityID neighbour : neighbours) { if (isGoal(neighbour, targets)) { ancestors.put(neighbour, next); next = neighbour; found = true; break; } else { if (!ancestors.containsKey(neighbour)) { open.add(neighbour); ancestors.put(neighbour, next); } } } } while (!found && !open.isEmpty()); if (!found) { // No path this.result = null; } // Walk back from goal to this.from EntityID current = next; LinkedList<EntityID> path = new LinkedList<>(); do { path.add(0, current); current = ancestors.get(current); if (current == null) { throw new RuntimeException("Found a node with no ancestor! Something is broken."); } } while (current != this.from); this.result = path; return this; } private boolean isGoal(EntityID e, Collection<EntityID> test) { return test.contains(e); } }
package time; /** * * @author Yifei Zhu * */ public class Date implements Comparable<Date> { private int year; private int month; private int day; public Date(int year, int month, int day) { setYear(year); setMonth(month); setDay(day); } //Constructor to change from dataBase string to an Object public Date(String dbDate) { String[] date = dbDate.split("-"); year = Integer.parseInt(date[0]); month = Integer.parseInt(date[1]); day = Integer.parseInt(date[2]); } public int getYear() { return year; } public void setYear(int year) { if(year<2000 || year>2099) { throw new IllegalArgumentException("Year must be > 2000 and <2099"); } this.year=year; } //Years that are divisible by four are leap years, //with the exception of years that are divisible by 100, //which are not leap years, and with the final exception of years divisible by 400, which are. public boolean isLeapYear() { //determine leap year if((year%4==0 && year%100 !=0)|| year%400==0) return true; return false; } public int getMonth() { return month; } public void setMonth(int month) { if(month<=0 || month>12) { throw new IllegalArgumentException("Invalid Input: Month"); } this.month = month; } public int getDay() { return day; } public void setDay(int day) { if(day<0||day>31) throw new IllegalArgumentException("Day cant <0 or >31"); if(getMonth()==2) { if(isLeapYear() && day<=29) { this.day=day; } else if(!isLeapYear()&&day<=28) { this.day=day; } else { throw new IllegalArgumentException("Feb. should be < 28 || < 29"); } } else { this.day = day; } } @Override public int compareTo(Date o) { if(o==null) { throw new NullPointerException("date is null"); } //if d==this if(this.year==o.year && this.month==o.month) return this.day-o.day; else if(this.year==o.year ) return this.month-o.month; return this.year-o.year; } public String toString() { return year+"-"+addZero(month)+"-"+addZero(day); } /** * Add a zero in front of num that <10 * @param num --the number * @return --return modified num */ private String addZero(int num) { if(num<10) return "0"+num; return ""+num; } private int getMonthIn() { switch(this.month) { case 1: return 6; case 2: return 2; case 3: return 2; case 4: return 5; case 5: return 0; case 6: return 3; case 7: return 5; case 8: return 1; case 9: return 4; case 10: return 6; case 11: return 2; case 12: return 4; } return 0; } private String getMyDayOfWeek(int num) { switch(num) { case 1: return "Monday"; case 2: return "Tuesday"; case 3: return "Wednesday"; case 4: return "Thursday"; case 5: return "Friday"; case 6: return "Saturday"; case 7: return "Sunday"; } return ""; //TODO } public String getDayOfWeek() { //Take the last 2 digits of the year and add a quarter onto itself int lastTwoNum = (int)((this.year%200)*(1+0.25)); int monthCode = getMonthIn(); int addAll = lastTwoNum+monthCode+this.day; //take away 7 int result=addAll%7; return getMyDayOfWeek(result); } }
package agentgui.envModel.p2Dsvg.imageProcessing; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Stack; import java.util.Vector; import javax.imageio.ImageIO; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import agentgui.envModel.p2Dsvg.ontology.ActiveObject; import agentgui.envModel.p2Dsvg.ontology.PassiveObject; import agentgui.envModel.p2Dsvg.ontology.Physical2DObject; import agentgui.envModel.p2Dsvg.ontology.Position; import agentgui.envModel.p2Dsvg.ontology.PositionUpdate; import agentgui.envModel.p2Dsvg.ontology.StaticObject; import agentgui.envModel.p2Dsvg.provider.EnvironmentProviderHelper; import agentgui.envModel.p2Dsvg.utils.EnvironmentWrapper; /** * The class provides methods for dynamic path finding. It also can detect collissions. * * @author Tim Lewen - DAWIS - ICB - University of Duisburg - Essen * */ public class ImageHelper { public static final int DIRECTION_FORWARD=0; public static final int DIRECTION_BACKWARD=1; public static final int DIRECTION_LEFT=2; public static final int DIRECTION_RIGHT=3; public static final int DIRECTION_UP_LEFT=4; public static final int DIRECTION_UP_RIGHT=5; public static final int DIRECTION_DOWN_LEFT=6; public static final int DIRECTION_DOWN_RIGHT=7; private static boolean READ_WORLD=false; private static boolean IS_IN_METHOD=false; private static boolean FIRST_CALL=true; private boolean is_setup=false; int divideHeight; int divideWidth; double lastDistance=-20; private BufferedImage evn=null; int endung=0; private float firstX; private float firstY; boolean first=false; boolean igoreNoDistanceChange=false; int counter=0; int compareDirectionsCounter=5; int directionsCounter=0; Position from=null; Position to=null; String fromID=""; String toID=""; EnvironmentProviderHelper helper; boolean DEBUG=true; Document manipulated=null; /** * @param fromID ID of the StartPoint * @param toID ID of the destination * @param helper The enviromentHelper */ public ImageHelper(String fromID,String toID, EnvironmentProviderHelper helper ) { this.fromID=fromID; this.toID=toID; this.helper=helper; } public ImageHelper(EnvironmentProviderHelper helper) { this.helper=helper; } public ImageHelper() { } public ImageHelper(Position destination, String ownID) { } /** * Uses recursion to delete node and child nodes * @param doc The SVG Document * @param node The node which should be deleted */ private void deleteNodes(Document doc,Node node) { NodeList list=node.getChildNodes(); for(int i=0;i<list.getLength();i++) { node.removeChild(list.item(i)); } if(list.getLength()!=0) { this.deleteNodes(doc, node); } } /** * It's used as an heuristic * * @param target_x The X position of the target * @param target_y The Y position of the target * @param x Own X Position * @param y Own Y Position * @return */ private double getDistance(float target_x,float target_y,float x,float y) { float xPosDiff=Math.abs(target_x-x); float yPosDiff=Math.abs(target_y-y); return Math.abs( Math.sqrt(xPosDiff*xPosDiff + yPosDiff*yPosDiff)); } /** * It's used as an heuristic * * @param target_x The X position of the target * @param target_y The Y position of the target * @param x Own X Position * @param y Own Y Position * @return */ private float getManhattanDistance(float target_x,float target_y,float x,float y) { float dx = Math.abs(target_x - x); float dy = Math.abs(target_y- y); float heuristic = dx+dy; return heuristic; } /** * Returns a node for the open/closed List * @param x Own X Position * @param y Own Y Position * @param parent Parent node * @param target_x Target X Position * @param target_y Target Y Position * @param ownDirection The directions the agent is moving to * @param width Width of the agent * @param height Height of the agent * @param startXIndex Start X Index * @param startYIndex Start Y Index * @return */ private agentgui.envModel.p2Dsvg.imageProcessing.StepNode fillNode(float x, float y,agentgui.envModel.p2Dsvg.imageProcessing.StepNode parent,float target_x,float target_y,int ownDirection,float width,float height,int startXIndex,int startYIndex) { agentgui.envModel.p2Dsvg.imageProcessing.StepNode result=new agentgui.envModel.p2Dsvg.imageProcessing.StepNode(); double first_distance= this.getManhattanDistance(target_x, target_y, x, y); //this.getDistance(target_x, target_y, x, y); double manhattan_distance_to_origin=this.getManhattanDistance(x, y,parent.getX(), parent.getY()); result.setDirection(ownDirection); result.setDistance(first_distance+manhattan_distance_to_origin); result.setParent(parent); result.setStoppInvestigating(false); result.setX(x); result.setY(y); double distance=this.getDistance( x,y,firstX,firstY); float dx = Math.abs(target_x - x); float dy = Math.abs(target_y- y); float heuristic = dx+dy; result.setDistanceToOrginal(distance); result.setTotal_distance(heuristic); return result; } /** * Another possible heuristic * @param startIndexX X startIndex in a grid * @param startIndexY Y startIndex in a grid * @param currentIndexX Current index of the grid * @param currentIndexY Current index of the grid * @return */ private int getHCost(int startIndexX,int startIndexY, int currentIndexX, int currentIndexY) { int val=Math.abs(startIndexX-currentIndexX)+Math.abs(startIndexY-currentIndexY); return val*10; } /** * Calculates the path * @param id Agent ID * @param target_x Target X postion * @param target_y Target Y position * @param width width of the agent * @param height height of the agent * @param target_id ID of the target * @param direction The direction the agent is moving * @param lookAhead How many pixels should be looked ahead * @param parent Parent Node * @param pixel The color of the pixel * @return * @throws Exception */ private synchronized agentgui.envModel.p2Dsvg.imageProcessing.StepNode withoutGrid(String id,float target_x,float target_y,float width,float height, int direction , float lookAhead, agentgui.envModel.p2Dsvg.imageProcessing.StepNode parent,int pixel,boolean useAdjustedWorld) throws Exception { System.out.println("Target in WITHOUTGRID:"+target_x+","+ target_y); ArrayList<agentgui.envModel.p2Dsvg.imageProcessing.StepNode> openList=new ArrayList<agentgui.envModel.p2Dsvg.imageProcessing.StepNode>(); ArrayList<agentgui.envModel.p2Dsvg.imageProcessing.StepNode> closedList=new ArrayList<agentgui.envModel.p2Dsvg.imageProcessing.StepNode>(); float worldWidth=helper.getEnvironment().getRootPlayground().getSize().getWidth(); float worldHeight=helper.getEnvironment().getRootPlayground().getSize().getHeight(); counter++; Document doc=null; if(!useAdjustedWorld) { doc=helper.getSVGDoc(); } else { doc=manipulated; } // Calculate pos final float xStart= parent.getX(); final float yStart= parent.getY(); System.out.println("X Start:"+xStart); System.out.println("Y Start:"+yStart); float currentXPos=xStart; float currentYPos=yStart; final int listXIndex= (int) (parent.getX()/lookAhead); final int listYIndex= (int) (parent.getY()/lookAhead); agentgui.envModel.p2Dsvg.imageProcessing.StepNode current=parent; closedList.add(current); // While you're not even close while(this.getDistance(target_x, target_y, currentXPos, currentYPos)>10) { // Up left agentgui.envModel.p2Dsvg.imageProcessing.StepNode new_current=null; if(currentXPos-lookAhead>0&&currentYPos-lookAhead>0) { if(!this.isInList(openList, closedList, currentXPos-lookAhead, currentYPos-lookAhead,ImageHelper.DIRECTION_UP_LEFT)) { new_current=this.fillNode(currentXPos-lookAhead, currentYPos-lookAhead, current, target_x, target_y, ImageHelper.DIRECTION_UP_LEFT,width,height,listXIndex,listYIndex); if(this.tranformAndCheckImage(this.evn, currentXPos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_UP_LEFT, Color.gray.getRGB())) { // openList.add(new_current); } else { if(new_current!=null) { if(DEBUG) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"red"); } } } } } // Up Right new_current=null; if(currentXPos+lookAhead<worldWidth&&currentYPos-lookAhead>=0) { if(!this.isInList(openList, closedList, currentXPos+lookAhead, currentYPos-lookAhead,ImageHelper.DIRECTION_UP_RIGHT)) { new_current=this.fillNode(currentXPos+lookAhead, currentYPos-lookAhead, current, target_x, target_y, ImageHelper.DIRECTION_UP_RIGHT,width,height,listXIndex,listYIndex); if(this.tranformAndCheckImage(this.evn, currentXPos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_UP_RIGHT, Color.gray.getRGB())) { //openList.add(new_current); } else { if(new_current!=null) { if(DEBUG) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"red"); } } } } } // Down left new_current=null; if(currentXPos-lookAhead>=0&&currentYPos+lookAhead<=worldHeight) { if(!this.isInList(openList, closedList, currentXPos-lookAhead, currentYPos+lookAhead,ImageHelper.DIRECTION_DOWN_LEFT)) { new_current=this.fillNode(currentXPos-lookAhead, currentYPos+lookAhead, current, target_x, target_y, ImageHelper.DIRECTION_DOWN_LEFT,width,height,listXIndex,listYIndex); if(this.tranformAndCheckImage(this.evn, currentXPos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_DOWN_LEFT, Color.gray.getRGB())) { //openList.add(new_current); } else { if(new_current!=null) { if(DEBUG) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"red"); } } } } } // DOWN right new_current=null; if(currentXPos+lookAhead<=worldWidth&&currentYPos+lookAhead<=worldHeight) { if(!this.isInList(openList, closedList, currentXPos-lookAhead, currentYPos+lookAhead,ImageHelper.DIRECTION_DOWN_RIGHT)) { new_current=this.fillNode(currentXPos+lookAhead, currentYPos+lookAhead, current, target_x, target_y, ImageHelper.DIRECTION_DOWN_RIGHT,width,height,listXIndex,listYIndex); if(this.tranformAndCheckImage(this.evn, currentXPos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_DOWN_RIGHT, Color.gray.getRGB())) { // openList.add(new_current); } else { if(new_current!=null) { if(DEBUG) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"red"); } } } } } // Left new_current=null; if(currentXPos-lookAhead>=0) { if(!this.isInList(openList, closedList, currentXPos-lookAhead, currentYPos,ImageHelper.DIRECTION_LEFT)) { new_current=this.fillNode(currentXPos-lookAhead, currentYPos, current, target_x, target_y, ImageHelper.DIRECTION_LEFT,width,height,listXIndex,listYIndex); if(this.tranformAndCheckImage(this.evn, currentXPos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_LEFT, Color.gray.getRGB())) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"black"); openList.add(new_current); } else { if(new_current!=null) { if(DEBUG) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"red"); } } } } } // Right new_current=null; if(currentXPos+lookAhead<worldWidth) { if(!this.isInList(openList, closedList, currentXPos+lookAhead, currentYPos,ImageHelper.DIRECTION_RIGHT)) { new_current=this.fillNode(currentXPos+lookAhead, currentYPos, current, target_x, target_y, ImageHelper.DIRECTION_RIGHT,width,height,listXIndex,listYIndex); if(this.tranformAndCheckImage(this.evn, currentXPos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_RIGHT, Color.gray.getRGB())) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"black"); openList.add(new_current); } else { if(new_current!=null) { if(DEBUG) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"red"); } } } } } // Forward new_current=null; if(currentYPos+lookAhead<worldHeight) { if(!this.isInList(openList, closedList, currentXPos, currentYPos+lookAhead,ImageHelper.DIRECTION_FORWARD)) { new_current=this.fillNode(currentXPos, currentYPos+lookAhead, current, target_x, target_y, ImageHelper.DIRECTION_FORWARD,width,height,listXIndex,listYIndex); if(this.tranformAndCheckImage(this.evn, currentXPos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_FORWARD, Color.gray.getRGB())) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"black"); openList.add(new_current); } else { if(new_current!=null) { if(DEBUG) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"red"); } } } } } // Backwards new_current=null; if(currentYPos-lookAhead>=0) { if(!this.isInList(openList, closedList, currentXPos, currentYPos-lookAhead , ImageHelper.DIRECTION_BACKWARD)) { new_current=this.fillNode(currentXPos, currentYPos-lookAhead, current, target_x, target_y, ImageHelper.DIRECTION_BACKWARD,width,height,listXIndex,listYIndex); if(this.tranformAndCheckImage(this.evn, currentXPos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_BACKWARD, Color.gray.getRGB())) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"black"); openList.add(new_current); } else { if(new_current!=null) { if(DEBUG) { this.drawLineToSave("l", String.valueOf(new_current.getX()), String.valueOf(width), String.valueOf(new_current.getY()), String.valueOf(height), doc,true,"red"); } } } } } closedList.add(current); int index=this.getMinimumDistance(openList); if(index==-1) { if(lookAhead-2<0) { System.out.println("Habe keinen Weg gefunden:" + id); if(DEBUG) { SVGSafe sg=new SVGSafe(); String name="WayPath"+ id+counter; File f=new File(name+".svg"); while(f.exists()) { counter++; name="WayPath"+id+counter; f=new File(name+".svg"); } //sg.write(name+".svg", doc); System.out.println("Datei geschrieben!"); } //current.setX(-666); //current.setY(-666); System.out.println("nichts gefunden"); return null;//current; } //No path is found. Try too look less pixel ahead else { if(DEBUG) { } //System.out.println("Write File"); //System.out.println("Rek with:"+ (lookAhead-2) +" ID:"+id); int faktor=2; if(lookAhead-faktor==0) { current.setX(-666); current.setY(-666); System.out.println("nichts gefunden"); return null; } SVGSafe sg=new SVGSafe(); String name="WayPath"+id+counter; File f=new File(name+".svg"); while(f.exists()) { counter++; name="WayPath"+ id+counter; f=new File(name+".svg"); } if(DEBUG) { sg.write(name+".svg", doc); } System.out.println("Neue Datei geschreieben"); System.out.println("Neuer Rekursiver Aufruf"); System.out.println("LookAhead-faktor:"+ (lookAhead-faktor)); return this.withoutGrid(id, target_x, target_y, width, height, direction, lookAhead-faktor, parent, pixel,useAdjustedWorld); } } current=openList.get(index); openList.remove(index); currentXPos=current.getX(); currentYPos=current.getY(); if(this.getDistance(target_x, target_y, currentXPos, currentYPos)<=10) { SVGSafe sg=new SVGSafe(); String name="WayPath"+id+counter; File f=new File(name+".svg"); while(f.exists()) { counter++; name="WayPath"+id+counter; f=new File(name+".svg"); } if(DEBUG) { sg.write(name+".svg", doc); } System.out.println("WayPath"+ id +""+counter+".svg gespeichert"); System.out.println("Schreib!"); //System.out.println("ID vollkommen:" + id); if(DEBUG) { //System.out.println("Rekursion!"); //sg.write("WayPath_"+id +","+counter+".svg", doc); } return current; } } //System.out.println("ID vollkommen:" + id); SVGSafe sg=new SVGSafe(); String name="WayPath"+ id +""+counter; File f=new File(name+".svg"); while(f.exists()) { counter++; name="WayPath"+ id +""+counter; f=new File(name+".svg"); } if(DEBUG) { sg.write(name+".svg", doc); } System.out.println("Datei geschrieben"); return current; } /** * Checks if a node is already in a list * @param open The list with the open Nodes * @param closed The list with the closed NOdes * @param x X Position of the node * @param y Y Position of the node * @param direction The Direction of the node * @return True or false */ private boolean isInList(ArrayList<agentgui.envModel.p2Dsvg.imageProcessing.StepNode> open,ArrayList<agentgui.envModel.p2Dsvg.imageProcessing.StepNode> closed, float x,float y,int direction) { for(int i=0;i<open.size();i++) { if(open.get(i).getX()==x&&open.get(i).getY()==y) { return true; } } for(int i=0;i<closed.size();i++) { if(closed.get(i).getX()==x&&closed.get(i).getY()==y) { return true; } } return false; } /** * Searches for the node with lowest costs * @param list The open node list * @return the node with the minimum costs */ private int getMinimumDistance(ArrayList<agentgui.envModel.p2Dsvg.imageProcessing.StepNode> list) { int min=Integer.MAX_VALUE; int result=-1; for(int i=0;i<list.size();i++) { if(min>list.get(i).getDistance()) { min=(int) list.get(i).getDistance(); result=i; } } return result; } /** * Creates the path * @param id The ID of the agent * @param target_id The ID of the target * @param direction The direction * @param lookAhead Numbers of pixel * @return target node of the path * @throws Exception */ public synchronized agentgui.envModel.p2Dsvg.imageProcessing.StepNode createPlanImage(String id,String target_id , int direction , float lookAhead) throws Exception { //System.out.println("Agent:"+id + " will create his own world!"); /** synchronized (this) { if(!READ_WORLD&&!IS_IN_METHOD&FIRST_CALL) { FIRST_CALL=false; System.out.println(id + " erstell Welt"); this.createManipulatedWorld(); } else { System.out.println(id + " liest Welt"); this.evn=ImageIO.read(new File("myWorld.jpg")); } } while(!READ_WORLD) { System.out.println("Warte!"+id); Thread.sleep(50); } */ System.out.println("ID:"+id); this.evn=this.createManipulatedWorldPerAgent(); Document doc=helper.getSVGDoc(); Element target=doc.getElementById(target_id); float target_x=Float.parseFloat(target.getAttribute("x")); float target_y=Float.parseFloat(target.getAttribute("y")); System.out.println("FirstCall Target:"+target_x+","+target_y); Element self=doc.getElementById(id); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=Float.parseFloat(self.getAttribute("x")); float y=Float.parseFloat(self.getAttribute("y")); //System.out.println(id + " x:" +x +"," + "Y:"+y); EnvironmentWrapper wrapper=new EnvironmentWrapper(this.helper.getEnvironment()); System.out.println("MyPos:"+wrapper.getObjectById(id).getPosition().getXPos()+ "," + wrapper.getObjectById(id).getPosition().getYPos()); System.out.println("Self X:"+x); System.out.println("Self Y:"+y); this.firstX=x; this.firstY=y; agentgui.envModel.p2Dsvg.imageProcessing.StepNode root=new agentgui.envModel.p2Dsvg.imageProcessing.StepNode(); root.setX(x); root.setY(y); final int listXIndex= (int) (root.getX()/lookAhead); final int listYIndex= (int) (root.getY()/lookAhead); final int targetXIndex= (int) (target_x/lookAhead); final int targetYIndex=(int) (target_y/lookAhead); root.setDistanceToOrginal(0.0); root.setDistance(this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex)); root.setTotal_distance((this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex))); root.setParent(null); //int color=this.getPixelsOnce(plan, x, y, width, height); agentgui.envModel.p2Dsvg.imageProcessing.StepNode targetNode= this.withoutGrid(id, target_x, target_y, width, height, direction, 10.0f,root , -1,false) ; //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, -1); // //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, color) ; //handle_subNodes_brute(id,target_x, target_y, width, height, target_id, direction, lookAhead,root,color); return targetNode; } public synchronized agentgui.envModel.p2Dsvg.imageProcessing.StepNode createPlanImage(String id,Position own,String target_id , int direction , float lookAhead) throws Exception { //System.out.println("Agent:"+id + " will create his own world!"); /** synchronized (this) { if(!READ_WORLD&&!IS_IN_METHOD&FIRST_CALL) { FIRST_CALL=false; System.out.println(id + " erstell Welt"); this.createManipulatedWorld(); } else { System.out.println(id + " liest Welt"); this.evn=ImageIO.read(new File("myWorld.jpg")); } } while(!READ_WORLD) { System.out.println("Warte!"+id); Thread.sleep(50); } */ this.evn=this.createManipulatedWorldPerAgent(); Document doc=helper.getSVGDoc(); Element target=doc.getElementById(target_id); float target_x=Float.parseFloat(target.getAttribute("x")); float target_y=Float.parseFloat(target.getAttribute("y")); System.out.println("FirstCall Target:"+target_x+","+target_y); Element self=doc.getElementById(id); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=own.getXPos(); float y=own.getYPos(); //System.out.println(id + " x:" +x +"," + "Y:"+y); EnvironmentWrapper wrapper=new EnvironmentWrapper(this.helper.getEnvironment()); this.firstX=x; this.firstY=y; agentgui.envModel.p2Dsvg.imageProcessing.StepNode root=new agentgui.envModel.p2Dsvg.imageProcessing.StepNode(); root.setX(x); root.setY(y); final int listXIndex= (int) (root.getX()/lookAhead); final int listYIndex= (int) (root.getY()/lookAhead); final int targetXIndex= (int) (target_x/lookAhead); final int targetYIndex=(int) (target_y/lookAhead); root.setDistanceToOrginal(0.0); root.setDistance(this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex)); root.setTotal_distance((this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex))); root.setParent(null); //int color=this.getPixelsOnce(plan, x, y, width, height); agentgui.envModel.p2Dsvg.imageProcessing.StepNode targetNode= this.withoutGrid(id, target_x, target_y, width, height, direction, 10.0f,root , -1,false) ; //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, -1); // //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, color) ; //handle_subNodes_brute(id,target_x, target_y, width, height, target_id, direction, lookAhead,root,color); return targetNode; } public synchronized agentgui.envModel.p2Dsvg.imageProcessing.StepNode createPlanImage(String id,Position target , int direction , float lookAhead) throws Exception { this.evn=this.createManipulatedWorldPerAgent(); Document doc=helper.getSVGDoc(); float target_x=target.getXPos(); float target_y=target.getYPos(); System.out.println("Target X:"+target_x +","+target_y); Element self=doc.getElementById(id); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=Float.parseFloat(self.getAttribute("x")); float y=Float.parseFloat(self.getAttribute("y")); this.firstX=x; this.firstY=y; agentgui.envModel.p2Dsvg.imageProcessing.StepNode root=new agentgui.envModel.p2Dsvg.imageProcessing.StepNode(); root.setX(x); root.setY(y); final int listXIndex= (int) (root.getX()/lookAhead); final int listYIndex= (int) (root.getY()/lookAhead); final int targetXIndex= (int) (target_x/lookAhead); final int targetYIndex=(int) (target_y/lookAhead); root.setDistanceToOrginal(0.0); root.setDistance(this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex)); root.setTotal_distance((this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex))); root.setParent(null); //int color=this.getPixelsOnce(plan, x, y, width, height); agentgui.envModel.p2Dsvg.imageProcessing.StepNode targetNode= this.withoutGrid(id, target_x, target_y, width, height, direction, 10.0f,root , -1,false) ; //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, -1); // //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, color) ; //handle_subNodes_brute(id,target_x, target_y, width, height, target_id, direction, lookAhead,root,color); return targetNode; } public synchronized agentgui.envModel.p2Dsvg.imageProcessing.StepNode createPlanImage(ArrayList<CombinedNameAndPos> otherAgent, Position own,String id ,String target , float lookAhead, double discreteTime) throws Exception { synchronized (this) { this.evn=this.createManipulatedWorldWithAgents(otherAgent,id,discreteTime); if(this.evn==null) { System.out.println("Sollte nicht vorkommen!"); return null; } } Document doc=helper.getSVGDoc(); Element targetElement=doc.getElementById(target); float target_x=Float.parseFloat(targetElement.getAttribute("x")); float target_y=Float.parseFloat(targetElement.getAttribute("y")); System.out.println("Target x:"+target_x); System.out.println("Target y:"+target_y); Element self=doc.getElementById(id); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=own.getXPos(); float y=own.getYPos(); //self.setAttribute("x", String.valueOf(x)); //self.setAttribute("y", String.valueOf(y)); this.firstX=x; this.firstY=y; System.out.println("Own X:"+x +"," + "Y:"+y); agentgui.envModel.p2Dsvg.imageProcessing.StepNode root=new agentgui.envModel.p2Dsvg.imageProcessing.StepNode(); root.setX(x); // correct it // root.setY(y); // Correct it // final int listXIndex= (int) (root.getX()/lookAhead); final int listYIndex= (int) (root.getY()/lookAhead); final int targetXIndex= (int) (target_x/lookAhead); final int targetYIndex=(int) (target_y/lookAhead); root.setDistanceToOrginal(0.0); root.setDistance(this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex)); root.setTotal_distance((this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex))); root.setParent(null); //int color=this.getPixelsOnce(plan, x, y, width, height); agentgui.envModel.p2Dsvg.imageProcessing.StepNode targetNode= this.withoutGrid(id, target_x, target_y, width, height,ImageHelper.DIRECTION_BACKWARD, 10.0f,root , -1,true) ; //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, -1); // //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, color) ; //handle_subNodes_brute(id,target_x, target_y, width, height, target_id, direction, lookAhead,root,color); return targetNode; } public synchronized agentgui.envModel.p2Dsvg.imageProcessing.StepNode createPlanImage(ArrayList<CombinedNameAndPos> otherAgent, Position own,String id ,Position target , float lookAhead, double discreteTime) throws Exception { synchronized (this) { this.evn=this.createManipulatedWorldWithAgents(otherAgent,id,discreteTime); if(this.evn==null) { System.out.println("Sollte nicht vorkommen!"); return null; } } Document doc=helper.getSVGDoc(); float target_x=target.getXPos(); float target_y=target.getYPos(); System.out.println("Target x:"+target_x); System.out.println("Target y:"+target_y); Element self=doc.getElementById(id); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=own.getXPos(); float y=own.getYPos(); //self.setAttribute("x", String.valueOf(x)); //self.setAttribute("y", String.valueOf(y)); this.firstX=x; this.firstY=y; agentgui.envModel.p2Dsvg.imageProcessing.StepNode root=new agentgui.envModel.p2Dsvg.imageProcessing.StepNode(); root.setX(x); // correct it // root.setY(y); // Correct it // final int listXIndex= (int) (root.getX()/lookAhead); final int listYIndex= (int) (root.getY()/lookAhead); final int targetXIndex= (int) (target_x/lookAhead); final int targetYIndex=(int) (target_y/lookAhead); root.setDistanceToOrginal(0.0); root.setDistance(this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex)); root.setTotal_distance((this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex))); root.setParent(null); //int color=this.getPixelsOnce(plan, x, y, width, height); agentgui.envModel.p2Dsvg.imageProcessing.StepNode targetNode= this.withoutGrid(id, target_x, target_y, width, height,ImageHelper.DIRECTION_BACKWARD, 10.0f,root , -1,true) ; //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, -1); // //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, color) ; //handle_subNodes_brute(id,target_x, target_y, width, height, target_id, direction, lookAhead,root,color); return targetNode; } public synchronized agentgui.envModel.p2Dsvg.imageProcessing.StepNode createPlanImage(String otherAgent,Position own,String id ,Position target , int direction , float lookAhead) throws Exception { synchronized (this) { if(!READ_WORLD&&!IS_IN_METHOD&FIRST_CALL) { FIRST_CALL=false; //this.evn=this.createManipulatedWorldWithAgents(otherAgent); } else { this.evn=ImageIO.read(new File("myWorld.jpg")); } } while(!READ_WORLD) { Thread.sleep(50); } Document doc=helper.getSVGDoc(); float target_x=target.getXPos(); float target_y=target.getYPos(); Element self=doc.getElementById(id); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=own.getXPos(); float y=own.getYPos(); this.firstX=x; this.firstY=y; agentgui.envModel.p2Dsvg.imageProcessing.StepNode root=new agentgui.envModel.p2Dsvg.imageProcessing.StepNode(); root.setX(x); root.setY(y); final int listXIndex= (int) (root.getX()/lookAhead); final int listYIndex= (int) (root.getY()/lookAhead); final int targetXIndex= (int) (target_x/lookAhead); final int targetYIndex=(int) (target_y/lookAhead); root.setDistanceToOrginal(0.0); root.setDistance(this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex)); root.setTotal_distance((this.getHCost(listXIndex, listYIndex, targetXIndex, targetYIndex))); root.setParent(null); //int color=this.getPixelsOnce(plan, x, y, width, height); agentgui.envModel.p2Dsvg.imageProcessing.StepNode targetNode= this.withoutGrid(id, target_x, target_y, width, height, direction, 10.0f,root , -1,false) ; //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, -1); // //this.originalAStar(id, target_x, target_y, width, height, target_id, direction, lookAhead, root, color) ; //handle_subNodes_brute(id,target_x, target_y, width, height, target_id, direction, lookAhead,root,color); return targetNode; } public void paintWay(String id,StepNode way,double width, double height) { StepNode tmp=way; Document doc=helper.getSVGDoc(); while(tmp!=null) { this.drawLineToSave("l", String.valueOf(tmp.getX()), String.valueOf(width), String.valueOf(tmp.getY()), String.valueOf(height), doc,true,"blue"); tmp=tmp.getParent(); } SVGSafe save=new SVGSafe(); try { int counter=0; File f=new File(id+counter+".svg"); while(f.exists()) { counter++; String name=id+counter; f=new File(name+".svg"); } save.write(id+counter+".svg", doc); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Return the a node with a specific node * @param node The list of nodes * @param nodeName The name which is searched * @return A node with a specific name */ private Node findNode(NodeList node, String nodeName) { Node result; for(int i=0;i<node.getLength();i++) { result=this.findNode(node.item(i),nodeName); if(result!=null) { return result; } } return null; } /** * Finds a specific node and returns the nide * @param node The node which should be searched * @param nodeName The name of the node * @return The node */ private Node findNode(Node node ,String nodeName) { if(node.getParentNode().getLocalName().equals(nodeName)) { return node.getParentNode(); } if(node.getChildNodes().getLength()>0) { return findNode(node.getChildNodes(),nodeName); } else { return null; } } /** * Prints a nodelist * @param node The nodelist which should be printed */ public void print(NodeList node) { for(int i=0;i<node.getLength();i++) { this.print(node.item(i)); } } /** * Print a node and all children of a node * @param node The node which should be printed */ public void print(Node node) { if(node.getChildNodes().getLength()>0) { this.print(node.getChildNodes()); } } /** * Create a new node * * @param nodename Name of Node which should be created * @param x Value of the x position * @param y Value of the y position * @param transform The value of the transformation attribute * @param width Value of width Attribute * @param height Value of height Attribue * @param id The id which should be set * @param doc The svn Document * @return an element whith the set attributes */ public Element createNewElement(String nodename,float x,float y, String transform, float width, float height, String id, Document doc) { Element e = doc.createElement(nodename); e.setAttribute("x", String.valueOf(x)); e.setAttribute("y", String.valueOf(y)); e.setAttribute("transform", transform); e.setAttribute("width", String.valueOf(width)); e.setAttribute("style", "fill:gray;stroke:none"); //System.out.println("Heigth:"+String.valueOf(height)); e.setAttribute("height", String.valueOf(height)); e.setAttribute("id", nodename); return e; } /** * Collision detection * @param world The image of the world * @param startx Starting search point * @param starty Starting search point * @param width width of the agent * @param height height of the agent * @param lookAhead How many pixel should be looked ahead * @param direction Which direction should be looked? * @param color Which color should be checked * @return true or false depending on the collision * @throws Exception */ public boolean tranformAndCheckImage(BufferedImage world, float startx, float starty, float width, float height,float lookAhead ,int direction, int color) throws Exception { int yExit= 0; int xExit=0; switch(direction) { case ImageHelper.DIRECTION_FORWARD: if(starty+lookAhead+height>helper.getEnvironment().getRootPlayground().getSize().getHeight() ||startx+width>helper.getEnvironment().getRootPlayground().getSize().getWidth()) { return false; } else { yExit=(int) Math.floor( starty+lookAhead+height); starty=starty+lookAhead; xExit=(int) Math.floor(startx+width); } break; case ImageHelper.DIRECTION_BACKWARD: if(starty-lookAhead<0) { return false; } yExit=(int) Math.floor( starty-lookAhead+height); starty=starty-lookAhead; xExit=(int) Math.floor(startx+width); break; case ImageHelper.DIRECTION_LEFT: if(startx-lookAhead<0) { return false; } xExit= (int) Math.floor(startx-lookAhead+width); startx=startx-lookAhead; yExit= (int) Math.floor(starty+height); break; case ImageHelper.DIRECTION_RIGHT: if(startx+lookAhead+width>helper.getEnvironment().getRootPlayground().getSize().getWidth()) { return false; } xExit=(int) Math.floor(startx+lookAhead+width); startx=startx+lookAhead; yExit=(int) Math.floor(starty+height); break; case ImageHelper.DIRECTION_UP_LEFT: if(startx-lookAhead<0||starty-lookAhead-height<0) { return false; } xExit= (int) Math.floor(startx+width-lookAhead); startx=startx-lookAhead; yExit=(int) Math.floor(starty-lookAhead+height); starty=(int) Math.floor(starty-lookAhead); break; case ImageHelper.DIRECTION_UP_RIGHT: if(startx+lookAhead+width>=helper.getEnvironment().getRootPlayground().getSize().getWidth()||starty-lookAhead-height<0) { return false; } xExit=(int) Math.floor(startx+width+lookAhead); startx=(int) Math.floor(startx+lookAhead); yExit=(int) Math.floor(starty-lookAhead+height); starty=(int) Math.floor(starty-lookAhead); break; case ImageHelper.DIRECTION_DOWN_LEFT: if(starty+lookAhead+height>=helper.getEnvironment().getRootPlayground().getSize().getHeight()||startx-lookAhead<0) { return false; } xExit=(int) Math.floor(startx-lookAhead+width); startx=(int) Math.floor(startx-lookAhead); yExit=(int) Math.floor(starty+height+lookAhead); starty= (int) Math.floor(starty+lookAhead); break; case ImageHelper.DIRECTION_DOWN_RIGHT: if(startx+lookAhead+height>helper.getEnvironment().getRootPlayground().getSize().getWidth()||starty+lookAhead+height>helper.getEnvironment().getRootPlayground().getSize().getHeight()) { return false; } xExit= (int) Math.floor(startx+lookAhead+width)-1; startx= (int) Math.floor(startx+lookAhead); yExit= (int) Math.floor(starty+lookAhead+height)-1; starty= (int) Math.floor(starty+lookAhead); break; } for(int y=(int) Math.floor(starty);y<=yExit;y++) { for(int x=(int)Math.floor(startx);x<=xExit;x++) { try { if(world.getRGB(x, y)==color) { return false; } } catch(Exception e) { //e.printStackTrace(); // System.out.println("Direction:"+direction); // System.out.println("StartX:"+startx); // System.out.println("XExit:"+xExit); // System.out.println("YExit:"+yExit); // System.out.println("X:"+x +"," + y +" "); } } } return true; } /** * It can draw the actual position of an agent. Can be used for checking all the places which are available for the agent * @param id The Id attribut * @param x X Pos * @param y Y Pos * @param width Width of the agent * @param height Height of the agent * @param direction Direction * @param lookAhead How Many pixel ahead * @param target_id targetID * @return Creates a list with all elements which are being checked. * @throws Exception */ public ArrayList<Element> draw_way(String id,float x,float y,float width,float height ,int direction,float lookAhead,String target_id) throws Exception { ArrayList<Element> elements=new ArrayList<Element>(); Document doc=helper.getSVGDoc(); NodeList list=doc.getElementsByTagName("g"); list=list.item(0).getChildNodes(); Element newElement=null; Node node=this.findNode(doc.getElementsByTagName("g"),"g"); if(node!=null) { this.deleteNodes(doc, node); } switch(direction) { case ImageHelper.DIRECTION_FORWARD: if(y+lookAhead+height>helper.getEnvironment().getRootPlayground().getSize().getHeight()) { newElement=this.createNewElement("rect", x, -1.0f, null, width, height, id, doc); } else { newElement=this.createNewElement("rect", x, y+lookAhead, null, width, height, id, doc); } node.appendChild(newElement); elements.add(newElement); break; case ImageHelper.DIRECTION_BACKWARD: newElement=this.createNewElement("rect", x, y-lookAhead, null, width, height, id, doc); if(y-lookAhead<0) { newElement=this.createNewElement("rect", x, -1.0f, null, width, height, id, doc); } node.appendChild(newElement); elements.add(newElement); break; case ImageHelper.DIRECTION_LEFT: newElement=this.createNewElement("rect", x-lookAhead, y, null, width, height, id, doc); if(x-lookAhead<0) { newElement=this.createNewElement("rect", -1.0f, y, null, width, height, id, doc); } node.appendChild(newElement); elements.add(newElement); break; case ImageHelper.DIRECTION_RIGHT: newElement=this.createNewElement("rect", x+lookAhead, y, null, width, height, id, doc); if(x+lookAhead+width>helper.getEnvironment().getRootPlayground().getSize().getWidth()) { newElement=this.createNewElement("rect", -1.0f, y, null, width, height, id, doc); } node.appendChild(newElement); elements.add(newElement); break; } for(int i=0;i<list.getLength();i++) { Node svgNode=list.item(i); if(svgNode.getParentNode().getNodeName().equals("svg")) { Node parent=svgNode.getParentNode(); parent.removeChild(svgNode); break; } } ImageIO.read(new File("plan.jpg")); this.endung++; return elements; } /** * Paints an area. Can be used for a graphical representation of the search * @param id ID * @param x1 X Pos * @param width Width * @param y1 Y Pos * @param height Height * @param doc SVNDocument * @param colored Should be colored? * @param color The color */ public void drawLineToSave(String id,String x1,String width, String y1,String height,Document doc,boolean colored,String color) { Element e = doc.createElement("rect"); e.setAttribute("x", x1); e.setAttribute("y", y1); e.setAttribute("transform", ""); e.setAttribute("width", String.valueOf(width)); if(colored) { e.setAttribute("style", "fill:"+color+";stroke:none"); } else { e.setAttribute("fill","none"); e.setAttribute("stroke", color); } e.setAttribute("id", "rect"); e.setAttribute("height", height); Node node=doc.getElementsByTagName("rect").item(0).getParentNode(); node.appendChild(e); } /** * Deletes every object of the SVG except the agent * @return The manipuated world saved in a BufferedImage */ public synchronized BufferedImage createManipulatedWorld() { try { if(!READ_WORLD&&!IS_IN_METHOD) { IS_IN_METHOD=true; Document doc=helper.getSVGDoc(); EnvironmentWrapper envWrap = new EnvironmentWrapper(helper.getEnvironment()); Vector<StaticObject> obstacles=envWrap.getObstacles(); Vector<ActiveObject> agents=envWrap.getAgents(); for(ActiveObject obj: agents) { Element element=doc.getElementById(obj.getId()); Node tmp= element.getParentNode(); tmp.removeChild(element); } NodeList list=doc.getElementsByTagName("rect"); for(int i=0;i<list.getLength();i++) { Node node=list.item(i); if(node.getParentNode().getNodeName().equals("svg")) { Node parent=node.getParentNode(); parent.removeChild(node); break; } } for(StaticObject obj: obstacles) { Element element=doc.getElementById(obj.getId()); String oldVal=element.getAttributeNS(null, "style"); String search="fill:"; int index=oldVal.indexOf(search); int end; if(index!=-1) { end=oldVal.indexOf(";"); if(end==-1) { oldVal="fill:gray"; } else { oldVal=oldVal.replaceFirst(oldVal.substring(index+search.length(),end), "gray"); } Attr style=element.getAttributeNode("style"); style.setValue(oldVal); } } //SVGImage img=new SVGImage( (SVGDocument)doc); //this.evn=(BufferedImage) img.createBufferedImage(); synchronized (this) { if(!READ_WORLD) { SVGSafe save=new SVGSafe(); save.write("myWorld.svg", doc); save.writeJPG("myworld.svg"); } } } this.evn=ImageIO.read(new File("myWorld.jpg")); // System.out.println("Setze Real_WORLD auf true!"); READ_WORLD=true; return evn; } catch(Exception e) { e.printStackTrace(); return null; } } public synchronized BufferedImage createManipulatedWorldPerAgent() { try { Document doc=helper.getSVGDoc(); EnvironmentWrapper envWrap = new EnvironmentWrapper(helper.getEnvironment()); Vector<StaticObject> obstacles=envWrap.getObstacles(); Vector<ActiveObject> agents=envWrap.getAgents(); Vector<PassiveObject> passiveObjects=envWrap.getPayloads(); for(PassiveObject passiveObject: passiveObjects) { Element element=doc.getElementById(passiveObject.getId()); Node tmp= element.getParentNode(); tmp.removeChild(element); } for(ActiveObject obj: agents) { Element element=doc.getElementById(obj.getId()); Node tmp= element.getParentNode(); tmp.removeChild(element); } NodeList list=doc.getElementsByTagName("rect"); for(int i=0;i<list.getLength();i++) { Node node=list.item(i); if(node.getParentNode().getNodeName().equals("svg")) { Node parent=node.getParentNode(); parent.removeChild(node); break; } } for(StaticObject obj: obstacles) { Element element=doc.getElementById(obj.getId()); String oldVal=element.getAttributeNS(null, "style"); String search="fill:"; int index=oldVal.indexOf(search); int end; if(index!=-1) { end=oldVal.indexOf(";"); if(end==-1) { oldVal="fill:gray"; } else { oldVal=oldVal.replaceFirst(oldVal.substring(index+search.length(),end), "gray"); } Attr style=element.getAttributeNode("style"); style.setValue(oldVal); } } //SVGImage img=new SVGImage( (SVGDocument)doc); //this.evn=(BufferedImage) img.createBufferedImage(); SVGSafe save=new SVGSafe(); int i=0; String name="myWorldAgent"+i; File f=new File(name+".svg"); while(f.exists()) { i++; name="myWorldAgent"+i; f=new File(name+".svg"); } save.write(name+".svg", doc); save.writeJPG(name+".svg"); System.out.println("Image geschrieben"); this.evn=ImageIO.read(new File(name+".jpg")); return evn; } catch(Exception e) { e.printStackTrace(); System.out.println("Return null!"); return null; } } public void setupEnviroment(String ownID,ArrayList<CombinedNameAndPos> otherAgent) { this.evn=this.createManipulatedWorldWithAgents(otherAgent, ownID, 0.0); this.is_setup=true; } public Position sidestepLeft(String ownID,ArrayList<CombinedNameAndPos> otherAgent) { if(!this.is_setup) { this.setupEnviroment(ownID, otherAgent); } Document doc=helper.getSVGDoc(); Element self=doc.getElementById(ownID); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=0.0f; float y=0.0f; for(int i=0;i<otherAgent.size();i++) { if(otherAgent.get(i).name.equals(ownID)) { x=otherAgent.get(i).getPos().getXPos(); y=otherAgent.get(i).getPos().getYPos(); } } //Float.parseFloat(self.getAttribute("x")); //Float.parseFloat(self.getAttribute("y")); System.out.println("Own ID:"+ownID); System.out.println("X:"+x); System.out.println("Y:"+y); //System.out.println("Vergleich:"+otherAgent.get(0).getPos().getXPos()+","+otherAgent.get(0).getPos().getYPos()+","+otherAgent.get(0).getName()); int lookAhead=10; boolean found=false; float currentXpos=x; float currentYPos=y; Position result = new Position(); // Left while(!found&&lookAhead>0) { try { found=this.tranformAndCheckImage(this.evn, currentXpos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_LEFT, Color.gray.getRGB()); if(found) { result.setXPos(currentXpos-lookAhead); result.setYPos(currentYPos); return result; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } lookAhead } return null; } public Position sidestepRight(String ownID,ArrayList<CombinedNameAndPos> otherAgent) { if(!this.is_setup) { this.setupEnviroment(ownID, otherAgent); } Document doc=helper.getSVGDoc(); Element self=doc.getElementById(ownID); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=Float.parseFloat(self.getAttribute("x")); float y=Float.parseFloat(self.getAttribute("y")); for(int i=0;i<otherAgent.size();i++) { if(otherAgent.get(i).name.equals(ownID)) { x=otherAgent.get(i).getPos().getXPos(); y=otherAgent.get(i).getPos().getYPos(); } } int lookAhead=10; boolean found=false; float currentXpos=x; float currentYPos=y; Position result = new Position(); // Left while(!found&&lookAhead>0) { try { found=this.tranformAndCheckImage(this.evn, currentXpos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_RIGHT, Color.gray.getRGB()); if(found) { result.setXPos(currentXpos+lookAhead); result.setYPos(currentYPos); return result; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } lookAhead } return null; } public Position sidesteppBackwards(String ownID,ArrayList<CombinedNameAndPos> otherAgent) { if(!this.is_setup) { this.setupEnviroment(ownID, otherAgent); } Document doc=helper.getSVGDoc(); Element self=doc.getElementById(ownID); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=Float.parseFloat(self.getAttribute("x")); float y=Float.parseFloat(self.getAttribute("y")); for(int i=0;i<otherAgent.size();i++) { if(otherAgent.get(i).name.equals(ownID)) { x=otherAgent.get(i).getPos().getXPos(); y=otherAgent.get(i).getPos().getYPos(); } } int lookAhead=10; boolean found=false; float currentXpos=x; float currentYPos=y; Position result = new Position(); // Left while(!found&&lookAhead>0) { try { found=this.tranformAndCheckImage(this.evn, currentXpos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_BACKWARD, Color.gray.getRGB()); if(found) { result.setXPos(currentXpos); result.setYPos(currentYPos-lookAhead); return result; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } lookAhead } return null; } public Position sidesteppForward(String ownID,ArrayList<CombinedNameAndPos> otherAgent) { if(!this.is_setup) { this.setupEnviroment(ownID, otherAgent); } Document doc=helper.getSVGDoc(); Element self=doc.getElementById(ownID); final float width=Float.parseFloat(self.getAttribute("width")); final float height=Float.parseFloat(self.getAttribute("height")); float x=Float.parseFloat(self.getAttribute("x")); float y=Float.parseFloat(self.getAttribute("y")); for(int i=0;i<otherAgent.size();i++) { if(otherAgent.get(i).name.equals(ownID)) { x=otherAgent.get(i).getPos().getXPos(); y=otherAgent.get(i).getPos().getYPos(); } } int lookAhead=10; boolean found=false; float currentXpos=x; float currentYPos=y; Position result = new Position(); // Left while(!found&&lookAhead>0) { try { found=this.tranformAndCheckImage(this.evn, currentXpos, currentYPos, width, height, lookAhead, ImageHelper.DIRECTION_FORWARD, Color.gray.getRGB()); if(found) { result.setXPos(currentXpos); result.setYPos(currentYPos+lookAhead); return result; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } lookAhead } return null; } public synchronized BufferedImage createManipulatedWorldWithAgents(ArrayList<CombinedNameAndPos> otherAgent , String id,double discreteTime) { try { IS_IN_METHOD=true; Document doc=helper.getSVGDoc(); EnvironmentWrapper envWrap = new EnvironmentWrapper(helper.getEnvironment()); Vector<StaticObject> obstacles=envWrap.getObstacles(); Vector<PassiveObject> passiveObjects=envWrap.getPayloads(); for(PassiveObject passiveObject: passiveObjects) { Element element=doc.getElementById(passiveObject.getId()); Node tmp= element.getParentNode(); tmp.removeChild(element); } for(int i=0;i<otherAgent.size();i++) { Element element=doc.getElementById(otherAgent.get(i).name); element.removeAttribute("x"); element.setAttribute("x", String.valueOf(otherAgent.get(i).getPos().getXPos())); element.removeAttribute("y"); element.setAttribute("y", String.valueOf(otherAgent.get(i).getPos().getYPos())); //System.out.println("Untersuche:"+ obj.getId()); if((otherAgent.get(i).getName().equals(id))) { //ode tmp= element.getParentNode(); //tmp.removeChild(element); } else /** if(seconds>discreteTime) { //System.out.println("Abstand zu weit weswegen der andere gelscht werden kann!"); //element.getParentNode().removeChild(element); } */ //else String oldVal=element.getAttributeNS(null, "style"); String search="fill:"; int index=oldVal.indexOf(search); int end; if(index!=-1) { end=oldVal.indexOf(";"); if(end==-1) { oldVal="fill:gray"; } else { oldVal=oldVal.replaceFirst(oldVal.substring(index+search.length(),end), "gray"); } Attr style=element.getAttributeNode("style"); style.setValue(oldVal); } } } NodeList list=doc.getElementsByTagName("rect"); if(list!=null) { for(int i=0;i<list.getLength();i++) { Node node=list.item(i); if(node.getParentNode().getNodeName().equals("svg")) { Node parent=node.getParentNode(); parent.removeChild(node); break; } } } for(StaticObject obj: obstacles) { Element element=doc.getElementById(obj.getId()); String oldVal=element.getAttributeNS(null, "style"); String search="fill:"; int index=oldVal.indexOf(search); int end; if(index!=-1) { end=oldVal.indexOf(";"); if(end==-1) { oldVal="fill:gray"; } else { oldVal=oldVal.replaceFirst(oldVal.substring(index+search.length(),end), "gray"); } Attr style=element.getAttributeNode("style"); style.setValue(oldVal); } } //SVGImage img=new SVGImage( (SVGDocument)doc); //this.evn=(BufferedImage) img.createBufferedImage(); int i=0; String name=id+"myWorldAgentWithOther"+i; synchronized (this) { SVGSafe save=new SVGSafe(); File f=new File(name+".svg"); while(f.exists()) { i++; name=id + "myWorldAgentWithOther"+i; f=new File(name+".svg"); } save.write(name+".svg", doc); save.writeJPG(name+".svg"); this.evn=ImageIO.read(new File(name+".jpg")); /** for(int counter=0;i<otherAgent.size();counter++) { // System.out.println("Other:"+otherAgent.get(counter)); Element element=doc.getElementById(otherAgent.get(counter)); element.setAttribute("x", oldX[counter]); element.setAttribute("y", oldY[counter]); } */ } manipulated=doc; return evn; } catch(Exception e) { e.printStackTrace(); return null; } } public PositionUpdate calculateNextCoord(int lastIndex,Position selfPos, Position destPos, final double msInSeconds,float speed, Stack<Position> position) { Position newPos=new Position(); // Save the Position which is passed to the simulation Agent here Position lastPosition=null; Answer answer=new Answer(); boolean reached=false; ArrayList<Position> partSolution=new ArrayList<Position>(); float xPosDiff=0.0f; // Difference float yPosDiff=0.0f; // Difference double total_seconds=0.0d; boolean multiStep=false; // Needed for calculation while(total_seconds<=msInSeconds) { xPosDiff = destPos.getXPos() - selfPos.getXPos(); yPosDiff = destPos.getYPos() - selfPos.getYPos(); double dist = (Math.sqrt(xPosDiff*xPosDiff + yPosDiff*yPosDiff)/10.0d); double seconds = dist / speed; // seconds to get to the point. Important to calculate dist in meter because speed is also in meter! total_seconds=total_seconds+seconds; //System.out.println("Total Seconds:"+total_seconds); //System.out.println("Seconds:"+seconds); // It's possible to do more than one moment at one time so we add the seconds if(total_seconds<=msInSeconds) // it's smaller so we can contioue walking { reached=true; multiStep=true; lastIndex++; // Increase the Index if(lastIndex<position.size()) // Are we add the end? { // We're not and adjust the positions selfPos.setXPos(destPos.getXPos()); selfPos.setYPos(destPos.getYPos()); destPos=position.get(lastIndex); newPos.setXPos(selfPos.getXPos()); newPos.setYPos(selfPos.getYPos()); Position add=new Position(); add.setXPos(newPos.getXPos()); add.setYPos(newPos.getYPos()); partSolution.add(add); } else { // we at the end selfPos=position.get(position.size()-1); newPos.setXPos(selfPos.getXPos()); newPos.setYPos(selfPos.getYPos()); partSolution.add(newPos); total_seconds=msInSeconds; lastIndex++; Position add=new Position(); add.setXPos(newPos.getXPos()); add.setYPos(newPos.getYPos()); partSolution.add(add); PositionUpdate posUpdate=new PositionUpdate(); posUpdate.setNewPosition(newPos); answer.setSpeed(new Long((long)speed)); answer.setWayToDestination(partSolution); posUpdate.setCustomizedParameter(answer); //System.out.println("Ende!!"); return posUpdate; } } else // The distance is too huge to do in one step { boolean flag=false; reached=false; // We haven't reached the full distance double max=((speed)*(msInSeconds)); // Calculate the maximum distance we can walk. Result is in meter and seconds if(multiStep) // We need to take the difference { //System.out.println("Multi Step"); double dif=Math.abs(msInSeconds-total_seconds+seconds); if(msInSeconds-total_seconds+seconds<0) { flag=true; } max=((speed)*(dif)); // Calculate the maximum distance we can walk is also in seconds } else { total_seconds=msInSeconds+1; } if(!flag) { max*=10; // calculate into pixel multiStep=false; double correctXDif=0.0d; double correctYDif=0.0d; if(xPosDiff>0) // We move to the right { correctXDif=max; } if(xPosDiff<0) // We move the left { correctXDif=max*-1; } if(yPosDiff>0) // We move forward { correctYDif=max; } if(yPosDiff<0) // We move backs { correctYDif=max*-1; } double newXValue=selfPos.getXPos()+correctXDif; double newYValue=selfPos.getYPos()+correctYDif; newPos.setXPos( (float) newXValue); newPos.setYPos( (float) newYValue); lastPosition=new Position(); lastPosition.setXPos(destPos.getXPos()); lastPosition.setYPos(destPos.getYPos()); selfPos.setXPos(newPos.getXPos()); selfPos.setYPos(newPos.getYPos()); } else { lastPosition=new Position(); lastPosition.setXPos(destPos.getXPos()); lastPosition.setYPos(destPos.getYPos()); reached=false; } } } PositionUpdate posUpdate=new PositionUpdate(); posUpdate.setNewPosition(newPos); Position add=new Position(); add.setXPos(newPos.getXPos()); add.setYPos(newPos.getYPos()); partSolution.add(add); answer.setWayToDestination(partSolution); if(reached) { lastIndex++; destPos=position.get(lastIndex); } else { destPos=lastPosition; } answer.setIndex(lastIndex); answer.setNextPosition(destPos); posUpdate.setCustomizedParameter(answer); posUpdate.setNewPosition(selfPos); return posUpdate; } public Stack<Position> orderAndMiddleCoordinates(StepNode way,float agentWidth,float agentHeight,float factor) { Stack<Position> pos=new Stack<Position>(); if(way.getParent()==null) { Position p=new Position(); float x=(way.getX()+agentWidth/2); // middle it float y=(way.getY()+agentHeight/2); // middle it p.setXPos(x/factor); p.setYPos(y/factor); pos.add(0,p); } while(way.getParent()!=null) { Position p=new Position(); float x=(way.getX()+agentWidth/2); // middle it float y=(way.getY()+agentHeight/2); // middle it p.setXPos(x/factor); p.setYPos(y/factor); pos.add(0,p); way=way.getParent(); } return pos; } public HashMap<String, ArrayList<CombinedNameAndPos>> getDynamicCollision(HashMap<String,PositionUpdate> update) { try { HashMap<String, ArrayList<CombinedNameAndPos>> nameList = new HashMap<String, ArrayList<CombinedNameAndPos>>(); // Let's find the name of the moving agents EnvironmentWrapper envWrapper=new EnvironmentWrapper(this.helper.getEnvironment()); Vector<ActiveObject> agents=envWrapper.getAgents(); for(int i=0;i<agents.size();i++) { ArrayList<CombinedNameAndPos> otherAgents=new ArrayList<CombinedNameAndPos>(); Physical2DObject agent=agents.get(i); PositionUpdate ownAgentPosition= update.get(agent.getId()); if(ownAgentPosition != null) // Consider that agents have already reached their target therefore don't send any answer { ArrayList<Position> ownAgentPositions=((Answer) ownAgentPosition.getCustomizedParameter()).getWayToDestination(); for(int counter=0;counter<agents.size();counter++) { if(i!=counter) { //System.out.println("Try to compare with:"+ agents.get(counter).getId()); PositionUpdate otherAgentPosition= update.get(agents.get(counter).getId()); if(otherAgentPosition != null) { ArrayList<Position> otherPositions=((Answer) otherAgentPosition.getCustomizedParameter()).getWayToDestination(); int max=Math.max(ownAgentPositions.size(), otherPositions.size()); int min=Math.min(ownAgentPositions.size(), otherPositions.size()); for(int iter=0;iter<max;iter++) { if(min!=0) { Physical2DObject obj=new Physical2DObject(); if(iter<ownAgentPositions.size()) { obj.setPosition(ownAgentPositions.get(iter)); } else { obj.setPosition(ownAgentPositions.get(min-1)); } obj.setSize(agent.getSize()); Physical2DObject other=agents.get(counter); if(iter < otherPositions.size()) { other.setPosition(otherPositions.get(iter)); } else { other.setPosition(otherPositions.get(min-1)); } // System.out.println(obj.getId() +" in Detection "+ obj.getPosition().getXPos()+","+obj.getPosition().getYPos()); // System.out.println(other.getId() +" in Detection "+ other.getPosition().getXPos()+","+other.getPosition().getYPos()); boolean result=this.checkTimeBetween(obj, other); //System.out.println("Result von berprfung:"+result +" Iter:"+iter); if(result) { CombinedNameAndPos combined=new CombinedNameAndPos(); combined.setName(agents.get(counter).getId()); combined.setPos(obj.getPosition()); otherAgents.add(combined); break; } } else { break; } } } } } } nameList.put(agent.getId(), otherAgents); } return nameList; } catch(Exception e) { e.printStackTrace(); return null; } } private boolean checkTimeBetween(Physical2DObject agent,Physical2DObject cmpr) { return agent.objectIntersects(cmpr)|| cmpr.objectIntersects(agent) || agent.objectContains(cmpr) || cmpr.objectContains(agent); } }
package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.maps.BestLocationListener; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.VenueView; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.app.AlertDialog.Builder; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.location.Location; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.CompoundButton.OnCheckedChangeListener; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class ShoutActivity extends Activity { public static final String TAG = "ShoutActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_VENUE_NAME = "com.joelapenna.foursquared.ShoutActivity.VENUE_NAME"; public static final String EXTRA_VENUE_ADDRESS = "com.joelapenna.foursquared.ShoutActivity.VENUE_ADDRESS"; public static final String EXTRA_VENUE_CROSSSTREET = "com.joelapenna.foursquared.ShoutActivity.VENUE_CROSSSTREET"; public static final String EXTRA_VENUE_CITY = "com.joelapenna.foursquared.ShoutActivity.VENUE_CITY"; public static final String EXTRA_VENUE_ZIP = "com.joelapenna.foursquared.ShoutActivity.VENUE_ZIP"; public static final String EXTRA_VENUE_STATE = "com.joelapenna.foursquared.ShoutActivity.VENUE_STATE"; public static final String EXTRA_IMMEDIATE_CHECKIN = "com.joelapenna.foursquared.ShoutActivity.IMMEDIATE_CHECKIN"; public static final String EXTRA_SHOUT = "com.joelapenna.foursquared.ShoutActivity.SHOUT"; public static final String STATE_DIALOG_STATE = "com.joelapenna.foursquared.ShoutActivity.DIALOG_STATE"; private static final int DIALOG_CHECKIN_PROGRESS = 1; private static final int DIALOG_CHECKIN_RESULT = 2; private StateHolder mStateHolder = new StateHolder(); private DialogStateHolder mDialogStateHolder = null; private boolean mIsShouting = true; private boolean mImmediateCheckin = true; private boolean mTellFriends = true; private boolean mTellTwitter = false; private String mShout = null; private Button mCheckinButton; private CheckBox mTwitterCheckBox; private CheckBox mFriendsCheckBox; private EditText mShoutEditText; private VenueView mVenueView; private BestLocationListener mLocationListener; private LocationManager mLocationManager; private BroadcastReceiver mLoggedInReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate"); registerReceiver(mLoggedInReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mLocationListener = ((Foursquared)getApplication()).getLocationListener(); mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(ShoutActivity.this); mTellFriends = settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, mTellFriends); mTellTwitter = settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, mTellTwitter); // Implies there is no UI. if (getIntent().hasExtra(EXTRA_IMMEDIATE_CHECKIN)) { mImmediateCheckin = getIntent().getBooleanExtra(EXTRA_IMMEDIATE_CHECKIN, true); if (DEBUG) Log.d(TAG, "Immediate Checkin (from extra): " + mImmediateCheckin); } else { mImmediateCheckin = PreferenceManager.getDefaultSharedPreferences(ShoutActivity.this) .getBoolean(Preferences.PREFERENCE_IMMEDIATE_CHECKIN, true); if (DEBUG) Log.d(TAG, "Immediate Checkin (from preference): " + mImmediateCheckin); } mIsShouting = getIntent().getBooleanExtra(ShoutActivity.EXTRA_SHOUT, false); if (mIsShouting) { if (DEBUG) Log.d(TAG, "Immediate checkin disabled, this is a shout."); mImmediateCheckin = false; } if (DEBUG) Log.d(TAG, "Is Shouting: " + mIsShouting); if (DEBUG) Log.d(TAG, "Immediate Checkin: " + mImmediateCheckin); // Try to restore the general state holder, from a configuration change. if (getLastNonConfigurationInstance() != null) { if (DEBUG) Log.d(TAG, "Using last non configuration instance"); mStateHolder = (StateHolder)getLastNonConfigurationInstance(); } else if (!mIsShouting) { // Translate the extras received in this intent into a venue, then attach it to the // venue view. mStateHolder.venue = new Venue(); intentExtrasIntoVenue(getIntent(), mStateHolder.venue); } // Try to restore the dialog state holder if (savedInstanceState != null) { mDialogStateHolder = savedInstanceState.getParcelable(STATE_DIALOG_STATE); } // If we can restore dialog state, we've already checked in. boolean checkinCompleted = (mDialogStateHolder != null); if (mImmediateCheckin) { setVisible(false); if (!checkinCompleted) { if (DEBUG) Log.d(TAG, "Immediate checkin is set."); mStateHolder.checkinTask = new CheckinTask().execute(); } else { if (DEBUG) Log.d(TAG, "We have an existing checkin, not launching checkin task."); } } else { initializeUi(); } } @Override public void onResume() { super.onResume(); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, BestLocationListener.LOCATION_UPDATE_MIN_TIME, BestLocationListener.LOCATION_UPDATE_MIN_DISTANCE, mLocationListener); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, BestLocationListener.LOCATION_UPDATE_MIN_TIME, BestLocationListener.LOCATION_UPDATE_MIN_DISTANCE, mLocationListener); } @Override public void onPause() { super.onPause(); mLocationManager.removeUpdates(mLocationListener); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedInReceiver); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(STATE_DIALOG_STATE, mDialogStateHolder); } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CHECKIN_PROGRESS: String title = (mIsShouting) ? "Shouting!" : "Checking in!"; String messageAction = (mIsShouting) ? "shout!" : "check-in!"; ProgressDialog dialog = new ProgressDialog(this); dialog.setCancelable(true); dialog.setIndeterminate(true); dialog.setTitle(title); dialog.setIcon(android.R.drawable.ic_dialog_info); dialog.setMessage("Please wait while we " + messageAction); dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mStateHolder.checkinTask.cancel(true); } }); return dialog; case DIALOG_CHECKIN_RESULT: Builder dialogBuilder = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) // icon .setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); // Set up the custom view for it. LayoutInflater inflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.checkin_result_dialog, (ViewGroup)findViewById(R.id.layout_root)); dialogBuilder.setView(layout); // Set the text message of the result. TextView messageView = (TextView)layout.findViewById(R.id.messageTextView); messageView.setText(mDialogStateHolder.message); // Set the title and web view which vary based on if the user is shouting. if (mDialogStateHolder.shouting) { dialogBuilder.setTitle("Shouted!"); } else { if (mDialogStateHolder.venueName != null) { dialogBuilder.setTitle("Checked in @ " + mDialogStateHolder.venueName); } else { dialogBuilder.setTitle("Checked in!"); } WebView webView = (WebView)layout.findViewById(R.id.webView); String userId = PreferenceManager.getDefaultSharedPreferences(this).getString( Preferences.PREFERENCE_ID, ""); webView.loadUrl(((Foursquared)getApplication()).getFoursquare() .checkinResultUrl(userId, mDialogStateHolder.checkinId)); } return dialogBuilder.create(); } return null; } /** * Because we cannot parcel venues properly yet (issue #5) we have to mutate a series of intent * extras into a venue so that we can code to this future possibility. */ public static final void intentExtrasIntoVenue(Intent intent, Venue venue) { Bundle extras = intent.getExtras(); venue.setId(extras.getString(Foursquared.EXTRA_VENUE_ID)); venue.setName(extras.getString(EXTRA_VENUE_NAME)); venue.setAddress(extras.getString(EXTRA_VENUE_ADDRESS)); venue.setCrossstreet(extras.getString(EXTRA_VENUE_CROSSSTREET)); venue.setCity(extras.getString(EXTRA_VENUE_CITY)); venue.setZip(extras.getString(EXTRA_VENUE_ZIP)); venue.setState(extras.getString(EXTRA_VENUE_STATE)); } public static final void venueIntoIntentExtras(Venue venue, Intent intent) { intent.putExtra(Foursquared.EXTRA_VENUE_ID, venue.getId()); intent.putExtra(ShoutActivity.EXTRA_VENUE_NAME, venue.getName()); intent.putExtra(ShoutActivity.EXTRA_VENUE_ADDRESS, venue.getAddress()); intent.putExtra(ShoutActivity.EXTRA_VENUE_CITY, venue.getCity()); intent.putExtra(ShoutActivity.EXTRA_VENUE_CROSSSTREET, venue.getCrossstreet()); intent.putExtra(ShoutActivity.EXTRA_VENUE_STATE, venue.getState()); intent.putExtra(ShoutActivity.EXTRA_VENUE_ZIP, venue.getZip()); } private void initializeUi() { setTheme(android.R.style.Theme_Dialog); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.shout_activity); mCheckinButton = (Button)findViewById(R.id.checkinButton); mFriendsCheckBox = (CheckBox)findViewById(R.id.tellFriendsCheckBox); mTwitterCheckBox = (CheckBox)findViewById(R.id.tellTwitterCheckBox); mShoutEditText = (EditText)findViewById(R.id.shoutEditText); mVenueView = (VenueView)findViewById(R.id.venue); mCheckinButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mCheckinButton.setEnabled(false); String shout = mShoutEditText.getText().toString(); if (!TextUtils.isEmpty(shout)) { mShout = shout; } mStateHolder.checkinTask = new CheckinTask().execute(); } }); mTwitterCheckBox.setChecked(mTellTwitter); mTwitterCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mTellTwitter = isChecked; mTwitterCheckBox.setEnabled(isChecked); } }); mFriendsCheckBox.setChecked(mTellFriends); mFriendsCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mTellFriends = isChecked; mTwitterCheckBox.setEnabled(isChecked); if (!isChecked) { mTellTwitter = false; mTwitterCheckBox.setChecked(false); } } }); if (mIsShouting) { mVenueView.setVisibility(ViewGroup.GONE); mFriendsCheckBox.setChecked(true); mFriendsCheckBox.setEnabled(false); mCheckinButton.setText("Shout!"); } else { mVenueView.setVenue(mStateHolder.venue); } } class CheckinTask extends AsyncTask<Void, Void, CheckinResult> { private Exception mReason; @Override public void onPreExecute() { showDialog(DIALOG_CHECKIN_PROGRESS); } @Override public CheckinResult doInBackground(Void... params) { String venueId; if (mStateHolder.venue == null) { venueId = null; } else { venueId = mStateHolder.venue.getId(); } boolean isPrivate = !mTellFriends; try { String geolat = null; String geolong = null; Location location = ((Foursquared)getApplication()).getLastKnownLocation(); if (location != null) { geolat = String.valueOf(location.getLatitude()); geolong = String.valueOf(location.getLongitude()); } return ((Foursquared)getApplication()).getFoursquare().checkin(venueId, null, geolat, geolong, mShout, isPrivate, mTellTwitter); } catch (Exception e) { Log.d(TAG, "Storing reason: ", e); mReason = e; } return null; } @Override public void onPostExecute(CheckinResult checkinResult) { if (DEBUG) Log.d(TAG, "CheckinTask: onPostExecute()"); dismissDialog(DIALOG_CHECKIN_PROGRESS); if (checkinResult == null) { NotificationsUtil.ToastReasonForFailure(ShoutActivity.this, mReason); if (mImmediateCheckin) { finish(); } else { mCheckinButton.setEnabled(true); } return; } else { // Store that we completed this action. mStateHolder.checkinResult = checkinResult; // Make sure the caller knows things worked out alright. setResult(Activity.RESULT_OK); // Show the dialog that will dismiss this activity. mDialogStateHolder = new DialogStateHolder(checkinResult, mIsShouting); showDialog(DIALOG_CHECKIN_RESULT); } } @Override public void onCancelled() { dismissDialog(DIALOG_CHECKIN_PROGRESS); if (mImmediateCheckin) { finish(); } else { mCheckinButton.setEnabled(true); } } } private static class StateHolder { // These are all enumerated because we currently cannot handle parceling venues! How sad! Venue venue = null; AsyncTask<Void, Void, CheckinResult> checkinTask = null; CheckinResult checkinResult = null; } private static class DialogStateHolder implements Parcelable { String venueName = null; String message = null; String checkinId = null; boolean shouting; public DialogStateHolder(CheckinResult checkinResult, boolean isShouting) { if (checkinResult == null) { throw new IllegalArgumentException("checkinResult cannot be null"); } if (checkinResult.getVenue() != null) { venueName = checkinResult.getVenue().getName(); } message = checkinResult.getMessage(); checkinId = checkinResult.getId(); shouting = isShouting; } @Override public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeString(message); out.writeString(venueName); out.writeString(checkinId); out.writeInt((shouting) ? 1 : 0); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public DialogStateHolder createFromParcel(Parcel in) { return new DialogStateHolder(in); } public DialogStateHolder[] newArray(int size) { return new DialogStateHolder[size]; } }; private DialogStateHolder(Parcel in) { message = in.readString(); venueName = in.readString(); checkinId = in.readString(); shouting = (in.readInt() == 1) ? true : false; } } }
package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.VenueView; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.CompoundButton.OnCheckedChangeListener; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class ShoutActivity extends Activity { public static final String TAG = "ShoutActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_VENUE_NAME = "com.joelapenna.foursquared.ShoutActivity.VENUE_NAME"; public static final String EXTRA_VENUE_ADDRESS = "com.joelapenna.foursquared.ShoutActivity.VENUE_ADDRESS"; public static final String EXTRA_VENUE_CROSSSTREET = "com.joelapenna.foursquared.ShoutActivity.VENUE_CROSSSTREET"; public static final String EXTRA_VENUE_CITY = "com.joelapenna.foursquared.ShoutActivity.VENUE_CITY"; public static final String EXTRA_VENUE_ZIP = "com.joelapenna.foursquared.ShoutActivity.VENUE_ZIP"; public static final String EXTRA_VENUE_STATE = "com.joelapenna.foursquared.ShoutActivity.VENUE_STATE"; public static final String EXTRA_IMMEDIATE_CHECKIN = "com.joelapenna.foursquared.ShoutActivity.IMMEDIATE_CHECKIN"; private static final int DIALOG_CHECKIN_PROGRESS = 1; private StateHolder mStateHolder = new StateHolder(); private boolean mIsShouting = true; private boolean mImmediateCheckin = false; private boolean mTellFriends = false; private boolean mTellTwitter = false; private String mShout = null; private Button mCheckinButton; private CheckBox mTwitterCheckBox; private CheckBox mFriendsCheckBox; private EditText mShoutEditText; private VenueView mVenueView; private BroadcastReceiver mLoggedInReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate"); registerReceiver(mLoggedInReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); // Implies there is no associated venue. mIsShouting = !getIntent().hasExtra(Foursquared.EXTRA_VENUE_ID); // Implies there is no UI. mImmediateCheckin = getIntent().getBooleanExtra(EXTRA_IMMEDIATE_CHECKIN, mImmediateCheckin); if (mImmediateCheckin && mIsShouting) { throw new IllegalStateException( "Cannot do immediate checkin and shout at the same time!"); } if (getLastNonConfigurationInstance() != null) { if (DEBUG) Log.d(TAG, "Using last non configuration instance"); mStateHolder = (StateHolder)getLastNonConfigurationInstance(); } else if (!mIsShouting) { // Translate the extras received in this intent int a venue, then attach it to the // venue view. mStateHolder.venue = new Venue(); intentExtrasIntoVenue(getIntent(), mStateHolder.venue); } if (!mImmediateCheckin) { initializeUi(); } else { setVisible(false); } if (mImmediateCheckin) { if (mStateHolder.checkinTask == null) { if (DEBUG) Log.d(TAG, "Immediate checkin is set."); mStateHolder.checkinTask = new CheckinTask().execute(); } } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedInReceiver); } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CHECKIN_PROGRESS: String title = (mIsShouting) ? "Shouting!" : "Checking in!"; String messageAction = (mIsShouting) ? "shout!" : "check-in!"; ProgressDialog dialog = new ProgressDialog(this); dialog.setCancelable(true); dialog.setIndeterminate(true); dialog.setTitle(title); dialog.setIcon(android.R.drawable.ic_dialog_info); dialog.setMessage("Please wait while we " + messageAction); dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mStateHolder.checkinTask.cancel(true); } }); return dialog; } return null; } /** * Because we cannot parcel venues properly yet (issue #5) we have to mutate a series of intent * extras into a venue so that we can code to this future possibility. */ public static void intentExtrasIntoVenue(Intent intent, Venue venue) { Bundle extras = intent.getExtras(); venue.setId(extras.getString(Foursquared.EXTRA_VENUE_ID)); venue.setName(extras.getString(EXTRA_VENUE_NAME)); venue.setAddress(extras.getString(EXTRA_VENUE_ADDRESS)); venue.setCrossstreet(extras.getString(EXTRA_VENUE_CROSSSTREET)); venue.setCity(extras.getString(EXTRA_VENUE_CITY)); venue.setZip(extras.getString(EXTRA_VENUE_ZIP)); venue.setState(extras.getString(EXTRA_VENUE_STATE)); } public static void venueIntoIntentExtras(Venue venue, Intent intent) { intent.putExtra(Foursquared.EXTRA_VENUE_ID, venue.getId()); intent.putExtra(ShoutActivity.EXTRA_VENUE_NAME, venue.getName()); intent.putExtra(ShoutActivity.EXTRA_VENUE_ADDRESS, venue.getAddress()); intent.putExtra(ShoutActivity.EXTRA_VENUE_CITY, venue.getCity()); intent.putExtra(ShoutActivity.EXTRA_VENUE_CROSSSTREET, venue.getCrossstreet()); intent.putExtra(ShoutActivity.EXTRA_VENUE_STATE, venue.getState()); intent.putExtra(ShoutActivity.EXTRA_VENUE_ZIP, venue.getZip()); } private AlertDialog createCheckinResultDialog(CheckinResult checkinResult) { LayoutInflater inflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.checkin_result_dialog, (ViewGroup)findViewById(R.id.layout_root)); String userId = PreferenceManager.getDefaultSharedPreferences(this).getString( Preferences.PREFERENCE_ID, ""); String checkinId = checkinResult.getId(); WebView webView = (WebView)layout.findViewById(R.id.webView); // Hrmm... Checkin scores look ugly when the background is dialog-colored, back to white... // webView.setBackgroundColor(0); // make it transparent... how do we do this in xml? webView.loadUrl(Foursquared.getFoursquare().checkinResultUrl(userId, checkinId)); TextView messageView = (TextView)layout.findViewById(R.id.messageTextView); messageView.setText(checkinResult.getMessage()); return new AlertDialog.Builder(this) .setView(layout) .setIcon(android.R.drawable.ic_dialog_info) // icon .setTitle("Checked in @ " + checkinResult.getVenue().getName()) // title .setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }) .create(); } private void setCheckinButtonEnabled(boolean enabled) { if (!mImmediateCheckin) { mCheckinButton.setEnabled(enabled); } } private void initializeUi() { setTheme(android.R.style.Theme_Dialog); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.shout_activity); mCheckinButton = (Button)findViewById(R.id.checkinButton); mFriendsCheckBox = (CheckBox)findViewById(R.id.tellFriendsCheckBox); mTwitterCheckBox = (CheckBox)findViewById(R.id.tellTwitterCheckBox); mShoutEditText = (EditText)findViewById(R.id.shoutEditText); mVenueView = (VenueView)findViewById(R.id.venue); SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(ShoutActivity.this); mCheckinButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mCheckinButton.setEnabled(false); String shout = mShoutEditText.getText().toString(); if (!TextUtils.isEmpty(shout)) { mShout = shout; } mStateHolder.checkinTask = new CheckinTask().execute(); } }); mTwitterCheckBox.setChecked(settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, mTellTwitter)); mFriendsCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mTellTwitter = isChecked; mTwitterCheckBox.setEnabled(isChecked); if (!isChecked) { mTwitterCheckBox.setChecked(false); } } }); mFriendsCheckBox.setChecked(settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, mTellFriends)); mFriendsCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mTellFriends = isChecked; } }); if (mIsShouting) { mVenueView.setVisibility(ViewGroup.GONE); mFriendsCheckBox.setChecked(true); mFriendsCheckBox.setEnabled(false); mCheckinButton.setText("Shout!"); } else { mVenueView.setVenue(mStateHolder.venue); } } class CheckinTask extends AsyncTask<Void, Void, CheckinResult> { private Exception mReason; @Override public void onPreExecute() { showDialog(DIALOG_CHECKIN_PROGRESS); } @Override public CheckinResult doInBackground(Void... params) { String venueId; if (mStateHolder.venue == null) { venueId = null; } else { venueId = mStateHolder.venue.getId(); } boolean isPrivate = !mTellFriends; try { return Foursquared.getFoursquare().checkin(venueId, null, mShout, isPrivate, mTellTwitter); } catch (Exception e) { mReason = e; } return null; } @Override public void onPostExecute(CheckinResult checkinResult) { if (DEBUG) Log.d(TAG, "CheckinTask: onPostExecute()"); dismissDialog(DIALOG_CHECKIN_PROGRESS); if (checkinResult != null) { setCheckinButtonEnabled(true); NotificationsUtil.ToastReasonForFailure(ShoutActivity.this, mReason); if (mImmediateCheckin) { finish(); } return; } else { setResult(Activity.RESULT_OK); createCheckinResultDialog(checkinResult).show(); } } @Override public void onCancelled() { dismissDialog(DIALOG_CHECKIN_PROGRESS); setCheckinButtonEnabled(true); if (mImmediateCheckin) { finish(); } } } private static class StateHolder { // These are all enumerated because we currently cannot handle parceling venues! How sad! Venue venue = null; AsyncTask<Void, Void, CheckinResult> checkinTask = null; } }
package com.miloshpetrov.sol2.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.miloshpetrov.sol2.*; import com.miloshpetrov.sol2.common.SolColor; import com.miloshpetrov.sol2.common.SolMath; import com.miloshpetrov.sol2.files.FileManager; import com.miloshpetrov.sol2.game.SolGame; import com.miloshpetrov.sol2.GameOptions; import java.util.ArrayList; import java.util.List; public class SolInputManager { private static final int POINTER_COUNT = 4; private static final float CURSOR_SHOW_TIME = 3; public static final float CURSOR_SZ = .07f; public static final float WARN_PERC_GROWTH_TIME = 1f; private final List<SolUiScreen> myScreens; private final List<SolUiScreen> myToRemove; private final List<SolUiScreen> myToAdd; private final Ptr[] myPtrs; private final Ptr myFlashPtr; private final Vector2 myMousePos; private final Vector2 myMousePrevPos; private final Sound myHoverSound; private float myMouseIdleTime; private final TextureAtlas.AtlasRegion myUiCursor; private final Color myWarnCol; private TextureAtlas.AtlasRegion myCurrCursor; private boolean myMouseOnUi; private float myWarnPerc; private boolean myWarnPercGrows; private Boolean myScrolledUp; public SolInputManager(TextureManager textureManager, float r) { myPtrs = new Ptr[POINTER_COUNT]; for (int i = 0; i < POINTER_COUNT; i++) { myPtrs[i] = new Ptr(); } SolInputProcessor sip = new SolInputProcessor(this); Gdx.input.setInputProcessor(sip); myFlashPtr = new Ptr(); myMousePos = new Vector2(); myMousePrevPos = new Vector2(); Gdx.input.setCursorCatched(true); myUiCursor = textureManager.getTex("ui/cursor", null); myScreens = new ArrayList<SolUiScreen>(); myToRemove = new ArrayList<SolUiScreen>(); myToAdd = new ArrayList<SolUiScreen>(); myWarnCol = new Color(SolColor.UI_WARN); FileHandle hoverSoundFile = FileManager.getInstance().getSoundsDirectory().child("ui").child("uiHover.ogg"); myHoverSound = Gdx.audio.newSound(hoverSoundFile); } public void maybeFlashPressed(int keyCode) { for (int i = 0, myScreensSize = myScreens.size(); i < myScreensSize; i++) { SolUiScreen screen = myScreens.get(i); boolean consumed = false; List<SolUiControl> controls = screen.getControls(); for (int i1 = 0, controlsSize = controls.size(); i1 < controlsSize; i1++) { SolUiControl c = controls.get(i1); if (c.maybeFlashPressed(keyCode)) consumed = true; } if (consumed) return; } } public void maybeFlashPressed(int x, int y) { setPtrPos(myFlashPtr, x, y); for (int i = 0, myScreensSize = myScreens.size(); i < myScreensSize; i++) { SolUiScreen screen = myScreens.get(i); List<SolUiControl> controls = screen.getControls(); for (int i1 = 0, controlsSize = controls.size(); i1 < controlsSize; i1++) { SolUiControl c = controls.get(i1); if (c.maybeFlashPressed(myFlashPtr)) return; } if (screen.isCursorOnBg(myFlashPtr)) return; } } public void setScreen(SolApplication cmp, SolUiScreen screen) { for (int i = 0, myScreensSize = myScreens.size(); i < myScreensSize; i++) { SolUiScreen oldScreen = myScreens.get(i); removeScreen(oldScreen, cmp); } addScreen(cmp, screen); } public void addScreen(SolApplication cmp, SolUiScreen screen) { myToAdd.add(screen); screen.onAdd(cmp); } private void removeScreen(SolUiScreen screen, SolApplication cmp) { myToRemove.add(screen); List<SolUiControl> controls = screen.getControls(); for (int i = 0, controlsSize = controls.size(); i < controlsSize; i++) { SolUiControl c = controls.get(i); c.blur(); } screen.blurCustom(cmp); } public boolean isScreenOn(SolUiScreen screen) { return myScreens.contains(screen); } private static void setPtrPos(Ptr ptr, int screenX, int screenY) { int h = Gdx.graphics.getHeight(); ptr.x = 1f * screenX / h; ptr.y = 1f * screenY / h; } public void update(SolApplication cmp) { updatePtrs(); boolean consumed = false; myMouseOnUi = false; boolean clickOutsideReacted = false; for (int i = 0, myScreensSize = myScreens.size(); i < myScreensSize; i++) { SolUiScreen screen = myScreens.get(i); boolean consumedNow = false; List<SolUiControl> controls = screen.getControls(); for (int i1 = 0, controlsSize = controls.size(); i1 < controlsSize; i1++) { SolUiControl c = controls.get(i1); c.update(myPtrs, myCurrCursor != null, !consumed, this, cmp); if (c.isOn() || c.isJustOff()) { consumedNow = true; } Rectangle area = c.getScreenArea(); if (area != null && area.contains(myMousePos)) { myMouseOnUi = true; } } if (consumedNow) consumed = true; boolean clickedOutside = false; if (!consumed) { for (int i1 = 0, myPtrsLength = myPtrs.length; i1 < myPtrsLength; i1++) { Ptr ptr = myPtrs[i1]; boolean onBg = screen.isCursorOnBg(ptr); if (ptr.pressed && onBg) { clickedOutside = false; consumed = true; break; } if (!onBg && ptr.isJustUnPressed() && !clickOutsideReacted) { clickedOutside = true; } } } if (clickedOutside && screen.reactsToClickOutside()) clickOutsideReacted = true; if (screen.isCursorOnBg(myPtrs[0])) myMouseOnUi = true; screen.updateCustom(cmp, myPtrs, clickedOutside); } SolGame game = cmp.getGame(); TutorialManager tutorialManager = game == null ? null : game.getTutMan(); if (tutorialManager != null && tutorialManager.isFinished()) { cmp.finishGame(); } updateCursor(cmp); addRemoveScreens(); updateWarnPerc(); myScrolledUp = null; } private void updateWarnPerc() { float dif = SolMath.toInt(myWarnPercGrows) * Const.REAL_TIME_STEP / WARN_PERC_GROWTH_TIME; myWarnPerc += dif; if (myWarnPerc < 0 || 1 < myWarnPerc) { myWarnPerc = SolMath.clamp(myWarnPerc); myWarnPercGrows = !myWarnPercGrows; } myWarnCol.a = myWarnPerc * .5f; } private void addRemoveScreens() { for (int i = 0, myToRemoveSize = myToRemove.size(); i < myToRemoveSize; i++) { SolUiScreen screen = myToRemove.get(i); myScreens.remove(screen); } myToRemove.clear(); for (int i = 0, myToAddSize = myToAdd.size(); i < myToAddSize; i++) { SolUiScreen screen = myToAdd.get(i); if (isScreenOn(screen)) continue; myScreens.add(0, screen); } myToAdd.clear(); } private void updateCursor(SolApplication cmp) { if (cmp.isMobile()) return; myMousePos.set(myPtrs[0].x, myPtrs[0].y); if (cmp.getOptions().controlType != GameOptions.CONTROL_KB) { SolGame game = cmp.getGame(); if (game == null || myMouseOnUi) { myCurrCursor = myUiCursor; } else { myCurrCursor = game.getScreens().mainScreen.shipControl.getInGameTex(); if (myCurrCursor == null) myCurrCursor = myUiCursor; } return; } if (myMousePrevPos.epsilonEquals(myMousePos, 0)) { myMouseIdleTime += Const.REAL_TIME_STEP; myCurrCursor = myMouseIdleTime < CURSOR_SHOW_TIME ? myUiCursor : null; } else { myCurrCursor = myUiCursor; myMouseIdleTime = 0; myMousePrevPos.set(myMousePos); } } private void maybeFixMousePos() { int mouseX = Gdx.input.getX(); int mouseY = Gdx.input.getY(); int w = Gdx.graphics.getWidth(); int h = Gdx.graphics.getHeight(); mouseX = (int)SolMath.clamp(mouseX, 0, w); mouseY = (int)SolMath.clamp(mouseY, 0, h); Gdx.input.setCursorPosition(mouseX, h - mouseY); } private void updatePtrs() { for (int i = 0; i < POINTER_COUNT; i++) { Ptr ptr = myPtrs[i]; int screenX = Gdx.input.getX(i); int screenY = Gdx.input.getY(i); setPtrPos(ptr, screenX, screenY); ptr.prevPressed = ptr.pressed; ptr.pressed = Gdx.input.isTouched(i); } } public void draw(UiDrawer uiDrawer, SolApplication cmp) { for (int i = myScreens.size() - 1; i >= 0; i SolUiScreen screen = myScreens.get(i); uiDrawer.setTextMode(false); screen.drawBg(uiDrawer, cmp); List<SolUiControl> ctrls = screen.getControls(); for (int i1 = 0, ctrlsSize = ctrls.size(); i1 < ctrlsSize; i1++) { SolUiControl ctrl = ctrls.get(i1); ctrl.drawButton(uiDrawer, cmp, myWarnCol); } screen.drawImgs(uiDrawer, cmp); uiDrawer.setTextMode(true); screen.drawText(uiDrawer, cmp); for (int i1 = 0, ctrlsSize = ctrls.size(); i1 < ctrlsSize; i1++) { SolUiControl ctrl = ctrls.get(i1); ctrl.drawDisplayName(uiDrawer); } } uiDrawer.setTextMode(null); SolGame game = cmp.getGame(); TutorialManager tutorialManager = game == null ? null : game.getTutMan(); if (tutorialManager != null && getTopScreen() != game.getScreens().menuScreen) tutorialManager.draw(uiDrawer); if (myCurrCursor != null) { uiDrawer.draw(myCurrCursor, CURSOR_SZ, CURSOR_SZ, CURSOR_SZ/2, CURSOR_SZ/2, myMousePos.x, myMousePos.y, 0, SolColor.W); } } public Vector2 getMousePos() { return myMousePos; } public Ptr[] getPtrs() { return myPtrs; } public boolean isMouseOnUi() { return myMouseOnUi; } public void playHover(SolApplication cmp) { myHoverSound.play(.7f * cmp.getOptions().volMul, .7f, 0); } public void playClick(SolApplication cmp) { myHoverSound.play(.7f * cmp.getOptions().volMul, .9f, 0); } public SolUiScreen getTopScreen() { return myScreens.isEmpty() ? null : myScreens.get(0); } public void scrolled(boolean up) { myScrolledUp = up; } public Boolean getScrolledUp() { return myScrolledUp; } public void dispose() { myHoverSound.dispose(); } public static class Ptr { public float x; public float y; public boolean pressed; public boolean prevPressed; public boolean isJustPressed() { return pressed && !prevPressed; } public boolean isJustUnPressed() { return !pressed && prevPressed; } } }
package com.eas.script; import com.eas.concurrent.DeamonThreadFactory; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptException; import javax.script.SimpleScriptContext; import jdk.nashorn.api.scripting.AbstractJSObject; import jdk.nashorn.api.scripting.JSObject; import jdk.nashorn.api.scripting.NashornScriptEngine; import jdk.nashorn.api.scripting.NashornScriptEngineFactory; import jdk.nashorn.api.scripting.ScriptUtils; import jdk.nashorn.api.scripting.URLReader; import jdk.nashorn.internal.ir.FunctionNode; import jdk.nashorn.internal.ir.IdentNode; import jdk.nashorn.internal.ir.LexicalContext; import jdk.nashorn.internal.ir.Node; import jdk.nashorn.internal.ir.VarNode; import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor; import jdk.nashorn.internal.ir.visitor.NodeVisitor; import jdk.nashorn.internal.parser.Lexer; import jdk.nashorn.internal.parser.Parser; import jdk.nashorn.internal.parser.Token; import jdk.nashorn.internal.parser.TokenStream; import jdk.nashorn.internal.parser.TokenType; import jdk.nashorn.internal.runtime.ErrorManager; import jdk.nashorn.internal.runtime.JSType; import jdk.nashorn.internal.runtime.ScriptEnvironment; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.ScriptRuntime; import jdk.nashorn.internal.runtime.Source; import jdk.nashorn.internal.runtime.Undefined; import jdk.nashorn.internal.runtime.options.Options; /** * * @author vv, mg */ public class Scripts { public static final String STRING_TYPE_NAME = "String";//NOI18N public static final String NUMBER_TYPE_NAME = "Number";//NOI18N public static final String DATE_TYPE_NAME = "Date";//NOI18N public static final String BOOLEAN_TYPE_NAME = "Boolean";//NOI18N public static final String GEOMETRY_TYPE_NAME = "Geometry";//NOI18N public static final String THIS_KEYWORD = "this";//NOI18N protected static volatile Path absoluteApiPath; protected static volatile URL platypusJsUrl; private static final ThreadLocal<LocalContext> contextRef = new ThreadLocal<>(); public static Space getSpace() { return getContext() != null ? getContext().getSpace() : null; } public static LocalContext getContext() { return contextRef.get(); } public static void setContext(LocalContext aContext) { if (aContext != null) { contextRef.set(aContext); } else { contextRef.remove(); } } public static class LocalContext { protected Object request; protected Object response; protected Object async; protected Object principal; protected Integer asyncsCount; protected Scripts.Space space; public Object getRequest() { return request; } public void setRequest(Object aRequest) { request = aRequest; } public Object getResponse() { return response; } public void setResponse(Object aResponse) { response = aResponse; } public Object getAsync() { return async; } public void setAsync(Object aValue) { async = aValue; } public Object getPrincipal() { return principal; } public void setPrincipal(Object aSession) { principal = aSession; } public int getAsyncsCount() { return asyncsCount != null ? asyncsCount : 0; } public void incAsyncsCount() { if (asyncsCount != null) { asyncsCount++; } } public void initAsyncs(Integer aSeed) { asyncsCount = aSeed; } public Space getSpace() { return space; } public void setSpace(Space aValue) { space = aValue; } } public static LocalContext createContext(Scripts.Space aSpace) { LocalContext res = new LocalContext(); res.setSpace(aSpace); return res; } public static class Pending { protected Consumer<Void> onLoad; protected Consumer<Exception> onError; public Pending(Consumer<Void> aOnLoad, Consumer<Exception> aOnError) { super(); onLoad = aOnLoad; onError = aOnError; } public void loaded() { onLoad.accept(null); } public void failed(Exception ex) { onError.accept(ex); } } public static class Space { private static final NashornScriptEngineFactory factory = new NashornScriptEngineFactory(); private static final NashornScriptEngine engine = (NashornScriptEngine)factory.getScriptEngine(); public static NashornScriptEngine getEngine() { return engine; } protected ScriptContext scriptContext; protected Object global; protected Object session; protected Map<String, JSObject> publishers = new HashMap<>(); protected Set<String> required = new HashSet<>(); protected Set<String> executed = new HashSet<>(); protected Map<String, List<Pending>> pending = new HashMap<>(); protected Space() { this(null); global = new Object(); } public Space(ScriptContext aScriptContext) { super(); scriptContext = aScriptContext; } public Object getSession() { return session; } public void setSession(Object aValue) { session = aValue; } public Set<String> getRequired() { return required; } public Set<String> getExecuted() { return executed; } public Map<String, List<Pending>> getPending() { return pending; } protected JSObject loadFunc; protected JSObject toPrimitiveFunc; protected JSObject lookupInGlobalFunc; protected JSObject putInGlobalFunc; protected JSObject toDateFunc; protected JSObject parseJsonFunc; protected JSObject parseJsonWithDatesFunc; protected JSObject writeJsonFunc; protected JSObject extendFunc; protected JSObject scalarDefFunc; protected JSObject collectionDefFunc; protected JSObject isArrayFunc; protected JSObject makeObjFunc; protected JSObject makeArrayFunc; protected JSObject listenFunc; protected JSObject listenElementsFunc; protected JSObject copyObjectFunc; public void setGlobal(Object aValue) { if (global == null) { global = aValue; } else { throw new IllegalStateException("Scripts space should be initialized only once."); } } public void putPublisher(String aClassName, JSObject aPublisher) { publishers.put(aClassName, aPublisher); } public JSObject getPublisher(String aClassName) { return publishers.get(aClassName); } public JSObject getLoadFunc() { assert loadFunc != null : SCRIPT_NOT_INITIALIZED; return loadFunc; } public void setLoadFunc(JSObject aValue) { assert loadFunc == null; loadFunc = aValue; } public JSObject getToPrimitiveFunc() { assert toPrimitiveFunc != null : SCRIPT_NOT_INITIALIZED; return toPrimitiveFunc; } public void setToPrimitiveFunc(JSObject aValue) { assert toPrimitiveFunc == null; toPrimitiveFunc = aValue; } public void setLookupInGlobalFunc(JSObject aValue) { assert lookupInGlobalFunc == null; lookupInGlobalFunc = aValue; } public void setPutInGlobalFunc(JSObject aValue) { assert putInGlobalFunc == null; putInGlobalFunc = aValue; } public JSObject getToDateFunc() { assert toDateFunc != null; return toDateFunc; } public void setToDateFunc(JSObject aValue) { assert toDateFunc == null; toDateFunc = aValue; } public void setParseJsonFunc(JSObject aValue) { assert parseJsonFunc == null; parseJsonFunc = aValue; } public void setParseJsonWithDatesFunc(JSObject aValue) { assert parseJsonWithDatesFunc == null; parseJsonWithDatesFunc = aValue; } public void setWriteJsonFunc(JSObject aValue) { assert writeJsonFunc == null; writeJsonFunc = aValue; } public void setExtendFunc(JSObject aValue) { assert extendFunc == null; extendFunc = aValue; } public void setScalarDefFunc(JSObject aValue) { assert scalarDefFunc == null; scalarDefFunc = aValue; } public void setCollectionDefFunc(JSObject aValue) { assert collectionDefFunc == null; collectionDefFunc = aValue; } public void setIsArrayFunc(JSObject aValue) { assert isArrayFunc == null; isArrayFunc = aValue; } public void setMakeObjFunc(JSObject aValue) { assert makeObjFunc == null; makeObjFunc = aValue; } public void setMakeArrayFunc(JSObject aValue) { assert makeArrayFunc == null; makeArrayFunc = aValue; } public void setListenFunc(JSObject aValue) { assert listenFunc == null; listenFunc = aValue; } public void setListenElementsFunc(JSObject aValue) { assert listenElementsFunc == null; listenElementsFunc = aValue; } public void setCopyObjectFunc(JSObject aValue) { assert copyObjectFunc == null; copyObjectFunc = aValue; } public JSObject getCopyObjectFunc() { return copyObjectFunc; } public Object toJava(Object aValue) { if (aValue instanceof ScriptObject) { aValue = ScriptUtils.wrap((ScriptObject) aValue); } if (aValue instanceof JSObject) { assert toPrimitiveFunc != null : SCRIPT_NOT_INITIALIZED; aValue = toPrimitiveFunc.call(null, new Object[]{aValue}); } else if (aValue == ScriptRuntime.UNDEFINED) { return null; } return aValue; } public Object toJs(Object aValue) { if (aValue instanceof Date) {// force js boxing of date, because of absence js literal of date value assert toDateFunc != null : SCRIPT_NOT_INITIALIZED; return toDateFunc.call(null, aValue); } else if (aValue instanceof HasPublished) { return ((HasPublished) aValue).getPublished(); } else { return aValue; } } public Object[] toJs(Object[] aArray) { Object[] publishedArgs = new Object[aArray.length]; for (int i = 0; i < aArray.length; i++) { publishedArgs[i] = toJs(aArray[i]); } return publishedArgs; } public Object parseJson(String json) { assert parseJsonFunc != null : SCRIPT_NOT_INITIALIZED; return parseJsonFunc.call(null, new Object[]{json}); } public Object parseJsonWithDates(String json) { assert parseJsonWithDatesFunc != null : SCRIPT_NOT_INITIALIZED; return parseJsonWithDatesFunc.call(null, new Object[]{json}); } public String toJson(Object aObj) { assert writeJsonFunc != null : SCRIPT_NOT_INITIALIZED; if (aObj instanceof Undefined) {//nashorn JSON parser could not work with undefined. aObj = null; } if (aObj instanceof JSObject || aObj instanceof CharSequence || aObj instanceof Number || aObj instanceof Boolean || aObj instanceof ScriptObject || aObj == null) { return JSType.toString(writeJsonFunc.call(null, new Object[]{aObj})); } else { throw new IllegalArgumentException("Java object couldn't be converted to JSON!"); } } public void extend(JSObject aChild, JSObject aParent) { assert extendFunc != null : SCRIPT_NOT_INITIALIZED; extendFunc.call(null, new Object[]{aChild, aParent}); } public JSObject scalarPropertyDefinition(JSObject targetEntity, String targetFieldName, String sourceFieldName) { assert scalarDefFunc != null : SCRIPT_NOT_INITIALIZED; return (JSObject) scalarDefFunc.newObject(new Object[]{targetEntity, targetFieldName, sourceFieldName}); } public JSObject collectionPropertyDefinition(JSObject sourceEntity, String targetFieldName, String sourceFieldName) { assert collectionDefFunc != null : SCRIPT_NOT_INITIALIZED; return (JSObject) collectionDefFunc.newObject(new Object[]{sourceEntity, targetFieldName, sourceFieldName}); } public boolean isArrayDeep(JSObject aInstance) { assert isArrayFunc != null : SCRIPT_NOT_INITIALIZED; Object oResult = isArrayFunc.call(null, new Object[]{aInstance}); return Boolean.TRUE.equals(oResult); } public JSObject makeObj() { assert makeObjFunc != null : SCRIPT_NOT_INITIALIZED; Object oResult = makeObjFunc.call(null, new Object[]{}); return (JSObject) oResult; } public JSObject makeArray() { assert makeArrayFunc != null : SCRIPT_NOT_INITIALIZED; Object oResult = makeArrayFunc.call(null, new Object[]{}); return (JSObject) oResult; } private static class Wrapper { public Object value; } public Object makeCopy(Object aSource) { assert copyObjectFunc != null : SCRIPT_NOT_INITIALIZED; Wrapper w = new Wrapper(); copyObjectFunc.call(null, new Object[]{aSource, new AbstractJSObject() { @Override public Object call(Object thiz, Object... args) { w.value = args.length > 0 ? args[0] : null; return null; } }}); return w.value; } public JSObject listen(JSObject aTarget, String aPath, JSObject aCallback) { assert listenFunc != null : SCRIPT_NOT_INITIALIZED; Object oResult = listenFunc.call(null, new Object[]{aTarget, aPath, aCallback}); return (JSObject) oResult; } public JSObject listenElements(JSObject aTarget, JSObject aCallback) { assert listenElementsFunc != null : SCRIPT_NOT_INITIALIZED; Object oResult = listenElementsFunc.call(null, new Object[]{aTarget, aCallback}); return (JSObject) oResult; } public JSObject createModule(String aModuleName) { assert lookupInGlobalFunc != null : SCRIPT_NOT_INITIALIZED; Object oConstructor = lookupInGlobalFunc.call(null, new Object[]{aModuleName}); if (oConstructor instanceof JSObject && ((JSObject) oConstructor).isFunction()) { JSObject jsConstructor = (JSObject) oConstructor; return (JSObject) jsConstructor.newObject(new Object[]{}); } else { return null; } } public JSObject lookupInGlobal(String aName) { assert lookupInGlobalFunc != null : SCRIPT_NOT_INITIALIZED; Object res = lookupInGlobalFunc.call(null, new Object[]{aName}); return res instanceof JSObject ? (JSObject) res : null; } public void putInGlobal(String aName, JSObject aValue) { assert putInGlobalFunc != null : SCRIPT_NOT_INITIALIZED; putInGlobalFunc.call(null, new Object[]{aName, aValue}); } public Object exec(URL aSourcePlace) throws ScriptException, URISyntaxException { scriptContext.setAttribute(ScriptEngine.FILENAME, aSourcePlace, ScriptContext.ENGINE_SCOPE); return engine.eval(new URLReader(aSourcePlace), scriptContext); } public Object exec(String aSource) throws ScriptException, URISyntaxException { assert scriptContext != null : SCRIPT_NOT_INITIALIZED; return engine.eval(aSource, scriptContext); } public void schedule(JSObject aJsTask, long aTimeout) { Scripts.LocalContext context = Scripts.getContext(); bio.submit(() -> { try { Thread.sleep(aTimeout); Scripts.setContext(context); try { process(() -> { aJsTask.call(null, new Object[]{}); }); } finally { Scripts.setContext(null); } } catch (InterruptedException ex) { Logger.getLogger(Scripts.class.getName()).log(Level.SEVERE, null, ex); } }); } public void enqueue(JSObject aJsTask) { process(() -> { aJsTask.call(null, new Object[]{}); }); } protected Queue<Runnable> queue = new ConcurrentLinkedQueue<>(); protected AtomicInteger queueVersion = new AtomicInteger(); protected AtomicReference worker = new AtomicReference(null); public void process(Runnable aTask) { Scripts.LocalContext context = Scripts.getContext(); Runnable taskWrapper = () -> { Scripts.setContext(context); try { aTask.run(); } finally { Scripts.setContext(null); } }; queue.offer(taskWrapper); offerTask(() -> { //Runnable processedTask = taskWrapper; int version; int newVersion; Thread thisThread = Thread.currentThread(); do { version = queueVersion.get(); // Zombie counter ... newVersion = version + 1; if (newVersion == Integer.MAX_VALUE) { newVersion = 0; } /* moved to top of body if (processedTask != null) {//Single attempt to offer aTask. queue.offer(processedTask); processedTask = null; } */ if (worker.compareAndSet(null, thisThread)) {// Worker electing. try { // already single threaded environment if (global == null) { Scripts.Space.this.initSpaceGlobal(); } // Zombie processing ... Runnable task = queue.poll(); while (task != null) { task.run(); task = queue.poll(); } } catch (Throwable t) { Logger.getLogger(Scripts.class.getName()).log(Level.SEVERE, null, t); } finally { boolean setted = worker.compareAndSet(thisThread, null); assert setted : "Worker electing assumption failed";// Always successfull CAS. } } } while (!queueVersion.compareAndSet(version, newVersion)); }); } public void initSpaceGlobal() { Bindings bindings = engine.createBindings(); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); bindings.put("space", this); try { Scripts.LocalContext ctx = Scripts.createContext(Scripts.Space.this); Scripts.setContext(ctx); try { scriptContext.setAttribute(ScriptEngine.FILENAME, platypusJsUrl, ScriptContext.ENGINE_SCOPE); engine.eval(new URLReader(platypusJsUrl), scriptContext); } finally { Scripts.setContext(null); } } catch (ScriptException ex) { Logger.getLogger(Scripts.class.getName()).log(Level.SEVERE, null, ex); } } public JSObject readJsArray(Collection<Map<String, Object>> aCollection) { JSObject result = makeArray(); JSObject jsPush = (JSObject) result.getMember("push"); aCollection.forEach((Map<String, Object> aItem) -> { JSObject jsItem = makeObj(); aItem.entrySet().forEach((Map.Entry<String, Object> aItemContent) -> { jsItem.setMember(aItemContent.getKey(), toJs(aItemContent.getValue())); }); jsPush.call(result, new Object[]{jsItem}); }); return result; } } protected static Consumer<Runnable> tasks; // bio thread pool protected static ThreadPoolExecutor bio; public static void init(Path aAbsoluteApiPath) throws MalformedURLException { absoluteApiPath = aAbsoluteApiPath; platypusJsUrl = absoluteApiPath.resolve("platypus.js").toUri().toURL(); } public static Path getAbsoluteApiPath() { return absoluteApiPath; } public static void initTasks(Consumer<Runnable> aTasks) { assert tasks == null : "Scripts tasks are already initialized"; tasks = aTasks; } public static void offerTask(Runnable aTask) { assert tasks != null : "Scripts tasks are not initialized"; Scripts.getContext().incAsyncsCount(); tasks.accept(aTask); } public static void initBIO(int aMaxThreads) { bio = new ThreadPoolExecutor(aMaxThreads, aMaxThreads, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new DeamonThreadFactory("platypus-abio-", false)); bio.allowCoreThreadTimeOut(true); } public static void shutdown() { if (bio != null) { bio.shutdownNow(); } } public static void startBIO(Runnable aBioTask) { LocalContext context = getContext(); context.incAsyncsCount(); bio.submit(() -> { setContext(context); try { aBioTask.run(); } finally { setContext(null); } }); } public static Space createSpace() throws ScriptException { Space space = new Space(new SimpleScriptContext()); return space; } public static Space createQueue() throws ScriptException { Space space = new Space(); return space; } public static boolean isInitialized() { Space space = getContext() != null ? getContext().getSpace() : null; return space != null && space.listenElementsFunc != null && space.listenFunc != null && space.scalarDefFunc != null && space.collectionDefFunc != null; } public static boolean isValidJsIdentifier(final String aName) { if (aName != null && !aName.trim().isEmpty()) { try { FunctionNode astRoot = parseJs(String.format("function %s() {}", aName)); return astRoot != null && !astRoot.getBody().getStatements().isEmpty(); } catch (Exception ex) { return false; } } return false; } public static FunctionNode parseJs(String aJsContent) { Source source = Source.sourceFor("", aJsContent);//NOI18N Options options = new Options(null); ScriptEnvironment env = new ScriptEnvironment(options, null, null); ErrorManager errors = new ErrorManager(); Parser p = new Parser(env, source, errors); return p.parse(); } /** * Extracts the comments tokens from a JavaScript source. * * @param aSource a source * @return a list of comment tokens */ public static List<Long> getCommentsTokens(String aSource) { TokenStream tokens = new TokenStream(); Lexer lexer = new Lexer(Source.sourceFor("", aSource), tokens);//NOI18N long t; TokenType tt = TokenType.EOL; int i = 0; List<Long> commentsTokens = new ArrayList<>(); while (tt != TokenType.EOF) { // Get next token in nashorn's parser way while (i > tokens.last()) { if (tokens.isFull()) { tokens.grow(); } lexer.lexify(); } t = tokens.get(i++); tt = Token.descType(t); if (tt == TokenType.COMMENT) { commentsTokens.add(t); } } return commentsTokens; } /** * Removes all commentaries from some JavaScript code. * * @param text a source * @return comments-free JavaScript code */ public static String removeComments(String text) { StringBuilder sb = new StringBuilder(); int i = 0; for (Long t : getCommentsTokens(text)) { int offset = Token.descPosition(t); int lenght = Token.descLength(t); sb.append(text.substring(i, offset)); for (int j = 0; j < lenght; j++) { sb.append(" ");//NOI18N } i = offset + lenght; } sb.append(text.substring(i)); return sb.toString(); } /** * Searches for all <code>this</code> aliases in a constructor. * * @param moduleConstructor a constructor to search in * @return a set of aliases including <code>this</code> itself */ public static Set<String> getThisAliases(final FunctionNode moduleConstructor) { final Set<String> aliases = new HashSet<>(); if (moduleConstructor != null && moduleConstructor.getBody() != null) { aliases.add(THIS_KEYWORD); LexicalContext lc = new LexicalContext(); moduleConstructor.accept(new NodeOperatorVisitor<LexicalContext>(lc) { @Override public boolean enterVarNode(VarNode varNode) { if (lc.getCurrentFunction() == moduleConstructor) { if (varNode.getAssignmentSource() instanceof IdentNode) { IdentNode in = (IdentNode) varNode.getAssignmentSource(); if (THIS_KEYWORD.equals(in.getName())) { aliases.add(varNode.getAssignmentDest().getName()); } } } return super.enterVarNode(varNode); } }); } return aliases; } protected static final String SCRIPT_NOT_INITIALIZED = "Platypus script functions are not initialized."; public static void unlisten(JSObject aCookie) { JSObject unlisten = (JSObject) aCookie.getMember("unlisten"); unlisten.call(null, new Object[]{}); } public static boolean isInNode(Node node, int offset) { return node.getStart() <= offset && offset <= node.getFinish() + 1; } public static boolean isInNode(Node outerNode, Node innerNode) { return outerNode.getStart() <= innerNode.getStart() && innerNode.getFinish() <= outerNode.getFinish(); } public static Node getOffsetNode(Node node, final int offset) { GetOffsetNodeVisitorSupport vs = new GetOffsetNodeVisitorSupport(node, offset); Node offsetNode = vs.getOffsetNode(); return offsetNode != null ? offsetNode : node; } private static class GetOffsetNodeVisitorSupport { private final Node root; private final int offset; private Node offsetNode; public GetOffsetNodeVisitorSupport(Node root, int offset) { this.root = root; this.offset = offset; } public Node getOffsetNode() { final LexicalContext lc = new LexicalContext(); root.accept(new NodeVisitor<LexicalContext>(lc) { @Override protected boolean enterDefault(Node node) { if (isInNode(node, offset)) { offsetNode = node; return true; } return false; } }); return offsetNode; } } }
package org.lockss.util; import java.util.*; import java.io.*; import java.net.URL; import javax.xml.parsers.*; import org.xml.sax.helpers.*; import org.lockss.test.*; import org.lockss.config.*; /** * Test class for <code>org.lockss.util.XmlPropertyLoader</code> and * <code>org.lockss.util.LockssConfigHandler</code>. */ public class TestXmlPropertyLoader extends LockssTestCase { private PropertyTree m_props = null; private XmlPropertyLoader m_xmlPropertyLoader = null; public static Class testedClasses[] = { org.lockss.util.XmlPropertyLoader.class }; public void setUp() throws Exception { super.setUp(); m_xmlPropertyLoader = new MockXmlPropertyLoader(); // Set default values for testing conditionals. setDefaultVersions(); parseXmlProperties(); } public void tearDown() throws Exception { super.tearDown(); } static Logger log = Logger.getLogger("TestXmlPropertyLoader"); /** * Parse the XML test configuration and set m_props. */ private void parseXmlProperties() throws Exception { String file = "configtest.xml"; URL url = getResource(file); InputStream istr = UrlUtil.openInputStream(url.toString()); PropertyTree props = new PropertyTree(); m_xmlPropertyLoader.loadProperties(props, istr); m_props = props; } /** * Test known-bad XML. */ public void testUnknownXmlTag() throws Exception { PropertyTree props = new PropertyTree(); StringBuffer sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <some-unknown-tag name=\"foo\" value=\"bar\" />\n"); sb.append("</lockss-config>\n"); InputStream istr = new ReaderInputStream(new StringReader(sb.toString())); try { m_xmlPropertyLoader.loadProperties(props, istr); fail("Should have thrown."); } catch (Throwable t) { } } public void testIllegalDaemonVersionCombo() throws Exception { PropertyTree props = new PropertyTree(); StringBuffer sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <if daemonVersion=\"2.0.0\" daemonVersionMax=\"3.0.0\">\n"); sb.append(" <property name=\"a\" value=\"foo\" />"); sb.append(" </if>\n"); sb.append(" <if daemonVersion=\"2.0.0\" daemonVersionMin=\"1.0.0\">\n"); sb.append(" <property name=\"b\" value=\"foo\" />"); sb.append(" </if>\n"); sb.append("</lockss-config>\n"); InputStream istr = new ReaderInputStream(new StringReader(sb.toString())); try { m_xmlPropertyLoader.loadProperties(props, istr); fail("Should have thrown."); } catch (Throwable t) { } } public void testIllegalPlatformVersionCombo() throws Exception { PropertyTree props = new PropertyTree(); StringBuffer sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <if platformVersion=\"150\" platformVersionMax=\"200\">\n"); sb.append(" <property name=\"a\" value=\"foo\" />"); sb.append(" </if>\n"); sb.append(" <if platformVersion=\"150\" platformVersionMin=\"100\">\n"); sb.append(" <property name=\"b\" value=\"foo\" />"); sb.append(" </if>\n"); sb.append("</lockss-config>\n"); InputStream istr = new ReaderInputStream(new StringReader(sb.toString())); try { m_xmlPropertyLoader.loadProperties(props, istr); fail("Should have thrown."); } catch (Throwable t) { } } /** * This test was added to exercise issue# 1526. */ public void testCXSerializerCompatibilityModeSetProperly() throws Exception { PropertyTree props; InputStream istr; StringBuffer sb; sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <property name=\"org.lockss\">\n"); sb.append(" <if>\n"); sb.append(" <not>\n"); sb.append(" <test group=\"dev\" daemonVersionMin=\"1.13.0\"/>\n"); sb.append(" </not>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"serialization.compatibilityMode\" value=\"1\" />\n"); sb.append(" </then>\n"); sb.append(" </if>\n"); sb.append(" </property>\n"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertNull(props.getProperty("org.lockss.serialization.compatibilityMode")); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.12.3", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("1", props.getProperty("org.lockss.serialization.compatibilityMode")); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.12.3", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("1", props.getProperty("org.lockss.serialization.compatibilityMode")); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("1", props.getProperty("org.lockss.serialization.compatibilityMode")); // This should be equivalent, implicit <and> sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <property name=\"org.lockss\">\n"); sb.append(" <if>\n"); sb.append(" <not>\n"); sb.append(" <test daemonVersionMin=\"1.13.0\"/>\n"); sb.append(" <test group=\"dev\"/>\n"); sb.append(" </not>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"serialization.compatibilityMode\" value=\"1\" />\n"); sb.append(" </then>\n"); sb.append(" </if>\n"); sb.append(" </property>\n"); sb.append("</lockss-config>\n"); // T T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertNull(props.getProperty("org.lockss.serialization.compatibilityMode")); // F F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.12.3", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("1", props.getProperty("org.lockss.serialization.compatibilityMode")); // F T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.12.3", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("1", props.getProperty("org.lockss.serialization.compatibilityMode")); // T F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("1", props.getProperty("org.lockss.serialization.compatibilityMode")); // This should be equivalent!! sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <property name=\"org.lockss\">\n"); sb.append(" <if>\n"); sb.append(" <not>\n"); sb.append(" <and>\n"); sb.append(" <test daemonVersionMin=\"1.13.0\"/>\n"); sb.append(" <test group=\"dev\"/>\n"); sb.append(" </and>\n"); sb.append(" </not>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"serialization.compatibilityMode\" value=\"1\" />\n"); sb.append(" </then>\n"); sb.append(" </if>\n"); sb.append(" </property>\n"); sb.append("</lockss-config>\n"); // T T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertNull(props.getProperty("org.lockss.serialization.compatibilityMode")); // F F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.12.3", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("1", props.getProperty("org.lockss.serialization.compatibilityMode")); // F T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.12.3", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("1", props.getProperty("org.lockss.serialization.compatibilityMode")); // T F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("1", props.getProperty("org.lockss.serialization.compatibilityMode")); } public void testExplicitAndCombinatorics() throws Exception { PropertyTree props; InputStream istr; StringBuffer sb; sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <if>\n"); sb.append(" <and>\n"); sb.append(" <test platformVersion=\"200\" />\n"); sb.append(" <test group=\"dev\" />\n"); sb.append(" </and>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"test\" value=\"foo\" />\n"); sb.append(" </then>\n"); sb.append(" <else>\n"); sb.append(" <property name=\"test\" value=\"bar\" />\n"); sb.append(" </else>\n"); sb.append(" </if>\n"); sb.append("</lockss-config>\n"); // T T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); // T F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); // F T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); // F F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); } public void testImplicitAndCombinatorics() throws Exception { PropertyTree props; InputStream istr; StringBuffer sb; sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <if>\n"); sb.append(" <test platformVersion=\"200\" />\n"); sb.append(" <test group=\"dev\" />\n"); sb.append(" <then>\n"); sb.append(" <property name=\"test\" value=\"foo\" />\n"); sb.append(" </then>\n"); sb.append(" <else>\n"); sb.append(" <property name=\"test\" value=\"bar\" />\n"); sb.append(" </else>\n"); sb.append(" </if>\n"); sb.append("</lockss-config>\n"); // T T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); // T F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); // F T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); // F F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); } public void testOrCombinatorics() throws Exception { PropertyTree props; InputStream istr; StringBuffer sb; sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <if>\n"); sb.append(" <or>\n"); sb.append(" <test platformVersion=\"200\" />\n"); sb.append(" <test group=\"dev\" />\n"); sb.append(" </or>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"test\" value=\"foo\" />\n"); sb.append(" </then>\n"); sb.append(" <else>\n"); sb.append(" <property name=\"test\" value=\"bar\" />\n"); sb.append(" </else>\n"); sb.append(" </if>\n"); sb.append("</lockss-config>\n"); // T T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); // T F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); // F T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); // F F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); } public void testSimpleNot() throws Exception { PropertyTree props; InputStream istr; StringBuffer sb; sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <if>\n"); sb.append(" <not>\n"); sb.append(" <test platformVersion=\"200\" />\n"); sb.append(" </not>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"test\" value=\"foo\" />\n"); sb.append(" </then>\n"); sb.append(" <else>\n"); sb.append(" <property name=\"test\" value=\"bar\" />\n"); sb.append(" </else>\n"); sb.append(" </if>\n"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); } public void testNotWithAnd() throws Exception { PropertyTree props; InputStream istr; StringBuffer sb; sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <if>\n"); sb.append(" <not>\n"); sb.append(" <and>\n"); sb.append(" <test platformVersion=\"200\" />\n"); sb.append(" <test group=\"dev\" />\n"); sb.append(" </and>\n"); sb.append(" </not>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"test\" value=\"foo\" />\n"); sb.append(" </then>\n"); sb.append(" <else>\n"); sb.append(" <property name=\"test\" value=\"bar\" />\n"); sb.append(" </else>\n"); sb.append(" </if>\n"); sb.append("</lockss-config>\n"); // T T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); // T F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); // F T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); // T F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); } public void testNotWithOr() throws Exception { PropertyTree props; InputStream istr; StringBuffer sb; sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <if>\n"); sb.append(" <not>\n"); sb.append(" <or>\n"); sb.append(" <test platformVersion=\"200\" />\n"); sb.append(" <test group=\"dev\" />\n"); sb.append(" </or>\n"); sb.append(" </not>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"test\" value=\"foo\" />\n"); sb.append(" </then>\n"); sb.append(" <else>\n"); sb.append(" <property name=\"test\" value=\"bar\" />\n"); sb.append(" </else>\n"); sb.append(" </if>\n"); sb.append("</lockss-config>\n"); // T T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); // T F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-200", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); // F T props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "dev"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("test")); // T F props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions("1.13.1", "OpenBSD CD-500", "testhost", "beta"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("test")); } /** * Test basic non-nested property getting from the static config. */ public void testGet() throws Exception { assertEquals("foo", m_props.get("a")); } /** * Test a nested property. */ public void testNestedGet() throws Exception { assertEquals("foo", m_props.get("b.c")); } /** * Test value tag (not in a list) */ public void testValueTag() throws Exception { assertEquals("bar", m_props.get("d")); } /** * Test a non-existent property. */ public void testNullValue() throws Exception { assertNull(m_props.get("this.prop.does.not.exist")); } /** * Test getting a list out of the config. */ public void testGetList() throws Exception { String s = m_props.getProperty("org.lockss.d"); assertNotNull(s); Vector<String> v = StringUtil.breakAt(s, ';', -1, true, true); Collections.sort(v); assertEquals("1", (String)v.get(0)); assertEquals("2", (String)v.get(1)); assertEquals("3", (String)v.get(2)); assertEquals("4", (String)v.get(3)); assertEquals("5", (String)v.get(4)); } /** * This test is meant to validate the test 'testListEntities()', * which is only meaningful if the XML library currently being used * chooses to split character data chunks on entity boundaries * (&amp;amp;, &amp;nbsp;, and the like). Our current library (as * of August 2004) exhibits this behavior. This test will fail if * that ever becomes false, and if this test fails, then the * 'testListEntities()' test may or may not be meaningful. */ public void testValidateListEntitiesTest() throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); StringBuffer sb = new StringBuffer(); sb.append("<test>a&amp;b&amp;c&amp;d</test>"); InputStream istr = new ReaderInputStream(new StringReader(sb.toString())); class TestHandler extends DefaultHandler { public int charCallCount = 0; public void characters(char[] ch, int start, int len) { charCallCount++; } } TestHandler handler = new TestHandler(); parser.parse(istr, handler); // Should have been called 7 times, may be library // dependant: a, &, b, &, c, &, d assertEquals(7, handler.charCallCount); } /** * Test to be sure that XML entities don't split list * entries. */ public void testListEntities() throws Exception { String s = m_props.getProperty("org.lockss.listtest"); assertNotNull(s); Vector v = StringUtil.breakAt(s, ';', -1, true, true); assertEquals(1, v.size()); assertEquals("this&should&be&one&value", v.get(0)); } public void testDaemonVersionEquals() throws Exception { assertNull(m_props.get("org.lockss.test.a")); assertEquals("foo", m_props.get("org.lockss.test.b")); } public void testDaemonVersionMax() throws Exception { assertNull(m_props.get("org.lockss.test.c")); assertEquals("foo", m_props.get("org.lockss.test.d")); } public void testDaemonVersionMin() throws Exception { assertEquals("foo", m_props.get("org.lockss.test.e")); assertNull(m_props.get("org.lockss.test.f")); } public void testDaemonVersionMaxAndMin() throws Exception { assertEquals("foo", m_props.get("org.lockss.test.g")); assertNull(m_props.get("org.lockss.test.h")); } public void testPlatformVersionEquals() throws Exception { assertEquals("foo", m_props.get("org.lockss.test.i")); assertNull(m_props.get("org.lockss.test.j")); } public void testPlatformVersionMax() throws Exception { assertNull(m_props.get("org.lockss.test.k")); assertEquals("foo", m_props.get("org.lockss.test.l")); } public void testPlatformVersionMin() throws Exception { assertEquals("foo", m_props.get("org.lockss.test.m")); assertNull(m_props.get("org.lockss.test.n")); } public void testPlatformVersionMinAndMax() throws Exception { assertEquals("foo", m_props.get("org.lockss.test.o")); assertNull(m_props.get("org.lockss.test.p")); } public void testGroupMembership() throws Exception { assertEquals("foo", m_props.get("org.lockss.test.q")); assertNull(m_props.get("org.lockss.test.r")); } public void testHostnameMembership() throws Exception { assertEquals("foo", m_props.get("org.lockss.test.s")); assertNull(m_props.get("org.lockss.test.t")); } public void testHostMembership() throws Exception { assertNull(m_props.get("org.lockss.test.platformName.linux")); assertEquals("openbsd", m_props.get("org.lockss.test.platformName.openbsd")); } public void testUnknownContionalsAreFalse() throws Exception { assertNull(m_props.get("org.lockss.test.unknown.a")); assertEquals("bar", m_props.get("org.lockss.test.unknown.b")); assertNull(m_props.get("org.lockss.test.unknown.c")); assertNull(m_props.get("org.lockss.test.unknown.d")); } public void testThenElse() { assertEquals("foo", m_props.get("org.lockss.test.u")); assertEquals("bar", m_props.get("org.lockss.test.v")); assertEquals("openbsd", m_props.get("org.lockss.test.ifelse.platformName")); } public void testConditionalCombo() throws Exception { assertEquals("bar", m_props.get("org.lockss.test.w")); assertEquals("foo", m_props.get("org.lockss.test.x")); } public void testTestNonNested() throws Exception { assertEquals("bar", m_props.get("org.lockss.test.y")); assertEquals("foo", m_props.get("org.lockss.test.z")); } public void testBooleanAnd() throws Exception { assertEquals("foo", m_props.get("org.lockss.and.a")); assertNull(m_props.get("org.lockss.and.b")); assertEquals("foo", m_props.get("org.lockss.and.c")); assertNull(m_props.get("org.lockss.and.d")); assertEquals("bar", m_props.get("org.lockss.and.e")); } public void testBooleanOr() throws Exception { assertEquals("foo", m_props.get("org.lockss.or.a")); assertNull(m_props.get("org.lockss.or.b")); assertEquals("foo", m_props.get("org.lockss.or.c")); assertNull(m_props.get("org.lockss.or.d")); assertEquals("bar", m_props.get("org.lockss.or.e")); } public void testBooleanNot() throws Exception { assertEquals("foo", m_props.get("org.lockss.not.a")); assertNull(m_props.get("org.lockss.not.b")); assertEquals("foo", m_props.get("org.lockss.not.c")); assertNull(m_props.get("org.lockss.or.d")); assertEquals("bar", m_props.get("org.lockss.not.e")); assertEquals("foo", m_props.get("org.lockss.not.f")); assertEquals("foo", m_props.get("org.lockss.not.g")); } public void testNestedIfs() throws Exception { assertEquals("foo", m_props.get("org.lockss.nestedIf.a")); assertEquals("bar", m_props.get("org.lockss.nestedIf.b")); assertEquals("baz", m_props.get("org.lockss.nestedIf.c")); assertEquals("baz", m_props.get("org.lockss.nestedIf.d")); assertEquals("quux", m_props.get("org.lockss.nestedIf.e")); assertEquals(null, m_props.get("org.lockss.nestedIf.f.control")); assertEquals(null, m_props.get("org.lockss.nestedIf.f")); } public void testNestedBoolean() throws Exception { assertEquals("foo", m_props.get("org.lockss.nested.a")); assertEquals("foo", m_props.get("org.lockss.nested.aa")); assertEquals("bar", m_props.get("org.lockss.nested.ab")); assertEquals("bar", m_props.get("org.lockss.nested.ac")); assertEquals("foo", m_props.get("org.lockss.nested.ad")); assertEquals("bar", m_props.get("org.lockss.nested.b")); assertEquals("bar", m_props.get("org.lockss.nested.c")); } /** * If any of the internal system values (daemon version, platform * version, hostname, or group) are null, all tests that depend on * them should return false. */ public void testNullHostname() throws Exception { setVersions(null, null, null, null); parseXmlProperties(); assertNull(m_props.get("org.lockss.test.s")); assertNull(m_props.get("org.lockss.test.t")); assertNull(m_props.get("org.lockss.nulltest.a")); assertEquals("bar", m_props.get("org.lockss.nulltest.b")); } public void testNullGroup() throws Exception { setVersions(null, null, null, null); parseXmlProperties(); assertNull(m_props.get("org.lockss.test.q")); assertNull(m_props.get("org.lockss.test.r")); assertNull(m_props.get("org.lockss.nulltest.c")); assertEquals("bar", m_props.get("org.lockss.nulltest.d")); } public void testNullDaemonVersion() throws Exception { setVersions(null, null, null, null); parseXmlProperties(); assertNull(m_props.get("org.lockss.test.a")); assertNull(m_props.get("org.lockss.test.b")); assertNull(m_props.get("org.lockss.nulltest.e")); assertEquals("bar", m_props.get("org.lockss.nulltest.f")); } public void testNullPlatformVersion() throws Exception { setVersions(null, null, null, null); parseXmlProperties(); assertNull(m_props.get("org.lockss.test.i")); assertNull(m_props.get("org.lockss.test.j")); assertNull(m_props.get("org.lockss.nulltest.g")); assertEquals("bar", m_props.get("org.lockss.nulltest.h")); } /* The following test comes from Issue 2790. Here's the bug: This construct resulted in machines in the test group (which are not in the prod group) not getting any of the props in the <then> clause. <if> <and> <test group="test" /> <not> <test group="prod" /> </not> </and> <then> <property name="id.initialV3PeerList"> </then> </if> */ public void testNotWithAnd2() throws Exception { PropertyTree props; InputStream istr; StringBuffer sb; sb = new StringBuffer(); sb.append("<if>\n"); sb.append(" <and>\n"); sb.append(" <test group=\"test\" />\n"); sb.append(" <not> <test group=\"prod\" /> </not>\n"); sb.append(" </and>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"result\" value=\"foo\" />\n"); sb.append(" </then>\n"); sb.append(" <else>\n"); sb.append(" <property name=\"result\" value=\"bar\" />\n"); sb.append(" </else>\n"); sb.append("</if>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("foo", props.getProperty("result")); // F, type 1 props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "prod"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("result")); // F, type 2 props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "experimental"); m_xmlPropertyLoader.loadProperties(props, istr); assertEquals("bar", props.getProperty("result")); } public void testEmptyList() throws Exception { PropertyTree props = new PropertyTree(); InputStream istr; String s; StringBuilder sb; Vector<String> vs; sb = new StringBuilder(); sb.append("<lockss-config>\n"); sb.append("<property name=\"emptyList\">"); sb.append(" <list>"); sb.append(" </list>"); sb.append("</property>"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); m_xmlPropertyLoader.loadProperties(props, istr); s = props.getProperty("emptyList"); assertEquals("", s); List<String> lst = StringUtil.breakAt(s, ';', -1, true, true); assertEmpty(lst); } public void testEmptyConfig() throws Exception { PropertyTree props = new PropertyTree(); InputStream istr; String s; StringBuilder sb; Vector<String> vs; sb = new StringBuilder(); sb.append("<lockss-config>\n"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); m_xmlPropertyLoader.loadProperties(props, istr); assertEmpty(props); } /** * This is a negative test: We should not accept "<else>" without a "<then>", or * a "<then>" after an "<else>". */ public void testElseBeforeThen() throws Exception { PropertyTree props; InputStream istr; StringBuffer sb; sb = new StringBuffer(); sb.append("<if>\n"); sb.append(" <test group=\"test\" />\n"); sb.append(" <else>\n"); sb.append(" <property name=\"result\" value=\"bar\" />\n"); sb.append(" </else>\n"); sb.append(" <then>\n"); sb.append(" <property name=\"result\" value=\"foo\" />\n"); sb.append(" </then>\n"); sb.append("</if>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); try { m_xmlPropertyLoader.loadProperties(props, istr); fail("An else before a then should cause an exception."); } catch (IllegalArgumentException e) { /* Passes test */ } } /** * Bug 2798: Add add-to-list functionality to XmlPropertyLoader. * * XML read by XmlPropertyLoader.LockssConfigHandler includes the <list> ... * </list> tag. When put inside a <property name="...">, it stores the list in * the property. * * Tom would like XML files to be able to add lists in multiple points.  The following * new action would be allowed: * * <property name="d"> * <list> * <value>1</value> * <value>2</value> * <value>3</value> * <value>4</value> * <value>5</value> * </list> * </property> * * . . . * * <property name="d"> * <list append="true"> * <value>6</value> * <value>7</value> * <value>8</value> * </list> * </property> */ public void testListAppend() throws Exception { PropertyTree props = new PropertyTree(); InputStream istr; String s; StringBuilder sb; Vector<String> vs; // Test: list with append adds the element to the series. sb = new StringBuilder(); sb.append("<lockss-config>\n"); sb.append("<property name=\"listAppend\">"); // Original list sb.append(" <list>"); sb.append(" <value>1</value>"); sb.append(" <value>2</value>"); sb.append(" </list>"); // Appended list sb.append(" <list append=\"true\">"); sb.append(" <value>3</value>"); sb.append(" <value>4</value>"); sb.append(" </list>"); sb.append("</property>"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); m_xmlPropertyLoader.loadProperties(props, istr); // Get the elements in listAppend. s = props.getProperty("listAppend"); assertNotNull(s); vs = StringUtil.breakAt(s, ';', -1, true, true); // Verify that the original elements are present. assertTrue(vs.contains("1")); assertTrue(vs.contains("2")); // Verify that the added elements are present. assertTrue(vs.contains("3")); assertTrue(vs.contains("4")); // Test: list with append adds the element to the series, with a break in the middle. sb = new StringBuilder(); // Original list sb.append("<lockss-config>\n"); sb.append("<property name=\"listAppend\">"); sb.append(" <list>"); sb.append(" <value>1</value>"); sb.append(" <value>2</value>"); sb.append(" </list>"); sb.append("</property>"); // Break in the middle. sb.append("<property name=\"foobar\">"); sb.append(" <list>"); sb.append(" <value>yarf</value>"); sb.append(" <value>yip</value>"); sb.append(" </list>"); sb.append("</property>"); // Appended list sb.append("<property name=\"listAppend\">"); sb.append(" <list append=\"true\">"); sb.append(" <value>3</value>"); sb.append(" <value>4</value>"); sb.append(" </list>"); sb.append("</property>"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); m_xmlPropertyLoader.loadProperties(props, istr); // Get the elements in listAppend. s = props.getProperty("listAppend"); assertNotNull(s); vs = StringUtil.breakAt(s, ';', -1, true, true); // Verify that the original elements are present. assertTrue(vs.contains("1")); assertTrue(vs.contains("2")); // Verify that the added elements are present. assertTrue(vs.contains("3")); assertTrue(vs.contains("4")); // Verify that the interrupting elements are NOT present. assertFalse(vs.contains("yarf")); assertFalse(vs.contains("yip")); // Test: Lists can have multiple appends sb = new StringBuilder(); sb.append("<lockss-config>\n"); sb.append("<property name=\"listAppend\">"); // Original list sb.append(" <list>"); sb.append(" <value>1</value>"); sb.append(" <value>2</value>"); sb.append(" </list>"); // Appended list 1 sb.append(" <list append=\"true\">"); sb.append(" <value>3</value>"); sb.append(" <value>4</value>"); sb.append(" <value>5</value>"); sb.append(" </list>"); // Appended list 2 sb.append(" <list append=\"true\">"); sb.append(" <value>6</value>"); sb.append(" </list>"); // Appended list 3 sb.append(" <list append=\"true\">"); sb.append(" <value>7</value>"); sb.append(" <value>8</value>"); sb.append(" <value>9</value>"); sb.append(" <value>10</value>"); sb.append(" </list>"); sb.append("</property>"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); m_xmlPropertyLoader.loadProperties(props, istr); // Get the elements in listAppend. s = props.getProperty("listAppend"); assertNotNull(s); vs = StringUtil.breakAt(s, ';', -1, true, true); // Verify that original list is present. assertTrue(vs.contains("1")); assertTrue(vs.contains("2")); // Verify that appended list 1 is present. assertTrue(vs.contains("3")); assertTrue(vs.contains("4")); assertTrue(vs.contains("5")); // Verify that appended list 2 is present. assertTrue(vs.contains("6")); // Verify that appended list 3 is present. assertTrue(vs.contains("7")); assertTrue(vs.contains("8")); assertTrue(vs.contains("9")); assertTrue(vs.contains("10")); // Test: Lists can have multiple appends, with breaks... sb = new StringBuilder(); sb.append("<lockss-config>\n"); // Original list sb.append("<property name=\"listAppend\">"); sb.append(" <list>"); sb.append(" <value>1</value>"); sb.append(" <value>2</value>"); sb.append(" </list>"); sb.append("</property>"); // Interrupting list sb.append("<property name=\"interrupt\">"); sb.append(" <list>"); sb.append(" <value>a</value>"); sb.append(" <value>b</value>"); sb.append(" </list>"); sb.append("</property>"); // Appended list 1 sb.append("<property name=\"listAppend\">"); sb.append(" <list append=\"true\">"); sb.append(" <value>3</value>"); sb.append(" <value>4</value>"); sb.append(" <value>5</value>"); sb.append(" </list>"); sb.append("</property>"); // Interrupting list with appends. sb.append("<property name=\"interrupt\">"); sb.append(" <list append=\"true\">"); sb.append(" <value>c</value>"); sb.append(" <value>d</value>"); sb.append(" </list>"); sb.append("</property>"); // Appended list 2 sb.append("<property name=\"listAppend\">"); sb.append(" <list append=\"true\">"); sb.append(" <value>6</value>"); sb.append(" </list>"); sb.append("</property>"); // Different interrupting list. sb.append("<property name=\"anotherInterrupt\">"); sb.append(" <list>"); sb.append(" <value>foo</value>"); sb.append(" <value>bar</value>"); sb.append(" </list>"); sb.append("</property>"); // Appended list 3 sb.append("<property name=\"listAppend\">"); sb.append(" <list append=\"true\">"); sb.append(" <value>7</value>"); sb.append(" <value>8</value>"); sb.append(" <value>9</value>"); sb.append(" <value>10</value>"); sb.append(" </list>"); sb.append("</property>"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); m_xmlPropertyLoader.loadProperties(props, istr); // Get the elements in listAppend. s = props.getProperty("listAppend"); assertNotNull(s); vs = StringUtil.breakAt(s, ';', -1, true, true); // Verify that original list is present. assertTrue(vs.contains("1")); assertTrue(vs.contains("2")); // Verify that appended list 1 is present. assertTrue(vs.contains("3")); assertTrue(vs.contains("4")); assertTrue(vs.contains("5")); // Verify that appended list 2 is present. assertTrue(vs.contains("6")); // Verify that appended list 3 is present. assertTrue(vs.contains("7")); assertTrue(vs.contains("8")); assertTrue(vs.contains("9")); assertTrue(vs.contains("10")); // Verify that interrupt is NOT present. assertFalse(vs.contains("a")); assertFalse(vs.contains("b")); assertFalse(vs.contains("c")); assertFalse(vs.contains("d")); // Verify that the other interrupting list is NOT present. assertFalse(vs.contains("foo")); assertFalse(vs.contains("bar")); // Test: appending to a non-existent list causes an error. sb = new StringBuilder(); sb.append("<lockss-config>\n"); sb.append("<property name=\"listAppend\">"); // Append to non-existent list. sb.append(" <list append=\"true\">"); sb.append(" <value>1</value>"); sb.append(" <value>2</value>"); sb.append(" </list>"); sb.append("</property>"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); try { m_xmlPropertyLoader.loadProperties(props, istr); fail("Appending to a non-existent list should have caused an error."); } catch (IllegalArgumentException e) { /* Passes test */ } // Test: "append=false" causes a new list to be created. sb = new StringBuilder(); sb.append("<lockss-config>\n"); sb.append("<property name=\"listAppend\">"); // Original list sb.append(" <list>"); sb.append(" <value>1</value>"); sb.append(" <value>2</value>"); sb.append(" </list>"); // NOT-Appended list sb.append(" <list append=\"false\">"); sb.append(" <value>3</value>"); sb.append(" <value>4</value>"); sb.append(" </list>"); sb.append("</property>"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); m_xmlPropertyLoader.loadProperties(props, istr); // Get the elements in listAppend. s = props.getProperty("listAppend"); assertNotNull(s); vs = StringUtil.breakAt(s, ';', -1, true, true); // Verify that the original list is not present. assertFalse(vs.contains("1")); assertFalse(vs.contains("2")); // Verify that the added elements are present. assertTrue(vs.contains("3")); assertTrue(vs.contains("4")); // Test: without "append=true", a new list is created. sb = new StringBuilder(); sb.append("<lockss-config>\n"); sb.append("<property name=\"listAppend\">"); // Original list sb.append(" <list>"); sb.append(" <value>1</value>"); sb.append(" <value>2</value>"); sb.append(" </list>"); // NOT-Appended list sb.append(" <list>"); sb.append(" <value>3</value>"); sb.append(" <value>4</value>"); sb.append(" </list>"); sb.append("</property>"); sb.append("</lockss-config>\n"); props = new PropertyTree(); istr = new ReaderInputStream(new StringReader(sb.toString())); setVersions(null, null, null, "test"); m_xmlPropertyLoader.loadProperties(props, istr); // Get the elements in listAppend. s = props.getProperty("listAppend"); assertNotNull(s); vs = StringUtil.breakAt(s, ';', -1, true, true); // Verify that the original list is not present. assertFalse(vs.contains("1")); assertFalse(vs.contains("2")); // Verify that the added elements are present. assertTrue(vs.contains("3")); assertTrue(vs.contains("4")); } /** * Test loading title database information. */ public void testLoadTdb() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<lockss-config>\n"); sb.append(" <property name=\"org.lockss\">\n"); sb.append(" <property name=\"title\">\n"); sb.append(" <property name=\"BioOneTheAmericanMidlandNaturalist139\">\n"); sb.append(" <property name=\"attributes.publisher\" value=\"University of Notre Dame\" />\n"); sb.append(" <property name=\"issn\" value=\"0003-0031\" />\n"); sb.append(" <property name=\"journalTitle\" value=\"The American Midland Naturalist\" />\n"); sb.append(" <property name=\"journalId\" value=\"0003-0031\" />\n"); sb.append(" <property name=\"title\" value=\"The American Midland Naturalist Volume 139\" />\n"); sb.append(" <property name=\"plugin\" value=\"org.lockss.plugin.bioone.BioOnePlugin\" />\n"); sb.append(" <property name=\"param.1\">\n"); sb.append(" <property name=\"key\" value=\"base_url\" />\n"); sb.append(" <property name=\"value\" value=\"http: sb.append(" </property>\n"); sb.append(" <property name=\"param.2\">\n"); sb.append(" <property name=\"key\" value=\"journal_id\" />\n"); sb.append(" <property name=\"value\" value=\"0003-0031\" />\n"); sb.append(" </property>\n"); sb.append(" <property name=\"param.3\">\n"); sb.append(" <property name=\"key\" value=\"volume\" />\n"); sb.append(" <property name=\"value\" value=\"139\" />\n"); sb.append(" </property>\n"); sb.append(" <property name=\"param.4\">\n"); sb.append(" <property name=\"key\" value=\"pub_down\" />\n"); sb.append(" <property name=\"value\" value=\"true\" />\n"); sb.append(" </property>\n"); sb.append(" </property>\n"); sb.append(" </property>\n"); sb.append(" </property>\n"); sb.append("</lockss-config>\n"); InputStream istr = new ReaderInputStream(new StringReader(sb.toString())); PropertyTree props = new PropertyTree(); m_xmlPropertyLoader.loadProperties(props, istr); assertFalse(props.isEmpty()); Object prop = props.get("org.lockss.title.BioOneTheAmericanMidlandNaturalist139.param.3.value"); assertNotNull(prop); assertEquals("139", prop); istr = new ReaderInputStream(new StringReader(sb.toString())); props = new PropertyTree(); Tdb tdb = new Tdb(); m_xmlPropertyLoader.loadProperties(props, tdb, istr); assertTrue(props.isEmpty()); assertFalse(tdb.isEmpty()); TdbPublisher pub = tdb.getTdbPublisher("University of Notre Dame"); assertNotNull(pub); TdbTitle title = pub.getTdbTitleById("0003-0031"); assertNotNull(title); Collection<TdbAu> aus = title.getTdbAusByName("The American Midland Naturalist Volume 139"); assertEquals(1, aus.size()); String volume = aus.iterator().next().getParam("volume"); assertEquals("139", volume); } /** * Set default values for testing conditionals. */ private void setDefaultVersions() { ((MockXmlPropertyLoader)m_xmlPropertyLoader).setVersions("1.2.8", "OpenBSD CD-135", "testhost", "beta"); } /** * Convenience method for overriding conditional values. */ private void setVersions(String daemonVersion, String platformVersion, String hostname, String group) { ((MockXmlPropertyLoader)m_xmlPropertyLoader).setVersions(daemonVersion, platformVersion, hostname, group); } }
package com.apptentive.android.sdk; import android.app.Application; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.text.TextUtils; import android.webkit.MimeTypeMap; import com.apptentive.android.sdk.conversation.Conversation; import com.apptentive.android.sdk.model.CommerceExtendedData; import com.apptentive.android.sdk.model.ExtendedData; import com.apptentive.android.sdk.model.LocationExtendedData; import com.apptentive.android.sdk.model.StoredFile; import com.apptentive.android.sdk.model.TimeExtendedData; import com.apptentive.android.sdk.module.engagement.EngagementModule; import com.apptentive.android.sdk.module.messagecenter.MessageManager; import com.apptentive.android.sdk.module.messagecenter.UnreadMessagesListener; import com.apptentive.android.sdk.model.CompoundMessage; import com.apptentive.android.sdk.module.metric.MetricModule; import com.apptentive.android.sdk.module.rating.IRatingProvider; import com.apptentive.android.sdk.module.survey.OnSurveyFinishedListener; import com.apptentive.android.sdk.util.Constants; import com.apptentive.android.sdk.util.Util; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Map; /** * This class contains the complete public API for accessing Apptentive features from within your app. */ public class Apptentive { /** * Must be called from the {@link Application#onCreate()} method in the {@link Application} object defined in your app's manifest. * * @param application The {@link Application} object for this app. */ public static void register(Application application) { Apptentive.register(application, null, null); } public static void register(Application application, String apptentiveKey, String apptentiveSignature) { register(application, apptentiveKey, apptentiveSignature, null); } private static void register(Application application, String apptentiveKey, String apptentiveSignature, String serverUrl) { ApptentiveLog.i("Registering Apptentive."); ApptentiveInternal.createInstance(application, apptentiveKey, apptentiveSignature, serverUrl); } //region Global Data Methods /** * Sets the user's email address. This email address will be sent to the Apptentive server to allow out of app * communication, and to help provide more context about this user. This email will be the definitive email address * for this user, unless one is provided directly by the user through an Apptentive UI. Calls to this method are * idempotent. Calls to this method will overwrite any previously entered email, so if you don't want to overwrite * the email provided by the user, make sure to check the value with {@link #getPersonEmail()} before you call this method. * * @param email The user's email address. */ public static void setPersonEmail(String email) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { // FIXME: Make sure Person object diff is sent. conversation.getPerson().setEmail(email); } } } /** * Retrieves the user's email address. This address may be set via {@link #setPersonEmail(String)}, * or by the user through Message Center. * * @return The person's email if set, else null. */ public static String getPersonEmail() { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { return conversation.getPerson().getEmail(); } } return null; } /** * Sets the user's name. This name will be sent to the Apptentive server and displayed in conversations you have * with this person. This name will be the definitive username for this user, unless one is provided directly by the * user through an Apptentive UI. Calls to this method are idempotent. Calls to this method will overwrite any * previously entered email, so if you don't want to overwrite the email provided by the user, make sure to check * the value with {@link #getPersonName()} before you call this method. * * @param name The user's name. */ public static void setPersonName(String name) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { // FIXME: Make sure Person object diff is sent. conversation.getPerson().setName(name); } } } /** * Retrieves the user's name. This name may be set via {@link #setPersonName(String)}, * or by the user through Message Center. * * @return The person's name if set, else null. */ public static String getPersonName() { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { return conversation.getPerson().getName(); } } return null; } /** * Add a custom data String to the Device. Custom data will be sent to the server, is displayed * in the Conversation view, and can be used in Interaction targeting. Calls to this method are * idempotent. * * @param key The key to store the data under. * @param value A String value. */ public static void addCustomDeviceData(String key, String value) { if (ApptentiveInternal.isApptentiveRegistered()) { if (value != null) { value = value.trim(); } Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getDevice().getCustomData().put(key, value); } } } /** * Add a custom data Number to the Device. Custom data will be sent to the server, is displayed * in the Conversation view, and can be used in Interaction targeting. Calls to this method are * idempotent. * * @param key The key to store the data under. * @param value A Number value. */ public static void addCustomDeviceData(String key, Number value) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getDevice().getCustomData().put(key, value); } } } /** * Add a custom data Boolean to the Device. Custom data will be sent to the server, is displayed * in the Conversation view, and can be used in Interaction targeting. Calls to this method are * idempotent. * * @param key The key to store the data under. * @param value A Boolean value. */ public static void addCustomDeviceData(String key, Boolean value) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getDevice().getCustomData().put(key, value); } } } private static void addCustomDeviceData(String key, Version version) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getDevice().getCustomData().put(key, version); } } } private static void addCustomDeviceData(String key, DateTime dateTime) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getDevice().getCustomData().put(key, dateTime); } } } /** * Remove a piece of custom data from the device. Calls to this method are idempotent. * * @param key The key to remove. */ public static void removeCustomDeviceData(String key) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getDevice().getCustomData().remove(key); } } } /** * Add a custom data String to the Person. Custom data will be sent to the server, is displayed * in the Conversation view, and can be used in Interaction targeting. Calls to this method are * idempotent. * * @param key The key to store the data under. * @param value A String value. */ public static void addCustomPersonData(String key, String value) { if (ApptentiveInternal.isApptentiveRegistered()) { if (value != null) { value = value.trim(); } Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getPerson().getCustomData().put(key, value); } } } /** * Add a custom data Number to the Person. Custom data will be sent to the server, is displayed * in the Conversation view, and can be used in Interaction targeting. Calls to this method are * idempotent. * * @param key The key to store the data under. * @param value A Number value. */ public static void addCustomPersonData(String key, Number value) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getPerson().getCustomData().put(key, value); } } } /** * Add a custom data Boolean to the Person. Custom data will be sent to the server, is displayed * in the Conversation view, and can be used in Interaction targeting. Calls to this method are * idempotent. * * @param key The key to store the data under. * @param value A Boolean value. */ public static void addCustomPersonData(String key, Boolean value) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getPerson().getCustomData().put(key, value); } } } private static void addCustomPersonData(String key, Version version) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getPerson().getCustomData().put(key, version); } } } private static void addCustomPersonData(String key, DateTime dateTime) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getPerson().getCustomData().remove(key); } } } /** * Remove a piece of custom data from the Person. Calls to this method are idempotent. * * @param key The key to remove. */ public static void removeCustomPersonData(String key) { if (ApptentiveInternal.isApptentiveRegistered()) { Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getPerson().getCustomData().remove(key); } } } //endregion //region Third Party Integrations /** * For internal use only. */ public static final String INTEGRATION_PUSH_TOKEN = "token"; /** * Call {@link #setPushNotificationIntegration(int, String)} with this value to allow Apptentive to send pushes * to this device without a third party push provider. Requires a valid GCM configuration. */ public static final int PUSH_PROVIDER_APPTENTIVE = 0; /** * Call {@link #setPushNotificationIntegration(int, String)} with this value to allow Apptentive to send pushes * to this device through your existing Parse Push integration. Requires a valid Parse integration. */ public static final int PUSH_PROVIDER_PARSE = 1; /** * Call {@link #setPushNotificationIntegration(int, String)} with this value to allow Apptentive to send pushes * to this device through your existing Urban Airship Push integration. Requires a valid Urban * Airship Push integration. */ public static final int PUSH_PROVIDER_URBAN_AIRSHIP = 2; /** * Call {@link #setPushNotificationIntegration(int, String)} with this value to allow Apptentive to send pushes * to this device through your existing Amazon AWS SNS integration. Requires a valid Amazon AWS SNS * integration. */ public static final int PUSH_PROVIDER_AMAZON_AWS_SNS = 3; public static void setPushNotificationIntegration(int pushProvider, String token) { if (!ApptentiveInternal.isApptentiveRegistered()) { return; } // Store the push stuff globally SharedPreferences prefs = ApptentiveInternal.getInstance().getGlobalSharedPrefs(); prefs.edit().putInt(Constants.PREF_KEY_PUSH_PROVIDER, pushProvider) .putString(Constants.PREF_KEY_PUSH_TOKEN, token) .apply(); // Also set it on the active Conversation, if there is one. Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.setPushIntegration(pushProvider, token); } } //endregion //region Push Notifications /** * Determines whether this Intent is a push notification sent from Apptentive. * * @param intent The received {@link Intent} you received in your BroadcastReceiver. * @return True if the Intent came from, and should be handled by Apptentive. */ public static boolean isApptentivePushNotification(Intent intent) { if (!ApptentiveInternal.checkRegistered()) { return false; } return ApptentiveInternal.getApptentivePushNotificationData(intent) != null; } /** * Determines whether this Bundle came from an Apptentive push notification. This method is used with Urban Airship * integrations. * * @param bundle The push payload bundle passed to GCM onMessageReceived() callback * @return True if the push came from, and should be handled by Apptentive. */ public static boolean isApptentivePushNotification(Bundle bundle) { if (!ApptentiveInternal.checkRegistered()) { return false; } return ApptentiveInternal.getApptentivePushNotificationData(bundle) != null; } /** * Determines whether push payload data came from an Apptentive push notification. * * @param data The push payload data obtained through FCM's RemoteMessage.getData(), when using FCM * @return True if the push came from, and should be handled by Apptentive. */ public static boolean isApptentivePushNotification(Map<String, String> data) { if (!ApptentiveInternal.checkRegistered()) { return false; } return ApptentiveInternal.getApptentivePushNotificationData(data) != null; } /** * <p>Use this method in your push receiver to build a pending Intent when an Apptentive push * notification is received. Pass the generated PendingIntent to * {@link android.support.v4.app.NotificationCompat.Builder#setContentIntent} to allow Apptentive * to display Interactions such as Message Center. Calling this method for a push {@link Intent} that did * not come from Apptentive will return a null object. If you receive a null object, your app will * need to handle this notification itself.</p> * <p>This is the method you will likely need if you integrated using:</p> * <ul> * <li>GCM</li> * <li>AWS SNS</li> * <li>Parse</li> * </ul> * * @param intent An {@link Intent} containing the Apptentive Push data. Pass in what you receive * in the Service or BroadcastReceiver that is used by your chosen push provider. * @return a valid {@link PendingIntent} to launch an Apptentive Interaction if the push data came from Apptentive, or null. */ public static PendingIntent buildPendingIntentFromPushNotification(@NonNull Intent intent) { if (!ApptentiveInternal.checkRegistered()) { return null; } String apptentivePushData = ApptentiveInternal.getApptentivePushNotificationData(intent); return ApptentiveInternal.generatePendingIntentFromApptentivePushData(apptentivePushData); } /** * <p>Use this method in your push receiver to build a pending Intent when an Apptentive push * notification is received. Pass the generated PendingIntent to * {@link android.support.v4.app.NotificationCompat.Builder#setContentIntent} to allow Apptentive * to display Interactions such as Message Center. Calling this method for a push {@link Bundle} that * did not come from Apptentive will return a null object. If you receive a null object, your app * will need to handle this notification itself.</p> * <p>This is the method you will likely need if you integrated using:</p> * <ul> * <li>Urban Airship</li> * </ul> * * @param bundle A {@link Bundle} containing the Apptentive Push data. Pass in what you receive in * the the Service or BroadcastReceiver that is used by your chosen push provider. * @return a valid {@link PendingIntent} to launch an Apptentive Interaction if the push data came from Apptentive, or null. */ public static PendingIntent buildPendingIntentFromPushNotification(@NonNull Bundle bundle) { if (!ApptentiveInternal.checkRegistered()) { return null; } String apptentivePushData = ApptentiveInternal.getApptentivePushNotificationData(bundle); return ApptentiveInternal.generatePendingIntentFromApptentivePushData(apptentivePushData); } /** * <p>Use this method in your push receiver to build a pending Intent when an Apptentive push * notification is received. Pass the generated PendingIntent to * {@link android.support.v4.app.NotificationCompat.Builder#setContentIntent} to allow Apptentive * to display Interactions such as Message Center. Calling this method for a push {@link Bundle} that * did not come from Apptentive will return a null object. If you receive a null object, your app * will need to handle this notification itself.</p> * <p>This is the method you will likely need if you integrated using:</p> * <ul> * <li>Firebase Cloud Messaging (FCM)</li> * </ul> * * @param data A {@link Map}&lt;{@link String},{@link String}&gt; containing the Apptentive Push * data. Pass in what you receive in the the Service or BroadcastReceiver that is * used by your chosen push provider. * @return a valid {@link PendingIntent} to launch an Apptentive Interaction if the push data came from Apptentive, or null. */ public static PendingIntent buildPendingIntentFromPushNotification(@NonNull Map<String, String> data) { if (!ApptentiveInternal.checkRegistered()) { return null; } String apptentivePushData = ApptentiveInternal.getApptentivePushNotificationData(data); return ApptentiveInternal.generatePendingIntentFromApptentivePushData(apptentivePushData); } /** * Use this method in your push receiver to get the notification title you can use to construct a * {@link android.app.Notification} object. * * @param intent An {@link Intent} containing the Apptentive Push data. Pass in what you receive * in the Service or BroadcastReceiver that is used by your chosen push provider. * @return a String value, or null. */ public static String getTitleFromApptentivePush(Intent intent) { if (!ApptentiveInternal.checkRegistered()) { return null; } if (intent != null) { return getTitleFromApptentivePush(intent.getExtras()); } return null; } /** * Use this method in your push receiver to get the notification body text you can use to * construct a {@link android.app.Notification} object. * * @param intent An {@link Intent} containing the Apptentive Push data. Pass in what you receive * in the Service or BroadcastReceiver that is used by your chosen push provider. * @return a String value, or null. */ public static String getBodyFromApptentivePush(Intent intent) { if (!ApptentiveInternal.checkRegistered()) { return null; } if (intent != null) { return getBodyFromApptentivePush(intent.getExtras()); } return null; } /** * Use this method in your push receiver to get the notification title you can use to construct a * {@link android.app.Notification} object. * * @param bundle A {@link Bundle} containing the Apptentive Push data. Pass in what you receive in * the the Service or BroadcastReceiver that is used by your chosen push provider. * @return a String value, or null. */ public static String getTitleFromApptentivePush(Bundle bundle) { if (!ApptentiveInternal.checkRegistered()) { return null; } if (bundle == null) { return null; } if (bundle.containsKey(ApptentiveInternal.TITLE_DEFAULT)) { return bundle.getString(ApptentiveInternal.TITLE_DEFAULT); } if (bundle.containsKey(ApptentiveInternal.PUSH_EXTRA_KEY_PARSE)) { String parseDataString = bundle.getString(ApptentiveInternal.PUSH_EXTRA_KEY_PARSE); if (parseDataString != null) { try { JSONObject parseJson = new JSONObject(parseDataString); return parseJson.optString(ApptentiveInternal.TITLE_DEFAULT, null); } catch (JSONException e) { return null; } } } else if (bundle.containsKey(ApptentiveInternal.PUSH_EXTRA_KEY_UA)) { Bundle uaPushBundle = bundle.getBundle(ApptentiveInternal.PUSH_EXTRA_KEY_UA); if (uaPushBundle == null) { return null; } return uaPushBundle.getString(ApptentiveInternal.TITLE_DEFAULT); } return null; } /** * Use this method in your push receiver to get the notification body text you can use to * construct a {@link android.app.Notification} object. * * @param bundle A {@link Bundle} containing the Apptentive Push data. Pass in what you receive in * the the Service or BroadcastReceiver that is used by your chosen push provider. * @return a String value, or null. */ public static String getBodyFromApptentivePush(Bundle bundle) { if (!ApptentiveInternal.checkRegistered()) { return null; } if (bundle == null) { return null; } if (bundle.containsKey(ApptentiveInternal.BODY_DEFAULT)) { return bundle.getString(ApptentiveInternal.BODY_DEFAULT); } if (bundle.containsKey(ApptentiveInternal.PUSH_EXTRA_KEY_PARSE)) { String parseDataString = bundle.getString(ApptentiveInternal.PUSH_EXTRA_KEY_PARSE); if (parseDataString != null) { try { JSONObject parseJson = new JSONObject(parseDataString); return parseJson.optString(ApptentiveInternal.BODY_PARSE, null); } catch (JSONException e) { return null; } } } else if (bundle.containsKey(ApptentiveInternal.PUSH_EXTRA_KEY_UA)) { Bundle uaPushBundle = bundle.getBundle(ApptentiveInternal.PUSH_EXTRA_KEY_UA); if (uaPushBundle == null) { return null; } return uaPushBundle.getString(ApptentiveInternal.BODY_UA); } else if (bundle.containsKey(ApptentiveInternal.BODY_UA)) { return bundle.getString(ApptentiveInternal.BODY_UA); } return null; } /** * Use this method in your push receiver to get the notification title you can use to construct a * {@link android.app.Notification} object. * * @param data A {@link Map}&lt;{@link String},{@link String}&gt; containing the Apptentive Push * data. Pass in what you receive in the the Service or BroadcastReceiver that is * used by your chosen push provider. * @return a String value, or null. */ public static String getTitleFromApptentivePush(Map<String, String> data) { if (!ApptentiveInternal.checkRegistered()) { return null; } if (data == null) { return null; } return data.get(ApptentiveInternal.TITLE_DEFAULT); } /** * Use this method in your push receiver to get the notification body text you can use to * construct a {@link android.app.Notification} object. * * @param data A {@link Map}&lt;{@link String},{@link String}&gt; containing the Apptentive Push * data. Pass in what you receive in the the Service or BroadcastReceiver that is * used by your chosen push provider. * @return a String value, or null. */ public static String getBodyFromApptentivePush(Map<String, String> data) { if (!ApptentiveInternal.checkRegistered()) { return null; } if (data == null) { return null; } return data.get(ApptentiveInternal.BODY_DEFAULT); } //endregion //region Rating /** * Use this to choose where to send the user when they are prompted to rate the app. This should be the same place * that the app was downloaded from. * * @param ratingProvider A {@link IRatingProvider} value. */ public static void setRatingProvider(IRatingProvider ratingProvider) { if (ApptentiveInternal.isApptentiveRegistered()) { ApptentiveInternal.getInstance().setRatingProvider(ratingProvider); } } /** * If there are any properties that your {@link IRatingProvider} implementation requires, populate them here. This * is not currently needed with the Google Play and Amazon Appstore IRatingProviders. * * @param key A String * @param value A String */ public static void putRatingProviderArg(String key, String value) { if (ApptentiveInternal.isApptentiveRegistered()) { ApptentiveInternal.getInstance().putRatingProviderArg(key, value); } } //endregion //region Message Center /** * Opens the Apptentive Message Center UI Activity * * @param context The context from which to launch the Message Center * @return true if Message Center was shown, else false. */ public static boolean showMessageCenter(Context context) { return showMessageCenter(context, null); } /** * Opens the Apptentive Message Center UI Activity, and allows custom data to be sent with the next message the user * sends. If the user sends multiple messages, this data will only be sent with the first message sent after this * method is invoked. Additional invocations of this method with custom data will repeat this process. * * @param context The context from which to launch the Message Center. This should be an * Activity, except in rare cases where you don't have access to one, in which * case Apptentive Message Center will launch in a new task. * @param customData A Map of String keys to Object values. Objects may be Strings, Numbers, or Booleans. * If any message is sent by the Person, this data is sent with it, and then * cleared. If no message is sent, this data is discarded. * @return true if Message Center was shown, else false. */ public static boolean showMessageCenter(Context context, Map<String, Object> customData) { try { if (!ApptentiveInternal.isConversationActive()) { ApptentiveLog.v(ApptentiveLogTag.MESSAGES, "No active Conversation."); return false; } return ApptentiveInternal.getInstance().showMessageCenterInternal(context, customData); } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.showMessageCenter()", e); MetricModule.sendError(e, null, null); } return false; } /** * Our SDK must connect to our server at least once to download initial configuration for Message * Center. Call this method to see whether or not Message Center can be displayed. * * @return true if a call to {@link #showMessageCenter(Context)} will display Message Center, else false. */ public static boolean canShowMessageCenter() { try { if (!ApptentiveInternal.isConversationActive()) { ApptentiveLog.v(ApptentiveLogTag.MESSAGES, "No active Conversation."); return false; } return ApptentiveInternal.getInstance().canShowMessageCenterInternal(); } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.canShowMessageCenter()", e); MetricModule.sendError(e, null, null); } return false; } /** * Set one and only listener to be notified when the number of unread messages in the Message Center changes. * if the app calls this method to set up a custom listener, the apptentive unread message badge, also an UnreadMessagesListener, * won't get notification. Please use {@link #addUnreadMessagesListener(UnreadMessagesListener)} instead. * * @param listener An UnreadMessagesListener that you instantiate. Pass null to remove existing listener. * Do not pass in an anonymous class, such as setUnreadMessagesListener(new UnreadMessagesListener() {...}). * Instead, create your listener as an instance variable and pass that in. This * allows us to keep a weak reference to avoid memory leaks. */ @Deprecated public static void setUnreadMessagesListener(UnreadMessagesListener listener) { try { if (!ApptentiveInternal.isConversationActive()) { ApptentiveLog.v(ApptentiveLogTag.MESSAGES, "No active Conversation."); return; } ApptentiveInternal.getInstance().getMessageManager().setHostUnreadMessagesListener(listener); } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.setUnreadMessagesListener()", e); MetricModule.sendError(e, null, null); } } /** * Add a listener to be notified when the number of unread messages in the Message Center changes. * * @param listener An UnreadMessagesListener that you instantiate. Do not pass in an anonymous class. * Instead, create your listener as an instance variable and pass that in. This * allows us to keep a weak reference to avoid memory leaks. */ public static void addUnreadMessagesListener(UnreadMessagesListener listener) { try { if (!ApptentiveInternal.isConversationActive()) { ApptentiveLog.v(ApptentiveLogTag.MESSAGES, "No active Conversation."); return; } Conversation conversation = ApptentiveInternal.getInstance().getConversation(); if (conversation != null) { conversation.getMessageManager().addHostUnreadMessagesListener(listener); } } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.addUnreadMessagesListener()", e); MetricModule.sendError(e, null, null); } } /** * Returns the number of unread messages in the Message Center. * * @return The number of unread messages. */ public static int getUnreadMessageCount() { try { if (!ApptentiveInternal.isConversationActive()) { ApptentiveLog.v(ApptentiveLogTag.MESSAGES, "No active Conversation."); return 0; } Conversation conversation = ApptentiveInternal.getInstance().getConversation(); return conversation.getMessageManager().getUnreadMessageCount(); } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.getUnreadMessageCount()", e); MetricModule.sendError(e, null, null); } return 0; } /** * Sends a text message to the server. This message will be visible in the conversation view on the server, but will * not be shown in the client's Message Center. * * @param text The message you wish to send. */ public static void sendAttachmentText(String text) { try { if (!ApptentiveInternal.isConversationActive()) { ApptentiveLog.i(ApptentiveLogTag.MESSAGES, "Can't send attachment: No active Conversation."); return; } Conversation conversation = ApptentiveInternal.getInstance().getConversation(); CompoundMessage message = new CompoundMessage(); message.setBody(text); message.setRead(true); message.setHidden(true); message.setSenderId(conversation.getPerson().getId()); message.setAssociatedFiles(null); MessageManager mgr = conversation.getMessageManager(); if (mgr != null) { mgr.sendMessage(message); } } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.sendAttachmentText(String)", e); MetricModule.sendError(e, null, null); } } /** * Sends a file to the server. This file will be visible in the conversation view on the server, but will not be shown * in the client's Message Center. A local copy of this file will be made until the message is transmitted, at which * point the temporary file will be deleted. * * @param uri The URI of the local resource file. */ public static void sendAttachmentFile(String uri) { try { if (!ApptentiveInternal.isConversationActive()) { ApptentiveLog.i(ApptentiveLogTag.MESSAGES, "Can't send attachment: No active Conversation."); return; } if (TextUtils.isEmpty(uri)) { return; } Conversation conversation = ApptentiveInternal.getInstance().getConversation(); CompoundMessage message = new CompoundMessage(); // No body, just attachment message.setBody(null); message.setRead(true); message.setHidden(true); message.setSenderId(conversation.getPerson().getId()); ArrayList<StoredFile> attachmentStoredFiles = new ArrayList<StoredFile>(); /* Make a local copy in the cache dir. By default the file name is "apptentive-api-file + nonce" * If original uri is known, the name will be taken from the original uri */ Context context = ApptentiveInternal.getInstance().getApplicationContext(); String localFilePath = Util.generateCacheFilePathFromNonceOrPrefix(context, message.getNonce(), Uri.parse(uri).getLastPathSegment()); String mimeType = Util.getMimeTypeFromUri(context, Uri.parse(uri)); MimeTypeMap mime = MimeTypeMap.getSingleton(); String extension = mime.getExtensionFromMimeType(mimeType); // If we can't get the mime type from the uri, try getting it from the extension. if (extension == null) { extension = MimeTypeMap.getFileExtensionFromUrl(uri); } if (mimeType == null && extension != null) { mimeType = mime.getMimeTypeFromExtension(extension); } if (!TextUtils.isEmpty(extension)) { localFilePath += "." + extension; } StoredFile storedFile = Util.createLocalStoredFile(uri, localFilePath, mimeType); if (storedFile == null) { return; } storedFile.setId(message.getNonce()); attachmentStoredFiles.add(storedFile); message.setAssociatedFiles(attachmentStoredFiles); MessageManager mgr = ApptentiveInternal.getInstance().getMessageManager(); if (mgr != null) { mgr.sendMessage(message); } } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.sendAttachmentFile(String)", e); MetricModule.sendError(e, null, null); } } /** * Sends a file to the server. This file will be visible in the conversation view on the server, but will not be shown * in the client's Message Center. A local copy of this file will be made until the message is transmitted, at which * point the temporary file will be deleted. * * @param content A byte array of the file contents. * @param mimeType The mime type of the file. */ public static void sendAttachmentFile(byte[] content, String mimeType) { try { if (!ApptentiveInternal.isConversationActive()) { ApptentiveLog.i(ApptentiveLogTag.MESSAGES, "Can't send attachment: No active Conversation."); return; } ByteArrayInputStream is = null; try { is = new ByteArrayInputStream(content); sendAttachmentFile(is, mimeType); } finally { Util.ensureClosed(is); } } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.sendAttachmentFile(byte[], String)", e); MetricModule.sendError(e, null, null); } } /** * Sends a file to the server. This file will be visible in the conversation view on the server, but will not be shown * in the client's Message Center. A local copy of this file will be made until the message is transmitted, at which * point the temporary file will be deleted. * * @param is An InputStream from the desired file. * @param mimeType The mime type of the file. */ public static void sendAttachmentFile(InputStream is, String mimeType) { try { if (!ApptentiveInternal.isConversationActive()) { ApptentiveLog.i(ApptentiveLogTag.MESSAGES, "Can't send attachment: No active Conversation."); return; } if (is == null) { return; } Conversation conversation = ApptentiveInternal.getInstance().getConversation(); CompoundMessage message = new CompoundMessage(); // No body, just attachment message.setBody(null); message.setRead(true); message.setHidden(true); message.setSenderId(conversation.getPerson().getId()); ArrayList<StoredFile> attachmentStoredFiles = new ArrayList<StoredFile>(); String localFilePath = Util.generateCacheFilePathFromNonceOrPrefix(ApptentiveInternal.getInstance().getApplicationContext(), message.getNonce(), null); String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); if (!TextUtils.isEmpty(extension)) { localFilePath += "." + extension; } // When created from InputStream, there is no source file uri or path, thus just use the cache file path StoredFile storedFile = Util.createLocalStoredFile(is, localFilePath, localFilePath, mimeType); if (storedFile == null) { return; } storedFile.setId(message.getNonce()); attachmentStoredFiles.add(storedFile); message.setAssociatedFiles(attachmentStoredFiles); ApptentiveInternal.getInstance().getMessageManager().sendMessage(message); } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.sendAttachmentFile(InputStream, String)", e); MetricModule.sendError(e, null, null); } } //endregion /** * This method takes a unique event string, stores a record of that event having been visited, determines * if there is an interaction that is able to run for this event, and then runs it. If more than one interaction * can run, then the most appropriate interaction takes precedence. Only one interaction at most will run per * invocation of this method. * * @param context The context from which to launch the Interaction. This should be an * Activity, except in rare cases where you don't have access to one, in which * case Apptentive Interactions will launch in a new task. * @param event A unique String representing the line this method is called on. For instance, you may want to have * the ability to target interactions to run after the user uploads a file in your app. You may then * call <strong><code>engage(context, "finished_upload");</code></strong> * @return true if the an interaction was shown, else false. */ public static synchronized boolean engage(Context context, String event) { return EngagementModule.engage(context, "local", "app", null, event, null, null, (ExtendedData[]) null); } /** * This method takes a unique event string, stores a record of that event having been visited, determines * if there is an interaction that is able to run for this event, and then runs it. If more than one interaction * can run, then the most appropriate interaction takes precedence. Only one interaction at most will run per * invocation of this method. * * @param context The context from which to launch the Interaction. This should be an * Activity, except in rare cases where you don't have access to one, in which * case Apptentive Interactions will launch in a new task. * @param event A unique String representing the line this method is called on. For instance, you may want to have * the ability to target interactions to run after the user uploads a file in your app. You may then * call <strong><code>engage(context, "finished_upload");</code></strong> * @param customData A Map of String keys to Object values. Objects may be Strings, Numbers, or Booleans. This data * is sent to the server for tracking information in the context of the engaged Event. * @return true if the an interaction was shown, else false. */ public static synchronized boolean engage(Context context, String event, Map<String, Object> customData) { return EngagementModule.engage(context, "local", "app", null, event, null, customData, (ExtendedData[]) null); } /** * This method takes a unique event string, stores a record of that event having been visited, determines * if there is an interaction that is able to run for this event, and then runs it. If more than one interaction * can run, then the most appropriate interaction takes precedence. Only one interaction at most will run per * invocation of this method. * * @param context The context from which to launch the Interaction. This should be an * Activity, except in rare cases where you don't have access to one, in which * case Apptentive Interactions will launch in a new task. * @param event A unique String representing the line this method is called on. For instance, you may want to have * the ability to target interactions to run after the user uploads a file in your app. You may then * call <strong><code>engage(context, "finished_upload");</code></strong> * @param customData A Map of String keys to Object values. Objects may be Strings, Numbers, or Booleans. This data * is sent to the server for tracking information in the context of the engaged Event. * @param extendedData An array of ExtendedData objects. ExtendedData objects used to send structured data that has * specific meaning to the server. By using an {@link ExtendedData} object instead of arbitrary * customData, special meaning can be derived. Supported objects include {@link TimeExtendedData}, * {@link LocationExtendedData}, and {@link CommerceExtendedData}. Include each type only once. * @return true if the an interaction was shown, else false. */ public static synchronized boolean engage(Context context, String event, Map<String, Object> customData, ExtendedData... extendedData) { return EngagementModule.engage(context, "local", "app", null, event, null, customData, extendedData); } /** * @param event A unique String representing the line this method is called on. For instance, you may want to have * the ability to target interactions to run after the user uploads a file in your app. You may then * call <strong><code>engage(context, "finished_upload");</code></strong> * @return true if an immediate call to engage() with the same event name would result in an Interaction being displayed, otherwise false. * @deprecated Use {@link #canShowInteraction(String)}() instead. The behavior is identical. Only the name has changed. */ public static synchronized boolean willShowInteraction(String event) { return canShowInteraction(event); } /** * This method can be used to determine if a call to one of the <strong><code>engage()</code></strong> methods such as * {@link #engage(Context, String)} using the same event name will * result in the display of an Interaction. This is useful if you need to know whether an Interaction will be * displayed before you create a UI Button, etc. * * @param event A unique String representing the line this method is called on. For instance, you may want to have * the ability to target interactions to run after the user uploads a file in your app. You may then * call <strong><code>engage(activity, "finished_upload");</code></strong> * @return true if an immediate call to engage() with the same event name would result in an Interaction being displayed, otherwise false. */ public static synchronized boolean canShowInteraction(String event) { try { if (ApptentiveInternal.isConversationActive()) { return EngagementModule.canShowInteraction("local", "app", event); } } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.canShowInteraction()", e); MetricModule.sendError(e, null, null); } return false; } /** * Pass in a listener. The listener will be called whenever a survey is finished. * Do not pass in an anonymous class, such as setOnSurveyFinishedListener(new OnSurveyFinishedListener() {...}). * Instead, create your listener as an instance variable and pass that in. This allows us to keep * a weak reference to avoid memory leaks. * * @param listener The {@link com.apptentive.android.sdk.module.survey.OnSurveyFinishedListener} listener * to call when the survey is finished. */ public static void setOnSurveyFinishedListener(OnSurveyFinishedListener listener) { try { ApptentiveInternal internal = ApptentiveInternal.getInstance(); if (internal != null) { internal.setOnSurveyFinishedListener(listener); } } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.setOnSurveyFinishedListener()", e); MetricModule.sendError(e, null, null); } } //region Login/Logout /** * Starts login process asynchronously. This call returns immediately. */ public static void login(String token, LoginCallback callback) { try { if (token == null) { if (callback != null) { callback.onLoginFail("token is null"); } return; } final ApptentiveInternal instance = ApptentiveInternal.getInstance(); if (instance == null) { ApptentiveLog.e("Unable to login: Apptentive instance is not properly initialized"); if (callback != null) { callback.onLoginFail("Apptentive instance is not properly initialized"); } } else { ApptentiveInternal.getInstance().login(token, callback); } } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.login()", e); MetricModule.sendError(e, null, null); } } /** * Callback interface for an async login process. */ public interface LoginCallback { /** * Called when a login attempt has completed successfully. */ void onLoginFinish(); /** * Called when a login attempt has failed. * * @param errorMessage failure cause message */ void onLoginFail(String errorMessage); } public static void logout() { try { final ApptentiveInternal instance = ApptentiveInternal.getInstance(); if (instance == null) { ApptentiveLog.e("Unable to logout: Apptentive instance is not properly initialized"); } else { instance.logout(); } } catch (Exception e) { ApptentiveLog.e("Exception in Apptentive.logout()", e); MetricModule.sendError(e, null, null); } } public static void addAuthenticationFailureListener(AuthenticationFailedListener listener) { try { if (!ApptentiveInternal.checkRegistered()) { return; } ApptentiveInternal.getInstance().setAuthenticationFailureListener(listener); } catch (Exception e) { ApptentiveLog.w("Error in Apptentive.addUnreadMessagesListener()", e); MetricModule.sendError(e, null, null); } } public interface AuthenticationFailedListener { void onAuthenticationFailed(AuthenticationFailedReason reason); } public enum AuthenticationFailedReason { UNKNOWN, INVALID_ALGORITHM, MALFORMED_TOKEN, INVALID_TOKEN, MISSING_SUB_CLAIM, MISMATCHED_SUB_CLAIM, INVALID_SUB_CLAIM, EXPIRED_TOKEN, REVOKED_TOKEN, MISSING_APP_KEY, MISSING_APP_SIGNATURE, INVALID_KEY_SIGNATURE_PAIR; private String error; public String error() { return error; } public static AuthenticationFailedReason parse(String errorType, String error) { try { AuthenticationFailedReason ret = AuthenticationFailedReason.valueOf(errorType); ret.error = error; return ret; } catch (IllegalArgumentException e) { ApptentiveLog.w("Error parsing unknown Apptentive.AuthenticationFailedReason: %s", errorType); } return UNKNOWN; } @Override public String toString() { return "AuthenticationFailedReason{" + "error='" + error + '\'' + "errorType='" + name() + '\'' + '}'; } } //endregion public static class Version implements Serializable, Comparable<Version> { private static final long serialVersionUID = 1L; public static final String KEY_TYPE = "_type"; public static final String TYPE = "version"; private String version; public Version() { } public Version(JSONObject json) throws JSONException { this.version = json.optString(TYPE, null); } public Version(long version) { this.version = Long.toString(version); } public void setVersion(String version) { this.version = version; } public void setVersion(long version) { setVersion(Long.toString(version)); } public String getVersion() { return version; } public void toJsonObject() { JSONObject ret = new JSONObject(); try { ret.put(KEY_TYPE, TYPE); ret.put(TYPE, version); } catch (JSONException e) { ApptentiveLog.e("Error creating Apptentive.Version.", e); } } @Override public int compareTo(Version other) { String thisVersion = getVersion(); String thatVersion = other.getVersion(); String[] thisArray = thisVersion.split("\\."); String[] thatArray = thatVersion.split("\\."); int maxParts = Math.max(thisArray.length, thatArray.length); for (int i = 0; i < maxParts; i++) { // If one SemVer has more parts than another, pad out the short one with zeros in each slot. long left = 0; if (thisArray.length > i) { left = Long.parseLong(thisArray[i]); } long right = 0; if (thatArray.length > i) { right = Long.parseLong(thatArray[i]); } if (left < right) { return -1; } else if (left > right) { return 1; } } return 0; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof Version) { return compareTo((Version) o) == 0; } return false; } @Override public String toString() { return getVersion(); } } public static class DateTime implements Serializable, Comparable<DateTime> { public static final String KEY_TYPE = "_type"; public static final String TYPE = "datetime"; public static final String SEC = "sec"; private String sec; public DateTime(JSONObject json) throws JSONException { this.sec = json.optString(SEC); } public DateTime(double dateTime) { setDateTime(dateTime); } public void setDateTime(double dateTime) { sec = String.valueOf(dateTime); } public double getDateTime() { return Double.valueOf(sec); } public JSONObject toJSONObject() { JSONObject ret = new JSONObject(); try { ret.put(KEY_TYPE, TYPE); ret.put(SEC, sec); } catch (JSONException e) { ApptentiveLog.e("Error creating Apptentive.DateTime.", e); } return ret; } @Override public String toString() { return Double.toString(getDateTime()); } @Override public int compareTo(DateTime other) { double thisDateTime = getDateTime(); double thatDateTime = other.getDateTime(); return Double.compare(thisDateTime, thatDateTime); } } }
package edu.atilim.acma.design; import static org.junit.Assert.*; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class FieldTests { private static Design testDesign; private static Type testType; private static Field testField; @BeforeClass public static void createDesign() { testDesign = new Design(); testType = testDesign.create("TestType", Type.class); testField = testType.createField("TestField"); testField.setType(testType); } @AfterClass public static void destroyDesign() { testType = null; testDesign = null; testField = null; } @Test public void testParent() { assertEquals(testField.getOwnerType(), testType); assertArrayEquals(testType.getFields().toArray(), new Object[] { testField }); testField.setOwnerType(null); assertEquals(testField.getOwnerType(), null); assertEquals(testType.getFields().size(), 0); } @Test //Tests accessor of a field public void testGetAccessors(){ //Create two method Method accessorMethod = new Method("TestMethod", testDesign); Method accessorMethod2 = new Method("TestMethod2", testDesign); //Set two method as accessedField to the "field" accessorMethod.addAccessedField(testField); accessorMethod2.addAccessedField(testField); //Call getAccessors() method List<Method> temp = testField.getAccessors(); //Check these method are really accessed to the "field" assertEquals(accessorMethod, temp.get(0)); assertEquals(accessorMethod2, temp.get(1)); } @Test public void testType(){ //Check current testField type assertEquals(testType, testField.getType()); Type typeNew = testDesign.create("TestTypeNew", Type.class); //SetType of the testField type to the typeNew testField.setType(typeNew); //Check type of testField assertEquals(typeNew, testField.getType()); //Set type of the testField to the null testField.setType(null); //Check type of testField assertNull(testField.getType()); } @Test public void testPackage(){ //TODO: } @Test public void testIsConstant(){ //Make field static and final testField.setStatic(true); testField.setFinal(true); //Check is field is constant assertTrue(testField.isConstant()); //Change this field to not final testField.setFinal(false); //Check is field is constant assertFalse(testField.isConstant()); //Change this field to not static but final testField.setStatic(false); testField.setFinal(true); //Check is field is constant assertFalse(testField.isConstant()); } @Test public void testToString(){ //Set type and owner type of testField testField.setType(testType); testField.setOwnerType(testType); String toString= "TestType.TestField:TestType"; String actualToString = testField.toString(); //Check toString method assertEquals(toString,actualToString); } @Test public void testRemove(){ Type typeRemoveTest = new Type("type", testDesign); Field fieldRemoveTest = new Field("field", testDesign); fieldRemoveTest.setOwnerType(typeRemoveTest); assertTrue(fieldRemoveTest.remove()); fieldRemoveTest = new Field("field", testDesign); fieldRemoveTest.setType(typeRemoveTest); assertTrue(fieldRemoveTest.remove()); } }
package aQute.lib.converter; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; import aQute.lib.base64.*; /** * General Java type converter from an object to any type. Supports number * conversion * * @author aqute */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class Converter { public interface Hook { Object convert(Type dest, Object o) throws Exception; } boolean fatal = true; Map<Type,Hook> hooks; List<Hook> allHooks; public <T> T convert(Class<T> type, Object o) throws Exception { // Is it a compatible type? if (type.isAssignableFrom(o.getClass())) return (T) o; return (T) convert((Type) type, o); } public <T> T convert(TypeReference<T> type, Object o) throws Exception { return (T) convert(type.getType(), o); } public Object convert(Type type, Object o) throws Exception { Class resultType = getRawClass(type); if (o == null) { if (resultType.isPrimitive() || Number.class.isAssignableFrom(resultType)) return convert(type, 0); return null; // compatible with any } if (allHooks != null) { for (Hook hook : allHooks) { Object r = hook.convert(type, o); if (r != null) return r; } } if (hooks != null) { Hook hook = hooks.get(type); if (hook != null) { Object value = hook.convert(type, o); if (value != null) return value; } } Class< ? > actualType = o.getClass(); // We can always make a string if (resultType == String.class) { if (actualType.isArray()) { if (actualType == char[].class) return new String((char[]) o); if (actualType == byte[].class) return Base64.encodeBase64((byte[]) o); int l = Array.getLength(o); StringBuilder sb = new StringBuilder("["); String del = ""; for (int i = 0; i < l; i++) { sb.append(del); del = ","; sb.append(convert(String.class, Array.get(o, i))); } sb.append("]"); return sb.toString(); } return o.toString(); } if (Collection.class.isAssignableFrom(resultType)) return collection(type, resultType, o); if (Map.class.isAssignableFrom(resultType)) return map(type, resultType, o); if (type instanceof GenericArrayType) { GenericArrayType gType = (GenericArrayType) type; return array(gType.getGenericComponentType(), o); } if (resultType.isArray()) { if (actualType == String.class) { String s = (String) o; if (byte[].class == resultType) return Base64.decodeBase64(s); if (char[].class == resultType) return s.toCharArray(); } if (byte[].class == resultType) { // Sometimes classes implement toByteArray try { Method m = actualType.getMethod("toByteArray"); if (m.getReturnType() == byte[].class) return m.invoke(o); } catch (Exception e) { // Ignore } } return array(resultType.getComponentType(), o); } if (resultType.isAssignableFrom(o.getClass())) return o; if (Map.class.isAssignableFrom(actualType) && resultType.isInterface()) { return proxy(resultType, (Map) o); } // Simple type coercion if (resultType == boolean.class || resultType == Boolean.class) { if (actualType == boolean.class || actualType == Boolean.class) return o; Number n = number(o); if (n != null) return n.longValue() == 0 ? false : true; resultType = Boolean.class; } else if (resultType == byte.class || resultType == Byte.class) { Number n = number(o); if (n != null) return n.byteValue(); resultType = Byte.class; } else if (resultType == char.class || resultType == Character.class) { Number n = number(o); if (n != null) return (char) n.shortValue(); resultType = Character.class; } else if (resultType == short.class || resultType == Short.class) { Number n = number(o); if (n != null) return n.shortValue(); resultType = Short.class; } else if (resultType == int.class || resultType == Integer.class) { Number n = number(o); if (n != null) return n.intValue(); resultType = Integer.class; } else if (resultType == long.class || resultType == Long.class) { Number n = number(o); if (n != null) return n.longValue(); resultType = Long.class; } else if (resultType == float.class || resultType == Float.class) { Number n = number(o); if (n != null) return n.floatValue(); resultType = Float.class; } else if (resultType == double.class || resultType == Double.class) { Number n = number(o); if (n != null) return n.doubleValue(); resultType = Double.class; } assert !resultType.isPrimitive(); if (actualType == String.class) { String input = (String) o; if (resultType == char[].class) return input.toCharArray(); if (resultType == byte[].class) return Base64.decodeBase64(input); if (Enum.class.isAssignableFrom(resultType)) { try { return Enum.valueOf((Class<Enum>) resultType, input); } catch( Exception e) { input = input.toUpperCase(); return Enum.valueOf((Class<Enum>) resultType, input); } } if (resultType == Pattern.class) { return Pattern.compile(input); } try { Constructor< ? > c = resultType.getConstructor(String.class); return c.newInstance(o.toString()); } catch (Throwable t) {} try { Method m = resultType.getMethod("valueOf", String.class); if (Modifier.isStatic(m.getModifiers())) return m.invoke(null, o.toString()); } catch (Throwable t) {} if (resultType == Character.class && input.length() == 1) return input.charAt(0); } Number n = number(o); if (n != null) { if (Enum.class.isAssignableFrom(resultType)) { try { Method values = resultType.getMethod("values"); Enum[] vs = (Enum[]) values.invoke(null); int nn = n.intValue(); if (nn > 0 && nn < vs.length) return vs[nn]; } catch (Exception e) { // Ignore } } } // Translate arrays with length 1 by picking the single element if (actualType.isArray() && Array.getLength(o) == 1) { return convert(type, Array.get(o, 0)); } // Translate collections with size 1 by picking the single element if (o instanceof Collection) { Collection col = (Collection) o; if (col.size() == 1) return convert(type, col.iterator().next()); } if (o instanceof Map) { String key = null; try { Map<Object,Object> map = (Map) o; Object instance = resultType.newInstance(); for (Map.Entry e : map.entrySet()) { key = (String) e.getKey(); try { Field f = resultType.getField(key); Object value = convert(f.getGenericType(), e.getValue()); f.set(instance, value); } catch (Exception ee) { // We cannot find the key, so try the __extra field Field f = resultType.getField("__extra"); Map<String,Object> extra = (Map<String,Object>) f.get(instance); if (extra == null) { extra = new HashMap<String,Object>(); f.set(instance, extra); } extra.put(key, convert(Object.class, e.getValue())); } } return instance; } catch (Exception e) { return error("No conversion found for " + o.getClass() + " to " + type + ", error " + e + " on key " + key); } } return error("No conversion found for " + o.getClass() + " to " + type); } private Number number(Object o) { if (o instanceof Number) return (Number) o; if (o instanceof Boolean) return ((Boolean) o).booleanValue() ? 1 : 0; if (o instanceof Character) return (int) ((Character) o).charValue(); if (o instanceof String) { String s = (String) o; try { return Double.parseDouble(s); } catch (Exception e) { // Ignore } } return null; } private Collection collection(Type collectionType, Class< ? extends Collection> rawClass, Object o) throws Exception { Collection collection; if (rawClass.isInterface() || Modifier.isAbstract(rawClass.getModifiers())) { if (rawClass.isAssignableFrom(ArrayList.class)) collection = new ArrayList(); else if (rawClass.isAssignableFrom(HashSet.class)) collection = new HashSet(); else if (rawClass.isAssignableFrom(TreeSet.class)) collection = new TreeSet(); else if (rawClass.isAssignableFrom(LinkedList.class)) collection = new LinkedList(); else if (rawClass.isAssignableFrom(Vector.class)) collection = new Vector(); else if (rawClass.isAssignableFrom(Stack.class)) collection = new Stack(); else if (rawClass.isAssignableFrom(ConcurrentLinkedQueue.class)) collection = new ConcurrentLinkedQueue(); else return (Collection) error("Cannot find a suitable collection for the collection interface " + rawClass); } else collection = rawClass.newInstance(); Type subType = Object.class; if (collectionType instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) collectionType; subType = ptype.getActualTypeArguments()[0]; } Collection input = toCollection(o); for (Object i : input) collection.add(convert(subType, i)); return collection; } private Map map(Type mapType, Class< ? extends Map< ? , ? >> rawClass, Object o) throws Exception { Map result; if (rawClass.isInterface() || Modifier.isAbstract(rawClass.getModifiers())) { if (rawClass.isAssignableFrom(HashMap.class)) result = new HashMap(); else if (rawClass.isAssignableFrom(TreeMap.class)) result = new TreeMap(); else if (rawClass.isAssignableFrom(ConcurrentHashMap.class)) result = new ConcurrentHashMap(); else { return (Map) error("Cannot find suitable map for map interface " + rawClass); } } else result = rawClass.newInstance(); Map< ? , ? > input = toMap(o); Type keyType = Object.class; Type valueType = Object.class; if (mapType instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) mapType; keyType = ptype.getActualTypeArguments()[0]; valueType = ptype.getActualTypeArguments()[1]; } for (Map.Entry< ? , ? > entry : input.entrySet()) { Object key = convert(keyType, entry.getKey()); Object value = convert(valueType, entry.getValue()); if (key == null) error("Key for map must not be null: " + input); else result.put(key, value); } return result; } public Object array(Type type, Object o) throws Exception { Collection< ? > input = toCollection(o); Class< ? > componentClass = getRawClass(type); Object array = Array.newInstance(componentClass, input.size()); int i = 0; for (Object next : input) { Array.set(array, i++, convert(type, next)); } return array; } private Class< ? > getRawClass(Type type) { if (type instanceof Class) return (Class< ? >) type; if (type instanceof ParameterizedType) return (Class< ? >) ((ParameterizedType) type).getRawType(); if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type).getGenericComponentType(); return Array.newInstance(getRawClass(componentType), 0).getClass(); } if (type instanceof TypeVariable) { Type componentType = ((TypeVariable) type).getBounds()[0]; return Array.newInstance(getRawClass(componentType), 0).getClass(); } if (type instanceof WildcardType) { Type componentType = ((WildcardType) type).getUpperBounds()[0]; return Array.newInstance(getRawClass(componentType), 0).getClass(); } return Object.class; } public Collection< ? > toCollection(Object o) { if (o instanceof Collection) return (Collection< ? >) o; if (o.getClass().isArray()) { if (o.getClass().getComponentType().isPrimitive()) { int length = Array.getLength(o); List<Object> result = new ArrayList<Object>(length); for (int i = 0; i < length; i++) { result.add(Array.get(o, i)); } return result; } return Arrays.asList((Object[]) o); } return Arrays.asList(o); } public Map< ? , ? > toMap(Object o) throws Exception { if (o instanceof Map) return (Map< ? , ? >) o; Map result = new HashMap(); Field fields[] = o.getClass().getFields(); for (Field f : fields) result.put(f.getName(), f.get(o)); if (result.isEmpty()) return null; return result; } private Object error(String string) { if (fatal) throw new IllegalArgumentException(string); return null; } public void setFatalIsException(boolean b) { fatal = b; } public Converter hook(Type type, Hook hook) { if (type != null) { if (hooks == null) hooks = new HashMap<Type,Converter.Hook>(); this.hooks.put(type, hook); } else { if (allHooks == null) allHooks = new ArrayList<Converter.Hook>(); allHooks.add(hook); } return this; } /** * Convert a map to an interface. * * @param interfc * @param properties * @return */ public <T> T proxy(Class<T> interfc, final Map< ? , ? > properties) { return (T) Proxy.newProxyInstance(interfc.getClassLoader(), new Class[] { interfc }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object o = properties.get(method.getName()); if (o == null) o = properties.get(mangleMethodName(method.getName())); return convert(method.getGenericReturnType(), o); } }); } public static String mangleMethodName(String id) { StringBuilder sb = new StringBuilder(id); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); boolean twice = i < sb.length() - 1 && sb.charAt(i + 1) == c; if (c == '$' || c == '_') { if (twice) sb.deleteCharAt(i + 1); else if (c == '$') sb.deleteCharAt(i--); // Remove dollars else sb.setCharAt(i, '.'); // Make _ into . } } return sb.toString(); } public static <T> T cnv(TypeReference<T> tr, Object source) throws Exception { return new Converter().convert(tr, source); } public static <T> T cnv(Class<T> tr, Object source) throws Exception { return new Converter().convert(tr, source); } public static Object cnv(Type tr, Object source) throws Exception { return new Converter().convert(tr, source); } }
package ceylon.language; import com.redhat.ceylon.compiler.java.metadata.Annotation; import com.redhat.ceylon.compiler.java.metadata.Annotations; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; import com.redhat.ceylon.compiler.java.metadata.TypeParameter; import com.redhat.ceylon.compiler.java.metadata.TypeParameters; import com.redhat.ceylon.compiler.java.metadata.Variance; @Ceylon(major = 1) @TypeParameters({@TypeParameter(value = "Element", variance = Variance.OUT), @TypeParameter(value = "Null", variance = Variance.OUT, satisfies="ceylon.language.Nothing")}) @SatisfiedTypes("ceylon.language.Container") public interface ContainerWithFirstElement<Element,Null> extends Container { @Annotations(@Annotation("formal")) @TypeInfo("Null|Element") public java.lang.Object getFirst(); }
package baekjoon_2565_line; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; public class Main { public static int N; public static List<Line> lines = new ArrayList<Line>(); public static int MAX_CNT; public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("input.txt"); System.setIn(fis); OutputStreamWriter osw = new OutputStreamWriter(System.out); BufferedWriter bw = new BufferedWriter(osw); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); for (int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); lines.add(new Line(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()))); } Collections.sort(lines); lis(); bw.write(N - MAX_CNT + "\n"); bw.flush(); bw.close(); br.close(); } public static void lis() { for (int i = 0; i < N; i++) { Line line = lines.get(i); line.lis = 1; for (int j = 0; j < i; j++) { Line linePre = lines.get(j); if (line.b > linePre.b && line.lis < linePre.lis + 1) { line.lis = linePre.lis + 1; if (MAX_CNT < line.lis) { MAX_CNT = line.lis; } } } } } static class Line implements Comparable<Line> { public int a; public int b; public int lis = 0; public Line(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Line other) { return this.a > other.a ? 1 : -1; } } }
package battleships.backend.actionhelpers; import battleships.backend.Settings; import battleships.backend.State; import game.impl.BoardLocation; import game.impl.GamePiece; import game.impl.Move; import java.util.List; public class NormalMoveExecutor implements MoveExecutable { private State state; public NormalMoveExecutor(State state) { this.state = state; } @Override public boolean executeMove(Move move, Move firstMove) { //firstmove is only for deploymode //we only care about move here. List<BoardLocation> boardLocations = state.getBoard().getLocations(); BoardLocation locationToAlter = boardLocations.get(boardLocations.indexOf(move.getDestination())); switch (state.getMessage()) { case Settings.PIECE_SHIPHIT_MESSAGE: locationToAlter.setPiece(new GamePiece(Character.toString(Settings.PIECE_ALREADYHIT))); return true; case Settings.PIECE_MISS_MESSAGE: locationToAlter.setPiece(new GamePiece(Character.toString(Settings.PIECE_MISS))); return true; } return true; } }
package be.ibridge.kettle.trans.step.exceloutput; import java.io.File; import java.util.Locale; import jxl.Workbook; import jxl.WorkbookSettings; import jxl.biff.EmptyCell; import jxl.write.DateFormat; import jxl.write.DateFormats; import jxl.write.DateTime; import jxl.write.Label; import jxl.write.NumberFormat; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.ResultFile; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStep; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; /** * Converts input rows to excel cells and then writes this information to one or more files. * * @author Matt * @since 7-sep-2006 */ public class ExcelOutput extends BaseStep implements StepInterface { private ExcelOutputMeta meta; private ExcelOutputData data; public ExcelOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(ExcelOutputMeta)smi; data=(ExcelOutputData)sdi; Row r; boolean result=true; r=getRow(); // This also waits for a row to be finished. if ( ( r==null && data.headerrow!=null && meta.isFooterEnabled() ) || ( r!=null && linesOutput>0 && meta.getSplitEvery()>0 && ((linesOutput+1)%meta.getSplitEvery())==0) ) { if (data.headerrow!=null) { if ( meta.isFooterEnabled() ) { writeHeader(); } } // Done with this part or with everything. closeFile(); // Not finished: open another file... if (r!=null) { if (!openNewFile()) { logError("Unable to open new file (split #"+data.splitnr+"..."); setErrors(1); return false; } if (meta.isHeaderEnabled() && data.headerrow!=null) if (writeHeader()) linesOutput++; } } if (r==null) // no more input to be expected... { setOutputDone(); return false; } result=writeRowToFile(r); if (!result) { setErrors(1); stopAll(); return false; } putRow(r); // in case we want it to go further... if ((linesOutput>0) && (linesOutput%Const.ROWS_UPDATE)==0)logBasic("linenr "+linesOutput); return result; } private boolean writeRowToFile(Row r) { Value v; try { if (first) { first=false; if ( meta.isHeaderEnabled() || meta.isFooterEnabled()) // See if we have to write a header-line) { data.headerrow=new Row(r); // copy the row for the footer! if (meta.isHeaderEnabled() && data.headerrow!=null) { if (writeHeader() ) { return false; } } } data.fieldnrs=new int[meta.getOutputFields().length]; for (int i=0;i<meta.getOutputFields().length;i++) { data.fieldnrs[i]=r.searchValueIndex(meta.getOutputFields()[i].getName()); if (data.fieldnrs[i]<0) { logError("Field ["+meta.getOutputFields()[i].getName()+"] couldn't be found in the input stream!"); setErrors(1); stopAll(); return false; } } } if (meta.getOutputFields()==null || meta.getOutputFields().length==0) { /* * Write all values in stream to text file. */ for (int i=0;i<r.size();i++) { v=r.getValue(i); if(!writeField(v, null)) return false; } // go to the next line data.positionX = 0; data.positionY++; } else { /* * Only write the fields specified! */ for (int i=0;i<meta.getOutputFields().length;i++) { v=r.getValue(data.fieldnrs[i]); if(!writeField(v, meta.getOutputFields()[i])) return false; } // go to the next line data.positionX = 0; data.positionY++; } } catch(Exception e) { logError("Error writing line :"+e.toString()); return false; } linesOutput++; return true; } /** * Write a value to Excel, increasing data.positionX with one afterwards. * @param v The value to write * @param excelField the field information (if any, otherwise : null) * @param isHeader true if this is part of the header/footer * @return */ private boolean writeField(Value v, ExcelField excelField) { return writeField(v, excelField, false); } /** * Write a value to Excel, increasing data.positionX with one afterwards. * @param v The value to write * @param excelField the field information (if any, otherwise : null) * @param isHeader true if this is part of the header/footer * @return */ private boolean writeField(Value v, ExcelField excelField, boolean isHeader) { try { String hashName = v.getName(); if (isHeader) hashName = "____header_field____"; // all strings, can map to the same format. WritableCellFormat cellFormat=(WritableCellFormat) data.formats.get(hashName); switch(v.getType()) { case Value.VALUE_TYPE_DATE: { if (!v.isNull() && v.getDate()!=null) { if (cellFormat==null) { if (excelField!=null && excelField.getFormat()!=null) { DateFormat dateFormat = new DateFormat(excelField.getFormat()); cellFormat=new WritableCellFormat(dateFormat); } else { cellFormat = new WritableCellFormat(DateFormats.FORMAT9); } data.formats.put(hashName, cellFormat); // save for next time around... } DateTime dateTime = new DateTime(data.positionX, data.positionY, v.getDate(), cellFormat); data.sheet.addCell(dateTime); } else { data.sheet.addCell(new EmptyCell(data.positionX, data.positionY)); } } break; case Value.VALUE_TYPE_STRING: case Value.VALUE_TYPE_BOOLEAN: case Value.VALUE_TYPE_BINARY: { if (!v.isNull()) { if (cellFormat==null) { cellFormat = new WritableCellFormat(data.writableFont); data.formats.put(hashName, cellFormat); } Label label = new Label(data.positionX, data.positionY, v.getString(), cellFormat); data.sheet.addCell(label); } else { data.sheet.addCell(new EmptyCell(data.positionX, data.positionY)); } } break; case Value.VALUE_TYPE_NUMBER: case Value.VALUE_TYPE_BIGNUMBER: case Value.VALUE_TYPE_INTEGER: { if (cellFormat==null) { String format; if (excelField!=null && excelField.getFormat()!=null) { format=excelField.getFormat(); } else { format = " } NumberFormat numberFormat = new NumberFormat(format); cellFormat = new WritableCellFormat(numberFormat); data.formats.put(v.getName(), cellFormat); // save for next time around... } jxl.write.Number number = new jxl.write.Number(data.positionX, data.positionY, v.getNumber(), cellFormat); data.sheet.addCell(number); } break; default: break; } } catch(Exception e) { logError("Error writing field ("+data.positionX+","+data.positionY+") : "+e.toString()); return false; } finally { data.positionX++; // always advance :-) } return true; } private boolean writeHeader() { boolean retval=false; Row r=data.headerrow; try { // If we have fields specified: list them in this order! if (meta.getOutputFields()!=null && meta.getOutputFields().length>0) { for (int i=0;i<meta.getOutputFields().length;i++) { String fieldName = meta.getOutputFields()[i].getName(); Value headerValue = new Value(fieldName, fieldName); writeField(headerValue, null, true); } } else if (r!=null) // Just put all field names in the header/footer { for (int i=0;i<r.size();i++) { String fieldName = r.getValue(i).getName(); Value headerValue = new Value(fieldName, fieldName); writeField(headerValue, null, true); } } } catch(Exception e) { logError("Error writing header line: "+e.toString()); logError(Const.getStackTracker(e)); retval=true; } finally { data.positionX=0; data.positionY++; } linesOutput++; return retval; } public String buildFilename() { return meta.buildFilename(getCopy(), data.splitnr); } public boolean openNewFile() { boolean retval=false; try { WorkbookSettings ws = new WorkbookSettings(); ws.setLocale(Locale.getDefault()); if (!Const.isEmpty(meta.getEncoding())) { ws.setEncoding(meta.getEncoding()); } File file = new File(buildFilename()); // Add this to the result file names... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname()); resultFile.setComment("This file was created with a text file output step"); addResultFile(resultFile); // Create the workboook data.workbook = Workbook.createWorkbook(file, ws); // Create a sheet? data.sheet = data.workbook.createSheet("Sheet1", 0); data.sheet.setName("Sheet1"); // Set the initial position... data.positionX = 0; data.positionY = 0; retval=true; } catch(Exception e) { logError("Error opening new file : "+e.toString()); } // System.out.println("end of newFile(), splitnr="+splitnr); data.splitnr++; return retval; } private boolean closeFile() { boolean retval=false; try { data.workbook.write(); data.workbook.close(); data.formats.clear(); retval=true; } catch(Exception e) { logError("Unable to close workbook file : "+e.toString()); } return retval; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(ExcelOutputMeta)smi; data=(ExcelOutputData)sdi; if (super.init(smi, sdi)) { data.splitnr=0; try { // Create the default font TODO: allow to change this later on. data.writableFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD); } catch(Exception we) { logError("Unexpected error preparing to write to Excel file : "+we.toString()); logError(Const.getStackTracker(we)); return false; } if (openNewFile()) { return true; } else { logError("Couldn't open file "+meta.getFileName()); setErrors(1L); stopAll(); } } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta=(ExcelOutputMeta)smi; data=(ExcelOutputData)sdi; super.dispose(smi, sdi); closeFile(); } // Run is were the action happens! public void run() { try { logBasic("Starting to run..."); while (processRow(meta, data) && !isStopped()); } catch(Exception e) { logError("Unexpected error : "+e.toString()); logError(Const.getStackTracker(e)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package ch.unizh.ini.caviar.hardwareinterface.usb; import ch.unizh.ini.caviar.aemonitor.*; import ch.unizh.ini.caviar.aemonitor.AEMonitorInterface; import ch.unizh.ini.caviar.chip.*; //import ch.unizh.ini.caviar.chip.EventExtractor2D; import ch.unizh.ini.caviar.eventprocessing.FilterChain; import ch.unizh.ini.caviar.event.EventPacket; import ch.unizh.ini.caviar.hardwareinterface.*; import ch.unizh.ini.caviar.util.*; import de.thesycon.usbio.PnPNotifyInterface; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.*; import java.io.*; import de.thesycon.usbio.*; import de.thesycon.usbio.structs.*; import java.util.*; import java.util.logging.Logger; import java.util.prefs.*; import javax.swing.*; import javax.swing.JProgressBar; /** * Acquires data from INI/USE USB2 board that uses Cypress FX2LP device and host driver firmware and software based on Thesycon Java USBIO. *Controls onchip biasgenerator using Cypress FX2 SPI interface. *<p> *<p> *In this class, you can also set the size of the host buffer with {@link #setAEBufferSize}, giving you more time between calls to process the events. *<p> *On the device, a timer sends all available events approximately every 10ms -- you don't need to wait for a fixed size buffer to be captured to be available to the host. *But if events come quickly enough, new events can be available much faster than this. *<p> *You can also request at any time an early transfer of events with {@link #requestEarlyTransfer}. This will send a vendor request to the device to immediately transfer * available events, but they won't be available to the host for a little while, depending on USBIOInterface and driver latency. *<p> *See the main() method for an example of use. * <p> * Fires PropertyChangeEvent on the following * <ul> * <li> NEW_EVENTS_PROPERTY_CHANGE - on new events from driver * <li> "readerStarted" - when the reader thread is started * </ul> * * * @author tobi */ public class CypressFX2 implements UsbIoErrorCodes, PnPNotifyInterface, AEMonitorInterface, ReaderBufferControl, RealTimeFilter { protected Preferences prefs=Preferences.userNodeForPackage(this.getClass()); protected Logger log=Logger.getLogger("CypressFX2"); protected AEChip chip; // note .bix file format is deprecated. The new binary file format is .iic (i2c) format which are image files for the EEPROM /** filename of FX2 binary executable, generated by uVision project and associated script that runs hex2bix */ public final static String FIRMWARE_FILENAME_DAREK_BOARD="/ch/unizh/ini/caviar/hardwareinterface/usb/USBAER_FX2.bix"; //"USBAEMonFirware.bin"; /** filename of FX2 binary executable, generated by uVision project and associated script that runs hex2bix */ public final static String FIRMWARE_FILENAME_TMPDIFF128_BIX="/ch/unizh/ini/caviar/hardwareinterface/usb/USBAER_FX2LP_Retina.bix"; //"USBAEMonFirware.bin"; /** filename of FX2 binary executable, generated by uVision project and associated script that runs hex2bix */ public final static String FIRMWARE_FILENAME_TMPDIFF128_HEX="/ch/unizh/ini/caviar/hardwareinterface/usb/USBAER_FX2LP_Retina.hex"; //"USBAEMonFirware.bin"; /** filename of FX2 binary executable, generated by uVision project and associated script that runs hex2bix */ public final static String FIRMWARE_FILENAME_MONITOR_SEQUENCER="/ch/unizh/ini/caviar/hardwareinterface/usb/USBAERmini2.bix"; /** filename of FX2 binary executable, generated by uVision project and associated script that runs hex2bix */ public final static String FIRMWARE_FILENAME_MONITOR_SEQUENCER_HEX="/ch/unizh/ini/caviar/hardwareinterface/usb/USBAERmini2.hex"; /** filename of FX2 binary executable, generated by uVision project and associated script that runs hex2bix */ public final static String FIRMWARE_FILENAME_MONITOR_SEQUENCER_IIC="/ch/unizh/ini/caviar/hardwareinterface/usb/USBAERmini2.iic"; public final static String FIRMWARE_FILENAME_MAPPER_IIC="/ch/unizh/ini/caviar/hardwareinterface/usb/USB2AERmapper.iic"; public final static String FIRMWARE_FILENAME_STEREO_IIC="/ch/unizh/ini/caviar/hardwareinterface/usb/TMPdiffStereo.iic"; // public final static String FIRMWARE_FILENAME_TCVS320_IIC="/ch/unizh/ini/caviar/hardwareinterface/usb/USBAERTCVS320.iic"; public final static String FIRMWARE_FILENAME_TCVS320_HEX="/ch/unizh/ini/caviar/hardwareinterface/usb/USBAERTCVS320.hex"; public final static String FIRMWARE_FILENAME_TCVS320_BIX="/ch/unizh/ini/caviar/hardwareinterface/usb/USBAERTCVS320.bix"; /** driver guid (Globally unique ID, for this USB driver instance */ //public final static String GUID = "{325ddf96-938c-11d3-9e34-0080c82727f4}"; // working from MouseSimple example. public final static String GUID = "{7794C79A-40A7-4a6c-8A29-DA141C20D78C}"; // see guid.txt at root of CypressFX2USB2, generated by tobi for CypressFX2RetinaBiasgen //public final static String GUID = "{96E73B6E-7A5A-11D4-9F24-0080C82727F4}"; // from default usbiowiz.inf file /** A blank Cypress FX2 has VID/PID of 0x04b4/0x8613. This VID/PID pair is used to indicate a blank device that needs programming. */ static final public short VID_BLANK=(short)0x04b4, PID_BLANK=(short)0x8613; static public final short VID=(short)0x0547; static public final short PID_TMPDIFF128_RETINA=(short)0x8700; static public final short PID_DAREK_FX2_BOARD=(short)0x8701; static public final short PID_USBAERmini2=(short)0x8801; static public final short PID_USBAERmini2_without_firmware=(short)0x8800; static public final short PID_USB2AERmapper=(short)0x8900; static public final short DID_STEREOBOARD=(short)0x2007; static public final short PID_TCVS320_RETINA=(short)0x8702; /** * event supplied to listeners when new events are collected. this is final because it is just a marker for the listeners that new events are available */ public final PropertyChangeEvent NEW_EVENTS_PROPERTY_CHANGE=new PropertyChangeEvent(this, "NewEvents", null,null); PropertyChangeSupport support=new PropertyChangeSupport(this); // consts final static byte AE_MONITOR_ENDPOINT_ADDRESS = (byte)0x86; // this is endpoint of AE fifo on Cypress FX2, 0x86 means IN endpoint EP6. final static byte STATUS_ENDPOINT_ADDRESS = (byte)0x81; // this is endpoint 1 IN for device to report status changes asynchronously final short CPUCS = (short)0xE600; // address of the CPUCS register, using for resetting 8051 and downloading firmware // vendor requests. final static byte VENDOR_REQUEST_START_TRANSFER=(byte)0xb3; // this is request to start sending events from FIFO endpoint final static byte VENDOR_REQUEST_STOP_TRANSFER=(byte)0xb4; // this is request to stop sending events from FIFO endpoint final static byte VENDOR_REQUEST_EARLY_TRANFER=(byte)0xb7; // this is request to transfer whatever you have now static final byte VENDOR_REQUEST_SEND_BIAS_BYTES=(byte)0xb8; // vendor command to send bias bytes out on SPI interface final byte VENDOR_REQUEST_POWERDOWN=(byte)0xb9; // vendor command to send bias bytes out on SPI interface final byte VENDOR_REQUEST_FLASH_BIASES=(byte)0xba; // vendor command to flash the bias values to EEPROM final byte VENDOR_REQUEST_RESET_TIMESTAMPS=(byte)0xbb; // vendor command to reset timestamps final byte VENDOR_REQUEST_SET_ARRAY_RESET=(byte)0xbc; // vendor command to set array reset of retina final byte VENDOR_REQUEST_DO_ARRAY_RESET=(byte)0xbd; // vendor command to do an array reset (toggle arrayReset for a fixed time) //final byte VENDOR_REQUEST_WRITE_EEPROM=(byte)0xbe; // vendor command to write EEPROM final byte VENDOR_REQUEST_SET_LED=(byte)0xbf; // vendor command to set the board's LED //final byte VENDOR_REQUEST_READ_EEPROM=(byte)0xca; // vendor command to write EEPROM // #define VR_EEPROM 0xa2 // loads (uploads) EEPROM final byte VR_EEPROM =(byte)0xa2; // #define VR_RAM 0xa3 // loads (uploads) external ram final byte VR_RAM =(byte)0xa3; // this is special hw vendor request for reading and writing RAM, used for firmware download static final byte VENDOR_REQUEST_FIRMWARE = (byte)0xA0; // download/upload firmware -- built in to FX2 final static short CONFIG_INDEX = 0; final static short CONFIG_NB_OF_INTERFACES = 1; final static short CONFIG_INTERFACE = 0; final static short CONFIG_ALT_SETTING = 0; final static int CONFIG_TRAN_SIZE = 512; // following are to support realtime filtering // the AEPacketRaw is used only within this class. Each packet is extracted using the chip extractor object from the first filter in the // realTimeFilterChain to a reused EventPacket. AEPacketRaw realTimeRawPacket=null; // used to hold raw events that are extracted for real time procesing EventPacket realTimePacket=null; // used to hold extracted real time events for processing /** start of events that have been captured but not yet processed by the realTimeFilters */ private int realTimeEventCounterStart=0; /** timeout in ms to reopen driver (reloading firmware) if no events are received for this time. This timeout will restart AE transmission if *another process (e.g. Biasgen) reloads the firmware. This timer is checked on every attempt to acquire events. */ public static long NO_AE_REOPEN_TIMEOUT=3000; final short TICK_US=1; // time in us of each timestamp count here on host, could be different on board short TICK_US_BOARD=10; // time in us of timestamp tick on USB board. raphael: should not be final, i need to overwrite it and set it to 1 /** default size of AE buffer for user processes. This is the buffer that is written by the hardware capture thread that holds events * that have not yet been transferred via {@link #acquireAvailableEventsFromDriver} to another thread * @see #acquireAvailableEventsFromDriver * @see AEReader * @see #setAEBufferSize */ public static final int AE_BUFFER_SIZE=10000; // changed from 0x1ffff to reduce hit on cache; /** the latest status returned from a USBIO call */ protected int status; /** the event reader - a buffer pool thread from USBIO subclassing */ protected AEReader aeReader=null; /** the thread that reads device status messages on EP1 */ protected AsyncStatusThread asyncStatusThread=null; /** a USBIO buffer used for calls */ protected UsbIoBuf BufDesc=null; /** The pool of raw AE packets, used for data transfer */ protected AEPacketRawPool aePacketRawPool=new AEPacketRawPool(); /** * Object that holds pool of AEPacketRaw that handles data interchange between capture and other (rendering) threads. * While the capture thread (AEReader.processData) captures events into one buffer (an AEPacketRaw) the other thread (AEViewer.run()) can * render the events. The only time the monitor on the pool needs to be acquired is when swapping or initializing the buffers, to prevent * either referencing unrelated data or having memory change out from under you. */ private class AEPacketRawPool{ AEPacketRaw[] buffers; AEPacketRaw lastBufferReference; volatile int readBuffer=0, writeBuffer=1; // this buffer is the one currently being read from AEPacketRawPool(){ allocateMemory(); reset(); } /** swap the buffers so that the buffer that was getting written is now the one that is read from, and the one that was read from is * now the one written to. Thread safe. */ synchronized final void swap(){ lastBufferReference=buffers[readBuffer]; if(readBuffer==0){ readBuffer=1; writeBuffer=0; }else{ readBuffer=0; writeBuffer=1; } writeBuffer().clear(); } /** @return buffer to read from */ synchronized final AEPacketRaw readBuffer(){ return buffers[readBuffer]; } /** @return buffer to write to */ synchronized final AEPacketRaw writeBuffer(){ return buffers[writeBuffer]; } /** Set the current buffer to be the first one and clear the write buffer */ synchronized final void reset(){ readBuffer=0; writeBuffer=1; buffers[writeBuffer].clear(); // new events go into this buffer which should be empty buffers[readBuffer].clear(); // clear read buffer in case this buffer was reset by resetTimestamps // log.info("buffers reset"); } // allocates AEPacketRaw each with capacity AE_BUFFER_SIZE void allocateMemory(){ buffers=new AEPacketRaw[2]; for(int i=0;i<buffers.length;i++){ buffers[i]=new AEPacketRaw(); buffers[i].ensureCapacity(AE_BUFFER_SIZE); // preallocate this memory for capture thread and to try to make it contiguous } } } int eventCounter=0; // counts events acquired but not yet passed to user /** the last events from {@link #acquireAvailableEventsFromDriver}, This packet is reused. */ protected AEPacketRaw lastEventsAcquired=new AEPacketRaw(); PnPNotify pnp=null; USBIO_CLASS_OR_VENDOR_REQUEST vendorRequest; // used for vendor requests to device (e.g. firmware download, start sending events, etc) protected boolean inEndpointEnabled=false; // raphael: changed from private to protected, because i need to access this member /** device open status */ protected boolean isOpened=false; private boolean aeReaderRunning=false; /** the device number, out of all potential compatible devices that could be opened */ protected int interfaceNumber=0; /** Creates a new instance of USBAEMonitor. Note that it is possible to construct several instances * and use each of them to open and read from the same device. *@param devNumber the desired device number, in range returned by CypressFX2Factory.getNumInterfacesAvailable *@see CypressFX2TmpdiffRetinaFactory */ protected CypressFX2(int devNumber) { this.interfaceNumber=devNumber; // pnp=new PnPNotify(this); // pnp.enablePnPNotification(GUID); } /** returns the device interface number. This is the index of this device as returned by the interface factory. * @return interface number, 0 based */ int getInterfaceNumber() { return interfaceNumber; } /** sets the device number to open, according to the order in the hardware interface factory. * @param interfaceNumber 0 based interface number */ void setInterfaceNumber(int interfaceNumber) { this.interfaceNumber = interfaceNumber; } /** acquire a device for exclusive use, other processes can't open the device anymore * used for example for continuous sequencing in matlab */ public void acquireDevice() throws HardwareInterfaceException { status=gUsbIo.acquireDevice(); if (status != 0) { throw new HardwareInterfaceException("Unable to acquire device for exclusive use: " + UsbIo.errorText(status)); } } /** release the device from exclusive use */ public void releaseDevice() throws HardwareInterfaceException { status=gUsbIo.releaseDevice(); if (status != 0) { throw new HardwareInterfaceException("Unable to release device from exclusive use: " + UsbIo.errorText(status)); } } public PropertyChangeSupport getSupport() { return this.support; } public String toString() { return (getClass().getSimpleName() + ": Interface " + getInterfaceNumber()); } /** the size in bytes of the EEPROM atttached to the CypressFX2LP */ public int EEPROM_SIZE=0x4000;//8192; /** size of control transfer data packets. Actually vendor request allows for larger data buffer, but windows limits largest xfer to 4096. Here we limit largest *to size of buffer for control xfers. */ public final int MAX_CONTROL_XFER_SIZE=64; // max control xfer size /** This is a BLOCKING write call to write the Cypress EEPROM. Max number of bytes is defined by {@link #EEPROM_SIZE}. *@param addr the starting address *@param bytes the bytes to write */ synchronized public void writeEEPROM(int addr, byte[] bytes) throws HardwareInterfaceException{ // log.info("writing EEPROM to addr="+addr+" with "+bytes.length+" bytes"); if(bytes.length>this.EEPROM_SIZE) throw new RuntimeException(bytes.length+" is too many bytes for EEPROM to hold ("+EEPROM_SIZE+")"); if(addr<0 || addr+bytes.length>EEPROM_SIZE) throw new RuntimeException(bytes.length+" is too many bytes for EEPROM to hold ("+EEPROM_SIZE+") starting at address "+addr); int result; // result of USBIO operations USBIO_DATA_BUFFER dataBuffer=null; USBIO_CLASS_OR_VENDOR_REQUEST vendorRequest=null; int numChunks, index; // make vendor request structure and populate it vendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); vendorRequest.Request=VR_EEPROM; // this is EEPROM command, direction of vendor request defines download here vendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; vendorRequest.Type=UsbIoInterface.RequestTypeVendor; // this is a vendor, not generic USB, request vendorRequest.Recipient=UsbIoInterface.RecipientDevice; // device (not endpoint, interface, etc) receives it vendorRequest.RequestTypeReservedBits=0; // set these bits to zero for Cypress-specific 'vendor request' rather that user defined vendorRequest.Index=0; //send all but last chunk vendorRequest.Value = (short)addr; //address to write to (starting) dataBuffer=new USBIO_DATA_BUFFER(MAX_CONTROL_XFER_SIZE); dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length); index=0; numChunks=bytes.length/MAX_CONTROL_XFER_SIZE; // this is number of full chunks to send for(int i=0;i<numChunks;i++){ System.arraycopy(bytes, i*MAX_CONTROL_XFER_SIZE, dataBuffer.Buffer(), 0, MAX_CONTROL_XFER_SIZE); result=gUsbIo.classOrVendorOutRequest(dataBuffer,vendorRequest); if(result!=USBIO_ERR_SUCCESS){ close(); throw new HardwareInterfaceException("Error on downloading segment number "+i+" of EEPROM write: "+UsbIo.errorText(result)); } vendorRequest.Value += MAX_CONTROL_XFER_SIZE; //change address of EEPROM write location } // now send final (short) chunk int numBytesLeft=bytes.length%MAX_CONTROL_XFER_SIZE; // remainder if(numBytesLeft>0){ dataBuffer=new USBIO_DATA_BUFFER(numBytesLeft); dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length); System.arraycopy(bytes, numChunks*MAX_CONTROL_XFER_SIZE, dataBuffer.Buffer(), 0, numBytesLeft); // send remaining part of firmware result=gUsbIo.classOrVendorOutRequest(dataBuffer,vendorRequest); if(result!=USBIO_ERR_SUCCESS){ close(); throw new HardwareInterfaceException("Error on downloading final segment of EEPROM write: "+UsbIo.errorText(result)); } } } // writeEEPROM /** erases the VID/PID/DID and device identifier strings */ synchronized protected void eraseEEPROM() throws HardwareInterfaceException{ log.info("erasing EEPROM by writing all zeros to it"); writeEEPROM(0,new byte[EEPROM_SIZE]); } /** Read the EEPROM contents. *@param addr the starting address *@param length the number of bytes to read */ synchronized protected byte[] readEEPROM(int addr, int length) throws HardwareInterfaceException{ int result; if(length>EEPROM_SIZE) throw new RuntimeException(length+" is more bytes than EEPROM can hold ("+EEPROM_SIZE+")"); if(addr<0 || addr+length>EEPROM_SIZE) throw new RuntimeException(length+" is too many bytes to read from EEPROM which holds "+EEPROM_SIZE+" bytes, if you start at address "+addr); USBIO_DATA_BUFFER dataBuffer=null; USBIO_CLASS_OR_VENDOR_REQUEST vendorRequest=null; byte[] uploadBuffer=new byte[length]; // make vendor request structure and populate it vendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); vendorRequest.Request=VR_EEPROM; // this is download/upload EEPROM command, direction of vendor request defines upload to host vendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; vendorRequest.Type=UsbIoInterface.RequestTypeVendor; // this is a vendor, not generic USB, request vendorRequest.Recipient=UsbIoInterface.RecipientDevice; // device (not endpoint, interface, etc) receives it vendorRequest.RequestTypeReservedBits=0; // set these bits to zero for Cypress-specific 'vendor request' rather that user defined vendorRequest.Index=0; dataBuffer=new USBIO_DATA_BUFFER(length); int bytesTransferred=0; dataBuffer.setNumberOfBytesToTransfer(length); vendorRequest.Value=(short)addr; // this is EEPROM addr to read from for this chunk result=gUsbIo.classOrVendorInRequest(dataBuffer, vendorRequest); // IN request defines direction, so will be understood as read EEPROM on device if(result!=USBIO_ERR_SUCCESS){ close(); throw new HardwareInterfaceException("Error during uploading EEPROM: "+UsbIo.errorText(result)); } if(dataBuffer.getBytesTransferred()!=length){ throw new HardwareInterfaceException("wrong number of bytes transferred, asked for "+length+", got "+dataBuffer.getBytesTransferred()); } System.arraycopy(dataBuffer.Buffer(), 0, uploadBuffer, 0, length); return uploadBuffer; } /** writes the Cypress "C0" load to the EEPROM that makes the Cypress FX2 have a Vender, Product, and Device ID on powerup. *@param VID *@param PID *@param DID the 'device' ID, can be used to individualize devices */ synchronized public void writeVIDPIDDID(short VID, short PID, short DID) throws HardwareInterfaceException{ byte[] b=new byte[8]; b[0]=(byte)0xC0; b[1]=(byte)(VID&0xFF); // vid LSB b[2]=(byte)((VID&0xFF00)>>>8); // vid MSB b[3]=(byte)(PID&0xFF); b[4]=(byte)((PID&0xFF00)>>>8); b[5]=(byte)(DID&0xFF); b[6]=(byte)((DID&0xFF00)>>>8); b[7]=(byte)(0); // configuration byte, DISCON=0 (not disconnected after reset), 400kHz=0 (100kHz I2C bus) writeEEPROM(0,b); } // private class WriteC2LoadFromHexFileTask extends SwingWorker{ // protected Object doInBackground() throws Exception { /** writes the Cypress "C2" load to the EEPROM that makes the Cypress have full EEPROM firmware, including VID, PID, DID. *On reset the Cypress will load its RAM from the EEPROM. *@param firmwareFilename a File containing the binary format .iic file * firmware as output from hex2bix. This is a flat firmware format that starts at address 0. * It does not include the VID/PID written for the C2 load. *@param VID *@param PID *@param DID the 'device' ID, can be used to individualize devices */ public void writeC2Load(String firmwareFilename, short VID, short PID, short DID) throws HardwareInterfaceException{ byte[] fw=null; try{ fw=loadBinaryFirmwareFile(firmwareFilename); }catch(IOException e){ throw new HardwareInterfaceException(e.getMessage()); } byte[] b=new byte[12]; b[0]=(byte)0xC2; b[1]=(byte)(VID&0xFF); // vid LSB b[2]=(byte)((VID&0xFF00)>>>8); // vid MSB b[3]=(byte)(PID&0xFF); b[4]=(byte)((PID&0xFF00)>>>8); b[5]=(byte)(DID&0xFF); b[6]=(byte)((DID&0xFF00)>>>8); b[7]=(byte)(0); // configuration byte, DISCON=0 (not disconnected after reset), 400kHz=0 (100kHz I2C bus) b[8]=(byte)((fw.length&0xFF00)>>>8); b[9]=(byte)((fw.length&0xFF)); // length of firmware in these bytes b[10]=0; b[11]=0; byte[] end=new byte[5]; end[0]=(byte)0x80; end[1]=(byte)0x01; end[2]=(byte)0xe6; end[4]=0; byte[] w=new byte[b.length+fw.length+end.length]; System.arraycopy(b,0,w,0,b.length); System.arraycopy(fw,0,w,b.length,fw.length); System.arraycopy(end,0,w,b.length+fw.length,end.length); writeEEPROM(0,w); } /** writes the Cypress "C2" load to the EEPROM that makes the Cypress have EEPROM firmware, including VID, PID, DID. *@param VID *@param PID *@param DID the 'device' ID, can be used to individualize devices *@param hexFileResourcePath a full path pointing to a resource containing the firmware as output from compiler in Intel hex format. This resource is a file that is somewhere in the classpath, i.e. it is a file *that is included in the project jar. For example: "/ch/unizh/ini/caviar/hardwareinterface/usb/USBAER_FX2LP_Retina.hex" *@see #FIRMWARE_FILENAME_TMPDIFF128_HEX *@see #FIRMWARE_FILENAME_MONITOR_SEQUENCER_HEX */ synchronized public void writeHexFileToEEPROM(String hexFileResourcePath, short VID, short PID, short DID) throws HardwareInterfaceException{ log.info("writing retina EEPROM firmware file "+hexFileResourcePath+" with VID="+HexString.toString(VID)+" PID="+HexString.toString(PID)+" DID="+HexString.toString(DID)); HexFileParser parser; try{ parser=new HexFileParser(hexFileResourcePath); }catch(IOException e2){ throw new HardwareInterfaceException(e2.getMessage()+": cannot open resource "+hexFileResourcePath); } ArrayList<HexFileParser.Record> records=parser.getRecords(); int index=0; byte[] b; log.info("writing "+records.size()+" records"); // JFrame frame=new JFrame("EEPROM progress"); // JProgressBar progressBar; // progressBar = new JProgressBar(0, records.size()); // progressBar.setName("EEPROM programming"); // progressBar.setValue(0); // progressBar.setStringPainted(true); // frame.getContentPane().add(progressBar); // frame.pack(); // frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); // frame.setVisible(true); b=new byte[12]; b[0]=(byte)0xC2; // write C2 load format header b[1]=(byte)(VID&0xFF); // vid LSB b[2]=(byte)((VID&0xFF00)>>>8); // vid MSB b[3]=(byte)(PID&0xFF); b[4]=(byte)((PID&0xFF00)>>>8); b[5]=(byte)(DID&0xFF); b[6]=(byte)((DID&0xFF00)>>>8); b[7]=(byte)(0); // configuration byte, DISCON=0 (not disconnected after reset), 400kHz=0 (100kHz I2C bus) writeEEPROM(0,b); // write VID/PID etc header starting at addr 0 index+=b.length; int recNum=0; // now for each hex file record, we must write this record, contiguous with the last one, and each record written to // flash must contain the starting address of how many bytes there are (up to 1023) and where the memory should go in the FX2 RAM. // now write hex file records, one by one for(HexFileParser.Record r:records){ b=new byte[4]; b[0]=(byte)((r.data.length&0xFF00)>>>8); b[1]=(byte)((r.data.length&0xFF)); b[2]=(byte)((r.address&0xFF00)>>>8); b[3]=(byte)((r.address&0xFF)); writeEEPROM(index,b); index+=b.length; writeEEPROM(index, r.data); index+=r.data.length; // progressBar.setValue(recNum++); } // now write footer b=new byte[5]; b[0]=(byte)0x80; b[1]=(byte)0x01; b[2]=(byte)0xe6; b[3]=(byte)0; b[4]=0; writeEEPROM(index,b); index+=b.length; log.info("done writing "+records.size()+" records to EEPROM"); // frame.dispose(); } /** downloads firmware to the FX2 RAM from a hex file. *@param hexFileResourcePath a full path pointing to a resource containing the firmware as output from compiler in Intel hex format. This resource is a file that is somewhere in the classpath, i.e. it is a file *that is included in the project jar. For example: "/ch/unizh/ini/caviar/hardwareinterface/usb/USBAER_FX2LP_Retina.hex" *@see #FIRMWARE_FILENAME_TMPDIFF128_HEX *@see #FIRMWARE_FILENAME_MONITOR_SEQUENCER_HEX */ synchronized public void downloadFirmwareHex(String hexFileResourcePath) throws HardwareInterfaceException{ log.info("downloading to RAM firmware file "+hexFileResourcePath); HexFileParser parser; try{ parser=new HexFileParser(hexFileResourcePath); }catch(FileNotFoundException e){ throw new HardwareInterfaceException(e.getMessage()+": cannot open resource "+hexFileResourcePath); }catch(IOException e2){ throw new HardwareInterfaceException(e2.getMessage()+": cannot open resource "+hexFileResourcePath); } ArrayList<HexFileParser.Record> records=parser.getRecords(); set8051Reset(true); // now for each hex file record, we must write this record, contiguous with the last one, and each record written to // flash must contain the starting address of how many bytes there are (up to 1023) and where the memory should go. // now write hex file records, one by one for(HexFileParser.Record r:records){ download8051RAM(r.address, r.data); } set8051Reset(false); } /** adds a listener for new events captured from the device. * Actually gets called whenever someone looks for new events and there are some using * acquireAvailableEventsFromDriver, not when data is actually captured by AEReader. * Thus it will be limited to the users sampling rate, e.g. the game loop rendering rate. * * @param listener the listener. It is called with a PropertyChangeEvent when new events * are received by a call to {@link #acquireAvailableEventsFromDriver}. * These events may be accessed by calling {@link #getEvents}. */ public void addAEListener(AEListener listener) { support.addPropertyChangeListener(listener); } public void removeAEListener(AEListener listener) { support.removePropertyChangeListener(listener); } /** starts reader buffer pool thread and enables in endpoints for AEs */ public void startAEReader() throws HardwareInterfaceException { // raphael: changed from private to protected, because i need to access this method int status=0; // don't use global status in this function // bind pipe // tobi commented out because old aeReader was preventing reading of events when device was removed and plugged back in. April 2007 // if(aeReaderRunning){ // log.warning("CypressFX2.startAEReader(): already running"); // return; // start the thread that listens for device status information (e.g. timestamp reset) // asyncStatusThread=new AsyncStatusThread(this); //asyncStatusThread.start(); // System.out.println("before starting aereader gUsbIo.isOpen()="+gUsbIo.isOpen()); setAeReader(new AEReader(this)); allocateAEBuffers(); getAeReader().startThread(3); // arg is number of errors before giving up // Thread.currentThread().yield(); // System.out.println("after starting aereader gUsbIo.isOpen()="+gUsbIo.isOpen()); // enableINEndpoint(); already gets enabled in setEventAcquistionEnabled HardwareInterfaceException.clearException(); } // startAEReader long lastTimeEventCaptured=System.currentTimeMillis(); // used for timer to restart IN transfers, in case another connection, e.g. biasgen, has disabled them /** Gets available events from driver. {@link HardwareInterfaceException} is thrown if there is an error. *{@link #overrunOccurred} will be reset after this call. *<p> *This method also starts event acquisition if it is not running already. * *Thread safe: synchronized on access to the capture buffer. * * @return number of events acquired. If this is zero there is no point in getting the events, because there are none. *@throws HardwareInterfaceException *@see #setEventAcquisitionEnabled * * . */ synchronized public AEPacketRaw acquireAvailableEventsFromDriver() throws HardwareInterfaceException { if(!isOpened){ open(); } // make sure event acquisition is running if(!inEndpointEnabled){ setEventAcquisitionEnabled(true); } // HardwareInterfaceException.clearException(); // make sure that event translation from driver is allowed to run if need be, to avoid holding up event sender // Thread.currentThread().yield(); // short[] addresses; // int[] timestamps; int nEvents; // get the 'active' buffer for events (the one that has just been written by the hardware thread) // synchronized(aePacketRawPool){ // synchronize on aeReader so that we don't try to access the events at the same time aePacketRawPool.swap(); lastEventsAcquired=aePacketRawPool.readBuffer(); // log.info(this+" acquired "+lastEventsAcquired); lastEventsAcquired.overrunOccuredFlag=false; // addresses=events.getAddresses(); // timestamps=events.getTimestamps(); nEvents=lastEventsAcquired.getNumEvents(); eventCounter=0; computeEstimatedEventRate(lastEventsAcquired); if(nEvents!=0) support.firePropertyChange(NEW_EVENTS_PROPERTY_CHANGE); // call listeners return lastEventsAcquired; // events=new AEPacketRaw(nEvents); // // reuse same packet to avoid constant new'ing // events.ensureCapacity(nEvents); // if(nEvents==0){ //// log.warning("got zero events from "+this); // computeEstimatedEventRate(null); // events.clear(); // return events; // }else{ // System.arraycopy(addresses, 0, events.getAddresses(), 0, nEvents); // System.arraycopy(timestamps, 0, events.getTimestamps(), 0, nEvents); // events.setNumEvents(nEvents); // computeEstimatedEventRate(events); // support.firePropertyChaNEW_EVENTS_PROPERTY_CHANGEY_CHANGE); // call listeners // return events; } /** the max capacity of this USB2 bus interface is 24MB/sec/4 bytes/event */ public int getMaxCapacity() { return 6000000; } private int estimatedEventRate=0; /** @return event rate in events/sec as computed from last acquisition. * */ public int getEstimatedEventRate() { return estimatedEventRate; } /** computes the estimated event rate for a packet of events */ void computeEstimatedEventRate(AEPacketRaw events){ if(events==null || events.getNumEvents()<2 ) estimatedEventRate=0; else{ int[] ts=events.getTimestamps(); int n=events.getNumEvents(); int dt=ts[n-1]-ts[0]; estimatedEventRate=(int)(1e6f*(float)n/(float)dt); } } /** Returns the number of events acquired by the last call to {@link * #acquireAvailableEventsFromDriver } * @return number of events acquired */ public int getNumEventsAcquired(){ return aePacketRawPool.readBuffer().getNumEvents(); } /** reset the timestamps to zero. This has two effects. First it sends a vendor request down the control endpoint * to tell the device to reset its own internal timestamp counters. Second, it tells the AEReader object to reset its * timestamps, meaning to reset its unwrap counter. */ synchronized public void resetTimestamps() { log.info(this+".resetTimestamps(): zeroing timestamps"); int status=0; // don't use global status in this function dontwrap=true; // this is a flag that is reset in translateEvents method // send vendor request for device to reset timestamps if(gUsbIo==null){ throw new RuntimeException("device must be opened before sending this vendor request"); } // make vendor request structure and populate it USBIO_CLASS_OR_VENDOR_REQUEST VendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); VendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; VendorRequest.Type=UsbIoInterface.RequestTypeVendor; VendorRequest.Recipient=UsbIoInterface.RecipientDevice; VendorRequest.RequestTypeReservedBits=0; VendorRequest.Request=VENDOR_REQUEST_RESET_TIMESTAMPS; VendorRequest.Index=0; VendorRequest.Value=0; USBIO_DATA_BUFFER dataBuffer=new USBIO_DATA_BUFFER(1); dataBuffer.setNumberOfBytesToTransfer(1); // dataBuffer.Buffer()[0]=1; status=gUsbIo.classOrVendorOutRequest(dataBuffer,VendorRequest); if(status!=USBIO_ERR_SUCCESS){ log.warning("CypressFX2.resetTimestamps: couldn't send vendor request to reset timestamps"); } if(getAeReader()!=null) getAeReader().resetTimestamps(); // reset wrap counter and flush buffers else log.warning("CypressFX2.resetTimestamps(): reader not yet started, can't reset timestamps"); // log.info(this+" notifying waiting threads that timestamps have been reset"); // notifyAll(); // notify waiting threads (e.g. StereoHardwareInterface) that timestamps have been reset } /** reset the entire pixel array */ public void resetPixelArray() { // send vendor request for device to reset array int status=0; // don't use global status in this function if(gUsbIo==null){ throw new RuntimeException("device must be opened before sending this vendor request"); } // make vendor request structure and populate it USBIO_CLASS_OR_VENDOR_REQUEST VendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); VendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; VendorRequest.Type=UsbIoInterface.RequestTypeVendor; VendorRequest.Recipient=UsbIoInterface.RecipientDevice; VendorRequest.RequestTypeReservedBits=0; VendorRequest.Request=VENDOR_REQUEST_DO_ARRAY_RESET; VendorRequest.Index=0; VendorRequest.Value=0; USBIO_DATA_BUFFER dataBuffer=new USBIO_DATA_BUFFER(1); dataBuffer.setNumberOfBytesToTransfer(1); // dataBuffer.Buffer()[0]=1; status=gUsbIo.classOrVendorOutRequest(dataBuffer,VendorRequest); if(status!=USBIO_ERR_SUCCESS){ log.warning("CypressFX2.resetPixelArray: couldn't send vendor request to reset array"); } } protected boolean arrayResetEnabled=false; /** set the board LED state. Useful for debugging. Not available for CypressFX2MonitorSequencer * @param value true to turn it on, false to turn it off. */ synchronized public void setLed(boolean value) { // send vendor request for device to reset array int status=0; // don't use global status in this function if(gUsbIo==null){ throw new RuntimeException("device must be opened before sending this vendor request"); } // make vendor request structure and populate it USBIO_CLASS_OR_VENDOR_REQUEST VendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); VendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; VendorRequest.Type=UsbIoInterface.RequestTypeVendor; VendorRequest.Recipient=UsbIoInterface.RecipientDevice; VendorRequest.RequestTypeReservedBits=0; VendorRequest.Request=VENDOR_REQUEST_SET_LED; VendorRequest.Index=0; VendorRequest.Value=(short)(value?0:1); // this is the request bit, if value true, send value 0, false send value 1 // on the board, 1 actually turns off the LED because the anode is tied to Vdd and the cathode to the GPIO output USBIO_DATA_BUFFER dataBuffer=new USBIO_DATA_BUFFER(0); // no data, value is in request value dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length); status=gUsbIo.classOrVendorOutRequest(dataBuffer,VendorRequest); if(status!=USBIO_ERR_SUCCESS){ log.warning("CypressFX2.resetPixelArray: couldn't send vendor request to set LED"); } } /** Is true if an overrun occured in the driver (><code> AE_BUFFER_SIZE</code> events) during the period before the last time {@link * #acquireAvailableEventsFromDriver } was called. This flag is cleared by {@link #acquireAvailableEventsFromDriver}, so you need to * check it before you acquire the events. *<p> *If there is an overrun, the events grabbed are the most ancient; events after the overrun are discarded. The timestamps continue on but will *probably be lagged behind what they should be. * @return true if there was an overrun. */ public boolean overrunOccurred(){ // synchronized(aePacketRawPool){ return aePacketRawPool.readBuffer().overrunOccuredFlag; } /** Closes the device. Never throws an exception. */ synchronized public void close(){ if(!isOpened){ // log.warning("CypressFX2.close(): not open"); return; } try{ // if (this.isEventAcquisitionEnabled()) { setEventAcquisitionEnabled(false); stopAEReader(); if(asyncStatusThread!=null) asyncStatusThread.stopThread(); }catch(HardwareInterfaceException e){ e.printStackTrace(); } // log.info("Cycling port on close()"); gUsbIo.cyclePort(); gUsbIo.close(); UsbIo.destroyDeviceList(gDevList); // log.info("USBIOInterface.close(): device closed"); inEndpointEnabled=false; isOpened=false; } // not really necessary to stop this thread, i believe, because close will unbind already according to usbio docs public void stopAEReader() { // raphael: changed from private to protected, because i need to access this method if(getAeReader()!=null){ // System.out.println("CypressFX2.stopAEReader(): stopping aeReader thread"); getAeReader().shutdownThread(); // unbind pipe getAeReader().unbind(); // close device getAeReader().close(); setAeReader(null); } // asyncStatusThread=null; } /** sends vendor request to trigger an immediate commit of whatever is in the endpoint fifo immediately. * next call to <@link #acquireAvailableEventsFromDriver} will get these events if you wait a bit. */ synchronized public void requestEarlyTransfer() throws HardwareInterfaceException { // start getting events by sending vendor request 0xb3 to control endpoint 0 // documented in firmware FX2_to_extFIFO.c // make vendor request structure and populate it USBIO_CLASS_OR_VENDOR_REQUEST VendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); int status=0; // don't use global status in this function VendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; VendorRequest.Type=UsbIoInterface.RequestTypeVendor; VendorRequest.Recipient=UsbIoInterface.RecipientDevice; VendorRequest.RequestTypeReservedBits=0; VendorRequest.Request=(byte)VENDOR_REQUEST_EARLY_TRANFER; VendorRequest.Index=0; USBIO_DATA_BUFFER dataBuffer=new USBIO_DATA_BUFFER(1); VendorRequest.Value=0; // (byte)VENDOR_REQUEST_START_TRANSFER; dataBuffer=new USBIO_DATA_BUFFER(1); dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length); dataBuffer.Buffer()[0]=1; status=gUsbIo.classOrVendorOutRequest(dataBuffer,VendorRequest); if(status!=USBIO_ERR_SUCCESS){ throw new HardwareInterfaceException("Unable to send vendor request to send events early: "+UsbIo.errorText(status)); } HardwareInterfaceException.clearException(); } /** @return true if inEndpoint was enabled. * However, some other connection (e.g. biasgen) could have disabled the in transfers. */ public boolean isInEndpointEnabled() { return this.inEndpointEnabled; } /** sends a vendor request to enable or disable in transfers of AEs *@param inEndpointEnabled true to send vendor request to enable, false to send request to disable */ public void setInEndpointEnabled(final boolean inEndpointEnabled) throws HardwareInterfaceException { if(inEndpointEnabled) enableINEndpoint(); else disableINEndpoint(); } synchronized void enableINEndpoint() throws HardwareInterfaceException { // start getting events by sending vendor request 0xb3 to control endpoint 0 // documented in firmware FX2_to_extFIFO.c // System.out.println("USBAEMonitor.enableINEndpoint()"); // make vendor request structure and populate it if(gUsbIo==null){ log.warning("CypressFX2.enableINEndpoint(): null USBIO device"); return; } int status=0; // don't use global status in this function USBIO_CLASS_OR_VENDOR_REQUEST VendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); VendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; VendorRequest.Type=UsbIoInterface.RequestTypeVendor; VendorRequest.Recipient=UsbIoInterface.RecipientDevice; VendorRequest.RequestTypeReservedBits=0; VendorRequest.Request=(byte)VENDOR_REQUEST_START_TRANSFER; VendorRequest.Index=0; VendorRequest.Value=0; USBIO_DATA_BUFFER dataBuffer=new USBIO_DATA_BUFFER(0); dataBuffer.setNumberOfBytesToTransfer(0); status=gUsbIo.classOrVendorOutRequest(dataBuffer,VendorRequest); if(status!=USBIO_ERR_SUCCESS){ close(); throw new HardwareInterfaceException("Unable to send vendor request to send events: "+UsbIo.errorText(status)); }else inEndpointEnabled=true; HardwareInterfaceException.clearException(); } synchronized void disableINEndpoint(){ // stop endpoint sending events by sending vendor request 0xb4 to control endpoint 0 // these requests are docuemented in firmware file FX2_to_extFIFO.c // make vendor request structure and populate it int status=0; // don't use global status in this function USBIO_CLASS_OR_VENDOR_REQUEST VendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); VendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; VendorRequest.Type=UsbIoInterface.RequestTypeVendor; VendorRequest.Recipient=UsbIoInterface.RecipientDevice; VendorRequest.RequestTypeReservedBits=0; VendorRequest.Request=VENDOR_REQUEST_STOP_TRANSFER; VendorRequest.Index=0; VendorRequest.Value=0; USBIO_DATA_BUFFER dataBuffer=new USBIO_DATA_BUFFER(0); dataBuffer.setNumberOfBytesToTransfer(0); status=gUsbIo.classOrVendorOutRequest(dataBuffer,VendorRequest); if(status!=USBIO_ERR_SUCCESS){ log.info("disableINEndpoint: couldn't send vendor request to disable IN transfers--it could be that device is gone or sendor is OFF and and completing GPIF cycle"); }else inEndpointEnabled=false; HardwareInterfaceException.clearException(); } class AsyncStatusThread extends Thread { UsbIoPipe pipe; CypressFX2 monitor; boolean stop=false; byte msg; AsyncStatusThread(CypressFX2 monitor) { this.monitor=monitor; } public void stopThread(){ if (pipe!=null) pipe.abortPipe(); interrupt(); } public void run(){ setName("AsyncStatusThread"); int status; UsbIoBuf buffer=new UsbIoBuf(64); // size of EP1 pipe=new UsbIoPipe(); status=pipe.bind(monitor.getInterfaceNumber(), STATUS_ENDPOINT_ADDRESS, gDevList, GUID); if(status!=USBIO_ERR_SUCCESS){ log.warning("error binding to pipe for EP1 for device status: "+UsbIo.errorText(status)); } USBIO_PIPE_PARAMETERS pipeParams=new USBIO_PIPE_PARAMETERS(); pipeParams.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; status=pipe.setPipeParameters(pipeParams); if (status != USBIO_ERR_SUCCESS) { log.warning("can't set pipe parameters: "+UsbIo.errorText(status)); } while(!stop && !isInterrupted()){ buffer.NumberOfBytesToTransfer=64; status=pipe.read(buffer); if (status == 0) { if(stop) log.info("Error submitting read on status pipe: "+UsbIo.errorText(buffer.Status)); break; } status=pipe.waitForCompletion(buffer); if (status != 0 && buffer.Status!=UsbIoErrorCodes.USBIO_ERR_CANCELED) { if(!stop && !isInterrupted()) log.warning("Error waiting for completion of read on status pipe: "+UsbIo.errorText(buffer.Status)); break; } if(buffer.BytesTransferred>0){ msg=buffer.BufferMem[0]; if(msg==1){ AEReader rd= getAeReader(); if (rd!=null) { log.info("*********************************** CypressFX2.AsyncStatusThread.run(): timestamps externally reset"); rd.resetTimestamps(); } else { log.info("Received timestamp external reset message, but monitor is not running"); } } } // we get 0 byte read on stopping device } // System.out.println("Status reader thread terminated."); } // run() } //protected boolean relativeTimestampMode=false; // not used anymore //raphael: need this variable to branch in AEReader volatile boolean dontwrap=false; // used for resetTimestamps int aeReaderFifoSize=prefs.getInt("CypressFX2.AEReader.fifoSize",8192); /** sets the buffer size for the aereader thread. optimal size depends on event rate, for high event * rates, at least 4096 bytes should be chosen, using caviarviewer and low event rates need smaller * buffer size to produce suitable frame rates*/ public void setAEReaderFifoSize(int size) { this.aeReaderFifoSize=size; prefs.putInt("CypressFX2.AEReader.fifoSize",size); } int aeReaderNumBuffers=prefs.getInt("CypressFX2.AEReader.numBuffers",4); /** sets the number of buffers for the aereader thread.*/ public void setAEReaderNumBuffers(int num) { this.aeReaderNumBuffers=num; prefs.putInt("CypressFX2.AEReader.numBuffers",num); } /** * AE reader class. the thread continually reads events into buffers. when a buffer is read, ProcessData transfers and transforms the buffer data to AE address * and timestamps information and puts it in the addresses and timestamps arrays. a call to acquireAvailableEventsFromDriver copies the events to enw user * arrays that can be accessed by getEvents() (this packet is also returned by {@link #acquireAvailableEventsFromDriver}). The relevant methods are synchronized so are thread safe. */ public class AEReader extends UsbIoReader implements ReaderBufferControl{ public final int MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT=10; private int numNonMonotonicTimeExceptionsPrinted=0; int cycleCounter=0; volatile boolean timestampsReset=false; // used to tell processData that another thread has reset timestamps private int badWrapCounter=0; // counts number of bad timestamp captures (timestamp went backwards) final int BAD_WRAP_PRINT_INTERVAL=100; // only print a warning every this many to avoid slowing down critical process /** the priority for this monitor acquisition thread. This should be set high (e.g. Thread.MAX_PRIORITY) so that the thread can * start new buffer reads in a timely manner so that the sender does not get blocked * */ public static final int MONITOR_PRIORITY=Thread.MAX_PRIORITY; // Thread.NORM_PRIORITY+2 /** size of CypressFX2 USB fifo's in bytes. */ public static final int CYPRESS_FIFO_SIZE=512; /** the default number of USB read buffers used in the reader */ public static final int CYPRESS_NUM_BUFFERS=2; /** the number of capture buffers for the buffer pool for the translated address-events. * These buffers allow for smoother access to buffer space by the event capture thread */ private int numBuffers=prefs.getInt("CypressFX2.AEReader.numBuffers",CYPRESS_NUM_BUFFERS); /** size of FIFOs in bytes used in AEReader for event capture from device. * This does not have to be the same size as the FIFOs in the CypressFX2 (512 bytes). If it is too small, then there * are frequent thread context switches that can greatly slow down rendering loops. */ private int fifoSize=prefs.getInt("CypressFX2.AEReader.fifoSize",CYPRESS_FIFO_SIZE); // 512; CypressFX2 monitor=null; public AEReader(CypressFX2 m) throws HardwareInterfaceException { super(); monitor=m; fifoSize=monitor.aeReaderFifoSize; numBuffers=monitor.aeReaderNumBuffers; int status; status = bind(monitor.getInterfaceNumber(),AE_MONITOR_ENDPOINT_ADDRESS, gDevList, GUID); // device has already been opened so we don't need all the params if (status != USBIO_ERR_SUCCESS) { throw new HardwareInterfaceException("can't bind pipe: "+UsbIo.errorText(status)); } USBIO_PIPE_PARAMETERS pipeParams=new USBIO_PIPE_PARAMETERS(); pipeParams.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; status=setPipeParameters(pipeParams); if (status != USBIO_ERR_SUCCESS) { throw new HardwareInterfaceException("can't set pipe parameters: "+UsbIo.errorText(status)); } } public String toString(){ return "AEReader for "+CypressFX2.this; } // called before buffer is submitted to driver public void processBuffer(UsbIoBuf Buf) { Buf.NumberOfBytesToTransfer = Buf.Size; Buf.BytesTransferred = 0; Buf.OperationFinished = false; // System.out.println("ProcessBuffer (before read)"); } /** Resets the timestamp unwrap value, resets the USBIO pipe, and resets the AEPacketRawPool. */ synchronized public void resetTimestamps(){ log.info(CypressFX2.this+": wrapAdd="+wrapAdd+", zeroing it"); wrapAdd=WRAP_START; lasttimestamp=0; lastshortts=0; // try{ // setEventAcquisitionEnabled(false); // abortPipe(); // resetPipe(); // make sure to flush all the buffers // setEventAcquisitionEnabled(true); // }catch(HardwareInterfaceException e){ // e.printStackTrace(); //aePacketRawPool.reset(); // raphael: took it out here because pool gets reset in processBuffer timestampsReset=true; // will inform reader thread that timestamps are reset } // log packet times // final int NTIMES=100; // long[] times=new long[NTIMES]; // PrintWriter timeWriter=null; // long lastTime=System.nanoTime(); /** Called on completion of read on a data buffer is received from USBIO driver. * @param Buf the data buffer with raw data */ public void processData(UsbIoBuf Buf) { cycleCounter++; // instrument cycle times // long thisTime=System.nanoTime(); // times[cycleCounter%NTIMES]=thisTime-lastTime; // lastTime=thisTime; // if(cycleCounter%NTIMES==0){ // try { // if(timeWriter==null){ // timeWriter=new PrintWriter("cycleTimes.csv"); // for(long t:times){ // timeWriter.format("%d\n",t); // timeWriter.flush(); // } catch (FileNotFoundException ex) { // ex.printStackTrace(); // System.out.print("."); // if(cycleCounter%80==0) System.out.println(""); // System.out.flush(); synchronized(aePacketRawPool){ if (Buf.Status == USBIO_ERR_SUCCESS || Buf.Status==USBIO_ERR_CANCELED ) { // System.out.println("ProcessData: "+Buf.BytesTransferred+" bytes transferred: "); if (monitor.getDID()==CypressFX2.DID_STEREOBOARD) { translateEvents_EmptyWrapEvent(Buf); } else if ((monitor.getPID()==PID_USBAERmini2) || (monitor.getPID()==PID_USB2AERmapper) ) { translateEvents_EmptyWrapEvent(Buf); CypressFX2MonitorSequencer seq=(CypressFX2MonitorSequencer)(CypressFX2.this); // seq.mapPacket(captureBufferPool.active()); } else if(monitor.getPID()==PID_TCVS320_RETINA){ translateEvents_TCVS320(Buf); }else { // original format with timestamps that just wrap translateEvents(Buf); } // pop.play(); if(chip!=null && chip.getFilterChain()!=null && chip.getFilterChain().getProcessingMode()==FilterChain.ProcessingMode.ACQUISITION){ // here we do the realTimeFiltering. We finished capturing this buffer's worth of events, now process them // apply realtime filters and realtime (packet level) mapping // synchronize here so that rendering thread doesn't swap the buffer out from under us while we process these events // aePacketRawPool.writeBuffer is also synchronized so we get the same lock twice which is ok AEPacketRaw buffer=aePacketRawPool.writeBuffer(); int[] addresses=buffer.getAddresses(); int[] timestamps=buffer.getTimestamps(); realTimeFilter(eventCounter,addresses,timestamps); } } else { log.warning("ProcessData: Bytes transferred: " + Buf.BytesTransferred + " Status: " + UsbIo.errorText(Buf.Status)); monitor.close(); } if(timestampsReset){ log.info("timestampsReset: flushing aePacketRawPool buffers"); aePacketRawPool.reset(); //this is already done in resetTimestamps() why do it again here? timestampsReset=false; } } } // sync so that we don't try to copy events while buffer is being translated // this method extracts addresses and timestamps and copies them to the instance addresses and timestamps arrays, where they will be accessed // later by the acquireAvailableEventsFromDriver method (which copies them to returned user arrays) // note timestamps are multiplied by 10 so that they are in us, because the cypress fx2 retina board uses the // timer1 interrupt with period 10us to clock the timestamps counters final int REAL_WRAP_TIME_MS=TICK_US_BOARD*((1<<16)-1)/1000; // this is wrap time in ms on device timestamp counter, e.g. 650ms // it is used below to check for bogus timetamp wraps due to glitches in sampling timestamp counter output long lastWrapTimeMs=System.currentTimeMillis(); volatile int lastshortts=0, tsinccounter=0; volatile int lasttimestamp=0; // final long START=(1L<<30L); final int WRAP_START=0; //(int)(0xFFFFFFFFL&(2147483648L-0x400000L)); // set high to test big wrap 1<<30; // wrapAdd is the time to add to short timestamp to unwrap it volatile int wrapAdd=WRAP_START; int lastWrapAdd=0; boolean wrappedBig=false; // indicates that wrapAdd has just wrapped itself, so that we should allow nonmonotonic timestamp /** Populates the AE array, translating from raw bufffer data to raw addresses and unwrapped timestamps. *<p> * Event addresses and timestamps are sent from USB device in BIG-ENDIAN format. MSB comes first, * The addresses are simply copied over, and the timestamps are unwrapped to make 32 bit int timestamps. *<p> * Wrapping is detected differently depending on whether the hardware sends empty wrap packets or simply wraps the timestamps. * When the timestamps simply wrap, then a wrap is detected when the present timestamp is less than the previous one. * Then we assume the counter has wrapped--but only once--and add into this and subsequent * timestamps the wrap value of 2^16. this offset is maintained and increases every time there * is a wrap. Hence it integrates the wrap offset. * *<p> *Newer USB monitor interfaces based on using a CPLD pumping data into the CypressFX2 in slave FIFO mode signal a timestamp *wrap by sending an empty wrap event;see {@link #translateEvents_EmptyWrapEvent}. * * <p> * The timestamp is returned in 1 us ticks. * This conversion is to make values more compatible with other CAVIAR software components. *<p> *If an overrun has occurred, then the data is still translated up to the overrun. *@see #translateEvents_EmptyWrapEvent *@see #translateEvents_TCVS320 *@param b the data buffer */ synchronized protected void translateEvents(UsbIoBuf b){ boolean badwrap; // System.out.println("buf has "+b.BytesTransferred+" bytes"); // synchronized(aePacketRawPool){ if(aePacketRawPool.writeBuffer().overrunOccuredFlag) return; // don't bother if there's already an overrun, consumer must get the events to clear this flag before there is more room for new events int shortts; byte[] aeBuffer=b.BufferMem; // byte lsb,msb; int bytesSent=b.BytesTransferred; if(bytesSent%4!=0){ // System.err.println("CypressFX2.AEReader.translateEvents(): warning: "+bytesSent+" bytes sent, which is not multiple of 4"); bytesSent=(bytesSent/4)*4; // truncate off any extra part-event } AEPacketRaw activeBuffer=aePacketRawPool.writeBuffer(); int[] addresses=activeBuffer.getAddresses(); int[] timestamps=activeBuffer.getTimestamps(); long timeNowMs=System.currentTimeMillis(); realTimeEventCounterStart=eventCounter; // write the start of the packet activeBuffer.lastCaptureIndex=eventCounter; for(int i=0;i<bytesSent;i+=4){ if(eventCounter>AE_BUFFER_SIZE-1){ activeBuffer.overrunOccuredFlag=true; // log.warning("overrun"); return; // return, output event buffer is full and we cannot add any more events to it. //no more events will be translated until the existing events have been consumed by acquireAvailableEventsFromDriver } // according to FX2 tech ref manual 10.2.8, words from GPIF databus are sent over usb as LSB then MSB. // therefore AE07 come first, then AE8-15, then TS0-7, then TS8-15 // address is LSB MSB addresses[eventCounter]=(short)(0xffff&((short)aeBuffer[i]&0xff | ((short)aeBuffer[i+1]&0xff)<<8)); // same for timestamp, LSB MSB shortts=(aeBuffer[i+2]&0xff | ((aeBuffer[i+3]&0xff)<<8)); // this is 16 bit value of timestamp in TICK_US tick // shortts could be a negative short value, but each ts should be greater than the last one until 16 bit rollover // tobi added following heuristic 12/05 to help deal with problem bit in timestamp counter that apparently gets read incorrectly // occasionally, leading to excessive numbers of timestamp wraps // the preceeding special condition still occurs on tmpdiff128 usb2 cypress retina boards depending on something probably // in cypress firmware and reset state, relative to cypress GPIF interface. not understood as of 10/2006. see below if(shortts<lastshortts){ // if new counter value is less than previous one, assume counter has wrapped around. if(dontwrap){ dontwrap=false; // this flag is set in outer method resetTimestamps, it should prevent badwrap messages here // even though resetting the timestamps has caused device timestamps to reset }else{ // we count how many bits have changed since last timestamp. if timestamp has gone backwards because of a real wrap, then // lots of bits should have changed, e.g from 0xfe to 0x03. but if the timestamp has gone backwards because a single // or two bits have been latched incorrectly, then we count this as bad wrap event. int or=shortts^lastshortts; int bc=Integer.bitCount(or); // System.err.println("wrap, "+bc+" bits changed"); // usually 15/16 bits change or at least 8 when activity is very low if(bc<7){ // the timestamp has gone backwards, but this one is due to reading timestamp counter incorrectly. // this is NOT a real wrap, caused by glitch in sampling counter output during count change or something wierd. long dt=timeNowMs-lastWrapTimeMs; // if(badWrapCounter++%BAD_WRAP_PRINT_INTERVAL==0){ // System.err.println("*** BAD WRAP: Event #"+eventCounter+" Real dt="+dt+" ms, shortts=" // +HexString.toString(shortts)+" lastshortts=" // +HexString.toString(lastshortts)+" wraps="+wrapAdd/0x10000L); // if this is a bad wrap, then keep the last shortts instead of choosing the one that goes backwards in time // shortts=lastshortts; // badwrap=true; // this has problem that lastshortts doesn't get updated, so there can be a lot of bad wraps signaled. }else{ // this IS a real counter wrap // now we need to increment the wrapAdd lastWrapAdd=wrapAdd; wrapAdd += 0x10000*TICK_US_BOARD; // we put the tick here to correctly detect big wraps // This is 0xFFFF +1; if we wrapped then increment wrap value by 2^16 // if(wrapAdd<lastWrapAdd) { // wrappedBig=true; // }else { // wrappedBig=false; lastWrapTimeMs=timeNowMs; // System.out.println(this+" incremented wrapAdd to "+wrapAdd/(0x10000L)/TICK_US_BOARD+" wraps"); } } } // compute tentative value of new timestamp /* hex translation 0 0x0 0000 1 0x1 0001 2 0x2 0010 3 0x3 0011 4 0x4 0100 5 0x5 0101 6 0x6 0110 7 0x7 0111 8 0x8 1000 9 0x9 1001 10 0xa 1010 11 0xb 1011 12 0xc 1100 13 0xd 1101 14 0xe 1110 15 0xf 1111 */ private int transState=0; // state of data translator private int lasty=0; private int lastts=0; // DEBUG // TobiLogger tobiLogger=new TobiLogger("CypressFX2","# logged cypressfx2 data\n#eventCounter buf[i] buf[i+1]"); /** Method to translate the UsbIoBuffer for the TCVS320 sensor which uses the 32 bit address space. *<p> * It has a CPLD to timetamp events and uses the CypressFX2 in slave * FIFO mode. *<p>The TCVS320 has a burst mode readout mechanism that outputs a row address, then all the latched column addresses. *The columns are output left to right. A timestamp is only meaningful at the row addresses level. Therefore *the board timestamps on row address, and then sends the data in the following sequence: row, timestamp, col, col, col,...., row,timestamp,col,col... * <p> *The bit encoding of the data is as follows *<literal> Address bit Address bit pattern 0 LSB Y or Polarity ON=1 1 Y1 or LSB X 2 Y2 or X1 3 Y3 or X2 4 Y4 or X3 5 Y5 or X4 6 Y6 or X5 7 MSBY or X6 8 intensity or X7 9 MSBX 10 Y=0, X=1 Address Address Name 00xx xxxx xxxx xxxx pixel address 01xx xxxx xxxx xxxx timestamp 10xx xxxx xxxx xxxx wrap 11xx xxxx xxxx xxxx timestamp reset </literal> *The msb of the 16 bit timestamp is used to signal a wrap (the actual timestamp is only 15 bits). * The wrapAdd is incremented when an emtpy event is received which has the timestamp bit 15 * set to one. *<p> * Therefore for a valid event only 15 bits of the 16 transmitted timestamp bits are valid, bit 15 * is the status bit. overflow happens every 32 ms. * This way, no roll overs go by undetected, and the problem of invalid wraps doesn't arise. *@param b the data buffer *@see #translateEvents */ protected void translateEvents_TCVS320(UsbIoBuf b){ try{ final int STATE_IDLE=0,STATE_GOTY=1,STATE_GOTTS=2; // if(tobiLogger.isEnabled()==false) tobiLogger.setEnabled(true); //debug synchronized(aePacketRawPool){ AEPacketRaw buffer=aePacketRawPool.writeBuffer(); if(buffer.overrunOccuredFlag) return; // don't bother if there's already an overrun, consumer must get the events to clear this flag before there is more room for new events int shortts; int NumberOfWrapEvents; NumberOfWrapEvents=0; int numberOfY=0; byte[] buf=b.BufferMem; int bytesSent=b.BytesTransferred; if(bytesSent%2!=0){ System.err.println("CypressFX2.AEReader.translateEvents(): warning: "+bytesSent+" bytes sent, which is not multiple of 2"); bytesSent=(bytesSent/2)*2; // truncate off any extra part-event } int[] addresses=buffer.getAddresses(); int[] timestamps=buffer.getTimestamps(); // write the start of the packet buffer.lastCaptureIndex=eventCounter; // tobiLogger.log("#packet"); for(int i=0;i<bytesSent;i+=2){ // tobiLogger.log(String.format("%d %x %x",eventCounter,buf[i],buf[i+1])); // DEBUG int val=(buf[i+1] << 8) + buf[i]; // 16 bit value of data int code=(buf[i+1]&0xC0)>>6; // (val&0xC000)>>>14; // log.info("code " + code); switch(code){ case 3: // due to some error in the vhdl code, addresses get coded as timestamp resets case 0: // address if ((buf[i+1] & 0x04) == 0x04) //// changed for debugging // received an X address((buf[i+1] & 0x02) == 0x02) { // x adddress int xadd=(((0x03 & buf[i+1]) ^ 0x02) << 8 ) | (buf[i]&0xff); addresses[eventCounter]= (lasty << 12 ) | xadd; //(0xffff&((short)buf[i]&0xff | ((short)buf[i+1]&0xff)<<8)); /** Method that translates the UsbIoBuffer when a board that has a CPLD to timetamp events and that uses the CypressFX2 in slave * FIFO mode, such as the USBAERmini2 board or StereoRetinaBoard, is used. * <p> *On these boards, the msb of the timestamp is used to signal a wrap (the actual timestamp is only 15 bits). * * The wrapAdd is incremented when an emtpy event is received which has the timestamp bit 15 * set to one. *<p> * Therefore for a valid event only 15 bits of the 16 transmitted timestamp bits are valid, bit 15 * is the status bit. overflow happens every 32 ms. * This way, no roll overs go by undetected, and the problem of invalid wraps doesn't arise. *@param b the data buffer *@see #translateEvents */ protected void translateEvents_EmptyWrapEvent(UsbIoBuf b){ // System.out.println("buf has "+b.BytesTransferred+" bytes"); synchronized(aePacketRawPool){ AEPacketRaw buffer=aePacketRawPool.writeBuffer(); if(buffer.overrunOccuredFlag) return; // don't bother if there's already an overrun, consumer must get the events to clear this flag before there is more room for new events int shortts; int NumberOfWrapEvents; NumberOfWrapEvents=0; byte[] aeBuffer=b.BufferMem; // byte lsb,msb; int bytesSent=b.BytesTransferred; if(bytesSent%4!=0){ // System.out.println("CypressFX2.AEReader.translateEvents(): warning: "+bytesSent+" bytes sent, which is not multiple of 4"); bytesSent=(bytesSent/4)*4; // truncate off any extra part-event } int[] addresses=buffer.getAddresses(); int[] timestamps=buffer.getTimestamps(); // write the start of the packet buffer.lastCaptureIndex=eventCounter; for(int i=0;i<bytesSent;i+=4){ if(eventCounter>AE_BUFFER_SIZE-1){ buffer.overrunOccuredFlag=true; // log.warning("overrun"); return; // return, output event buffer is full and we cannot add any more events to it. //no more events will be translated until the existing events have been consumed by acquireAvailableEventsFromDriver } if((aeBuffer[i+3]&0x80)==0x80){ // timestamp bit 16 is one -> wrap // now we need to increment the wrapAdd if (this.monitor.getPID()== this.monitor.PID_USBAERmini2 && this.monitor.getDID()==(short)0x0001) { wrapAdd+=0x4000L; //uses only 14 bit timestamps } else { wrapAdd+=0x8000L; // This is 0x7FFF +1; if we wrapped then increment wrap value by 2^15 } //System.out.println("received wrap event, index:" + eventCounter + " wrapAdd: "+ wrapAdd); NumberOfWrapEvents++; } else if ((aeBuffer[i+3]&0x40)==0x40 && this.monitor.getPID()==this.monitor.PID_USBAERmini2 && this.monitor.getDID() == (short)0x0001 ) { // this firmware version uses reset events to reset timestamps this.resetTimestamps(); // log.info("got reset event, timestamp " + (0xffff&((short)aeBuffer[i]&0xff | ((short)aeBuffer[i+1]&0xff)<<8))); } else { // address is LSB MSB addresses[eventCounter]=(int)((aeBuffer[i]&0xFF) | ((aeBuffer[i+1]&0xFF)<<8)); // same for timestamp, LSB MSB shortts=(aeBuffer[i+2]&0xff | ((aeBuffer[i+3]&0xff)<<8)); // this is 15 bit value of timestamp in TICK_US tick /** * Applies the filterChain processing on the most recently captured data. The processing is done * by extracting the events just captured and then applying the filter chain. * <strong>The filter outputs are discarded and * will not be visble in the rendering of the chip output, but may be used for motor control or other purposes. * </strong> * <p> * TODO: at present this processing is redundant in that the most recently captured events are copied to a * different AEPacketRaw, extracted to an EventPacket, and then processed. This effort is duplicated * later in rendering. This should be fixed somehow. * @param eventCounter the number of valid events stored in arrays * @param addresses the raw input addresses; these are filtered in place * @param timestamps the input timestamps */ private void realTimeFilter(int eventCounter, int[] addresses, int[] timestamps) { if(!chip.getFilterChain().isAnyFilterEnabled()) return; // initialize packets if(realTimeRawPacket==null) realTimeRawPacket=new AEPacketRaw(getNumRealTimeEvents()); else realTimeRawPacket.ensureCapacity(getNumRealTimeEvents()); // // copy data to real time raw packet // if(addresses==null || timestamps==null){ // log.warning("realTimeFilter: addresses or timestamp array became null"); // }else{ int nevents=getNumRealTimeEvents(); try{ System.arraycopy(addresses,realTimeEventCounterStart,realTimeRawPacket.getAddresses(),0,nevents); System.arraycopy(timestamps,realTimeEventCounterStart,realTimeRawPacket.getTimestamps(),0,nevents); }catch(IndexOutOfBoundsException e){ e.printStackTrace(); } realTimeRawPacket.setNumEvents(nevents); // init extracted packet if(realTimePacket==null) realTimePacket=new EventPacket(chip.getEventClass()); // extract events for this filter. This duplicates later effort during rendering and should be fixed for later. // at present this may mess up everything else because the output packet is reused. chip.getEventExtractor().extractPacket(realTimeRawPacket,realTimePacket); getChip().getFilterChain().filterPacket(realTimePacket); // we don't do following because the results are an AEPacketRaw that still needs to be written to addresses/timestamps // and this is not done yet. at present results of realtime filtering are just not rendered at all. // that means that user will see raw events, e.g. if BackgroundActivityFilter is used, then user will still see all // events because the filters are not applied for normal rendering. (If they were applied, then the filters would // be in a funny state becaues they would process the same data more than once and out of order, resulting in all kinds // of problems.) // However, the graphical annotations (like the boxes drawn around clusters in RectangularClusterTracker) // done by the real time processing are still shown when the rendering thread calls the // annotate methods. // chip.getEventExtractor().reconstructRawPacket(realTimePacket); } } int getNumRealTimeEvents(){ return eventCounter-realTimeEventCounterStart; } void allocateAEBuffers(){ synchronized(aePacketRawPool){ aePacketRawPool.allocateMemory(); } } /** @return the size of the buffer for AEs */ public int getAEBufferSize() { return aePacketRawPool.writeBuffer().getCapacity(); } /** set the size of the host buffer. Default is AE_BUFFER_SIZE. You can set this larger if you *have overruns because your host processing (e.g. rendering) is taking too long. *<p> *This call discards collected events. * @param size of buffer in events */ public void setAEBufferSize(int size) { allocateAEBuffers(); } public void onAdd() { log.info("USBAEMonitor.onAdd(): device added"); } public void onRemove() { log.info("USBAEMonitor.onRemove(): device removed"); } /** start or stops the event acquisition. sends apropriate vendor request to * device and starts or stops the AEReader * @param enable boolean to enable or disable event acquisition */ synchronized public void setEventAcquisitionEnabled(boolean enable) throws HardwareInterfaceException { // log.info("setting event acquisition="+enable); setInEndpointEnabled(enable); if(enable) startAEReader(); else stopAEReader(); } public boolean isEventAcquisitionEnabled() { return isInEndpointEnabled(); } public String getTypeName() { return "CypressFX2"; } /** the first USB string descriptor (Vendor name) (if available) */ protected USB_STRING_DESCRIPTOR stringDescriptor1 = new USB_STRING_DESCRIPTOR(); /** the second USB string descriptor (Product name) (if available) */ protected USB_STRING_DESCRIPTOR stringDescriptor2 = new USB_STRING_DESCRIPTOR(); /** the third USB string descriptor (Serial number) (if available) */ protected USB_STRING_DESCRIPTOR stringDescriptor3 = new USB_STRING_DESCRIPTOR(); protected int numberOfStringDescriptors=2; /** returns number of string descriptors * @return number of string descriptors: 2 for TmpDiff128, 3 for MonitorSequencer */ public int getNumberOfStringDescriptors() { return numberOfStringDescriptors; } /** the USBIO device descriptor */ protected USB_DEVICE_DESCRIPTOR deviceDescriptor = new USB_DEVICE_DESCRIPTOR(); /** the UsbIo interface to the device. This is assigned on construction by the * factory which uses it to open the device. here is used for all USBIO access * to the device*/ protected UsbIo gUsbIo=null; /** the devlist handle for USBIO */ protected int gDevList; // 'handle' (an integer) to an internal device list static to UsbIo // void buildUsbInterfaceList(){ // buildUsbIoList(); // usbList=new ArrayList<USBInterface>(); // for(UsbIo u:usbioList){ // try{ //// open(); //// usbList.add(this); //// CypressFX2 dev=new CypressFX2(); //// dev.gUsbIo=u; //// dev.open(); // openUsbIo(u); // usbList.add(this); // }catch(USBInterfaceException e){ // return; /** checks if device has a string identifier that is a non-empty string *@return false if not, true if there is one */ protected boolean hasStringIdentifier(){ // get string descriptor status = gUsbIo.getStringDescriptor(stringDescriptor1,(byte)1,0); if (status != USBIO_ERR_SUCCESS) { return false; } else { if(stringDescriptor1.Str.length()>0) return true; } return false; } /** constrcuts a new USB connection, opens it. Does NOT start event acquisition. * @see #setEventAcquisitionEnabled */ public void open() throws HardwareInterfaceException { // log.info(Thread.currentThread()+": CypressFX2.open()"); openUsbIo(); // setEventAcquisitionEnabled(true); // don't enable anymore, do this instead in acquireAvailableEventsFromDriver if necessary HardwareInterfaceException.clearException(); } /** * This method does the hard work of opening the device, downloading the firmware, making sure everything is OK. *<p> * This method is synchronized to prevent multiple threads from trying to open at the same time, e.g. a GUI thread and the main thread. *<p> * Opening the device after it has already been opened has no effect. * * @see #close *@throws HardwareInterfaceException if there is a problem. Diagnostics are printed to stderr. */ synchronized protected void openUsbIo() throws HardwareInterfaceException { //device has already been UsbIo Opened by now, in factory // opens the USBIOInterface device, configures it, binds a reader thread with buffer pool to read from the device and starts the thread reading events. // we got a UsbIo object when enumerating all devices and we also made a device list. the device has already been // opened from the UsbIo viewpoint, but it still needs firmware download, setting up pipes, etc. if(isOpened){ // log.warning("CypressFX2.openUsbIo(): already opened interface and setup device"); return; } int status; gUsbIo=new UsbIo(); gDevList=UsbIo.createDeviceList(GUID); status = gUsbIo.open(getInterfaceNumber(),gDevList,GUID); if (status != USBIO_ERR_SUCCESS) { UsbIo.destroyDeviceList(gDevList); isOpened=false; throw new HardwareInterfaceException("CypressFX2.openUsbIo(): can't open USB device: "+UsbIo.errorText(status)); } status=gUsbIo.acquireDevice(); if (status != USBIO_ERR_SUCCESS) { log.warning("couldn't acquire device for exclusive use"); throw new HardwareInterfaceException("couldn't acquire device for exclusive use: "+UsbIo.errorText(status)); } // get device descriptor (possibly before firmware download, when still bare cypress device or running off EEPROM firmware) status = gUsbIo.getDeviceDescriptor(deviceDescriptor); if (status != USBIO_ERR_SUCCESS) { UsbIo.destroyDeviceList(gDevList); throw new HardwareInterfaceException("CypressFX2.openUsbIo(): getDeviceDescriptor: "+UsbIo.errorText(status)); } else { // log.info("getDeviceDescriptor: Vendor ID (VID) " // + HexString.toString((short)deviceDescriptor.idVendor) // + " Product ID (PID) " + HexString.toString((short)deviceDescriptor.idProduct)); } checkBlankDevice(); // possibly download binary firmware to Cypress RAM downloadFirmwareBinary(); boolean success=false; int triesLeft=10; long delay=400; while(!success && triesLeft>0){ try{Thread.currentThread().sleep(delay);}catch(InterruptedException e){} gDevList=UsbIo.createDeviceList(GUID); gUsbIo=new UsbIo(); status = gUsbIo.open(getInterfaceNumber(),gDevList,GUID); if (status != USBIO_ERR_SUCCESS) { UsbIo.destroyDeviceList(gDevList); triesLeft }else{ success=true; } } if(!success) throw new HardwareInterfaceException("couldn't reopen device after firmware download and renumeration: "+UsbIo.errorText(status)); try{ unconfigureDevice(); // in case it was left configured from a terminated process }catch(HardwareInterfaceException e){ log.warning("CypressFX2.open(): can't unconfigure,will try simulated disconnect"); int cycleStatus=gUsbIo.cyclePort(); if(cycleStatus!=USBIO_ERR_SUCCESS){ throw new HardwareInterfaceException("Error cycling port: "+UsbIo.errorText(cycleStatus)); } throw new HardwareInterfaceException("couldn't unconfigure device"); } // set configuration -- must do this BEFORE downloading firmware! USBIO_SET_CONFIGURATION Conf = new USBIO_SET_CONFIGURATION(); Conf.ConfigurationIndex = CONFIG_INDEX; Conf.NbOfInterfaces = CONFIG_NB_OF_INTERFACES; Conf.InterfaceList[0].InterfaceIndex = CONFIG_INTERFACE; Conf.InterfaceList[0].AlternateSettingIndex = CONFIG_ALT_SETTING; Conf.InterfaceList[0].MaximumTransferSize = CONFIG_TRAN_SIZE; status = gUsbIo.setConfiguration(Conf); if (status != USBIO_ERR_SUCCESS) { // gUsbIo.destroyDeviceList(gDevList); // if (status !=0xE0001005) throw new HardwareInterfaceException("CypressFX2.openUsbIo(): setting configuration after firmware download: "+UsbIo.errorText(status)); } // try{Thread.currentThread().sleep(100);} catch(InterruptedException e){}; // pause for renumeration // System.out.println("after firmware download and reenumeration, descriptors are"); // get device descriptor status = gUsbIo.getDeviceDescriptor(deviceDescriptor); if (status != USBIO_ERR_SUCCESS) { UsbIo.destroyDeviceList(gDevList); throw new HardwareInterfaceException("CypressFX2.openUsbIo(): getDeviceDescriptor: "+UsbIo.errorText(status)); } else { // log.info("getDeviceDescriptor: Vendor ID (VID) " // + HexString.toString((short)deviceDescriptor.idVendor) // + " Product ID (PID) " + HexString.toString((short)deviceDescriptor.idProduct)); } if (deviceDescriptor.iSerialNumber!=0) this.numberOfStringDescriptors=3; // get string descriptor status = gUsbIo.getStringDescriptor(stringDescriptor1,(byte)1,0); if (status != USBIO_ERR_SUCCESS) { UsbIo.destroyDeviceList(gDevList); throw new HardwareInterfaceException("CypressFX2.openUsbIo(): getStringDescriptor: "+UsbIo.errorText(status)); } else { // log.info("getStringDescriptor 1: " + stringDescriptor1.Str); } // get string descriptor status = gUsbIo.getStringDescriptor(stringDescriptor2,(byte)2,0); if (status != USBIO_ERR_SUCCESS) { UsbIo.destroyDeviceList(gDevList); throw new HardwareInterfaceException("CypressFX2.openUsbIo(): getStringDescriptor: "+UsbIo.errorText(status)); } else { // log.info("getStringDescriptor 2: " + stringDescriptor2.Str); } if (this.numberOfStringDescriptors==3) { // get serial number string descriptor status = gUsbIo.getStringDescriptor(stringDescriptor3,(byte)3,0); if (status != USBIO_ERR_SUCCESS) { UsbIo.destroyDeviceList(gDevList); throw new HardwareInterfaceException("CypressFX2.openUsbIo(): getStringDescriptor: "+UsbIo.errorText(status)); } else { // log.info("getStringDescriptor 3: " + stringDescriptor3.Str); } } if(!gUsbIo.isOperatingAtHighSpeed()){ log.warning("CypressFX2.openUsbIo(): Warning: device is not operating at USB 2.0 High Speed, performance will be limited to about 300 keps"); } // get pipe information and extract the FIFO size USBIO_CONFIGURATION_INFO ConfigurationInfo = new USBIO_CONFIGURATION_INFO(); status = gUsbIo.getConfigurationInfo(ConfigurationInfo); if (status != USBIO_ERR_SUCCESS) { UsbIo.destroyDeviceList(gDevList); throw new HardwareInterfaceException("CypressFX2.openUsbIo(): getConfigurationInfo: "+UsbIo.errorText(status)); } if(ConfigurationInfo.NbOfPipes==0){ // gUsbIo.cyclePort(); throw new HardwareInterfaceException("CypressFX2.openUsbIo(): didn't find any pipes to bind to"); } // start the thread that listens for device status information (e.g. timestamp reset) asyncStatusThread=new AsyncStatusThread(this); asyncStatusThread.start(); // log.info("resetting 8051"); // set8051Reset(true); // set8051Reset(false); isOpened=true; } // unconfigure device in case it was still configured from a prior terminated process synchronized void unconfigureDevice() throws HardwareInterfaceException { int status; // System.out.println("CypressFX2RetinaBiasgen.unconfigureDevice()"); status = gUsbIo.unconfigureDevice(); if (status != USBIO_ERR_SUCCESS) { gUsbIo.destroyDeviceList(gDevList); //System.out.println("unconfigureDevice: "+UsbIo.errorText(status)); // throw new USBAEMonitorException("getStringDescriptor: "+gUsbIo.errorText(status)); throw new HardwareInterfaceException("unconfigureDevice: "+UsbIo.errorText(status)); // System.out.println("getConfigurationInfo ok"); } // System.out.println("unconfigured device"); } /** return the string USB descriptors for the device *@return String[] of length 2 of USB descriptor strings. */ public String[] getStringDescriptors() { if(stringDescriptor1==null) { log.warning("USBAEMonitor: getStringDescriptors called but device has not been opened"); String[] s=new String[numberOfStringDescriptors]; for (int i=0;i<numberOfStringDescriptors;i++) { s[i]=""; } return s; } String[] s=new String[numberOfStringDescriptors]; s[0]=stringDescriptor1.Str; s[1]=stringDescriptor2.Str; if (numberOfStringDescriptors==3) { s[2]=stringDescriptor3.Str; } return s; } /** return the USB VID/PID of the interface *@return int[] of length 2 containing the Vendor ID (VID) and Product ID (PID) of the device. First element is VID, second element is PID. */ public int[] getVIDPID() { if(deviceDescriptor==null) { log.warning("USBAEMonitor: getVIDPID called but device has not been opened"); return new int[2]; } int[] n=new int[2]; n[0]=deviceDescriptor.idVendor; n[1]=deviceDescriptor.idProduct; return n; } public short getVID() { if(deviceDescriptor==null) { log.warning("USBAEMonitor: getVIDPID called but device has not been opened"); return 0; } // int[] n=new int[2]; n is never used return (short)deviceDescriptor.idVendor; } public short getPID() { if(deviceDescriptor==null) { log.warning("USBAEMonitor: getVIDPID called but device has not been opened"); return 0; } return (short)deviceDescriptor.idProduct; } /** @return bcdDevice (the binary coded decimel device version */ public short getDID() { // this is not part of USB spec in device descriptor. return (short)deviceDescriptor.bcdDevice; } /** reports if interface is {@link #open}. * @return true if already open */ public boolean isOpen() { return isOpened; } /** Loads a binary firmware file into memory. * The filename is used to search the resource path (i.e. the jar archives on the classpath). *@param firmwareFilename the resource path **/ public byte[] loadBinaryFirmwareFile(String firmwareFilename) throws IOException{ log.info("loading firmware file "+firmwareFilename); InputStream firmwareFileStream; byte[] fwBuffer; // load firmware file (this is binary file of 8051 firmware) try{ firmwareFileStream=getClass().getResourceAsStream(firmwareFilename); if(firmwareFileStream!=null){ fwBuffer=new byte[firmwareFileStream.available()]; firmwareFileStream.read(fwBuffer); firmwareFileStream.close(); }else{ fwBuffer=loadBinaryFirmwareFileSystemFile(firmwareFilename); } }catch(IOException e){ close(); log.warning(e.getMessage()); throw new IOException("can't load binary Cypress FX2 firmware file "+firmwareFilename); } return fwBuffer; } /** Loads a binary firmware file into memory from a file system path (as opposed to resource path). *@param firmwareFilename the file path **/ public byte[] loadBinaryFirmwareFileSystemFile(String firmwareFilename) throws IOException{ log.info("writing firmware file "+firmwareFilename); InputStream firmwareFileStream; byte[] fwBuffer; // load firmware file (this is binary file of 8051 firmware) try{ File f=new File(firmwareFilename); firmwareFileStream=new FileInputStream(f); fwBuffer=new byte[firmwareFileStream.available()]; firmwareFileStream.read(fwBuffer); firmwareFileStream.close(); }catch(IOException e){ close(); log.warning(e.getMessage()); throw new IOException("can't load binary Cypress FX2 firmware file "+firmwareFilename); } return fwBuffer; } /** downloads firmware to FX2 RAM. adapted from John Arthur's example, which comes from Cypress example. * Firmware file is a binary file produced by uVision2 (Keil) from source code for firmware. *<p> *Firmware that is actually downloaded depends on discovered PID of device. If the PID is discovered to be a bare CypressFX2, then *a dialog is shown that user can use to program the VID/PID of the device. *<p> *In addition, there is a problem if firmware is downloaded more than once to an FX2LP device between hard resets. Therefore if this method detects *that the device has string identitifers, it assumes the firmware has already been downloaded. * * * Firmware file is loaded as a resource from the jar archive. */ synchronized void downloadFirmwareBinary(String firmwareFilename) throws HardwareInterfaceException { byte[] fwBuffer; // buffer to hold contents of firmware file (binary 8051 code) try{ fwBuffer=loadBinaryFirmwareFile(firmwareFilename); }catch(IOException e){ close(); log.warning(e.getMessage()); throw new HardwareInterfaceException("can't load binary Cypress FX2 firmware file "+firmwareFilename); } set8051Reset(true); download8051RAM(0, fwBuffer); set8051Reset(false); } /** downloads firmware to FX2 RAM. adapted from John Arthur's example, which comes from Cypress example. * Firmware file is a binary file produced by uVision2 (Keil) from source code for firmware. *<p> *Firmware that is actually downloaded depends on discovered PID of device. If the PID is discovered to be a bare CypressFX2, then *a dialog is shown that user can use to program the VID/PID of the device. *<p> *In addition, there is a problem if firmware is downloaded more than once to an FX2LP device between hard resets. Therefore if this method detects *that the device has string identitifers, it assumes the firmware has already been downloaded. * * * Firmware file is loaded as a resource from the jar archive. */ synchronized void downloadFirmwareBinary() throws HardwareInterfaceException { if(hasStringIdentifier()){ return; } log.info("device has no string identifier, downloading firmware to RAM"); // firmware load variables byte[] fwBuffer; // buffer to hold contents of firmware file (binary 8051 code) String firmwareFilename = getFirmwareFilenameBinaryFromVIDPID(); try{ fwBuffer=loadBinaryFirmwareFile(firmwareFilename); }catch(IOException e){ close(); log.warning(e.getMessage()); throw new HardwareInterfaceException("can't load binary Cypress FX2 firmware file "+firmwareFilename); } set8051Reset(true); download8051RAM(0, fwBuffer); set8051Reset(false); } // downloadFirmwareBinary() /** * Returns the firmware filenmae corresponding to a VID/PID pair. * This filename is a full path to a resource on the classpath which is in the project jar jAER.jar. * */ protected String getFirmwareFilenameBinaryFromVIDPID() { final String defaultResource=FIRMWARE_FILENAME_TCVS320_BIX; String firmwareFilename=null; if(getPID()==PID_DAREK_FX2_BOARD){ firmwareFilename=FIRMWARE_FILENAME_DAREK_BOARD; } else if (getPID()==PID_USBAERmini2_without_firmware){ firmwareFilename=FIRMWARE_FILENAME_MONITOR_SEQUENCER; }else if (getPID()==PID_USBAERmini2){ firmwareFilename=FIRMWARE_FILENAME_MONITOR_SEQUENCER; }else if (getPID()==PID_TCVS320_RETINA){ firmwareFilename=FIRMWARE_FILENAME_TCVS320_BIX; }else if (getPID()==PID_TMPDIFF128_RETINA){ firmwareFilename=FIRMWARE_FILENAME_TMPDIFF128_BIX; }else{ log.warning("unknown device product ID (PID)="+HexString.toString(getPID())+", assuming this needs "+defaultResource); firmwareFilename=defaultResource; } return firmwareFilename; } // returns the firmware filenmae corresponding to a VID/PID pair // this filename is actually a full path to a resource on the classpath protected String getFirmwareFilenameHexFromVIDPID() { String firmwareFilename=null; if (getVIDPID()[1]==PID_USBAERmini2_without_firmware){ firmwareFilename=FIRMWARE_FILENAME_MONITOR_SEQUENCER_HEX; }else{ firmwareFilename=FIRMWARE_FILENAME_TMPDIFF128_HEX; } return firmwareFilename; } /** Downloads to RAM on FX2 using built-in vendor request to CPUCS. * Remember to set8051Reset() before and after calling this method. *@param address the starting address in the 8051 RAM *@param FWBuffer the data *@see #set8051Reset */ protected void download8051RAM(int address, final byte[] FWBuffer) throws HardwareInterfaceException { log.info("downloading "+FWBuffer.length+" bytes to CypressFX2 RAM starting at "+address); /* From Fx2 tech ref guide, chapter 2 "endpoint 0" * *The USB endpoint-zero protocol provides a mechanism for mixing vendor-specific requests with standard device requests. Bits 6:5 of the bmRequestType field are set to 00 for a standard device request and to 10 for a vendor request. **/ // need to perform the following steps: // 1) reset the Cypress (write 0x01 into CPUCS register) // 2) send the firmware to Control Endpoint 0 // 3) pull the Cypress out of reset (write 0x00 into the CPUCS register) // this is achieved by using the vendor request VENDOR_REQUEST_FIRMWARE, where the Value of the request is the // address to write to and the buffer passed to USBIO_CLASS_OR_VENDOR_REQUEST defines data to be written // starting at this address and the number of bytes to be written. // thus the same vendor request can reset the 8051 (one byte written to CPUCS) and download successive chunks // of code. finally the request can unreset the 8051. int result; USBIO_CLASS_OR_VENDOR_REQUEST vendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); USBIO_DATA_BUFFER dataBuffer; int fwIndex; int numChunks; vendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; vendorRequest.Type=UsbIoInterface.RequestTypeVendor; // this is a vendor, not generic USB, request vendorRequest.Recipient=UsbIoInterface.RecipientDevice; // device (not endpoint, interface, etc) receives it vendorRequest.RequestTypeReservedBits=0; // set these bits to zero for Cypress-specific 'vendor request' rather that user defined vendorRequest.Request=VENDOR_REQUEST_FIRMWARE; // this is download/upload firmware request. really it is just a 'fill RAM request' vendorRequest.Index=0; // 2) send the firmware to Control Endpoint 0 // when sending firmware, we need to break up the loaded fimware // into MAX_CONTROL_XFER_SIZE blocks // this means: // a) the address to load it to needs to be changed (VendorRequest.Value) // b) need a pointer that moves through FWbuffer (pBuffer) // c) keep track of remaining bytes to transfer (FWsize_left); //send all but last chunk vendorRequest.Value = 0; //address of firmware location dataBuffer=new USBIO_DATA_BUFFER(MAX_CONTROL_XFER_SIZE); dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length); fwIndex=0; numChunks=FWBuffer.length/MAX_CONTROL_XFER_SIZE; // this is number of full chunks to send for(int i=0;i<numChunks;i++){ System.arraycopy(FWBuffer, i*MAX_CONTROL_XFER_SIZE, dataBuffer.Buffer(), 0, MAX_CONTROL_XFER_SIZE); result=gUsbIo.classOrVendorOutRequest(dataBuffer,vendorRequest); if(result!=USBIO_ERR_SUCCESS){ close(); throw new HardwareInterfaceException("Error on downloading segment number "+i+" of 8051 firmware: "+UsbIo.errorText(result)); } vendorRequest.Value += MAX_CONTROL_XFER_SIZE; //change address of firmware location } // now send final (short) chunk int numBytesLeft=FWBuffer.length%MAX_CONTROL_XFER_SIZE; // remainder if(numBytesLeft>0){ dataBuffer=new USBIO_DATA_BUFFER(numBytesLeft); dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length); System.arraycopy(FWBuffer, numChunks*MAX_CONTROL_XFER_SIZE, dataBuffer.Buffer(), 0, numBytesLeft); // send remaining part of firmware result=gUsbIo.classOrVendorOutRequest(dataBuffer,vendorRequest); if(result!=USBIO_ERR_SUCCESS){ close(); throw new HardwareInterfaceException("Error on downloading final segment of 8051 firmware: "+UsbIo.errorText(result)); } } } /** * sends vendor request to CPUCS register to set 8051 in CPU reset (or not) *@param value true to reset, false to run *@see #download8051RAM */ protected void set8051Reset(boolean value) throws HardwareInterfaceException { // log.info("setting 8051 reset="+value); int result; USBIO_DATA_BUFFER dataBuffer; USBIO_CLASS_OR_VENDOR_REQUEST vendorRequest; // make vendor request structure and populate it vendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); vendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; vendorRequest.Type=UsbIoInterface.RequestTypeVendor; // this is a vendor, not generic USB, request vendorRequest.Recipient=UsbIoInterface.RecipientDevice; // device (not endpoint, interface, etc) receives it vendorRequest.RequestTypeReservedBits=0; // set these bits to zero for Cypress-specific 'vendor request' rather that user defined vendorRequest.Request=VENDOR_REQUEST_FIRMWARE; // this is download/upload firmware request. really it is just a 'fill RAM request' vendorRequest.Index=0; // 1) reset the Cypress (write 0x01 into CPUCS register) vendorRequest.Value=CPUCS; // we're writing to this RAM address, which is actually the only register that the host can write to dataBuffer=new USBIO_DATA_BUFFER(1); // make a new buffer to define the length of the request data correctly dataBuffer.Buffer()[0]= (byte)(value?1:0); // 1 to reset, 0 to run dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length); result=gUsbIo.classOrVendorOutRequest(dataBuffer,vendorRequest); if(result!=USBIO_ERR_SUCCESS){ close(); throw new HardwareInterfaceException("Unable to reset 8051 for firmware download: "+UsbIo.errorText(result)); } } /** @return timestamp tick in us * NOTE: DOES NOT RETURN THE TICK OF THE USBAERmini2 board*/ final public int getTimestampTickUs() { return TICK_US; } /** returns last events from {@link #acquireAvailableEventsFromDriver} *@return the event packet */ public AEPacketRaw getEvents() { return this.lastEventsAcquired; } /** sends a vender request without data, value and index are set to zero. *@param request the vendor request byte, identifies the request on the device */ synchronized public void sendVendorRequest(byte request) throws HardwareInterfaceException { sendVendorRequest(request, (short)0, (short)0, null); } /** sends a vender request without any data. *@param request the vendor request byte, identifies the request on the device *@param value the value of the request (bValue USB field) *@param index the "index" of the request (bIndex USB field) */ synchronized public void sendVendorRequest(byte request, short value, short index) throws HardwareInterfaceException { sendVendorRequest(request, value, index, null); } /** sends a vender request with data. *@param request the vendor request byte, identifies the request on the device *@param value the value of the request (bValue USB field) *@param index the "index" of the request (bIndex USB field) *@param dataBuffer the data which is to be transmitted to the device */ synchronized public void sendVendorRequest(byte request, short value, short index, USBIO_DATA_BUFFER dataBuffer) throws HardwareInterfaceException { if (!isOpen()) { open(); } // make vendor request structure and populate it USBIO_CLASS_OR_VENDOR_REQUEST VendorRequest=new USBIO_CLASS_OR_VENDOR_REQUEST(); int status; VendorRequest.Flags=UsbIoInterface.USBIO_SHORT_TRANSFER_OK; VendorRequest.Type=UsbIoInterface.RequestTypeVendor; VendorRequest.Recipient=UsbIoInterface.RecipientDevice; VendorRequest.RequestTypeReservedBits=0; VendorRequest.Request= request; VendorRequest.Index= index; VendorRequest.Value= value; //System.out.println("request= " + request + " value: " + value); if (dataBuffer==null) { dataBuffer=new USBIO_DATA_BUFFER(1); dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length); } else { dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length); } status=gUsbIo.classOrVendorOutRequest(dataBuffer,VendorRequest); if(status!=USBIO_ERR_SUCCESS){ throw new HardwareInterfaceException("Unable to send vendor request "+ request + ": " + UsbIo.errorText(status)); } HardwareInterfaceException.clearException(); } public AEReader getAeReader() { return aeReader; } public void setAeReader(AEReader aeReader) { this.aeReader = aeReader; } public int getFifoSize() { if(aeReader==null) return 0; else return aeReader.getFifoSize(); } public void setFifoSize(int fifoSize) { if(aeReader==null) return; aeReader.shutdownThread(); aeReader.setFifoSize(fifoSize); aeReader.startThread(3); } public int getNumBuffers() { if(aeReader==null) return 0; else return aeReader.getNumBuffers(); } public void setNumBuffers(int numBuffers) { if(aeReader==null) return; aeReader.shutdownThread(); aeReader.setNumBuffers(numBuffers); aeReader.startThread(3); } public void setChip(AEChip chip) { this.chip=chip; } public AEChip getChip() { return chip; } /** Resets the USB device using USBIO resetDevice */ public void resetUSB(){ if(gUsbIo==null) return; gUsbIo.resetDevice(); } /** Cycles the port using USBIO cyclePort */ public void cyclePort(){ if(gUsbIo==null) return; gUsbIo.cyclePort(); } private void checkBlankDevice() { if(deviceDescriptor.idVendor==VID_BLANK && deviceDescriptor.idProduct==PID_BLANK){ log.warning("blank CypressFX2 detected"); } } }
package com.bryanjswift.simplenote.persistence; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log; import com.bryanjswift.simplenote.Constants; import com.bryanjswift.simplenote.model.Note; /** * Handle database access * @author bryanjswift */ public class SimpleNoteDao { /* Sql Column names */ public static final String KEY = "key"; public static final String BODY = "body"; public static final String MODIFY = "modify"; public static final String DELETED = "deleted"; public static final String SYNCED = "synced"; private static final String[] columns = new String[] { BaseColumns._ID, KEY, BODY, MODIFY, DELETED, SYNCED }; /* Database information/names */ private static final String DATABASE_NAME = "simplenotes_data.db"; private static final String DATABASE_TABLE = "notes"; private static final int DATABASE_VERSION = 3; /* Internal constants */ private static final String LOGGING_TAG = Constants.TAG + "DAO"; /* Internal fields */ private final DatabaseHelper dbHelper; /** * Construct Dao with Activity context * @param context - where the Dao was created */ public SimpleNoteDao(Context context) { this.dbHelper = new DatabaseHelper(context); } /** * Handle the creation and upgrading of the database * @author bryanjswift */ private static class DatabaseHelper extends SQLiteOpenHelper { /** * Database creation sql statement */ private static final String DATABASE_CREATE = (String.format( "create table %s (%s integer primary key autoincrement, " + "%s text not null, %s text not null, %s text not null, " + "%s boolean default 0, %s boolean default 1);", DATABASE_TABLE, BaseColumns._ID, KEY, BODY, MODIFY, DELETED, SYNCED)); private static final String INDEX_CREATE = (String.format( "create index if not exists key_index on %s (%s);", DATABASE_TABLE, KEY)); DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); db.execSQL(INDEX_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(LOGGING_TAG, "Upgrading database from version " + oldVersion + " to " + newVersion); switch (oldVersion) { case 1: final String tmpTable = "tmp_notes"; final String oldCols = BaseColumns._ID + "," + KEY + "," + BODY + "," + MODIFY + "," + DELETED + ", NOT needs_sync"; final String cols = BaseColumns._ID + "," + KEY + "," + BODY + "," + MODIFY + "," + DELETED + "," + SYNCED; db.execSQL(DATABASE_CREATE.replace("table " + DATABASE_TABLE, "table " + tmpTable)); db.execSQL("INSERT INTO " + tmpTable + " (" + cols + ") SELECT " + oldCols + " FROM " + DATABASE_TABLE + ";"); db.execSQL("DROP TABLE " + DATABASE_TABLE); db.execSQL("ALTER TABLE tmp_notes RENAME TO " + DATABASE_TABLE); db.execSQL(INDEX_CREATE); break; case 2: db.execSQL(INDEX_CREATE); default: Log.i(LOGGING_TAG, "No upgrade necessary."); break; } } } /** * Class to wrap a Cursor so values can be queried by column name * @author bryanjswift */ private static class CursorWrapper { private final Cursor cursor; CursorWrapper(Cursor cursor) { this.cursor = cursor; } private String getString(String column) { return cursor.getString(cursor.getColumnIndex(column)); } private long getLong(String column) { return cursor.getLong(cursor.getColumnIndex(column)); } private boolean getBoolean(String column) { return cursor.getInt(cursor.getColumnIndex(column)) == 1; } } /** * Write a Note to the database * @param note to store * @return the Note if it was saved successfully, null otherwise */ public Note save(Note note) { /* Setup values */ ContentValues values = new ContentValues(); values.put(KEY, note.getKey()); values.put(BODY, note.getBody()); values.put(MODIFY, note.getDateModified()); values.put(DELETED, note.isDeleted()); values.put(SYNCED, note.isSynced()); /* Perform query */ Note result = writeNote(values, note); return result; } /** * Retrieve a specific Note from the database * @param id of the Note to retrieved * @return the Note if it exists, null otherwise */ public Note retrieve(long id) { Log.i(LOGGING_TAG, String.format("Retrieving note with id '%d' from DB", id)); final SQLiteDatabase db = dbHelper.getReadableDatabase(); Note result = null; Cursor cursor = null; try { db.beginTransaction(); cursor = db.query(DATABASE_TABLE, columns, BaseColumns._ID + "=" + id, null, null, null, null); if (cursor.moveToFirst()) { // there is something in the Cursor so create a Note CursorWrapper c = new CursorWrapper(cursor); result = new Note(c.getLong(BaseColumns._ID), c.getString(BODY), c.getString(KEY), c.getString(MODIFY), c.getBoolean(DELETED)); } db.setTransactionSuccessful(); } finally { db.endTransaction(); db.close(); if (cursor != null) { cursor.close(); } } return result; } /** * Retrieve a specific Note from the database * @param key of the Note to retrieved * @return the Note if it exists, null otherwise */ public Note retrieveByKey(String key) { Log.i(LOGGING_TAG, String.format("Retrieving note with key '%s' from DB", key)); final SQLiteDatabase db = dbHelper.getReadableDatabase(); Note result = null; Cursor cursor = null; try { db.beginTransaction(); cursor = db.query(DATABASE_TABLE, columns, KEY + " LIKE '" + key + "'", null, null, null, null); if (cursor.moveToFirst()) { // there is something in the Cursor so create a Note CursorWrapper c = new CursorWrapper(cursor); result = new Note(c.getLong(BaseColumns._ID), c.getString(BODY), c.getString(KEY), c.getString(MODIFY), c.getBoolean(DELETED)); } db.setTransactionSuccessful(); } finally { db.endTransaction(); db.close(); if (cursor != null) { cursor.close(); } } return result; } /** * Retrieve a Note[] of all Notes in database ordered by modified date, descending * @return Note[] containing all undeleted notes */ public Note[] retrieveAll() { Log.i(LOGGING_TAG, "Getting all notes from DB"); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = null; Note[] notes = new Note[0]; try { db.beginTransaction(); cursor = db.query(DATABASE_TABLE, columns, DELETED + " = 0", null, null, null, MODIFY + " DESC"); if (cursor != null) { db.setTransactionSuccessful(); } db.endTransaction(); notes = cursorToNotes(cursor); } finally { if (cursor != null) { cursor.close(); } db.close(); } return notes; } /** * Retrieve all notes that need to be synchronized with SimpleNote's servers * @return Note[] of all unsynchronized notes */ public Note[] retrieveUnsynced() { Log.i(LOGGING_TAG, "Getting all unsynchronized notes from DB"); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = null; Note[] notes = new Note[0]; try { db.beginTransaction(); cursor = db.query(DATABASE_TABLE, columns, // table, columns to select SYNCED + " = 0", // where clause null, null, null, MODIFY + " DESC"); // __, __, __, order by if (cursor != null) { db.setTransactionSuccessful(); } db.endTransaction(); notes = cursorToNotes(cursor); } finally { if (cursor != null) { cursor.close(); } db.close(); } return notes; } /** * Mark a Note for deletion in the database * @param note to mark for deletion * @return whether or not the Note was successfully updated */ public boolean delete(Note note) { Log.i(LOGGING_TAG, String.format("Marking %s for deletion", note.getKey())); /* Setup values */ ContentValues values = new ContentValues(); values.put(DELETED, true); values.put(SYNCED, false); /* Perform query */ boolean success = writeNote(values, note) != null; return success; } /** * Mark a Note as up to date with the server in the database * @param note to mark synchronized * @return whether or not the note was successfully updated */ public boolean markSynced(Note note) { Log.i(LOGGING_TAG, String.format("Marking %s synchronized", note.getKey())); final ContentValues values = new ContentValues(); values.put(SYNCED, true); boolean success = writeNote(values, note) != null; return success; } /** * Remove a Note from the database * @param note to remove from the database * @return whether or not the Note was successfully deleted */ synchronized public boolean kill(Note note) { Log.w(LOGGING_TAG, String.format("Killing %s", note.getKey())); final SQLiteDatabase db = dbHelper.getWritableDatabase(); boolean success = false; /* Perform query */ try { db.beginTransaction(); int rows = db.delete(DATABASE_TABLE, BaseColumns._ID + "=" + note.getId(), null); success = rows == 1; if (success) { db.setTransactionSuccessful(); } } finally { db.endTransaction(); db.close(); } return success; } /** * Delete all Note objects from the database * @return true if any notes deleted, false otherwise */ synchronized public boolean killAll() { Log.w(LOGGING_TAG, String.format("Killing all notes")); final SQLiteDatabase db = dbHelper.getWritableDatabase(); boolean success = false; /* Perform query */ try { db.beginTransaction(); int rows = db.delete(DATABASE_TABLE, null, null); success = rows > 0; if (success) { db.setTransactionSuccessful(); } } finally { db.endTransaction(); db.close(); } return success; } synchronized private Note writeNote(ContentValues values, Note note) { final SQLiteDatabase db = dbHelper.getWritableDatabase(); Note result = null; try { db.beginTransaction(); if (note.getId() != Constants.DEFAULT_ID) { Log.i(LOGGING_TAG, String.format("Updating note with id: %d", note.getId())); int rows = db.update(DATABASE_TABLE, values, BaseColumns._ID + " = " + note.getId(), null); if (rows == 1) { result = note; db.setTransactionSuccessful(); } } else { Log.i(LOGGING_TAG, "Inserting new note into DB"); long id = db.insert(DATABASE_TABLE, null, values); if (id != Constants.DEFAULT_ID) { result = note.setId(id); db.setTransactionSuccessful(); } } } finally { db.endTransaction(); db.close(); } return result; } /** * Turn a cursor into an array of Note objects * @param cursor to read data from * @return an array of Notes with data from provided Cursor */ private static Note[] cursorToNotes(Cursor cursor) { final CursorWrapper c = new CursorWrapper(cursor); final Note[] notes = new Note[cursor.getCount()]; while (cursor != null && cursor.moveToNext()) { notes[cursor.getPosition()] = new Note(c.getLong(BaseColumns._ID), c.getString(BODY), c.getString(KEY), c.getString(MODIFY), c.getBoolean(DELETED)); } return notes; } }
package ru.qa.rtsoft; public class MyFirstProgram { public static void main(String[] args) { System.out.println("Hello, World!"); } }
package engine; import stage.Game; import stage.Scene; import jgame.JGColor; import jgame.JGFont; import jgame.JGPoint; import jgame.platform.StdGame; import objects.GameObject; import objects.NonPlayer; import objects.Player; import java.awt.Dimension; import java.io.File; import java.util.ArrayList; import java.util.List; public class GameEngine extends StdGame{ public static final Dimension SIZE = new Dimension(800, 600); public static final String TITLE = "Platformer Game Editor"; public static final int FRAMES_PER_SECOND = 20; public static final int MAX_FRAMES_TO_SKIP = 2; public static final int JGPOINT_X = 800; public static final int JGPOINT_Y = 600; private String Mode = "Edit";//String or boolean ? private Scene currentScene;//ID or Object ? private List<int[]> collsionPair = new ArrayList<int[]>(); protected Game myGame; public GameEngine(){ // initEngine(JGPOINT_X, JGPOINT_Y);//just for testing; will be deleted later initEngineComponent(JGPOINT_X, JGPOINT_Y); } @Override public void initCanvas () { setCanvasSettings(1, // width of the canvas in tiles 1, // height of the canvas in tiles displayWidth(), // width of one tile displayHeight(), // height of one tile null,// foreground colour -> use default colour white null,// background colour -> use default colour black null); // standard font -> use default font } @Override public void initGame () { setFrameRate(FRAMES_PER_SECOND, MAX_FRAMES_TO_SKIP); //setGameState(Mode); // defineMedia("TestMediaTable.tbl"); // setBGImage("StartGameBGImage"); } public void startEdit(){ //setBGImage(currentScene.getBackgroundImage()); } public void doFrameEdit(){ moveObjects(); for (int[] cp: collsionPair){ checkCollision(cp[0], cp[1]); } } public void paintFrameEdit(){ } public void addCollisionPair(int srccid, String type, int dstcid, int levelID, int sceneID){ collsionPair.add(new int[]{srccid,dstcid}); List<GameObject> objects = myGame.getObjectsByColid(dstcid); for(GameObject o: objects){ o.setCollisionBehavior(srccid, type); } } public void setCurrentScene (int currentLevelID, int currentSceneID) { for(GameObject go: currentScene.getGameObjects()){ go.suspend(); } currentScene = myGame.getScene(currentLevelID, currentSceneID); for(GameObject go: currentScene.getGameObjects()){ go.resume(); } //setGameState(Mode); } public void setGame (Game mygame) { myGame = mygame; } /* * (non-Javadoc) * @see jgame.platform.StdGame#doFrame() * For inGame States */ @Override public void doFrame(){ } /* * (non-Javadoc) * @see jgame.platform.StdGame#paintFrame() * For inGame states */ @Override public void paintFrame () { } @Override public void doFrameEnterHighscore(){ } @Override public void paintFrameStartLevel(){ } @Override public void paintFrameTitle(){ } @Override public void paintFrameEnterHighscore(){ } @Override public void paintFrameGameOver(){ } @Override public void paintFrameHighscores(){ } @Override public void paintFrameLevelDone(){ } @Override public void paintFrameLifeLost(){ } @Override public void paintFramePaused(){ } @Override public void paintFrameStartGame(){ } /* * Should be called by the GameFactory to createPlayer * Return a created GameObject */ public GameObject createPlayer(int unique_id, String url, double xpos, double ypos, String name, int colid, int levelID, int sceneID){ File file = new File(url); String filename = file.getName(); GameObject object = new Player(unique_id, filename, xpos, ypos, name, colid); object.setPos(xpos, ypos);//just to make sure; may be deleted later myGame.setPlayer(object); return object; } public GameObject createActor(int unique_id, String url, double xpos, double ypos, String name, int colid, int levelID, int sceneID){ File file = new File(url); String filename = file.getName(); GameObject object = new NonPlayer(unique_id, filename, xpos, ypos, name, colid); object.setPos(xpos, ypos);//just to make sure; may be deleted later myGame.addObject(levelID, sceneID, object); return object; } public void removeActor(GameObject object){ object.remove(); } /* * For reference only */ // private Mass getMassById(String id){ // Object thisObject = this.getObject(id); // Mass returnObject = (Mass) thisObject; // return returnObject; }
package com.jwetherell.algorithms.data_structures; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; public class SuffixTree<C extends CharSequence> { private static final char DEFAULT_END_SEQ_CHAR = '$'; private static boolean DEBUG = false; private String string = null; private char[] characters = null; private Map<Integer, Link> suffixLinks = new HashMap<Integer, Link>(); private Map<Integer, Edge<C>> edgeMap = new TreeMap<Integer, Edge<C>>(); private int currentNode = 0; private int firstCharIndex = 0; private int lastCharIndex = -1; private char END_SEQ_CHAR = DEFAULT_END_SEQ_CHAR; /** * Create suffix tree with sequence and default end sequence. * * @param seq to create a suffix tree with. */ public SuffixTree(C seq) { this(seq, DEFAULT_END_SEQ_CHAR); } /** * Create suffix tree with sequence and end sequence parameter. * * @param seq to create a suffix tree with. * @param endSeq which defines the end of a sequence. */ public SuffixTree(C seq, char endSeq) { END_SEQ_CHAR = endSeq; StringBuilder builder = new StringBuilder(seq); if (builder.indexOf(String.valueOf(seq))>=0) builder.append(END_SEQ_CHAR); string = builder.toString(); int length = string.length(); characters = new char[length]; for (int i = 0; i < length; i++) { characters[i] = string.charAt(i); } for (int i = 0; i < length; i++) { addPrefix(i); } } /** * Add another string * * @param seq */ public void add(C seq) { StringBuilder builder = new StringBuilder(string); int start = string.length(); builder.append(seq); if (builder.indexOf(String.valueOf(seq))>=0) builder.append(END_SEQ_CHAR); string = builder.toString(); int length = string.length(); characters = new char[length]; for (int i = 0; i < length; i++) { characters[i] = string.charAt(i); } for (int i = start; i < length; i++) { addPrefix(i); } } /** * Does the sub-sequence exist in the suffix tree. * * @param sub sub-sequence to locate in the tree. * @return True if the sub-sequence exist in the tree. */ public boolean doesSubStringExist(C sub) { char[] chars = new char[sub.length()]; for (int i = 0; i < sub.length(); i++) { chars[i] = sub.charAt(i); } int[] indices = searchEdges(chars); int start = indices[0]; int end = indices[1]; int length = end - start; if (length == (chars.length - 1)) return true; return false; } /** * Get all the suffixes in the tree. * * @return set of suffixes in the tree. */ public Set<String> getSuffixes() { Set<String> set = getSuffixes(0); return set; } /** * Get all suffixes at starting node. * * @param start node. * @return set of suffixes in the tree at start node. */ private Set<String> getSuffixes(int start) { Set<String> set = new TreeSet<String>(); for (int key : edgeMap.keySet()) { Edge<C> e = edgeMap.get(key); if (e == null) continue; if (e.startNode != start) continue; String s = (string.substring(e.firstCharIndex, e.lastCharIndex + 1)); Link n = suffixLinks.get(e.endNode); if (n == null) { int index = s.indexOf(END_SEQ_CHAR); if (index>=0) s = s.substring(0, index); if (s.length() > 0) set.add(s); } else { Set<String> set2 = getSuffixes(e.endNode); for (String s2 : set2) { int index = s.indexOf(END_SEQ_CHAR); if (index>=0) s2 = s2.substring(0, index); set.add(s + s2); } } } return set; } /** * Get all edges in the table * * @return debug string. */ public String getEdgesTable() { StringBuilder builder = new StringBuilder(); if (edgeMap.size() > 0) { int lastCharIndex = characters.length; builder.append("Edge\tStart\tEnd\tSuf\tfirst\tlast\tString\n"); for (int key : edgeMap.keySet()) { Edge<C> e = edgeMap.get(key); Link link = suffixLinks.get(e.endNode); int suffix = (link != null) ? link.suffixNode : -1; builder.append("\t" + e.startNode + "\t" + e.endNode + "\t" + suffix + "\t" + e.firstCharIndex + "\t" + e.lastCharIndex + "\t"); int begin = e.firstCharIndex; int end = (lastCharIndex < e.lastCharIndex) ? lastCharIndex : e.lastCharIndex; builder.append(string.substring(begin, end + 1)); builder.append("\n"); } builder.append("Link\tStart\tEnd\n"); for (int key : suffixLinks.keySet()) { Link link = suffixLinks.get(key); builder.append("\t" + link.node + "\t" + link.suffixNode + "\n"); } } return builder.toString(); } /** * Add prefix at index. * * @param index */ private void addPrefix(int index) { int parentNodeIndex = 0; int lastParentIndex = -1; while (true) { Edge<C> edge = null; parentNodeIndex = currentNode; if (isExplicit()) { edge = Edge.find(this, currentNode, characters[index]); if (edge != null) { // Edge already exists break; } } else { // Implicit node, a little more complicated edge = Edge.find(this, currentNode, characters[firstCharIndex]); int span = lastCharIndex - firstCharIndex; if (characters[edge.firstCharIndex + span + 1] == characters[index]) { // If the edge is the last char, don't split break; } parentNodeIndex = edge.split(currentNode, firstCharIndex, lastCharIndex); } edge = new Edge<C>(this, index, characters.length - 1, parentNodeIndex); if (DEBUG) System.out.printf("Created edge to new leaf: " + edge + "\n"); if (lastParentIndex > 0) { // Last parent is not root, create a link. if (DEBUG) System.out.printf("Creating suffix link from node " + lastParentIndex + " to node " + parentNodeIndex + ".\n"); suffixLinks.get(lastParentIndex).suffixNode = parentNodeIndex; } lastParentIndex = parentNodeIndex; if (currentNode == 0) { if (DEBUG) System.out.printf("Can't follow suffix link, I'm at the root\n"); firstCharIndex++; } else { // Current node is not root, follow link if (DEBUG) System.out.printf("Following suffix link from node " + currentNode + " to node " + suffixLinks.get(currentNode).suffixNode + ".\n"); currentNode = suffixLinks.get(currentNode).suffixNode; } canonize(); } if (lastParentIndex > 0) { // Last parent is not root, create a link. if (DEBUG) System.out.printf("Creating suffix link from node " + lastParentIndex + " to node " + parentNodeIndex + ".\n"); suffixLinks.get(lastParentIndex).suffixNode = parentNodeIndex; } lastParentIndex = parentNodeIndex; lastCharIndex++; // Now the endpoint is the next active point canonize(); }; /** * Is the tree explicit * * @return True if explicit. */ private boolean isExplicit() { return firstCharIndex > lastCharIndex; } /** * Canonize the tree. */ private void canonize() { if (!isExplicit()) { Edge<C> edge = Edge.find(this, currentNode, characters[firstCharIndex]); int edge_span = edge.lastCharIndex - edge.firstCharIndex; while (edge_span <= (lastCharIndex - firstCharIndex)) { if (DEBUG) System.out.printf("Canonizing"); firstCharIndex = firstCharIndex + edge_span + 1; currentNode = edge.endNode; if (DEBUG) System.out.printf(" " + this); if (firstCharIndex <= lastCharIndex) { edge = Edge.find(this, edge.endNode, characters[firstCharIndex]); edge_span = edge.lastCharIndex - edge.firstCharIndex; } if (DEBUG) System.out.printf(".\n"); } } } /** * Returns a two element int array who's 0th index is the start index and * 1th is the end index. */ private int[] searchEdges(char[] query) { int start_node = 0; int qp = 0; // query position int start_index = -1; int end_index = -1; boolean stop = false; while (!stop && qp < query.length) { Edge<C> edge = Edge.find(this, start_node, query[qp]); if (edge == null) { stop = true; break; } if (start_node == 0) start_index = edge.firstCharIndex; for (int i = edge.firstCharIndex; i <= edge.lastCharIndex; i++) { if (qp >= query.length) { stop = true; break; } else if (query[qp] == characters[i]) { qp++; end_index = i; } else { stop = true; break; } } if (!stop) { // proceed with next node start_node = edge.endNode; if (start_node == -1) stop = true; } } return (new int[] { start_index, end_index }); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("String = ").append(this.string).append("\n"); builder.append("End of word character = ").append(END_SEQ_CHAR).append("\n"); builder.append(TreePrinter.getString(this)); return builder.toString(); } private static class Link implements Comparable<Link> { private int node = 0; private int suffixNode = -1; public Link(int node) { this.node = node; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("node=").append(node).append("\n"); builder.append("suffix_node=").append(suffixNode).append("\n"); return builder.toString(); } @Override public int compareTo(Link link) { if (link == null) return -1; if (node < link.node) return -1; if (node > link.node) return 1; if (suffixNode < link.suffixNode) return -1; if (suffixNode > link.suffixNode) return 1; return 0; } }; private static class Edge<C extends CharSequence> implements Comparable<Edge<C>> { private static final int KEY_MOD = 2179; // Should be a prime that is // roughly 10% larger than the // String private static int count = 1; private SuffixTree<C> tree = null; private int startNode = -1; private int endNode = 0; private int firstCharIndex = 0; private int lastCharIndex = 0; private Edge(SuffixTree<C> tree, int init_first, int init_last, int parent_node) { this.tree = tree; firstCharIndex = init_first; lastCharIndex = init_last; startNode = parent_node; endNode = count++; insert(this); } private int getKey() { return key(startNode, tree.characters[firstCharIndex]); } private static int key(int node, char c) { return ((node << 8) + c) % KEY_MOD; } private void insert(Edge<C> edge) { tree.edgeMap.put(edge.getKey(), edge); } private void remove(Edge<C> edge) { int i = edge.getKey(); Edge<C> e = tree.edgeMap.remove(i); while (true) { e.startNode = -1; int j = i; while (true) { i = ++i % KEY_MOD; e = tree.edgeMap.get(i); if (e == null) return; int r = key(e.startNode, tree.characters[e.firstCharIndex]); if (i >= r && r > j) continue; if (r > j && j > i) continue; if (j > i && i >= r) continue; break; } tree.edgeMap.put(j, e); } } private static <C extends CharSequence> Edge<C> find(SuffixTree<C> tree, int node, char c) { int key = key(node, c); return tree.edgeMap.get(key); } private int split(int originNode, int firstCharIndex, int lastCharIndex) { if (DEBUG) System.out.printf("Splitting edge: " + this + "\n"); remove(this); Edge<C> new_edge = new Edge<C>(tree, this.firstCharIndex, this.firstCharIndex + lastCharIndex - firstCharIndex, originNode); Link link = tree.suffixLinks.get(new_edge.endNode); if (link == null) { link = new Link(new_edge.endNode); tree.suffixLinks.put(new_edge.endNode, link); } tree.suffixLinks.get(new_edge.endNode).suffixNode = originNode; this.firstCharIndex += lastCharIndex - firstCharIndex + 1; this.startNode = new_edge.endNode; insert(this); if (DEBUG) System.out.printf("Old edge: " + this + "\n"); if (DEBUG) System.out.printf("New edge: " + new_edge + "\n"); return new_edge.endNode; } @Override public int hashCode() { return getKey(); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj instanceof Edge) return false; @SuppressWarnings("unchecked") Edge<C> e = (Edge<C>) obj; if (startNode == e.startNode && tree.characters[firstCharIndex] == tree.characters[e.firstCharIndex]) { return true; } return false; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("start_node=").append(startNode).append("\n"); builder.append("end_node=").append(endNode).append("\n"); builder.append("first_char_index=").append(firstCharIndex).append("\n"); builder.append("last_char_index=").append(lastCharIndex).append("\n"); String s = tree.string.substring(firstCharIndex, lastCharIndex + 1); builder.append("string=").append(s).append("\n"); return builder.toString(); } @Override public int compareTo(Edge<C> edge) { if (edge == null) return -1; if (startNode < edge.startNode) return -1; if (startNode > edge.startNode) return 1; if (endNode < edge.endNode) return -1; if (endNode > edge.endNode) return 1; if (firstCharIndex < edge.firstCharIndex) return -1; if (firstCharIndex > edge.firstCharIndex) return 1; if (lastCharIndex < edge.lastCharIndex) return -1; if (lastCharIndex > edge.lastCharIndex) return 1; return 0; } } protected static class TreePrinter { public static <C extends CharSequence> void printNode(SuffixTree<C> tree) { System.out.println(getString(tree, null, "", true)); } public static <C extends CharSequence> String getString(SuffixTree<C> tree) { return getString(tree, null, "", true); } private static <C extends CharSequence> String getString(SuffixTree<C> tree, Edge<C> e, String prefix, boolean isTail) { StringBuilder builder = new StringBuilder(); int value = 0; if (e != null) { value = e.endNode; String string = tree.string.substring(e.firstCharIndex, e.lastCharIndex + 1); int index = string.indexOf(tree.END_SEQ_CHAR); if (index>=0) string = string.substring(0, index+1); builder.append(prefix + (isTail ? " " : " ") + "(" + value + ") " + string + "\n"); } else { builder.append(prefix + (isTail ? " " : " ") + "(" + 0 + ")" + "\n"); } if (tree.edgeMap.size() > 0) { List<Edge<C>> children = new LinkedList<Edge<C>>(); for (Edge<C> edge : tree.edgeMap.values()) { if (edge != null && (edge.startNode == value)) { children.add(edge); } } if (children != null) { for (int i = 0; i < children.size() - 1; i++) { Edge<C> edge = children.get(i); builder.append(getString(tree, edge, prefix + (isTail ? " " : " "), false)); } if (children.size() >= 1) { Edge<C> edge = children.get(children.size() - 1); builder.append(getString(tree, edge, prefix + (isTail ? " " : " "), true)); } } } return builder.toString(); } } }
package com.opengamma.transport.socket; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.Lifecycle; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.util.ArgumentChecker; public abstract class AbstractSocketProcess implements Lifecycle { private static final Logger s_logger = LoggerFactory.getLogger(AbstractSocketProcess.class); private InetAddress _inetAddress; private int _portNumber; private boolean _started; private Socket _socket; /** * @return the inetAddress */ public InetAddress getInetAddress() { return _inetAddress; } /** * @param inetAddress the inetAddress to set */ public void setInetAddress(InetAddress inetAddress) { _inetAddress = inetAddress; } public void setAddress(final String host) throws UnknownHostException { setInetAddress(InetAddress.getByName(host)); } /** * @return the portNumber */ public int getPortNumber() { return _portNumber; } /** * @param portNumber the portNumber to set */ public void setPortNumber(int portNumber) { _portNumber = portNumber; } protected Socket getSocket() { return _socket; } protected void startIfNecessary() { if (!isRunning()) { s_logger.debug("Starting implicitly as start() was not called before use."); start(); } } @Override public synchronized boolean isRunning() { return _started; } @Override public synchronized void start() { ArgumentChecker.notNullInjected(getInetAddress(), "Remote InetAddress"); ArgumentChecker.isTrue(getPortNumber() > 0, "Must specify valid portNumber property"); if (_started && (_socket != null)) { s_logger.warn("Already connected to {}:{}", getInetAddress(), getPortNumber()); } else { openRemoteConnection(); _started = true; } } protected synchronized void openRemoteConnection() { s_logger.info("Opening remote connection to {}:{}", getInetAddress(), getPortNumber()); OutputStream os = null; InputStream is = null; try { _socket = new Socket(getInetAddress(), getPortNumber()); os = _socket.getOutputStream(); is = _socket.getInputStream(); } catch (IOException ioe) { throw new OpenGammaRuntimeException("Unable to open remote connection to " + getInetAddress() + ":" + getPortNumber(), ioe); } os = new BufferedOutputStream(os); socketOpened(_socket, os, is); } @Override public synchronized void stop() { if (_started) { if (_socket != null) { if (_socket.isConnected()) { try { _socket.close(); } catch (IOException e) { s_logger.warn("Unable to close connected socket to {}", new Object[] {_socket.getRemoteSocketAddress()}, e); } } _socket = null; } _started = false; socketClosed(); } else { s_logger.warn("Already stopped {}:{}", getInetAddress(), getPortNumber()); } } protected boolean exceptionForcedByClose(final Exception e) { return (e instanceof SocketException) && "Socket closed".equals(e.getMessage()); } protected abstract void socketOpened(Socket socket, OutputStream os, InputStream is); protected void socketClosed() { } }
package com.qmetry.qaf.automation.step.client; import static com.qmetry.qaf.automation.data.MetaDataScanner.getMetadata; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.testng.internal.TestNGMethod; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.xml.XmlSuite.ParallelMode; import org.testng.xml.XmlTest; /** * com.qmetry.qaf.automation.step.client.TestNGScenario.java * * @author chirag.jayswal */ public class TestNGScenario extends TestNGMethod { private static final long serialVersionUID = 6225163528424712337L; private Scenario scenario; private Map<String, Object> metadata; private String qualifiledName; public TestNGScenario(Method method, IAnnotationFinder finder, XmlTest xmlTest, Object instance) { super(method, finder, xmlTest, instance); init(instance); } private void init(Object instance) { if (Scenario.class.isAssignableFrom(getRealClass())) { scenario = (Scenario) instance; if (scenario.getPriority() < 1000 || !getXmlTest().getParallel().isParallel() || getXmlTest().getParallel().equals(ParallelMode.TESTS)) { setPriority(scenario.getPriority()); } setGroups(scenario.getM_groups()); setGroupsDependedUpon(scenario.getM_groupsDependedUpon(), new ArrayList<String>()); setMethodsDependedUpon(scenario.getM_methodsDependedUpon()); setDescription(scenario.getDescription()); setEnabled(scenario.isM_enabled()); setAlwaysRun(scenario.isM_isAlwaysRun()); setIgnoreMissingDependencies(scenario.getIgnoreMissingDependencies()); metadata = scenario.getMetadata(); qualifiledName = scenario.getTestName(); } else { metadata = getMetadata(getMethod(), true); qualifiledName = getRealClass().getName() + "." + getMethodName(); } metadata.put("name", getMethodName()); metadata.put("sign", getSignature()); } @Override public String getMethodName() { return scenario != null ? scenario.getTestName() : super.getMethodName(); } @Override public String getSignature() { return scenario != null ? computeSign() : super.getSignature(); } private String computeSign() { StringBuilder result = new StringBuilder(scenario.getSignature()); result.append("[pri:").append(getPriority()).append(", instance:").append(getInstance()).append("]"); return result.toString(); } public Map<String, Object> getMetaData() { return metadata; } // useful to correct invocation count in case of retry public int decAndgetCurrentInvocationCount() { m_currentInvocationCount = new AtomicInteger(getCurrentInvocationCount() - 1); return super.getCurrentInvocationCount(); } @Override public String getQualifiedName() { return qualifiledName; } }
package com.redhat.ceylon.compiler.typechecker.tree; import java.util.List; import com.redhat.ceylon.common.Backend; import com.redhat.ceylon.common.BackendSupport; import com.redhat.ceylon.model.typechecker.model.Annotation; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Function; import com.redhat.ceylon.model.typechecker.model.Parameter; import com.redhat.ceylon.model.typechecker.model.TypedDeclaration; import com.redhat.ceylon.model.typechecker.model.Unit; public class TreeUtil { public static final String MISSING_NAME = "program element with missing name"; public static String name(Tree.Identifier id) { if (id==null) { return MISSING_NAME; } else { return id.getText(); } } public static boolean hasAnnotation(Tree.AnnotationList al, String name, Unit unit) { return getAnnotation(al, name, unit) != null; } public static Tree.Annotation getAnnotation(Tree.AnnotationList al, String name, Unit unit) { if (al!=null) { for (Tree.Annotation a: al.getAnnotations()) { Tree.BaseMemberExpression p = (Tree.BaseMemberExpression) a.getPrimary(); if (p!=null) { String an = name(p.getIdentifier()); String alias = unit==null ? name : //WTF?! unit.getModifiers().get(name); if (an.equals(alias)) { return a; } } } } return null; } public static String getAnnotationArgument(Tree.Annotation ann, String defaultValue) { String result = defaultValue; Tree.Expression expression = null; Tree.PositionalArgumentList pal = ann.getPositionalArgumentList(); if (pal!=null) { List<Tree.PositionalArgument> args = pal.getPositionalArguments(); if (!args.isEmpty()) { Tree.PositionalArgument arg = args.get(0); if (arg instanceof Tree.ListedArgument) { Tree.ListedArgument la = (Tree.ListedArgument) arg; expression = la.getExpression(); } } } Tree.NamedArgumentList nal = ann.getNamedArgumentList(); if (nal!=null) { List<Tree.NamedArgument> args = nal.getNamedArguments(); if (!args.isEmpty()) { Tree.SpecifiedArgument arg = (Tree.SpecifiedArgument) args.get(0); expression = arg.getSpecifierExpression() .getExpression(); } } if (expression!=null) { Tree.Literal literal = (Tree.Literal) expression.getTerm(); result = literal.getText(); if (result.startsWith("\"") && result.endsWith("\"")) { result = result.substring(1, result.length() - 1); } } return result; } public static boolean isForBackend(Tree.AnnotationList al, Backend forBackend, Unit unit) { return isForBackend(al, forBackend.backendSupport, unit); } public static boolean isForBackend(Tree.AnnotationList al, BackendSupport backendSupport, Unit unit) { String be = getNativeBackend(al, unit); return isForBackend(be, backendSupport); } public static boolean isForBackend(String backendName, Backend forBackend) { return isForBackend(backendName, forBackend.backendSupport); } public static boolean isForBackend(String backendName, BackendSupport backendSupport) { if (backendName != null) { Backend backend = Backend.fromAnnotation(backendName); if (backend == null || !backendSupport.supportsBackend(backend)) { return false; } } return true; } public static String getNativeBackend(Tree.AnnotationList al, Unit unit) { Tree.Annotation ann = getAnnotation(al, "native", unit); return ann == null ? null : getAnnotationArgument(ann, ""); } public static boolean hasUncheckedNulls(Tree.Term term) { return hasUncheckedNulls(term, false); } private static boolean hasUncheckedNulls(Tree.Term term, boolean invoking) { if (term instanceof Tree.MemberOrTypeExpression) { Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) term; Declaration d = mte.getDeclaration(); if (d instanceof TypedDeclaration) { TypedDeclaration td = (TypedDeclaration) d; return td.hasUncheckedNullType() && // only consider method types when invoking them, // because java method references can't be null (!(d instanceof Function) || invoking); } else { return false; } } else if (term instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.QualifiedMemberOrTypeExpression qmte = (Tree.QualifiedMemberOrTypeExpression) term; return hasUncheckedNulls(qmte.getPrimary(), invoking); } else if (term instanceof Tree.InvocationExpression) { Tree.InvocationExpression ite = (Tree.InvocationExpression) term; return hasUncheckedNulls(ite.getPrimary(), true); } else if (term instanceof Tree.DefaultOp) { Tree.DefaultOp op = (Tree.DefaultOp) term; return hasUncheckedNulls(op.getRightTerm(), invoking); } else if (term instanceof Tree.Expression) { Tree.Expression e = (Tree.Expression) term; return hasUncheckedNulls(e.getTerm(), invoking); } else { return false; } } public static String formatPath(List<Tree.Identifier> nodes) { StringBuilder sb = new StringBuilder(); boolean first = true; for (Node node: nodes) { if (first) { first = false; } else { sb.append("."); } sb.append(node.getText()); } return sb.toString(); } /** * Returns the best Node to attach errors to. This code * is used by both backends. */ public static Node getIdentifyingNode(Node node) { Node result = null; if (node instanceof Tree.Declaration) { Tree.Declaration d = (Tree.Declaration) node; result = d.getIdentifier(); } else if (node instanceof Tree.ModuleDescriptor) { Tree.ModuleDescriptor md = (Tree.ModuleDescriptor) node; result = md.getImportPath(); } else if (node instanceof Tree.PackageDescriptor) { Tree.PackageDescriptor pd = (Tree.PackageDescriptor) node; result = pd.getImportPath(); } else if (node instanceof Tree.NamedArgument) { Tree.NamedArgument na = (Tree.NamedArgument) node; result = na.getIdentifier(); } else if (node instanceof Tree.StaticMemberOrTypeExpression) { Tree.StaticMemberOrTypeExpression smte = (Tree.StaticMemberOrTypeExpression) node; result = smte.getIdentifier(); } else if (node instanceof Tree.ExtendedTypeExpression) { //TODO: whoah! this is really ugly! CustomTree.ExtendedTypeExpression ete = (CustomTree.ExtendedTypeExpression) node; result = ete.getType() .getIdentifier(); } else if (node instanceof Tree.SimpleType) { Tree.SimpleType st = (Tree.SimpleType) node; result = st.getIdentifier(); } else if (node instanceof Tree.ImportMemberOrType) { Tree.ImportMemberOrType imt = (Tree.ImportMemberOrType) node; result = imt.getIdentifier(); } else { result = node; } if (result == null) { result = node; } return result; } public static Tree.Term eliminateParensAndWidening(Tree.Term term) { while (term instanceof Tree.OfOp || term instanceof Tree.Expression) { if (term instanceof Tree.OfOp) { term = ((Tree.OfOp) term).getTerm(); } else if (term instanceof Tree.Expression) { term = ((Tree.Expression) term).getTerm(); } } return term; } public static Tree.Term unwrapExpressionUntilTerm(Tree.Term term){ while (term instanceof Tree.Expression) { Tree.Expression e = (Tree.Expression) term; term = e.getTerm(); } return term; } public static boolean hasErrorOrWarning(Node node) { return hasError(node, true); } public static boolean hasError(Node node) { return hasError(node, false); } static boolean hasError(Node node, final boolean includeWarnings) { // we use an exception to get out of the visitor // as fast as possible when an error is found // TODO: wtf?! because it's the common case that // a node has an error? that's just silly @SuppressWarnings("serial") class ErrorFoundException extends RuntimeException {} class ErrorVisitor extends Visitor { @Override public void handleException(Exception e, Node that) { if (e instanceof ErrorFoundException) { throw (ErrorFoundException) e; } super.handleException(e, that); } @Override public void visitAny(Node that) { if (that.getErrors().isEmpty()) { super.visitAny(that); } else if (includeWarnings) { throw new ErrorFoundException(); } else { // UsageWarning don't count as errors for (Message error: that.getErrors()) { if (!error.isWarning()) { // get out fast throw new ErrorFoundException(); } } // no real error, proceed super.visitAny(that); } } } ErrorVisitor ev = new ErrorVisitor(); try { node.visit(ev); return false; } catch (ErrorFoundException x) { return true; } } public static void buildAnnotations(Tree.AnnotationList al, List<Annotation> annotations) { if (al!=null) { Tree.AnonymousAnnotation aa = al.getAnonymousAnnotation(); if (aa!=null) { Annotation ann = new Annotation(); ann.setName("doc"); String text = aa.getStringLiteral().getText(); ann.addPositionalArgment(text); annotations.add(ann); } for (Tree.Annotation a: al.getAnnotations()) { Annotation ann = new Annotation(); Tree.BaseMemberExpression bma = (Tree.BaseMemberExpression) a.getPrimary(); String name = bma.getIdentifier().getText(); ann.setName(name); Tree.NamedArgumentList nal = a.getNamedArgumentList(); if (nal!=null) { for (Tree.NamedArgument na: nal.getNamedArguments()) { if (na instanceof Tree.SpecifiedArgument) { Tree.SpecifiedArgument sa = (Tree.SpecifiedArgument) na; Tree.SpecifierExpression sie = sa.getSpecifierExpression(); Tree.Expression e = sie.getExpression(); if (e!=null) { Tree.Term t = e.getTerm(); Parameter p = sa.getParameter(); if (p!=null) { String text = toString(t); if (text!=null) { ann.addNamedArgument(p.getName(), text); } } } } } } Tree.PositionalArgumentList pal = a.getPositionalArgumentList(); if (pal!=null) { for (Tree.PositionalArgument pa: pal.getPositionalArguments()) { if (pa instanceof Tree.ListedArgument) { Tree.ListedArgument la = (Tree.ListedArgument) pa; Tree.Term t = la.getExpression().getTerm(); String text = toString(t); if (text!=null) { ann.addPositionalArgment(text); } } } } annotations.add(ann); } } } private static String toString(Tree.Term t) { if (t instanceof Tree.Literal) { return ((Tree.Literal) t).getText(); } else if (t instanceof Tree.StaticMemberOrTypeExpression) { Tree.StaticMemberOrTypeExpression mte = (Tree.StaticMemberOrTypeExpression) t; String id = mte.getIdentifier().getText(); if (mte instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.QualifiedMemberOrTypeExpression qmte = (Tree.QualifiedMemberOrTypeExpression) mte; Tree.Primary p = qmte.getPrimary(); if (p instanceof Tree.StaticMemberOrTypeExpression) { Tree.StaticMemberOrTypeExpression smte = (Tree.StaticMemberOrTypeExpression) p; return toString(smte) + '.' + id; } return null; } else { return id; } } else if (t instanceof Tree.TypeLiteral) { Tree.TypeLiteral tl = (Tree.TypeLiteral) t; Tree.StaticType type = tl.getType(); if (type!=null) { return toString(type); } else { if (t instanceof Tree.InterfaceLiteral) { return "interface"; } if (t instanceof Tree.ClassLiteral) { return "class"; } } return null; } else if (t instanceof Tree.MemberLiteral) { Tree.MemberLiteral ml = (Tree.MemberLiteral) t; Tree.Identifier id = ml.getIdentifier(); Tree.StaticType type = ml.getType(); if (type!=null) { String qualifier = toString(type); if (qualifier!=null && id!=null) { return qualifier + "." + id.getText(); } return null; } return id.getText(); } else if (t instanceof Tree.ModuleLiteral) { Tree.ModuleLiteral ml = (Tree.ModuleLiteral) t; String importPath = toString(ml.getImportPath()); return importPath == null ? "module" : "module " + importPath; } else if (t instanceof Tree.PackageLiteral) { Tree.PackageLiteral pl = (Tree.PackageLiteral) t; String importPath = toString(pl.getImportPath()); return importPath == null ? "package" : "package " + importPath; } else { return null; } } private static String toString(Tree.ImportPath importPath) { if (importPath != null) { StringBuilder sb = new StringBuilder(); if (importPath.getIdentifiers() != null) { for (Tree.Identifier identifier : importPath.getIdentifiers()) { if (sb.length() != 0) { sb.append("."); } sb.append(identifier.getText()); } } return sb.toString(); } return null; } private static String toString(Tree.StaticType type) { // FIXME: we're discarding syntactic types and union/intersection types if (type instanceof Tree.BaseType){ Tree.BaseType bt = (Tree.BaseType) type; return bt.getIdentifier().getText(); } else if(type instanceof Tree.QualifiedType) { Tree.QualifiedType qt = (Tree.QualifiedType) type; String qualifier = toString(qt.getOuterType()); if(qualifier != null) { Tree.SimpleType st = (Tree.SimpleType) type; return qualifier + "." + st.getIdentifier().getText(); } return null; } return null; } public static boolean isSelfReference(Tree.Primary that) { return that instanceof Tree.This || that instanceof Tree.Outer; } public static boolean isEffectivelyBaseMemberExpression(Tree.Term term) { return term instanceof Tree.BaseMemberExpression || term instanceof Tree.QualifiedMemberExpression && isSelfReference(((Tree.QualifiedMemberExpression) term) .getPrimary()); } public static boolean isInstantiationExpression( Tree.Expression e) { Tree.Term term = e.getTerm(); if (term instanceof Tree.InvocationExpression) { Tree.InvocationExpression ie = (Tree.InvocationExpression) term; Tree.Primary p = ie.getPrimary(); if (p instanceof Tree.BaseTypeExpression || p instanceof Tree.QualifiedTypeExpression) { return true; } } return false; } }
package com.ecyrd.jspwiki; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * A mock HttpServletRequest object, used for testing. The following methods * work as they should: {@link #getCookies()},{@link #getUserPrincipal()}, * {@link #getRemoteUser()},{@link #getRemoteAddr()}, * {@link #isUserInRole(String)},{@link #getSession()}, * {@link #getSession(boolean)}. All others either return null, or don't work * they way they should. * @author Andrew R. Jaquith */ public class TestHttpServletRequest implements HttpServletRequest { protected Cookie[] m_cookies = new Cookie[0]; protected Map m_params = new Hashtable(); protected String m_remoteAddr = "127.0.0.1"; protected String m_remoteUser = null; protected Set m_roles = new HashSet(); protected Principal m_userPrincipal = null; /** Everything to right of servlet root */ protected String m_servletPath = "/"; protected HttpSession m_session = null; /** * @see javax.servlet.ServletRequest#getAttribute(java.lang.String) */ public Object getAttribute( String arg0 ) { return null; } /** * @see javax.servlet.ServletRequest#getAttributeNames() */ public Enumeration getAttributeNames() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getAuthType() */ public String getAuthType() { return null; } /** * @see javax.servlet.ServletRequest#getCharacterEncoding() */ public String getCharacterEncoding() { return null; } /** * @see javax.servlet.ServletRequest#getContentLength() */ public int getContentLength() { return 0; } /** * @see javax.servlet.ServletRequest#getContentType() */ public String getContentType() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getContextPath() */ public String getContextPath() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getCookies() */ public Cookie[] getCookies() { return m_cookies; } /** * @see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String) */ public long getDateHeader( String arg0 ) { return 0; } /** * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String) */ public String getHeader( String arg0 ) { return null; } /** * @see javax.servlet.http.HttpServletRequest#getHeaderNames() */ public Enumeration getHeaderNames() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String) */ public Enumeration getHeaders( String arg0 ) { return null; } /** * @see javax.servlet.ServletRequest#getInputStream() */ public ServletInputStream getInputStream() throws IOException { return null; } /** * @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String) */ public int getIntHeader( String arg0 ) { return 0; } /** * @see javax.servlet.ServletRequest#getLocale() */ public Locale getLocale() { return Locale.ENGLISH; } /** * @see javax.servlet.ServletRequest#getLocales() */ public Enumeration getLocales() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getMethod() */ public String getMethod() { return null; } /** * @see javax.servlet.ServletRequest#getParameter(java.lang.String) */ public String getParameter( String arg0 ) { return (String)m_params.get( arg0 ); } /** * @see javax.servlet.ServletRequest#getParameterMap() */ public Map getParameterMap() { return m_params; } /** * @see javax.servlet.ServletRequest#getParameterNames() */ public Enumeration getParameterNames() { return ((Hashtable)m_params).keys(); } /** * @see javax.servlet.ServletRequest#getParameterValues(java.lang.String) */ public String[] getParameterValues( String arg0 ) { return (String[])m_params.entrySet().toArray( new String[m_params.size()] ); } /** * @see javax.servlet.http.HttpServletRequest#getPathInfo() */ public String getPathInfo() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getPathTranslated() */ public String getPathTranslated() { return null; } /** * @see javax.servlet.ServletRequest#getProtocol() */ public String getProtocol() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getQueryString() */ public String getQueryString() { return null; } /** * @see javax.servlet.ServletRequest#getReader() */ public BufferedReader getReader() throws IOException { return null; } /** * @see javax.servlet.ServletRequest#getRealPath(java.lang.String) * @deprecated */ public String getRealPath( String arg0 ) { return null; } /** * @see javax.servlet.ServletRequest#getRemoteAddr() */ public String getRemoteAddr() { return m_remoteAddr; } /** * @see javax.servlet.ServletRequest#getRemoteHost() */ public String getRemoteHost() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getRemoteUser() */ public String getRemoteUser() { return m_remoteUser; } /** * @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String) */ public RequestDispatcher getRequestDispatcher( String arg0 ) { return null; } /** * @see javax.servlet.http.HttpServletRequest#getRequestedSessionId() */ public String getRequestedSessionId() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getRequestURI() */ public String getRequestURI() { return null; } /** * @see javax.servlet.http.HttpServletRequest#getRequestURL() */ public StringBuffer getRequestURL() { return null; } /** * @see javax.servlet.ServletRequest#getScheme() */ public String getScheme() { return null; } /** * @see javax.servlet.ServletRequest#getServerName() */ public String getServerName() { return null; } /** * @see javax.servlet.ServletRequest#getServerPort() */ public int getServerPort() { return 0; } /** * @see javax.servlet.http.HttpServletRequest#getServletPath() */ public String getServletPath() { return m_servletPath; } /** * @see javax.servlet.http.HttpServletRequest#getSession() */ public HttpSession getSession() { return getSession( true ); } /** * @see javax.servlet.http.HttpServletRequest#getSession(boolean) */ public HttpSession getSession( boolean arg0 ) { if ( arg0 && m_session == null ) { m_session = new TestHttpSession(); } return m_session; } /** * @see javax.servlet.http.HttpServletRequest#getUserPrincipal() */ public Principal getUserPrincipal() { return m_userPrincipal; } /** * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie() */ public boolean isRequestedSessionIdFromCookie() { return false; } /** * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl() * @deprecated */ public boolean isRequestedSessionIdFromUrl() { return false; } /** * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL() */ public boolean isRequestedSessionIdFromURL() { return false; } /** * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid() */ public boolean isRequestedSessionIdValid() { return false; } /** * @see javax.servlet.ServletRequest#isSecure() */ public boolean isSecure() { return false; } /** * @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String) */ public boolean isUserInRole( String arg0 ) { return m_roles.contains( arg0 ); } /** * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String) */ public void removeAttribute( String arg0 ) { } /** * @see javax.servlet.ServletRequest#setAttribute(java.lang.String, * java.lang.Object) */ public void setAttribute( String arg0, Object arg1 ) { } /** * @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String) */ public void setCharacterEncoding( String arg0 ) throws UnsupportedEncodingException { } /** * @param cookies The cookies to set. */ public void setCookies( Cookie[] cookies ) { m_cookies = cookies; } public void setParameter( String key, String value ) { m_params.put( key, value ); } /** * @param remoteAddr The remoteAddr to set. */ public void setRemoteAddr( String remoteAddr ) { m_remoteAddr = remoteAddr; } /** * @param remoteUser The remoteUser to set. */ public void setRemoteUser( String remoteUser ) { m_remoteUser = remoteUser; } /** * Sets the roles that this request's user should be considered a member of. * The * @param roles The roles to set. */ public void setRoles( String[] roles ) { for( int i = 0; i < roles.length; i++ ) { m_roles.add( roles[i] ); } } /** * Sets the servlet path; e.g., /JSPWiki/Wiki.jsp. * @param path the servlet path */ public void setServletPath( String path ) { m_servletPath = path; } /** * @param userPrincipal The userPrincipal to set. */ public void setUserPrincipal( Principal principal ) { m_userPrincipal = principal; } public int getRemotePort() { // TODO Auto-generated method stub return 0; } public String getLocalName() { // TODO Auto-generated method stub return null; } public String getLocalAddr() { // TODO Auto-generated method stub return null; } public int getLocalPort() { // TODO Auto-generated method stub return 0; } }
package org.geogit.api.porcelain; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.geogit.api.AbstractGeoGitOp; import org.geogit.api.ObjectId; import org.geogit.api.Platform; import org.geogit.api.Ref; import org.geogit.api.RevCommit; import org.geogit.api.RevTree; import org.geogit.api.SymRef; import org.geogit.api.plumbing.CreateTree; import org.geogit.api.plumbing.RefParse; import org.geogit.api.plumbing.ResolveTreeish; import org.geogit.api.plumbing.RevObjectParse; import org.geogit.api.plumbing.RevParse; import org.geogit.api.plumbing.UpdateRef; import org.geogit.api.plumbing.UpdateSymRef; import org.geogit.api.plumbing.WriteTree; import org.geogit.repository.CommitBuilder; import org.geogit.repository.Repository; import org.geogit.storage.ObjectInserter; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.inject.Inject; /** * Commits the staged changed in the index to the repository, creating a new commit pointing to the * new root tree resulting from moving the staged changes to the repository, and updating the HEAD * ref to the new commit object. * <p> * Like {@code git commit -a}, If the {@link #setAll(boolean) all} flag is set, first stages all the * changed objects in the index, but does not state newly created (unstaged) objects that are not * already staged. * </p> * * @author groldan * */ public class CommitOp extends AbstractGeoGitOp<RevCommit> { private String author; private String committer; private String message; private Long timeStamp; /** * This commit's parents. Will be the current HEAD, but when we support merges it should include * the equivalent to git's .git/MERGE_HEAD */ private List<ObjectId> parents = new LinkedList<ObjectId>(); // like the -a option in git commit private boolean all; private Repository repository; private Platform platform; private boolean allowEmpty; @Inject public CommitOp(final Repository repository, final Platform platform) { this.repository = repository; this.platform = platform; } public CommitOp setAuthor(final String author) { this.author = author; return this; } public CommitOp setCommitter(final String committer) { this.committer = committer; return this; } /** * Sets the {@link RevCommit#getMessage() commit message}. * * @param message description of the changes to record the commit with. * @return {@code this}, to ease command chaining */ public CommitOp setMessage(final String message) { this.message = message; return this; } /** * Sets the {@link RevCommit#getTimestamp() timestamp} the commit will be marked to, or if not * set defaults to the current system time at the time {@link #call()} is called. * * @param timestamp commit timestamp, in milliseconds, as in {@link Date#getTime()} * @return {@code this}, to ease command chaining */ public CommitOp setTimestamp(final Long timestamp) { this.timeStamp = timestamp; return this; } /** * If {@code true}, tells {@link #call()} to stage all the unstaged changes that are not new * object before performing the commit. * * @param all {@code true} to {@link AddOp#setUpdateOnly(boolean) stage changes) before commit, * {@code false} to not do that. Defaults to {@code false}. * @return {@code this}, to ease command chaining */ public CommitOp setAll(boolean all) { this.all = all; return this; } /** * @return the commit just applied, or {@code null} iif * {@code getProgressListener().isCanceled()} * @see org.geogit.api.AbstractGeoGitOp#call() * @throws NothingToCommitException if there are no staged changes by comparing the index * staging tree and the repository HEAD tree. */ public RevCommit call() throws Exception { // TODO: check repository is in a state that allows committing getProgressListener().started(); float writeTreeProgress = 99f; if (all) { writeTreeProgress = 50f; command(AddOp.class).addPattern(".").setUpdateOnly(true) .setProgressListener(subProgress(49f)).call(); } if (getProgressListener().isCanceled()) { return null; } final Optional<Ref> currHead = command(RefParse.class).setName(Ref.HEAD).call(); Preconditions.checkState(currHead.isPresent(), "Repository has no HEAD, can't commit"); final ObjectId currHeadCommitId = command(RevParse.class).setRefSpec(Ref.HEAD).call(); parents.add(currHeadCommitId); // final ObjectId newTreeId = index.writeTree(currHead.get(), subProgress(49f)); final ObjectId newTreeId = command(WriteTree.class).setOldRoot(resolveOldRoot()) .setProgressListener(subProgress(writeTreeProgress)).call(); if (getProgressListener().isCanceled()) { return null; } final ObjectId currentRootTreeId = repository.getRootTreeId(); if (currentRootTreeId.equals(newTreeId)) { if (!allowEmpty) { throw new NothingToCommitException("Nothing to commit after " + currHeadCommitId); } } final ObjectId commitId; { CommitBuilder cb = new CommitBuilder(); cb.setAuthor(getAuthor()); cb.setCommitter(getCommitter()); cb.setMessage(getMessage()); cb.setParentIds(parents); cb.setTreeId(newTreeId); cb.setTimestamp(getTimeStamp()); // cb.setBounds(bounds); if (getProgressListener().isCanceled()) { return null; } ObjectInserter objectInserter = repository.newObjectInserter(); commitId = objectInserter.insert(repository.newCommitWriter(cb.build(ObjectId.NULL))); } final RevCommit commit = repository.getCommit(commitId); // set the HEAD pointing to the new commit final String branch = "refs/heads/master"; final Optional<Ref> branchHead = command(UpdateRef.class).setName(branch) .setNewValue(commitId).call(); Preconditions.checkState(commitId.equals(branchHead.get().getObjectId())); LOGGER.fine("New head: " + branchHead); final Optional<SymRef> newHead = command(UpdateSymRef.class).setName(Ref.HEAD) .setNewValue(branch).call(); Preconditions.checkState(branch.equals(newHead.get().getTarget())); ObjectId treeId = repository.getCommit(branchHead.get().getObjectId()).getTreeId(); Preconditions.checkState(newTreeId.equals(treeId)); getProgressListener().progress(100f); getProgressListener().complete(); return commit; } private Supplier<RevTree> resolveOldRoot() { Supplier<RevTree> supplier = new Supplier<RevTree>() { @Override public RevTree get() { ObjectId id = command(ResolveTreeish.class).setTreeish(Ref.HEAD).call(); if (id.isNull()) { return command(CreateTree.class).setIndex(false).call(); } return (RevTree) command(RevObjectParse.class).setObjectId(id).call(); } }; return Suppliers.memoize(supplier); } private long getTimeStamp() { return timeStamp == null ? platform.currentTimeMillis() : timeStamp.longValue(); } private String getMessage() { return message; } private String getCommitter() { return committer; } private String getAuthor() { return author; } /** * @param allowEmptyCommit whether to allow a commit that represents no changes over its parent */ public CommitOp setAllowEmpty(boolean allowEmptyCommit) { this.allowEmpty = allowEmptyCommit; return this; } public boolean isAllowEmpty() { return allowEmpty; } }
package de.andreasgiemza.mangadownloader.gui.panels; import de.andreasgiemza.mangadownloader.data.Chapter; import de.andreasgiemza.mangadownloader.data.Image; import de.andreasgiemza.mangadownloader.data.Manga; import de.andreasgiemza.mangadownloader.helpers.FilenameHelper; import de.andreasgiemza.mangadownloader.helpers.JsoupHelper; import de.andreasgiemza.mangadownloader.sites.Site; import java.awt.event.WindowEvent; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.swing.JOptionPane; /** * * @author Andreas Giemza <andreas@giemza.net> */ public class Download extends javax.swing.JDialog { private volatile boolean interrupted = false; private final Site site; private final Manga selectedManga; private final List<Chapter> chapters; private int chapterCount = 0; private Thread thread; public Download(java.awt.Frame parent, boolean modal, Site site, Manga selectedManga, List<Chapter> chapters) { super(parent, modal); this.site = site; this.selectedManga = selectedManga; this.chapters = chapters; initComponents(); // Setup manga info mangaTitleLabel.setText(selectedManga.getTitle()); // Setup Chapter info for (Chapter chapter : chapters) { if (chapter.isDownload()) { chapterCount++; } } chapterProgressBar.setMaximum(chapterCount); chapterProgressBar.setString(0 + " of " + chapterCount); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (thread.isAlive()) { JOptionPane.showMessageDialog( getOwner(), "Downloading in progress! Wait or cancel it.", "Error", JOptionPane.ERROR_MESSAGE); } else { dispose(); } } }); } @Override public void setVisible(boolean b) { thread = new Thread(new Worker()); thread.start(); super.setVisible(b); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mangaLabel = new javax.swing.JLabel(); mangaTitleLabel = new javax.swing.JLabel(); chapterLabel = new javax.swing.JLabel(); chapterTileLabel = new javax.swing.JLabel(); chapterProgressBar = new javax.swing.JProgressBar(); imageLabel = new javax.swing.JLabel(); imageProgressBar = new javax.swing.JProgressBar(); cancelButton = new javax.swing.JButton(); errorLogPanel = new javax.swing.JPanel(); errorLogScrollPane = new javax.swing.JScrollPane(); errorLogTextArea = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); setTitle("Downloading ..."); setResizable(false); mangaLabel.setText("Manga:"); mangaTitleLabel.setText("TEMP"); chapterLabel.setText("Chapter:"); chapterTileLabel.setText(" "); chapterProgressBar.setString(""); chapterProgressBar.setStringPainted(true); imageLabel.setText("Images:"); imageProgressBar.setString(""); imageProgressBar.setStringPainted(true); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); errorLogPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Error Log")); errorLogTextArea.setEditable(false); errorLogTextArea.setColumns(20); errorLogTextArea.setRows(10); errorLogScrollPane.setViewportView(errorLogTextArea); javax.swing.GroupLayout errorLogPanelLayout = new javax.swing.GroupLayout(errorLogPanel); errorLogPanel.setLayout(errorLogPanelLayout); errorLogPanelLayout.setHorizontalGroup( errorLogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(errorLogScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE) ); errorLogPanelLayout.setVerticalGroup( errorLogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(errorLogScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(chapterProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(imageProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(errorLogPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(chapterLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE) .addComponent(mangaLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mangaTitleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(chapterTileLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mangaLabel) .addComponent(mangaTitleLabel)) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(chapterLabel) .addComponent(chapterTileLabel)) .addGap(6, 6, 6) .addComponent(chapterProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addComponent(imageLabel) .addGap(6, 6, 6) .addComponent(imageProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(cancelButton) .addGap(18, 18, 18) .addComponent(errorLogPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed interrupted = true; cancelButton.setEnabled(false); }//GEN-LAST:event_cancelButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelButton; private javax.swing.JLabel chapterLabel; private javax.swing.JProgressBar chapterProgressBar; private javax.swing.JLabel chapterTileLabel; private javax.swing.JPanel errorLogPanel; private javax.swing.JScrollPane errorLogScrollPane; private javax.swing.JTextArea errorLogTextArea; private javax.swing.JLabel imageLabel; private javax.swing.JProgressBar imageProgressBar; private javax.swing.JLabel mangaLabel; private javax.swing.JLabel mangaTitleLabel; // End of variables declaration//GEN-END:variables private class Worker implements Runnable { private String errorLog = null; @Override public void run() { int chapterDone = 1; for (Chapter chapter : chapters) { if (chapter.isDownload()) { Path mangaFile = FilenameHelper.buildChapterPath(selectedManga, chapter); if (interrupted) { chapterError(mangaFile, chapter, "Aborted while downloading: "); updateGui(); return; } chapterTileLabel.setText(chapter.getTitle()); chapterProgressBar.setValue(chapterDone); chapterProgressBar.setString(chapterDone + " of " + chapterCount); imageProgressBar.setValue(0); imageProgressBar.setString("Getting image links ..."); List<Image> imageLinks; try { imageLinks = site.getChapterImageLinks(chapter); } catch (IOException ex) { chapterDone++; chapterError(mangaFile, chapter, "Error while downloading: "); continue; } imageProgressBar.setMaximum(imageLinks.size()); try { if (!Files.exists(mangaFile.getParent())) { Files.createDirectories(mangaFile.getParent()); } if (Files.exists(mangaFile)) { Files.delete(mangaFile); } try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(mangaFile.toFile()))) { for (int i = 0; i < imageLinks.size(); i++) { if (interrupted) { zos.close(); chapterError(mangaFile, chapter, "Aborted while downloading: "); updateGui(); return; } imageProgressBar.setValue(i + 1); imageProgressBar.setString((i + 1) + " of " + imageLinks.size()); ZipEntry ze = new ZipEntry((i + 1) + "." + imageLinks.get(i).getExtension()); zos.putNextEntry(ze); byte[] image; image = JsoupHelper.getImage(imageLinks.get(i)); zos.write(image, 0, image.length); zos.closeEntry(); } } } catch (IOException ex) { chapterDone++; chapterError(mangaFile, chapter, "Error while downloading: "); continue; } chapterDone++; chapter.setAlreadyDownloaded(true); chapter.setDownload(false); } } updateGui(); JOptionPane.showMessageDialog( getOwner(), "Done downloading chapter(s)!", "Information", JOptionPane.INFORMATION_MESSAGE); } private void updateGui() { cancelButton.setEnabled(false); setTitle(getTitle() + " Done!"); } private void chapterError(Path mangaFile, Chapter chapter, String message) { if (Files.exists(mangaFile)) { try { Files.delete(mangaFile); } catch (IOException ex) { } } if (errorLog == null) { errorLog = message + chapter.getTitle(); } else { errorLog += "\n" + message + chapter.getTitle(); } errorLogTextArea.setText(errorLog); } } }
package edu.ntnu.idi.goldfish.preprocessors; import edu.ntnu.idi.goldfish.configurations.Config; import edu.ntnu.idi.goldfish.mahout.DBModel; import edu.ntnu.idi.goldfish.mahout.DBModel.DBRow; import org.apache.commons.math3.stat.correlation.PearsonsCorrelation; import org.apache.mahout.cf.taste.common.TasteException; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; public class PreprocessorStat extends Preprocessor{ private final int THRESHOLD = 3; public static enum PredictionMethod { LinearRegression, ClosestNeighbor, EqualBins } public DBModel getProcessedModel(Config config) throws TasteException, IOException { DBModel model = config.get("model"); PredictionMethod predictionMethod = config.get("predictionMethod"); int minTimeOnPage = config.get("minTimeOnPage"); double correlationLimit = config.get("correlationLimit"); int rating = config.get("rating"); List<DBModel.DBRow> allResults = model.getFeedbackRows(); List<DBModel.DBRow> results = allResults.stream().filter(row -> row.rating == 0).collect(Collectors.toList()); for (DBRow r : results) { long itemID = r.itemid; List<DBModel.DBRow> feedbackForItemID = allResults.stream() .filter(row -> row.itemid == itemID) .filter(row -> row.rating > 0) .collect(Collectors.toList()); if(hasImplicit(r.implicitfeedback) && enoughImplicitFeedback(feedbackForItemID)){ double[] dependentVariables = new double[feedbackForItemID.size()]; // the explicit ratings to infer double[][] independentVariables = new double[feedbackForItemID.size()][]; // the implicit feedback double[] implicitFeedback = null; int index = 0; for (DBRow f : feedbackForItemID) { dependentVariables[index] = f.rating; implicitFeedback = new double[f.implicitfeedback.length]; for (int i = 0; i < implicitFeedback.length; i++) { implicitFeedback[i] = f.implicitfeedback[i]; } independentVariables[index] = implicitFeedback; index++; } int bestCorrelated = getBestCorrelated(dependentVariables, independentVariables); double correlation = getCorrelation(dependentVariables, independentVariables, bestCorrelated); if(correlation > correlationLimit){ float pseudoRating = 0; switch (predictionMethod) { case LinearRegression: pseudoRating = getPseudoRatingLinearRegression(dependentVariables, independentVariables, bestCorrelated, r.implicitfeedback); break; case ClosestNeighbor: pseudoRating = getPseudoRatingClosestNeighbor(dependentVariables, independentVariables, bestCorrelated, r.implicitfeedback); break; case EqualBins: pseudoRating = getPseudoRatingEqualBins(independentVariables, bestCorrelated, r.implicitfeedback, correlation); break; default: pseudoRating = getPseudoRatingLinearRegression(dependentVariables, independentVariables, bestCorrelated, r.implicitfeedback); break; } model.setPreference(r.userid, r.itemid, (float) Math.round(pseudoRating)); addPseudoPref(r.userid, r.itemid); // System.out.println(String.format("%d, %d, %.0f", r.userid, r.itemid, pseudoRating)); } } else if(timeOnPageFeedback(r.implicitfeedback, minTimeOnPage, 120000)){ model.setPreference(r.userid, r.itemid, rating); addPseudoPref(r.userid, r.itemid); } } return model; } public boolean hasImplicit(float[] implicitfeedback){ for (int i = 0; i < implicitfeedback.length; i++) { if(implicitfeedback[i] > 0) return true; } return false; } public boolean enoughImplicitFeedback(List<DBModel.DBRow> feedbackForItemID ){ int[] feedbackCount = new int[feedbackForItemID.get(0).implicitfeedback.length]; for (DBRow row : feedbackForItemID) { for (int i = 0; i < row.implicitfeedback.length; i++) { if(row.implicitfeedback[i] > 0) { feedbackCount[i] += 1; } } } for (int i = 0; i < feedbackCount.length; i++) { if(feedbackCount[i] >= THRESHOLD) return true; } return false; } public double getCorrelation(double[] dv, double[][] iv, int feedbackIndex){ double[] itemFeedback = new double[iv.length]; for (int i = 0; i < iv.length; i++) { itemFeedback[i] = iv[i][feedbackIndex]; } PearsonsCorrelation pc = new PearsonsCorrelation(); return Math.abs(pc.correlation(dv, itemFeedback)); } public int getBestCorrelated(double[] dv, double[][] iv){ int bestCorrelated = 0; double maxCorr = 0; double tempCorr = 0; for (int i = 0; i < iv[0].length; i++) { tempCorr = getCorrelation(dv, iv, i); if(tempCorr > maxCorr){ maxCorr = tempCorr; bestCorrelated = i; } } return bestCorrelated; } private float getPseudoRatingLinearRegression(double[] dv, double[][] iv, int bestCorrelated, float[] implicitfeedback){ double[] itemFeedback = new double[iv.length]; for (int i = 0; i < iv.length; i++) { itemFeedback[i] = iv[i][bestCorrelated]; } TrendLine t = new PolyTrendLine(1); t.setValues(dv, itemFeedback); return (float) Math.round(t.predict(implicitfeedback[bestCorrelated])); } private float getPseudoRatingClosestNeighbor(double[] dv, double[][] iv, int bestCorrelated, float[] implicitFeedback) { float diff = Float.MAX_VALUE; float closestPref = 0; for (int i = 0; i < iv.length; i++) { float tempDiff = (float) Math.abs(implicitFeedback[bestCorrelated] - iv[i][bestCorrelated]); if(tempDiff < diff){ diff = tempDiff; closestPref = (float) dv[i]; } } return closestPref; } private float getPseudoRatingEqualBins(double[][] iv, int bestCorrelated, float[] implicitFeedback, double correlation) { float min = Integer.MAX_VALUE; float max = Integer.MIN_VALUE; float pseudoRating; for (int i = 0; i < iv.length; i++) { if(iv[i][bestCorrelated] < min){ min = (float) iv[i][bestCorrelated]; } if(iv[i][bestCorrelated] > max){ max = (float) iv[i][bestCorrelated]; } } if (min == max) { return 3; } if(implicitFeedback[bestCorrelated] < min){ pseudoRating = 1; } else if(implicitFeedback[bestCorrelated] > max) { pseudoRating = 5; } else{ float binSize = (max-min)/5; float dif = implicitFeedback[bestCorrelated] - min; pseudoRating = (float) (1 + Math.floor(dif/binSize)); } if (correlation < 0) { pseudoRating = 6 - pseudoRating; } return pseudoRating; } public boolean timeOnPageFeedback(float[] feedback, int min, int max){ return feedback[0] > min && feedback[0] < max; } }
package edu.psu.compbio.seqcode.projects.shaun; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import cern.jet.random.Binomial; import cern.jet.random.Poisson; import cern.jet.random.engine.DRand; import edu.psu.compbio.seqcode.genome.Genome; import edu.psu.compbio.seqcode.genome.Species; import edu.psu.compbio.seqcode.genome.location.Point; import edu.psu.compbio.seqcode.genome.location.Region; import edu.psu.compbio.seqcode.genome.location.RepeatMaskedRegion; import edu.psu.compbio.seqcode.genome.location.StrandedPoint; import edu.psu.compbio.seqcode.genome.location.StrandedRegion; import edu.psu.compbio.seqcode.gse.datasets.seqdata.SeqLocator; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.chipseq.MACSParser; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.chipseq.MACSPeakRegion; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.PointParser; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.RegionParser; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.RepeatMaskedGenerator; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.sequence.SequenceGenerator; import edu.psu.compbio.seqcode.gse.projects.gps.DeepSeqExpt; import edu.psu.compbio.seqcode.gse.projects.gps.ReadHit; import edu.psu.compbio.seqcode.gse.projects.gps.features.Feature; import edu.psu.compbio.seqcode.gse.tools.utils.Args; import edu.psu.compbio.seqcode.gse.utils.ArgParser; import edu.psu.compbio.seqcode.gse.utils.NotFoundException; import edu.psu.compbio.seqcode.gse.utils.Pair; import edu.psu.compbio.seqcode.gse.utils.io.RegionFileUtilities; import edu.psu.compbio.seqcode.gse.utils.sequence.SequenceUtils; public class PeaksAnalysis { private Species org=null; private Genome gen =null; private List<Region> posSet; private List<Point> posPeaks=null; private List<String> posLines; private List<Region> negSet; private List<Point> negPeaks=null; private List<String> negLines; private List<Region> towers = new ArrayList<Region>(); private int window=200; private boolean shiftTags = false; private int readShift=0; private int readExtension=0; protected String exptLabel; protected DeepSeqExpt IP=null; protected DeepSeqExpt IP2=null; protected boolean dbconnected=false; protected boolean twoExpts=false; protected boolean normCounts = false; private double iphittot=0; private int metaBinSize=20; private int fixedPBCutoff=-1; protected int readLen=32; public static void main(String[] args) { ArgParser ap = new ArgParser(args); if(!ap.hasKey("species") ||(!ap.hasKey("peaks")&&!ap.hasKey("macspeaks")&&!ap.hasKey("motifhits"))) { System.err.println("Usage:\n " + "PeaksAnalysis \n" + " Required: \n" + " --species <species;version> " + " --peaks <file containing coordinates of peaks in Shaun's format> \n" + " OR" + " --macspeaks <file containing coordinates of peaks in MACS format> \n" + " OR" + " --motifhits <file containing motif hit coordinates> \n" + " --neg <file containing negative regions in Shaun's format> \n" + " OR" + " --macsneg <file containing negative regions in MACS format> \n" + " --towers <file containing towers in Shaun's format>\n" + " More Info: \n"+ " --win <window of sequence around peaks> \n"+ " Options: \n" + " --out output filename\n" + " --cache [flag to cache sequences] AND --seq <path to genome files>\n" + " --printseqs [flag to print sequences under peaks] \n" + " --printseqkmers [flag to print k-mer counts for sequences under peaks] \n" + " --printxy [flag to print hit counts under peaks for two expts]\n" + " --readlen <rlen>\n" + " --fixedpb <cutoff>\n" + " --expt <IP expt names> \n" + " --expt2 <IP2 expt names> \n" + " --exptlabel <experiment name> \n" + " --format <ELAND/NOVO/BOWTIE>\n" + " --metapeak [flag to print a metapeak (IP expt handles reqd)] \n" + " --weightcount <provide a metapeak file, get back weighted counts in the window around peaks>\n" + " --counts [flag to print raw counts per peak]\n" + " --orderbycounts [flag to print peaks ordered by raw counts per peak]\n" + " --quick [flag to do things quickly without tower & needle filters]\n" + " --normcounts [sum the counts per peak, weighting each experiment by the total number of reads]\n" + " --repscreen [when printing sequences, screen out anything overlapping a repeat]\n" + ""); return; } try { Pair<Species, Genome> pair = Args.parseGenome(args); Species currorg = pair.car(); Genome currgen = pair.cdr(); String peaksFile = ap.hasKey("peaks") ? ap.getKeyValue("peaks") : (ap.hasKey("macspeaks") ? ap.getKeyValue("macspeaks"):null); String motifHitsFile = ap.hasKey("motifhits") ? ap.getKeyValue("motifhits") : null; boolean macsformatpeaks = ap.hasKey("macspeaks"); String negFile = ap.hasKey("neg") ? ap.getKeyValue("neg") : (ap.hasKey("macsneg") ? ap.getKeyValue("macsneg"):null); boolean hasNeg = negFile==null ? false : true; boolean macsformatneg = ap.hasKey("macsneg"); String towerFile = ap.hasKey("towers") ? ap.getKeyValue("towers") : null; boolean hasTowers = towerFile==null ? false : true; boolean printxy = ap.hasKey("printxy"); int win = ap.hasKey("win") ? new Integer(ap.getKeyValue("win")).intValue():-1; int fpb = ap.hasKey("fixedpb") ? new Integer(ap.getKeyValue("fixedpb")).intValue():-1; int rL = ap.hasKey("readlen") ? new Integer(ap.getKeyValue("readlen")).intValue():32; String outFile = ap.hasKey("out") ? ap.getKeyValue("out") : "out.txt"; String label = ap.hasKey("exptlabel") ? ap.getKeyValue("exptlabel") : "IP"; String mFile = ap.hasKey("weightcount") ? ap.getKeyValue("weightcount") : null; //options boolean printSeqs = ap.hasKey("printseqs"); boolean printSeqKmers = ap.hasKey("printseqkmers"); boolean printTiledSeqKmers = ap.hasKey("printtiledseqkmers"); boolean printSeqKmersCoOccurence = ap.hasKey("printSeqKmersCoOccurence"); int printSeqKmersCoOccurenceK = ap.hasKey("printSeqKmersCoOccurence") ? new Integer(ap.getKeyValue("printSeqKmersCoOccurence")).intValue():4; int printSeqKmersK = ap.hasKey("printseqkmers") ? new Integer(ap.getKeyValue("printseqkmers")).intValue():4;; boolean printMeta = ap.hasKey("metapeak"); boolean weightedCounts = ap.hasKey("weightcount"); boolean normCounts = ap.hasKey("normcounts"); boolean counts = ap.hasKey("counts"); boolean orderByCounts = ap.hasKey("orderbycounts"); boolean quick = ap.hasKey("quick"); boolean repeatScreen = ap.hasKey("repscreen"); boolean useCache = ap.hasKey("cache"); String genomePath = ""; if(useCache){ genomePath = ap.getKeyValue("seq"); } ///////////// START //initialize PeaksAnalysis analyzer = new PeaksAnalysis(currorg, currgen); analyzer.setWin(win); analyzer.setReadLen(rL); analyzer.setFixedPB(fpb); //load positive & negative sets analyzer.loadPeaks(peaksFile, motifHitsFile, macsformatpeaks); if(hasNeg) analyzer.loadNegs(negFile, macsformatneg); if(hasTowers) analyzer.loadTowers(towerFile); //Options if(printSeqs) analyzer.printPeakSeqs(repeatScreen); if(printSeqKmers) analyzer.printPeakSeqKmers(printSeqKmersK, useCache, genomePath); if(printTiledSeqKmers){ int kmin = ap.hasKey("kmin") ? new Integer(ap.getKeyValue("kmin")).intValue():3; int kmax = ap.hasKey("kmax") ? new Integer(ap.getKeyValue("kmax")).intValue():8; analyzer.printPeakSeqTiledKmers(kmin, kmax, useCache, genomePath); } if(printSeqKmersCoOccurence){ int s = ap.hasKey("slide") ? new Integer(ap.getKeyValue("slide")).intValue():10; analyzer.printPeakSeqKmerCoocurrence(printSeqKmersCoOccurenceK, useCache,genomePath , s); } //analyzer.printMotifInfo(); analyzer.loadExperiments(args); if(printMeta){ analyzer.buildMetaPeak(outFile); } if(printxy){ analyzer.printXY(); } if(weightedCounts){ double [] meta = analyzer.loadMetaPeakFile(mFile); analyzer.weightedCounts(meta, label, outFile); } if(orderByCounts){ analyzer.orderByCounts(label, outFile); } if(counts){ if(normCounts) analyzer.setNormCounts(true); if(quick) analyzer.quickcounts(label, outFile); else analyzer.counts(label, outFile); } analyzer.close(); } catch (NotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public PeaksAnalysis(Species o, Genome g){ org = o; gen=g; } //Options first //Print the sequences for each peak public void printPeakSeqs(boolean repeatScreen){ RepeatMaskedGenerator repMask = new RepeatMaskedGenerator(gen); SequenceGenerator seqgen = new SequenceGenerator(); for(Region r : posSet){ String seq = seqgen.execute(r); if(repeatScreen){ boolean repOver = false; Iterator<RepeatMaskedRegion> repItr = repMask.execute(r); while(repItr.hasNext()){ RepeatMaskedRegion currRep = repItr.next(); if(currRep.overlaps(r)){ repOver=true; } } if(!repOver){ if(r instanceof StrandedRegion && ((StrandedRegion)r).getStrand()=='-'){ seq = SequenceUtils.reverseComplement(seq); System.out.println(">"+r.toString()+"\n"+seq); }else System.out.println(">"+r.toString()+"\n"+seq); } }else{ if(r instanceof StrandedRegion && ((StrandedRegion)r).getStrand()=='-'){ seq = SequenceUtils.reverseComplement(seq); System.out.println(">"+r.toString()+"\n"+seq); }else System.out.println(">"+r.toString()+"\n"+seq); } } } //Print the k-mers in the sequences for each peak public void printPeakSeqKmers(int k, boolean useCache, String genPath ){ SequenceGenerator seqgen = new SequenceGenerator(); seqgen.useCache(useCache); if(useCache){ seqgen.useLocalFiles(true); seqgen.setGenomePath(genPath); } int numK = (int)Math.pow(4, k); int [] kmerCounts = new int[numK]; System.out.print("Region"); for(int i=0; i<numK; i++) System.out.print("\t"+RegionFileUtilities.int2seq(i, k)); System.out.println(""); for(Region r : posSet){ for(int i=0; i<numK; i++) kmerCounts[i]=0; String seq = seqgen.execute(r).toUpperCase(); //Check if the sequence (seq) contains any N's if present ignore them if(seq.contains("N")) continue; for(int i=0; i<(seq.length()-k+1); i++){ String currK = seq.substring(i, i+k); String revCurrK =SequenceUtils.reverseComplement(currK); int currKInt = RegionFileUtilities.seq2int(currK); int revCurrKInt = RegionFileUtilities.seq2int(revCurrK); int kmer = currKInt<revCurrKInt ? currKInt : revCurrKInt; kmerCounts[kmer]++; } System.out.print(r.getLocationString()); for(int i=0; i<numK; i++) System.out.print("\t"+kmerCounts[i]); System.out.println(""); } } // Print the number of times 2 kmers co-occurr in a given sliding window // and // Prints the kmer frequency counts // Prints only those kmer-pairs that frequently occur in the given list of peaks. This is to maintain a manageble feature space public void printPeakSeqKmerCoocurrence(int k, boolean useCache, String genPath, int s){ // Claculate the probability of seeing a kmer-pair within a given window size double p_k1_k2_not = 1-Math.pow(0.25, 2*k); double p_k1_k2_w_s = 1-Math.pow(p_k1_k2_not, (double)s*window); Binomial bt = new Binomial(100,0.5,new DRand()); bt.setNandP(posSet.size(), p_k1_k2_w_s); SequenceGenerator seqgen = new SequenceGenerator(); seqgen.useCache(useCache); if(useCache){ seqgen.useLocalFiles(true); seqgen.setGenomePath(genPath); } int numK = (int)Math.pow(4, k); int[] kmerCounts = new int[numK]; int[][] kmerCoO = new int[numK][numK]; //Print header System.out.print("Region"); for(int i=0; i<numK; i++){ System.out.print("\t"+RegionFileUtilities.int2seq(i, k)); } for(int r=0; r<numK; r++){ for(int c=r; c<numK; c++){ System.out.print("\t"+RegionFileUtilities.int2seq(r, k)+"-"+RegionFileUtilities.int2seq(c, k)); } } System.out.println(""); double[][] kmerCountsAvg = new double[posSet.size()][numK]; double[][][] kmerCoOAvg = new double[posSet.size()][numK][numK]; int reg_index=0; for(Region r: posSet){ // Initialize for(int i=0; i<numK; i++) kmerCounts[i]=0; for(int i=0; i<numK; i++){ for(int j=0; j<numK; j++){ kmerCoO[i][j]=0; } } String seq = seqgen.execute(r).toUpperCase(); if(seq.contains("N")){ for(int i=0; i<numK; i++){ kmerCountsAvg[reg_index][i]=0; } for(int i=0;i<numK; i++){ for(int j=0; j<numK; j++){ kmerCoOAvg[reg_index][i][j]=0; } } reg_index++; continue; } // Count kmer freqs for(int i=0; i<(seq.length()-k+1); i++){ String currK = seq.substring(i, i+k); String revCurrK =SequenceUtils.reverseComplement(currK); int currKInt = RegionFileUtilities.seq2int(currK); int revCurrKInt = RegionFileUtilities.seq2int(revCurrK); int kmer = currKInt<revCurrKInt ? currKInt : revCurrKInt; kmerCounts[kmer]++; kmerCountsAvg[reg_index][kmer]++; } // Count the co-occurrence for(int i=0; i<(seq.length()-s+1);i++){ String currSubSeq = seq.substring(i,i+s); for(int j=0;j<(currSubSeq.length()-k+1-1);j++){ String currKP1 = currSubSeq.substring(j, j+k); String revCurrKP1 = SequenceUtils.reverseComplement(currKP1); int currKP1Int = RegionFileUtilities.seq2int(currKP1); int revCurrKP1Int = RegionFileUtilities.seq2int(revCurrKP1); int kmerP1 = currKP1Int<revCurrKP1Int? currKP1Int:revCurrKP1Int; for(int l=j+1;l<(currSubSeq.length()-k+1); l++){ String currKP2 = currSubSeq.substring(l,l+k); String revCurrKP2 = SequenceUtils.reverseComplement(currKP2); int currKP2Int = RegionFileUtilities.seq2int(currKP2); int revCurrKP2Int = RegionFileUtilities.seq2int(revCurrKP2); int kmerP2 = currKP2Int<revCurrKP2Int? currKP2Int: revCurrKP2Int; kmerCoO[kmerP1][kmerP2]=1; kmerCoO[kmerP2][kmerP1]=1; kmerCoOAvg[reg_index][kmerP1][kmerP2]=1; kmerCoOAvg[reg_index][kmerP2][kmerP1]=1; } } } System.out.print(r.getLocationString()); for(int i=0; i<numK; i++) System.out.print("\t"+kmerCounts[i]); for(int i=0; i<numK; i++){ for(int j=i; j<numK; j++){ System.out.print("\t"+kmerCoO[i][j]); } } System.out.println(""); reg_index++; } System.out.print("Overall_incidence"); for(int i=0; i<numK; i++){ int sum=0; for(int ri=0; ri<kmerCountsAvg.length; ri++){ if(kmerCountsAvg[ri][i]>0){ sum++; } } System.out.print("\t"+sum); } for(int i=0; i<numK; i++){ for(int j=i; j<numK; j++){ int sum=0; for(int ri=0; ri<kmerCoOAvg.length; ri++){ if(kmerCoOAvg[ri][i][j] > 0){ sum++; } } System.out.print("\t"+sum); } } System.out.println(""); System.out.print("Incidence_Pval"); for(int i=0; i<numK; i++){ System.out.print("\t0"); } for(int i=0; i<numK; i++){ for(int j=i; j<numK; j++){ int sum=0; for(int ri=0; ri<kmerCoOAvg.length; ri++){ if(kmerCoOAvg[ri][i][j] > 0){ sum++; } } System.out.print("\t"+Double.toString(1-bt.cdf(sum))); } } System.out.println(""); } //Divide the sequence into 3 regions and print kmer counts in the left, right and central regions public void printPeakSeqTiledKmers(int kmin, int kmax, boolean useCache, String genPath){ SequenceGenerator seqgen = new SequenceGenerator(); seqgen.useCache(useCache); if(useCache){ seqgen.useLocalFiles(true); seqgen.setGenomePath(genPath); } int TnumK = 0; for(int k=kmin; k<=kmax; k++){ TnumK = TnumK + ((int)Math.pow(4, k))*3; } int[] kmerCounts = new int[TnumK]; System.out.print("Region"); int currIndex = 0; //Print header for(int k=kmin; k<=kmax; k++){ int numK = (int)Math.pow(4, k); //Print left kmers for(int i=0; i<numK; i++){ System.out.print("\t"+RegionFileUtilities.int2seq(i, k)+"_L"); } //Print central kmers for(int i=0; i<numK; i++){ System.out.print("\t"+RegionFileUtilities.int2seq(i, k)+"_C"); } // Print right kmers for(int i=0; i<numK; i++){ System.out.print("\t"+RegionFileUtilities.int2seq(i, k)+"_R"); } } System.out.println(""); for(Region r : posSet){ for(int i=0; i<kmerCounts.length; i++){ kmerCounts[i] = 0; } StrandedRegion sr = (StrandedRegion)r; String seq = seqgen.execute(r).toUpperCase(); if(seq.contains("N")) continue; for(int k=kmin; k<=kmax; k++){ int currKStart = 0; for(int k_sub=kmin; k_sub<k; k_sub++){ currKStart = currKStart + ((int)Math.pow(4, k_sub))*3; } // Count left kmers for(int i=0; i<((int)(seq.length()/3)-k+1); i++){ String currK = seq.substring(i, i+k); String revCurrK =SequenceUtils.reverseComplement(currK); int currKInt = RegionFileUtilities.seq2int(currK); int revCurrKInt = RegionFileUtilities.seq2int(revCurrK); int kmer = currKInt<revCurrKInt ? currKInt : revCurrKInt; if(sr.getStrand() == '+') kmerCounts[currKStart+kmer]++; else kmerCounts[currKStart+ ((int)Math.pow(4, k))*2+kmer]++; } //Count central kmers for(int i=(int)(seq.length()/3); i<((int)(seq.length()*2/3)-k+1); i++){ String currK = seq.substring(i, i+k); String revCurrK =SequenceUtils.reverseComplement(currK); int currKInt = RegionFileUtilities.seq2int(currK); int revCurrKInt = RegionFileUtilities.seq2int(revCurrK); int kmer = currKInt<revCurrKInt ? currKInt : revCurrKInt; kmerCounts[currKStart+ ((int)Math.pow(4, k))+kmer]++; } //Count right kmers for(int i=(int)(seq.length()*2/3); i<(seq.length()-k+1); i++){ String currK = seq.substring(i, i+k); String revCurrK =SequenceUtils.reverseComplement(currK); int currKInt = RegionFileUtilities.seq2int(currK); int revCurrKInt = RegionFileUtilities.seq2int(revCurrK); int kmer = currKInt<revCurrKInt ? currKInt : revCurrKInt; if(sr.getStrand() == '+') kmerCounts[currKStart+ ((int)Math.pow(4, k))*2+kmer]++; else kmerCounts[currKStart+kmer]++; } } System.out.print(r.getLocationString()); for(int i=0; i<kmerCounts.length; i++) System.out.print("\t"+kmerCounts[i]); System.out.println(""); } } public void setWin(int w){window=w;} public void setReadLen(int rl){readLen=rl;} public void setFixedPB(int fpb){fixedPBCutoff = fpb;} public void setNormCounts(boolean x){normCounts = x;} //load positive public void loadPeaks(String fname, String motifHitsFile, boolean macs){ if(fname == null && motifHitsFile != null){ posSet=new ArrayList<Region>(); posPeaks=new ArrayList<Point>(); List<StrandedRegion> regs = RegionFileUtilities.loadStrandedRegionsFromMotifFile(gen, motifHitsFile, window); List<StrandedPoint> points = RegionFileUtilities.loadStrandedPointsFromMotifFile(gen, motifHitsFile, window); for(StrandedRegion r : regs) posSet.add(r); for(StrandedPoint p : points) posPeaks.add(p); posLines = RegionFileUtilities.loadLinesFromFile(motifHitsFile); }else{ if(macs){ posSet=new ArrayList<Region>(); List<MACSPeakRegion> mprs = MACSParser.parseMACSOutput(fname,gen); for(MACSPeakRegion m : mprs){ posSet.add(m.getPeak().expand(window/2)); } }else{ posSet = RegionFileUtilities.loadRegionsFromPeakFile(gen, fname, window); posPeaks = RegionFileUtilities.loadPeaksFromPeakFile(gen, fname, window); } posLines = RegionFileUtilities.loadLinesFromFile(fname); } }//load negative public void loadNegs(String fname, boolean macs){ if(macs){ negSet=new ArrayList<Region>(); List<MACSPeakRegion> mprs = MACSParser.parseMACSOutput(fname,gen); for(MACSPeakRegion m : mprs){ negSet.add(m.getPeak().expand(window/2)); } }else{ negSet = RegionFileUtilities.loadRegionsFromPeakFile(gen, fname, window); negPeaks = RegionFileUtilities.loadPeaksFromPeakFile(gen, fname, window); }negLines = RegionFileUtilities.loadLinesFromFile(fname); }//load towers public void loadTowers(String fname){ towers = RegionFileUtilities.loadRegionsFromPeakFile(gen, fname, -1); } //load metapeak public double [] loadMetaPeakFile(String fname){ double [] meta = new double [(window/metaBinSize)+1]; try{ File pFile = new File(fname); if(!pFile.isFile()){System.err.println("Invalid positive file name");System.exit(1);} BufferedReader reader = new BufferedReader(new FileReader(pFile)); String line; int lineCount=0, bCount=0;; while ((line = reader.readLine()) != null) { if(lineCount>=2 && bCount<=(window/metaBinSize)){ line = line.trim(); String[] words = line.split("\\s+"); meta[bCount]=Double.valueOf(words[4]); bCount++; } lineCount++; }reader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return(meta); } //Print the read counts under each peak public void printXY(){ try { FileWriter fout = new FileWriter("XYcounts.txt"); for(Region r : posSet){ //Initialize tower filter ArrayList<Region> currTowers = new ArrayList<Region>(); for(Region t : towers) if(r.overlaps(t)) currTowers.add(t); int IPcount=0, IP2count=0; for(ReadHit h : IP.loadHits(r)){ boolean inTower=false; for(Region t : currTowers) if(h.overlaps(t)) inTower=true; if(!inTower){IPcount++;} } for(ReadHit h : IP2.loadHits(r)){ boolean inTower=false; for(Region t : currTowers) if(h.overlaps(t)) inTower=true; if(!inTower){IP2count++;} } fout.write(String.format("%s\t%d\t%d\n", r, IPcount, IP2count)); }fout.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Print the distribution of reads around the peaks //With tower & needle filters public void weightedCounts(double[] meta, String label, String outName){ int topX=-1; boolean absoluteDist=true; boolean needleFiltering=true; int min=0, max=window/2; int numBins = ((max-min)/metaBinSize); int perBaseMax = getPoissonThreshold(Math.pow(10, -9), IP.getWeightTotal(), 1, gen.getGenomeLength(), 0.8, 1, 1); double [] positive = new double [numBins+1]; for(int w=0; w<=numBins; w++){ positive[w]=0; } try{ FileWriter fw = new FileWriter(outName); fw.write("Region\t"+label+"\n"); //Positive set int count =0; for(Region r : posSet){ double score=0; if(topX==-1 || count<topX){ Point p = posPeaks.get(count); List<ReadHit> hits = IP.loadHits(r); //Towers & Needles init ArrayList<Region> currTowers = new ArrayList<Region>(); for(Region t : towers) if(r.overlaps(t)) currTowers.add(t); int [] counts = new int[r.getWidth()+1]; for(int i=0; i<=r.getWidth(); i++){counts[i]=0;} for(ReadHit h : hits){ boolean inTower=false; for(Region t : currTowers) if(r.overlaps(t)) inTower=true; if(!inTower){ int offset=h.getFivePrime()-r.getStart()<0 ? 0 : h.getFivePrime()-r.getStart(); if(offset>r.getWidth()) offset=r.getWidth(); counts[offset]++; if(!needleFiltering || (counts[offset] <= perBaseMax)){ int dist = h.getStrand()=='+' ? p.getLocation()-h.getFivePrime() : h.getFivePrime()-p.getLocation(); if(absoluteDist){dist = Math.abs(dist);} if(dist>=min && dist<=max){ score+=meta[(dist-min)/metaBinSize]; } } } } fw.write(String.format("%s\t%.2f\n", p.getLocationString(),score)); }count++; } fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Print the distribution of reads around the peaks //With tower & needle filters public void counts(String label, String outName){ int topX=-1; boolean needleFiltering=true; double ipWeightTotal=IP.getWeightTotal(); int perBaseMax = fixedPBCutoff>0 ? fixedPBCutoff : getPoissonThreshold(Math.pow(10, -9), ipWeightTotal, 1, gen.getGenomeLength(), 0.8, 1, 1); try{ FileWriter fw = new FileWriter(outName); fw.write("Region\t"+label+"\n"); //Positive set int count =0; for(Region r : posSet){ double score=0; if(topX==-1 || count<topX){ Point p = posPeaks.get(count); List<ReadHit> hits = IP.loadHits(r); //Towers & Needles init ArrayList<Region> currTowers = new ArrayList<Region>(); for(Region t : towers) if(r.overlaps(t)) currTowers.add(t); int [] counts = new int[r.getWidth()+1]; for(int i=0; i<=r.getWidth(); i++){counts[i]=0;} for(ReadHit h : hits){ boolean inTower=false; for(Region t : currTowers) if(r.overlaps(t)) inTower=true; if(!inTower){ int offset=h.getFivePrime()-r.getStart()<0 ? 0 : h.getFivePrime()-r.getStart(); if(offset>r.getWidth()) offset=r.getWidth(); counts[offset]++; if(!needleFiltering || (counts[offset] <= perBaseMax)){ score++; } } } if(normCounts) fw.write(String.format("%s\t%e\n", r.getLocationString(), score/ipWeightTotal)); else fw.write(String.format("%s\t%.2f\n", r.getLocationString() ,score)); }count++; } fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Order the input peaks by read counts in surrounding window //With tower & needle filters public void orderByCounts(String label, String outName){ int topX=-1; boolean needleFiltering=true; double ipWeightTotal=IP.getWeightTotal(); int perBaseMax = fixedPBCutoff>0 ? fixedPBCutoff : getPoissonThreshold(Math.pow(10, -9), ipWeightTotal, 1, gen.getGenomeLength(), 0.8, 1, 1); ArrayList<Pair<Integer, Double>> peakScores = new ArrayList<Pair<Integer, Double>>(); try{ FileWriter fw = new FileWriter(outName); //Positive set int count =0; for(Region r : posSet){ double score=0; if(topX==-1 || count<topX){ Point p = posPeaks.get(count); List<ReadHit> hits = IP.loadHits(r); //Towers & Needles init ArrayList<Region> currTowers = new ArrayList<Region>(); for(Region t : towers) if(r.overlaps(t)) currTowers.add(t); int [] counts = new int[r.getWidth()+1]; for(int i=0; i<=r.getWidth(); i++){counts[i]=0;} for(ReadHit h : hits){ boolean inTower=false; for(Region t : currTowers) if(r.overlaps(t)) inTower=true; if(!inTower){ int offset=h.getFivePrime()-r.getStart()<0 ? 0 : h.getFivePrime()-r.getStart(); if(offset>r.getWidth()) offset=r.getWidth(); counts[offset]++; if(!needleFiltering || (counts[offset] <= perBaseMax)){ score++; } } } peakScores.add(new Pair<Integer,Double>(count, score)); }count++; } //Sort Collections.sort(peakScores, new Comparator<Pair<Integer,Double>>(){ public int compare(Pair<Integer,Double> o1, Pair<Integer,Double> o2){return o2.cdr().compareTo(o1.cdr());} }); //Print for(int x=0; x<peakScores.size(); x++){ fw.write(posLines.get(peakScores.get(x).car())+"\n"); } fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Print the distribution of reads around the peaks //NO tower & needle filters -- built for speed public void quickcounts(String label, String outName){ int topX=-1; double ipWeightTotal=IP.getWeightTotal(); ArrayList<Pair<String, Double>> results = new ArrayList<Pair<String, Double>>(); try{ //Positive set int count =0; for(Region r : posSet){ double score=0; if(topX==-1 || count<topX){ Point p = posPeaks.get(count); score = IP.sumWeights(r); if(normCounts) results.add(new Pair<String,Double>(r.getLocationString(),score/ipWeightTotal)); else results.add(new Pair<String,Double>(r.getLocationString(),score)); }count++; } FileWriter fw = new FileWriter(outName); fw.write("Region\t"+label+"\n"); for(Pair<String,Double> res:results){ if(normCounts) fw.write(String.format("%s\t%e\n", res.car(), res.cdr())); else fw.write(String.format("%s\t%.2f\n", res.car(), res.cdr())); } fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Print the distribution of reads around the peaks //With tower & needle filters public void buildMetaPeak(String outName){ System.out.println("Building Meta-peak"); int topX=-1; boolean absoluteDist=true; boolean needleFiltering=true; int min=0, max=window/2; int numBins = ((max-min)/metaBinSize); int perBaseMax = getPoissonThreshold(Math.pow(10, -9), IP.getWeightTotal(), 1, gen.getGenomeLength(), 0.8, 1, 1); //Initialize: add pseudocount of 1 to everything double [] positive = new double [numBins+1]; double [] negative = new double [numBins+1]; for(int w=0; w<=numBins; w++){ positive[w]=1; negative[w]=1; }double posTotalHits=numBins+1, posTotalPeaks=0, negTotalHits=numBins+1, negTotalPeaks=0; //Positive set int count =0; for(Region r : posSet){ // System.out.println("POSITIVE: "+r); if(topX==-1 || count<topX){ Point p = posPeaks.get(count); List<ReadHit> hits = IP.loadHits(r); //Towers & Needles init ArrayList<Region> currTowers = new ArrayList<Region>(); for(Region t : towers) if(r.overlaps(t)) currTowers.add(t); int [] counts = new int[r.getWidth()+1]; for(int i=0; i<=r.getWidth(); i++){counts[i]=0;} for(ReadHit h : hits){ boolean inTower=false; for(Region t : currTowers) if(r.overlaps(t)) inTower=true; if(!inTower){ int offset=h.getFivePrime()-r.getStart()<0 ? 0 : h.getFivePrime()-r.getStart(); if(offset>r.getWidth()) offset=r.getWidth(); counts[offset]++; if(!needleFiltering || (counts[offset] <= perBaseMax)){ int dist = h.getStrand()=='+' ? p.getLocation()-h.getFivePrime() : h.getFivePrime()-p.getLocation(); if(absoluteDist){dist = Math.abs(dist);} if(dist>=min && dist<=max){ positive[(dist-min)/metaBinSize]++; posTotalHits++; } } } }posTotalPeaks++; }count++; } //Negative set count =0; for(Region r : negSet){ //System.out.println("NEGATIVE: "+r); if(topX==-1 || count<topX){ Point p = negPeaks.get(count); List<ReadHit> hits = IP.loadHits(r); //Towers & Needles init ArrayList<Region> currTowers = new ArrayList<Region>(); for(Region t : towers) if(r.overlaps(t)) currTowers.add(t); int [] counts = new int[r.getWidth()+1]; for(int i=0; i<=r.getWidth(); i++){counts[i]=0;} for(ReadHit h : hits){ boolean inTower=false; for(Region t : currTowers) if(r.overlaps(t)) inTower=true; if(!inTower){ int offset=h.getFivePrime()-r.getStart()<0 ? 0 : h.getFivePrime()-r.getStart(); if(offset>r.getWidth()) offset=r.getWidth(); counts[offset]++; if(!needleFiltering || (counts[offset] <= perBaseMax)){ int dist = h.getStrand()=='+' ? p.getLocation()-h.getFivePrime() : h.getFivePrime()-p.getLocation(); if(absoluteDist){dist = Math.abs(dist);} if(dist>=min && dist<=max){ negative[(dist-min)/metaBinSize]++; negTotalHits++; } } } }negTotalPeaks++; }count++; } //Normalize for(int w=0; w<=numBins; w++){ positive[w]=positive[w]/posTotalPeaks; negative[w]=negative[w]/negTotalPeaks; } try{ FileWriter fw = new FileWriter(outName); fw.write("Tag distributions around peaks\n"); fw.write("RelPos\tPositive\tNegative\tDifference\tOverRep\n"); for(int w=0; w<numBins; w++){ int rel = (w*metaBinSize)+min; fw.write(rel+"\t"+positive[w]+"\t"+negative[w]+"\t"+(positive[w]-negative[w])+"\t"+(positive[w]/negative[w])+"\n"); } fw.close(); System.out.println("Results written to "+outName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void loadExperiments(String [] args){ List<SeqLocator> dbexpts = Args.parseSeqExpt(args,"dbexpt"); List<SeqLocator> dbexpts2 = Args.parseSeqExpt(args,"dbexpt2"); List<SeqLocator> rdbexpts = Args.parseSeqExpt(args,"rdbexpt"); List<SeqLocator> rdbexpts2 = Args.parseSeqExpt(args,"rdbexpt2"); List<File> expts = Args.parseFileHandles(args, "expt"); List<File> expts2 = Args.parseFileHandles(args, "expt2"); String fileFormat = Args.parseString(args, "format", "ELAND"); if(expts.size()>0 && dbexpts.size() == 0 && rdbexpts.size()==0){ IP = new DeepSeqExpt(gen, expts, false, fileFormat, readLen); }else if(dbexpts.size()>0 && expts.size() == 0){ IP = new DeepSeqExpt(gen, dbexpts, "db", readLen); dbconnected=true; }else if(rdbexpts.size()>0 && expts.size() == 0){ IP = new DeepSeqExpt(gen, rdbexpts, "readdb", readLen); dbconnected=true; }else{} if(expts2.size()>0 && dbexpts2.size() == 0){ IP2 = new DeepSeqExpt(gen, expts2, false, fileFormat, readLen); twoExpts=true; }else if(dbexpts2.size()>0 && expts2.size() == 0){ IP2 = new DeepSeqExpt(gen, dbexpts2, "db", readLen); twoExpts=true; dbconnected=true; }else if(rdbexpts2.size()>0 && expts2.size() == 0){ IP2 = new DeepSeqExpt(gen, rdbexpts2, "readdb", readLen); twoExpts=true; dbconnected=true; }else{ if(dbexpts2.size()>0 && expts2.size()>0){ System.err.println("Cannot mix files and db loading yet...");System.exit(1); }else{ twoExpts=false; IP2=null; } } } //Poisson threshold for needle filter public int getPoissonThreshold(double threshold, double count, double hitLength, double seqLen, double mappable, double binWidth, double binOffset){ int countThres=0; DRand re = new DRand(); Poisson P = new Poisson(0, re); double pMean = (count*(hitLength/binOffset + binWidth/binOffset))/(seqLen*mappable/binOffset); P.setMean(pMean); double l=1; for(int b=1; l>threshold; b++){ l=1-P.cdf(b); countThres=b; } return(Math.max(1,countThres)); } //Clean up the loaders public void close(){ if(IP!=null) IP.closeLoaders(); if(IP2!=null) IP2.closeLoaders(); } }
package edu.ucsb.cs56.projects.games.poker; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.IOException; final class PokerSinglePlayer extends PokerGameGui { /** * Timer for calling turnDecider() */ Timer timer; /** * The milliseconds for timer */ int timer_value = 2000; // milliseconds /** * Whether or not it's your turn to bet */ boolean yourTurnToBet = true; /** * No arg constructor to create instance of PokerSinglePlayer to begin game */ public PokerSinglePlayer(){ for(Player player:players) player.setDelegate(this); /* players.get(0).setDelegate(this); players.get(1).setDelegate(this); */ } /** * Constructor to set the player and opponent's initial chips. * This is used when we continue playing the game * @param pChips the player's chips * @param oChips the opponent's chips */ public PokerSinglePlayer(int pChips, int oChips){ for(Player player:players) { player.setChips(pChips); player.setDelegate(this); } Player opponent = players.get(1); opponent.setChips(oChips); } public PokerSinglePlayer(int pChips, int o1Chips, int o2Chips, int o3Chips){ players.get(0).setChips(pChips); players.get(1).setChips(o1Chips); players.get(2).setChips(o2Chips); players.get(3).setChips(o3Chips); for(Player player:players) player.setDelegate(this); } /** * Starts game between you and AI */ public void go() { super.setUp(); layoutSubViews(); //sets up all of the buttons and panels and GUI controlButtons(); //this function is in PokerGameGui. if(!gameOver){ step = Step.BLIND; //This is the first step in the game. int currentPlayers = players.size(); int rng = (int) (Math.random()*currentPlayers); //generate random num 0-4 Player first = players.get(rng); first.turn = true; turn = rng; rng++; if (turn == 0) { //1 = player 1 goes first. message = "player 1 goes first!"; prompt = "what will you do?"; } else prompt = "player " + rng + " goes first!"; //Here, we are using a timer to control how the turns work //The timer comes from the swing class if you want to read up on it //Another thing to note is we used a lambda function deal with the thread in timer. timer = new Timer(timer_value, e -> turnDecider()); timer.setRepeats(false); //We want the timer to go off once. We will restart it as needed instead. updateFrame(); //function is inside of PokerGameGui timer.restart(); first.turn = false; } } /** * Method that directs the turn to who it needs to go to */ public void turnDecider () { Player currentTurn = players.get(turn); currentTurn.takeTurn(); /* if (turn == 0) { players.get(0).takeTurn(); } else { players.get(1).takeTurn(); } */ } /** * Method to activate the opponent AI on turn change. * Changes between you and the AI */ public void changeTurn() { if (turn < 3) turn++; else turn = 0; int number = turn++; Player current = players.get(turn); if (current.type == 0) { if (responding == true) { /* if (turn == 0) { if (responding == true) { turn = 1; */ controlButtons(); message = "computer " + number + " is thinking..."; updateFrame(); timer.restart(); } else { updateFrame(); nextStep(); if (step != Step.SHOWDOWN) { controlButtons(); prompt = "computer " + number + "'s Turn."; message = "computer " + number + " is thinking..."; updateFrame(); timer.restart(); } } } else { if (responding == true) { controlButtons(); responding = false; prompt = "Player " + number + "'s turn. What will you do?"; updateFrame(); } else { prompt = "Player " + number + "'s turn. What will you do?"; controlButtons(); updateFrame(); } } } /** * Updates GUI based on the player's decision */ public void userTurn() { controlButtons(); updateFrame(); } /** * Method that moves the game to the next phase */ public void nextStep() { if (step == Step.BLIND) { // Most like able to skip/remove this step step = Step.FLOP; } else if (step == Step.FLOP) { step = Step.TURN; } else if (step == Step.TURN) { step = Step.RIVER; } else { step = Step.SHOWDOWN; message = "All bets are in."; prompt = "Determine Winner: "; controlButtons(); } } /** * Method overridden to allow for a new single player game to start. */ // BUG: must refactor accordingly to fit GUI public void showWinnerAlert() { if(!gameOver){ String message = ""; oSubPane1.remove(backCardLabel1); oSubPane1.remove(backCardLabel2); oSubPane2.remove(backCardLabel3); oSubPane2.remove(backCardLabel4); oSubPane3.remove(backCardLabel5); oSubPane3.remove(backCardLabel6); // BUG: chips not added or decreased properly oSubPane2.remove(opponent2ChipsLabel); // change opponent.getHand for(int i=0;i<2;i++){ oSubPane1.add(new JLabel(getCardImage((players.get(1).getHand()).get(i)))); oSubPane2.add(new JLabel(getCardImage((players.get(2).getHand()).get(i)))); oSubPane3.add(new JLabel(getCardImage((players.get(3).getHand()).get(i)))); } oSubPane2.add(opponent2ChipsLabel); updateFrame(); message = winningHandMessage(); int winner = 0; for (Player player:players) { if (player.winStatus == true) { int index = players.indexOf(player); index++; if (player.type == 1) { System.out.println("player"); message = message + ("\n\nPlayer " + index + " wins!\n\nNext round?"); } else { index++; System.out.println("computer"); message = message + ("\n\nComputer " + index + " wins.\n\nNext round?"); } winner++; } } if (winner == 0){ /* if (!Fold) { message = winningHandMessage(); } else { message = ("Folded!"); } if (winnerIdx == 0) { System.out.println("player"); message = message + ("\n\nYou win!\n\nNext round?"); } else if (winnerIdx != 0) { System.out.println("opponent"); message = message + ("\n\nOpponent wins.\n\nNext round?"); } else if (winnerIdx < 0){ */ System.out.println("tie"); message = message + ("\n\nTie \n\nNext round?"); } int option = JOptionPane.showConfirmDialog(null, message, "Winner", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { // Restart mainFrame.dispose(); PokerSinglePlayer singlePlayerReplay; int Continue = 0; // Check if players have enough chips. // Create new game. for (Player player:players) { if (player.getChips() < 5){ JOptionPane.showMessageDialog(null, "Resetting chips..."); singlePlayerReplay = new PokerSinglePlayer(); singlePlayerReplay.go(); Continue++; } } if (Continue == 0) { singlePlayerReplay = new PokerSinglePlayer(players.get(0).getChips(),players.get(1).getChips(),players.get(2).getChips(),players.get(3).getChips()); singlePlayerReplay.go(); } } else if (option == JOptionPane.NO_OPTION) { for (Player player:players) { if(player.getChips() < 5) { gameOver("GAME OVER! No chips left!"); } /* if(players.get(0).getChips() < 5 || players.get(1).getChips() < 5){ JOptionPane.showMessageDialog(null, "Resetting chips..."); singlePlayerReplay = new PokerSinglePlayer(); singlePlayerReplay.go(); } else { singlePlayerReplay = new PokerSinglePlayer(players.get(0).getChips(),players.get(1).getChips()); singlePlayerReplay.go(); } } else if (option == JOptionPane.NO_OPTION) { if(players.get(0).getChips() < 5 || players.get(0).getChips() < 5) { gameOver("GAME OVER! No chips left!"); */ } gameOver("GAME OVER! Thanks for playing.\n\n"); } else { // Quit System.exit(1); } } } /** * Restarts the timer controlling turnDecider() */ public void restartTimer() { timer.restart(); } }
package edu.umn.cs.spatial.mapReduce; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.LineRecordReader; import org.apache.hadoop.mapred.RecordReader; import edu.umn.edu.spatial.Rectangle; /** * Parses a spatial file and returns a list of <id, rectangle> tuples. * Used with range query (spatial selection) * @author aseldawy * */ public class RQRectangleRecordReader implements RecordReader<IntWritable, Rectangle> { private RecordReader<LongWritable, Text> lineRecordReader; private LongWritable subKey; private Text subValue; public RQRectangleRecordReader(Configuration job, FileSplit split) throws IOException { lineRecordReader = new LineRecordReader(job, split); } /** * Reads a rectangle and emits it. * It skips bytes until end of line is found. * After this, it starts reading rectangles with a line in each rectangle. * It consumes the end of line also when reading the rectangle. * It stops after reading the first end of line (after) end. */ public boolean next(IntWritable key, Rectangle value) throws IOException { if (!lineRecordReader.next(subKey, subValue) || subValue.getLength() < 4) { // Stop on wrapped reader EOF or a very short line which indicates EOF too return false; } // Convert to a regular string to be able to use split String line = new String(subValue.getBytes(), 0, subValue.getLength()); String[] parts = line.split(","); key.set(Integer.parseInt(parts[0])); value.id = key.get(); value.x1 = Float.parseFloat(parts[1]); value.y1 = Float.parseFloat(parts[2]); value.x2 = Float.parseFloat(parts[3]); value.y2 = Float.parseFloat(parts[4]); return true; } public long getPos() throws IOException { return lineRecordReader.getPos(); } public void close() throws IOException { lineRecordReader.close(); } public float getProgress() throws IOException { return lineRecordReader.getProgress(); } @Override public IntWritable createKey() { subKey = lineRecordReader.createKey(); return new IntWritable(); } @Override public Rectangle createValue() { subValue = lineRecordReader.createValue(); return new Rectangle(); } }
package org.muml.uppaal; import org.eclipse.emf.common.util.EList; import org.muml.uppaal.core.CommentableElement; import org.muml.uppaal.core.NamedElement; import org.muml.uppaal.declarations.GlobalDeclarations; import org.muml.uppaal.declarations.SystemDeclarations; import org.muml.uppaal.templates.Template; import org.muml.uppaal.types.PredefinedType; public interface NTA extends NamedElement, CommentableElement { /** * Returns the value of the '<em><b>Global Declarations</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The global declarations for the NTA. * <!-- end-model-doc --> * @return the value of the '<em>Global Declarations</em>' containment reference. * @see #setGlobalDeclarations(GlobalDeclarations) * @see org.muml.uppaal.UppaalPackage#getNTA_GlobalDeclarations() * @model containment="true" * extendedMetaData="kind='element' name='globalDeclarations'" * @generated */ GlobalDeclarations getGlobalDeclarations(); /** * Sets the value of the '{@link org.muml.uppaal.NTA#getGlobalDeclarations <em>Global Declarations</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Global Declarations</em>' containment reference. * @see #getGlobalDeclarations() * @generated */ void setGlobalDeclarations(GlobalDeclarations value); /** * Returns the value of the '<em><b>Template</b></em>' containment reference list. * The list contents are of type {@link org.muml.uppaal.templates.Template}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The Timed Automata templates of the NTA. * <!-- end-model-doc --> * @return the value of the '<em>Template</em>' containment reference list. * @see org.muml.uppaal.UppaalPackage#getNTA_Template() * @model containment="true" required="true" * extendedMetaData="kind='element' name='template'" * @generated */ EList<Template> getTemplate(); /** * Returns the value of the '<em><b>System Declarations</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The declarations of process instantiations. * <!-- end-model-doc --> * @return the value of the '<em>System Declarations</em>' containment reference. * @see #setSystemDeclarations(SystemDeclarations) * @see org.muml.uppaal.UppaalPackage#getNTA_SystemDeclarations() * @model containment="true" required="true" * extendedMetaData="kind='element' name='systemDeclarations'" * @generated */ SystemDeclarations getSystemDeclarations(); /** * Sets the value of the '{@link org.muml.uppaal.NTA#getSystemDeclarations <em>System Declarations</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>System Declarations</em>' containment reference. * @see #getSystemDeclarations() * @generated */ void setSystemDeclarations(SystemDeclarations value); /** * Returns the value of the '<em><b>Int</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The predefined type 'int'. * <!-- end-model-doc --> * @return the value of the '<em>Int</em>' containment reference. * @see #setInt(PredefinedType) * @see org.muml.uppaal.UppaalPackage#getNTA_Int() * @model containment="true" required="true" * @generated */ PredefinedType getInt(); /** * Sets the value of the '{@link org.muml.uppaal.NTA#getInt <em>Int</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Int</em>' containment reference. * @see #getInt() * @generated */ void setInt(PredefinedType value); /** * Returns the value of the '<em><b>Bool</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The predefined type 'bool'. * <!-- end-model-doc --> * @return the value of the '<em>Bool</em>' containment reference. * @see #setBool(PredefinedType) * @see org.muml.uppaal.UppaalPackage#getNTA_Bool() * @model containment="true" required="true" * @generated */ PredefinedType getBool(); /** * Sets the value of the '{@link org.muml.uppaal.NTA#getBool <em>Bool</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Bool</em>' containment reference. * @see #getBool() * @generated */ void setBool(PredefinedType value); /** * Returns the value of the '<em><b>Clock</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The predefined type 'clock'. * <!-- end-model-doc --> * @return the value of the '<em>Clock</em>' containment reference. * @see #setClock(PredefinedType) * @see org.muml.uppaal.UppaalPackage#getNTA_Clock() * @model containment="true" required="true" * @generated */ PredefinedType getClock(); /** * Sets the value of the '{@link org.muml.uppaal.NTA#getClock <em>Clock</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Clock</em>' containment reference. * @see #getClock() * @generated */ void setClock(PredefinedType value); /** * Returns the value of the '<em><b>Chan</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The predefined type 'chan'. * <!-- end-model-doc --> * @return the value of the '<em>Chan</em>' containment reference. * @see #setChan(PredefinedType) * @see org.muml.uppaal.UppaalPackage#getNTA_Chan() * @model containment="true" required="true" * @generated */ PredefinedType getChan(); /** * Sets the value of the '{@link org.muml.uppaal.NTA#getChan <em>Chan</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Chan</em>' containment reference. * @see #getChan() * @generated */ void setChan(PredefinedType value); /** * Returns the value of the '<em><b>Void</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The predefined dummy type 'void'. * <!-- end-model-doc --> * @return the value of the '<em>Void</em>' containment reference. * @see #setVoid(PredefinedType) * @see org.muml.uppaal.UppaalPackage#getNTA_Void() * @model containment="true" required="true" * @generated */ PredefinedType getVoid(); /** * Sets the value of the '{@link org.muml.uppaal.NTA#getVoid <em>Void</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Void</em>' containment reference. * @see #getVoid() * @generated */ void setVoid(PredefinedType value); } // NTA
// Modified or written by Object Mentor, Inc. for inclusion with FitNesse. package fit; import java.lang.reflect.Method; import fit.exception.CouldNotParseFitFailureException; import fit.exception.FitFailureException; import fit.exception.NoSuchMethodFitFailureException; public class ActionFixture extends Fixture { protected Parse cells; private Fixture actor; public void doCells(Parse cells) { this.cells = cells; String methodName = cells.text(); try { getClass().getMethod(methodName).invoke(this); } catch (Exception e) { exception(cells, e); } } public void start() throws Throwable { Parse fixture = cells.more; if (isNullOrBlank(fixture)) throw new FitFailureException("You must specify a fixture to start."); actor = loadFixture(fixture.text()); } private boolean isNullOrBlank(Parse fixture) { return fixture == null || fixture.text().equals(""); } public Fixture getActor() { return this.actor; } public void enter() throws Exception { Parse argumentCell = cells.more.more; if (argumentCell == null) throw new FitFailureException("You must specify an argument."); Method enterMethod = tryFindMethodWithArgs(1); Class<?> parameterType = enterMethod.getParameterTypes()[0]; String argument = argumentCell.text(); enterMethod.invoke(actor, adaptArgumentToType(parameterType, argument)); } private Object adaptArgumentToType(Class<?> parameterType, String argument) throws Exception { Object arg; try { arg = TypeAdapter.on(actor, parameterType).parse(argument); } catch (NumberFormatException e) { throw new CouldNotParseFitFailureException(argument, parameterType.getName()); } return arg; } public void press() throws Exception { tryFindMethodWithArgs(0).invoke(actor); } public void check() throws Throwable { Method checkMethod = tryFindMethodWithArgs(0); Class<?> returnType = checkMethod.getReturnType(); Parse checkValueCell = cells.more.more; if (checkValueCell == null) throw new FitFailureException("You must specify a value to check."); check(checkValueCell, getTypeAdapter(checkMethod, returnType)); } private TypeAdapter getTypeAdapter(Method checkMethod, Class<?> returnType) { try { return(TypeAdapter.on(actor, checkMethod)); } catch (Throwable e) { // NOSONAR throw new FitFailureException("Can not parse return type: " + returnType.getName()); } } protected Method tryFindMethodWithArgs(int args) throws NoSuchMethodException { Parse methodCell = cells.more; if (isNullOrBlank(methodCell)) throw new FitFailureException("You must specify a method."); String methodName = camel(methodCell.text()); if (actor == null) throw new FitFailureException("You must start a fixture using the 'start' keyword."); Method theMethod = findMethodWithArgs(methodName, args); if (theMethod == null) { throw new NoSuchMethodFitFailureException(methodName); } return theMethod; } private Method findMethodWithArgs(String methodName, int args) { Method[] methods = actor.getClass().getMethods(); Method theMethod = null; for (Method m : methods) { if (m.getName().equals(methodName) && m.getParameterTypes().length == args) { if (theMethod == null) { theMethod = m; } else { throw new FitFailureException("You can only have one " + methodName + "(arg) method in your fixture."); } } } return theMethod; } }
package com.microsoft.azure; import java.util.ArrayDeque; import java.util.Map; import java.util.Queue; /** * Type representing a DAG (directed acyclic graph). * <p> * each node in a DAG is represented by {@link DAGNode} * * @param <T> the type of the data stored in the graph nodes * @param <U> the type of the nodes in the graph */ public class DAGraph<T, U extends DAGNode<T>> extends Graph<T, U> { private Queue<String> queue; private boolean hasParent; private U rootNode; /** * Creates a new DAG. * * @param rootNode the root node of this DAG */ public DAGraph(U rootNode) { this.rootNode = rootNode; this.queue = new ArrayDeque<>(); this.rootNode.setPreparer(true); this.addNode(rootNode); } /** * @return <tt>true</tt> if this DAG is merged with another DAG and hence has a parent */ public boolean hasParent() { return hasParent; } /** * Checks whether the given node is root node of this DAG. * * @param node the node {@link DAGNode} to be checked * @return <tt>true</tt> if the given node is root node */ public boolean isRootNode(U node) { return this.rootNode == node; } /** * @return <tt>true</tt> if this dag is the preparer responsible for * preparing the DAG for traversal. */ public boolean isPreparer() { return this.rootNode.isPreparer(); } /** * Merge this DAG with another DAG. * <p> * This will mark this DAG as a child DAG, the dependencies of nodes in this DAG will be merged * with (copied to) the parent DAG * * @param parent the parent DAG */ public void merge(DAGraph<T, U> parent) { this.hasParent = true; parent.rootNode.addDependency(this.rootNode.key()); for (Map.Entry<String, U> entry: graph.entrySet()) { String key = entry.getKey(); if (!parent.graph.containsKey(key)) { parent.graph.put(key, entry.getValue()); } } } /** * Prepares this DAG for traversal using getNext method, each call to getNext returns next node * in the DAG with no dependencies. */ public void prepare() { if (isPreparer()) { for (U node : graph.values()) { // Prepare each node for traversal node.initialize(); if (!this.isRootNode(node)) { // Mark other sub-DAGs as non-preparer node.setPreparer(false); } } initializeDependentKeys(); initializeQueue(); } } /** * Gets next node in the DAG which has no dependency or all of it's dependencies are resolved and * ready to be consumed. * * @return next node or null if all the nodes have been explored */ public U getNext() { return graph.get(queue.poll()); } /** * Gets the data stored in a graph node with a given key. * * @param key the key of the node * @return the value stored in the node */ public T getNodeData(String key) { return graph.get(key).data(); } /** * Reports that a node is resolved hence other nodes depends on it can consume it. * * @param completed the node ready to be consumed */ public void reportedCompleted(U completed) { completed.setPreparer(true); String dependency = completed.key(); for (String dependentKey : graph.get(dependency).dependentKeys()) { DAGNode<T> dependent = graph.get(dependentKey); dependent.reportResolved(dependency); if (dependent.hasAllResolved()) { queue.add(dependent.key()); } } } /** * Initializes dependents of all nodes. * <p> * The DAG will be explored in DFS order and all node's dependents will be identified, * this prepares the DAG for traversal using getNext method, each call to getNext returns next node * in the DAG with no dependencies. */ private void initializeDependentKeys() { visit(new Visitor<U>() { // This 'visit' will be called only once per each node. @Override public void visit(U node) { if (node.dependencyKeys().isEmpty()) { return; } String dependentKey = node.key(); for (String dependencyKey : node.dependencyKeys()) { graph.get(dependencyKey) .addDependent(dependentKey); } } }); } /** * Initializes the queue that tracks the next set of nodes with no dependencies or * whose dependencies are resolved. */ private void initializeQueue() { this.queue.clear(); for (Map.Entry<String, U> entry: graph.entrySet()) { if (!entry.getValue().hasDependencies()) { this.queue.add(entry.getKey()); } } if (queue.isEmpty()) { throw new RuntimeException("Found circular dependency"); } } }
package com.gooddata.connector; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.gooddata.integration.model.Column; import com.gooddata.integration.model.SLI; import com.gooddata.integration.rest.GdcRESTApiWrapper; import org.apache.log4j.Logger; import org.apache.log4j.MDC; import com.gooddata.exception.InvalidParameterException; import com.gooddata.exception.ProcessingException; import com.gooddata.modeling.generator.MaqlGenerator; import com.gooddata.modeling.model.SourceColumn; import com.gooddata.modeling.model.SourceSchema; import com.gooddata.naming.N; import com.gooddata.processor.CliParams; import com.gooddata.processor.Command; import com.gooddata.processor.ProcessingContext; import com.gooddata.util.FileUtil; import com.gooddata.util.StringUtil; /** * GoodData abstract connector implements functionality that can be reused in several connectors. * * @author zd <zd@gooddata.com> * @version 1.0 */ public abstract class AbstractConnector implements Connector { private static Logger l = Logger.getLogger(AbstractConnector.class); /** * The LDM schema of the data source */ protected SourceSchema schema; /** * Project id */ protected String projectId; /** * Default constructor */ protected AbstractConnector() { } /** * {@inheritDoc} */ public SourceSchema getSchema() { return schema; } /** * {@inheritDoc} */ public void setSchema(SourceSchema schema) { this.schema = schema; } /** * {@inheritDoc} */ public abstract void extract(String dir) throws IOException; /** * {@inheritDoc} */ public void deploy(SLI sli, List<Column> columns, String dir, String archiveName) throws IOException { String fn = dir + System.getProperty("file.separator") + GdcRESTApiWrapper.DLI_MANIFEST_FILENAME; String cn = sli.getSLIManifest(columns); FileUtil.writeStringToFile(cn, fn); l.debug("Manifest file written to file '"+fn+"'. Content: "+cn); FileUtil.compressDir(dir, archiveName); } /** * Initializes the source and PDM schemas from the config file * @param configFileName the config file * @throws IOException in cas the config file doesn't exists */ protected void initSchema(String configFileName) throws IOException { schema = SourceSchema.createSchema(new File(configFileName)); } public String generateMaqlCreate() { MaqlGenerator mg = new MaqlGenerator(schema); return mg.generateMaqlCreate(); } /** * {@inheritDoc} */ public boolean processCommand(Command c, CliParams cli, ProcessingContext ctx) throws ProcessingException { l.debug("Processing command "+c.getCommand()); try { if(c.match("GenerateMaql")) { generateMAQL(c, cli, ctx); } else if(c.match("ExecuteMaql")) { executeMAQL(c, cli, ctx); } else if(c.match("TransferData") || c.match("TransferAllSnapshots") || c.match("TransferLastSnapshot") || c.match("TransferSnapshots")) { transferData(c, cli, ctx); } else if (c.match( "GenerateUpdateMaql")) { generateUpdateMaql(c, cli, ctx); } else { l.debug("No match for command "+c.getCommand()); return false; } l.debug("Command "+c.getCommand()+" processed."); return true; } catch (IOException e) { throw new ProcessingException(e); } catch (InterruptedException e) { throw new ProcessingException(e); } } /** * Generates the MAQL * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void generateMAQL(Command c, CliParams p, ProcessingContext ctx) throws IOException { Connector cc = ctx.getConnectorMandatory(); String maqlFile = c.getParamMandatory("maqlFile"); l.debug("Executing maql generation."); String maql = cc.generateMaqlCreate(); l.debug("Finished maql generation maql:\n"+maql); FileUtil.writeStringToFile(maql, maqlFile); l.info("MAQL script successfully generated into "+maqlFile); } /** * Executes MAQL * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void executeMAQL(Command c, CliParams p, ProcessingContext ctx) throws IOException { l.debug("Executing MAQL."); String pid = ctx.getProjectIdMandatory(); final String maqlFile = c.getParamMandatory("maqlFile"); final String ifExistsStr = c.getParam("ifExists"); final boolean ifExists = (ifExistsStr != null && "true".equalsIgnoreCase(ifExistsStr)); final File mf = FileUtil.getFile(maqlFile, ifExists); if (mf != null) { final String maql = FileUtil.readStringFromFile(maqlFile); ctx.getRestApi(p).executeMAQL(pid, maql); } l.debug("Finished MAQL execution."); l.info("MAQL script "+maqlFile+" successfully executed."); } /** * Transfers the data to GoodData project * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues * @throws InterruptedException internal problem with making file writable */ private void transferData(Command c, CliParams p, ProcessingContext ctx) throws IOException, InterruptedException { l.debug("Transferring data."); Connector cc = ctx.getConnectorMandatory(); String pid = ctx.getProjectIdMandatory(); // connector's schema name String ssn = StringUtil.toIdentifier(cc.getSchema().getName()); boolean waitForFinish = true; if(c.checkParam("waitForFinish")) { String w = c.getParam( "waitForFinish"); if(w != null && w.equalsIgnoreCase("false")) waitForFinish = false; } extractAndTransfer(c, pid, cc, null, waitForFinish, p, ctx); l.debug("Data transfer finished."); l.info("Data transfer finished."); } protected String[] populateCsvHeaderFromSchema() { SourceSchema schema = getSchema(); List<SourceColumn> columns = schema.getColumns(); String[] header = new String[columns.size()]; for(int i = 0; i < header.length; i++) { header[i] = StringUtil.toIdentifier(columns.get(i).getName()); } return header; } protected List<Column> populateColumnsFromSchema(SourceSchema schema) { List<Column> columns = new ArrayList<Column>(); String ssn = StringUtil.toIdentifier(schema.getName()); for(SourceColumn sc : schema.getColumns()) { String scn = StringUtil.toIdentifier(sc.getName()); if(!sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_IGNORE)) { Column c = new Column(sc.getName()); c.setMode(Column.LM_FULL); if(sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_ATTRIBUTE) || sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_CONNECTION_POINT) || sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_REFERENCE) || sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_DATE)) c.setReferenceKey(1); if(sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_ATTRIBUTE) || sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_CONNECTION_POINT)) c.setPopulates(new String[] {"label." + ssn + "." + scn}); if(sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_REFERENCE)) c.setPopulates(new String[] {"label." + StringUtil.toIdentifier(sc.getSchemaReference()) + "." + StringUtil.toIdentifier(sc.getReference())}); if(sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_LABEL)) c.setPopulates(new String[] {"label." + ssn + "." + StringUtil.toIdentifier(sc.getReference()) + "." + scn}); if(sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_DATE)) { String fmt = sc.getFormat(); if(fmt != null && fmt.length() > 0) { c.setFormat(fmt); } else { c.setFormat(Constants.DEFAULT_DATE_FMT_STRING); } String sr = sc.getSchemaReference(); if(sr != null && sr.length() > 0) { sr = StringUtil.toIdentifier(sr); c.setPopulates(new String[] {sr + "." + Constants.DEFAULT_DATE_LABEL}); } //TODO - HANDLE DATES WITHOUT schemaReference } if(sc.getLdmType().equalsIgnoreCase(SourceColumn.LDM_TYPE_FACT)) c.setPopulates(new String[] {"fact." + ssn + "." + scn}); columns.add(c); } } return columns; } /** * Extract data from the internal database and transfer them to a GoodData project * @param c command * @param pid project id * @param cc connector * @param p cli parameters * @param ctx current context * @param snapshots transferred snapshots * @param waitForFinish synchronous execution flag * @throws IOException IO issues * @throws InterruptedException internal problem with making file writable */ private void extractAndTransfer(Command c, String pid, Connector cc, int[] snapshots, boolean waitForFinish, CliParams p, ProcessingContext ctx) throws IOException, InterruptedException { // connector's schema name String ssn = StringUtil.toIdentifier(cc.getSchema().getName()); l.debug("Extracting data."); File tmpDir = FileUtil.createTempDir(); File tmpZipDir = FileUtil.createTempDir(); String archiveName = tmpDir.getName(); MDC.put("GdcDataPackageDir",archiveName); String archivePath = tmpZipDir.getAbsolutePath() + System.getProperty("file.separator") + archiveName + ".zip"; // get information about the data loading package SLI sli = ctx.getRestApi(p).getSLIById("dataset." + ssn, pid); List<Column> sliColumns = ctx.getRestApi(p).getSLIColumns(sli.getUri()); List<Column> columns = populateColumnsFromSchema(cc.getSchema()); /* l.info("SLI COLUMNS"); for(Column co : sliColumns) { l.info("name = "+co.getName()+" populates = "+co.getPopulates()); } l.info("XML COLUMNS"); for(Column co : columns) { l.info("name = "+co.getName()+" populates = "+co.getPopulates()); } */ if(sliColumns.size() > columns.size()) throw new InvalidParameterException("The GoodData data loading interface (SLI) expects more columns."); String incremental = c.getParam("incremental"); if(incremental != null && incremental.length() > 0 && incremental.equalsIgnoreCase("true")) { l.debug("Using incremental mode."); setIncremental(columns); } // extract the data to the CSV that is going to be transferred to the server cc.extract(tmpDir.getAbsolutePath()); cc.deploy(sli, columns, tmpDir.getAbsolutePath(), archivePath); // transfer the data package to the GoodData server ctx.getFtpApi(p).transferDir(archivePath); // kick the GooDData server to load the data package to the project String taskUri = ctx.getRestApi(p).startLoading(pid, archiveName); if(waitForFinish) { checkLoadingStatus(taskUri, tmpDir.getName(), p, ctx); } //cleanup l.debug("Cleaning the temporary files."); FileUtil.recursiveDelete(tmpDir); FileUtil.recursiveDelete(tmpZipDir); MDC.remove("GdcDataPackageDir"); l.debug("Data extract finished."); } /** * Sets the incremental loading status for a part * @param cols SLI columns */ private void setIncremental(List<Column> cols) { for(Column col : cols) { col.setMode(Column.LM_INCREMENTAL); } } /** * Checks the status of data integration process in the GoodData platform * @param taskUri the uri where the task status is determined * @param tmpDir temporary dir where the temporary data reside. This directory will be deleted. * @param p cli parameters * @param ctx current context * @throws IOException IO issues * @throws InterruptedException internal problem with making file writable */ private void checkLoadingStatus(String taskUri, String tmpDir, CliParams p, ProcessingContext ctx) throws InterruptedException,IOException { l.debug("Checking data transfer status."); String status = ""; while(!status.equalsIgnoreCase("OK") && !status.equalsIgnoreCase("ERROR") && !status.equalsIgnoreCase("WARNING")) { status = ctx.getRestApi(p).getLoadingStatus(taskUri); l.debug("Loading status = "+status); Thread.sleep(500); } l.debug("Data transfer finished with status "+status); if(status.equalsIgnoreCase("OK")) { l.info("Data successfully loaded."); } else if(status.equalsIgnoreCase("WARNING")) { l.info("Data loading succeeded with warnings. Status: "+status); Map<String,String> result = ctx.getFtpApi(p).getTransferLogs(tmpDir); for(String file : result.keySet()) { l.info(file+":\n"+result.get(file)); } } else { l.info("Data loading failed. Status: "+status); Map<String,String> result = ctx.getFtpApi(p).getTransferLogs(tmpDir); for(String file : result.keySet()) { l.info(file+":\n"+result.get(file)); } } } /** * Generate the MAQL for new columns * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issue */ private void generateUpdateMaql(Command c, CliParams p, ProcessingContext ctx) throws IOException { l.debug("Updating MAQL."); //final String configFile = c.getParamMandatory( "configFile"); //final SourceSchema schema = SourceSchema.createSchema(new File(configFile)); final Connector cc = ctx.getConnectorMandatory(); final SourceSchema schema = cc.getSchema(); final String pid = ctx.getProjectIdMandatory(); final String maqlFile = c.getParamMandatory( "maqlFile"); final String dataset = schema.getDatasetName(); final GdcRESTApiWrapper gd = ctx.getRestApi(p); final SLI sli = gd.getSLIById(dataset, pid); final DataSetDiffMaker diffMaker = new DataSetDiffMaker(gd, sli, schema); final List<SourceColumn> newColumns = diffMaker.findNewColumns(); final List<SourceColumn> deletedColumns = diffMaker.findDeletedColumns(); final MaqlGenerator mg = new MaqlGenerator(schema); final StringBuilder maql = new StringBuilder(); if (!newColumns.isEmpty()) { mg.setSynchronize(false); maql.append(mg.generateMaqlAdd(newColumns, diffMaker.sourceColumns)); } if (!deletedColumns.isEmpty()) { mg.setSynchronize(false); maql.append(mg.generateMaqlDrop(deletedColumns)); } if (maql.length() > 0) { maql.append(mg.generateMaqlSynchronize()); l.debug("Finished maql generation maql:\n"+maql.toString()); FileUtil.writeStringToFile(maql.toString(), maqlFile); l.debug("MAQL update finished."); l.info("MAQL update successfully finished."); } else { l.info("MAQL update successfully finished - no changes detected."); } } /** * Finds the attributes and facts with no appropriate part or part column * TODO: a generic detector of new labels etc could be added too * @param parts SLI parts * @param schema former source schema * @return list of new columns */ private Changes findColumnChanges(List<Column> columns, SourceSchema schema) { Set<String> fileNames = new HashSet<String>(); Set<String> factColumns = new HashSet<String>(); // TODO look at TestFindColumnChange and move the logic here throw new UnsupportedOperationException("Not implemented yet"); } private List<SourceColumn> lookups2columns(SourceSchema schema, List<String> lookups) { List<SourceColumn> result = new ArrayList<SourceColumn>(); for (String l : lookups) { String prefix = N.LKP_PFX + StringUtil.toIdentifier(schema.getName()) + "_"; if (!l.startsWith(prefix)) { throw new IllegalStateException("Lookup table " + l + " does not start with expected prefix " + prefix); } String name = l.replaceAll("^" + prefix, ""); result.add(new SourceColumn(name, SourceColumn.LDM_TYPE_ATTRIBUTE, name)); } return result; } private List<SourceColumn> facts2columns(List<String> facts) { List<SourceColumn> result = new ArrayList<SourceColumn>(); for (String factColumn : facts) { String factName = factColumn.replaceAll("^" + N.FCT_PFX, ""); result.add(new SourceColumn(factName, SourceColumn.LDM_TYPE_FACT, factName)); } return result; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } /** * Sets the project id from context * @param ctx process context * @throws InvalidParameterException if the project id isn't initialized */ protected void setProjectId(ProcessingContext ctx) throws InvalidParameterException { String pid = ctx.getProjectIdMandatory(); if(pid != null && pid.length() > 0) setProjectId(pid); } /** * Class wrapping local changes to a server-side model */ private static class Changes { private List<SourceColumn> newColumns = new ArrayList<SourceColumn>(); private List<SourceColumn> deletedColumns = new ArrayList<SourceColumn>(); } }
package io.github.dead_i.bungeerelay.commands; import io.github.dead_i.bungeerelay.IRC; import io.github.dead_i.bungeerelay.Util; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.plugin.Command; import net.md_5.bungee.api.plugin.Plugin; public class IRCNickCommand extends Command { Plugin plugin; public IRCNickCommand(Plugin plugin) { super("ircnick", "irc.nick"); this.plugin = plugin; } @Override public void execute(CommandSender sender, String[] args) { if (args.length == 0) { sender.sendMessage(new TextComponent(ChatColor.RED + "Usage: /ircnick <nick>")); return; } if (!IRC.sock.isConnected()) { sender.sendMessage(new TextComponent(ChatColor.RED + "The proxy is not connected to IRC.")); return; } String uid = Util.getUidByNick(args[0]); if (uid != null) { sender.sendMessage(new TextComponent(ChatColor.RED + "The nick " + args[0] + " is already in use.")); return; } IRC.out.println(":" + IRC.uids.get(sender) + " NICK " + msg); } }
package org.jfree.data.xy; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.fail ; import org.jfree.chart.TestUtilities; import org.jfree.data.Range; import org.jfree.data.UnknownKeyException; import org.jfree.util.PublicCloneable; import org.junit.Test; /** * Tests for the {@link XYSeriesCollection} class. */ public class XYSeriesCollectionTest { private static final double EPSILON = 0.0000000001; /** * Some checks for the constructor. */ @Test public void testConstructor() { XYSeriesCollection xysc = new XYSeriesCollection(); assertEquals(0, xysc.getSeriesCount()); assertEquals(1.0, xysc.getIntervalWidth(), EPSILON); assertEquals(0.5, xysc.getIntervalPositionFactor(), EPSILON); } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { XYSeries s1 = new XYSeries("Series"); s1.add(1.0, 1.1); XYSeriesCollection c1 = new XYSeriesCollection(); c1.addSeries(s1); XYSeries s2 = new XYSeries("Series"); s2.add(1.0, 1.1); XYSeriesCollection c2 = new XYSeriesCollection(); c2.addSeries(s2); assertEquals(c1, c2); assertEquals(c2, c1); c1.addSeries(new XYSeries("Empty Series")); assertFalse(c1.equals(c2)); c2.addSeries(new XYSeries("Empty Series")); assertEquals(c1, c2); c1.setIntervalWidth(5.0); assertFalse(c1.equals(c2)); c2.setIntervalWidth(5.0); assertEquals(c1, c2); c1.setIntervalPositionFactor(0.75); assertFalse(c1.equals(c2)); c2.setIntervalPositionFactor(0.75); assertEquals(c1, c2); c1.setAutoWidth(true); assertFalse(c1.equals(c2)); c2.setAutoWidth(true); assertEquals(c1, c2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XYSeries s1 = new XYSeries("Series"); s1.add(1.0, 1.1); XYSeriesCollection c1 = new XYSeriesCollection(); c1.addSeries(s1); XYSeriesCollection c2 = (XYSeriesCollection) c1.clone(); assertNotSame(c1, c2); assertSame(c1.getClass(), c2.getClass()); assertEquals(c1, c2); // check independence s1.setDescription("XYZ"); assertFalse(c1.equals(c2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { Object c1 = new XYSeriesCollection(); assertTrue(c1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { XYSeries s1 = new XYSeries("Series"); s1.add(1.0, 1.1); XYSeriesCollection c1 = new XYSeriesCollection(); c1.addSeries(s1); XYSeriesCollection c2 = (XYSeriesCollection) TestUtilities.serialised(c1); assertEquals(c1, c2); } /** * A test for bug report 1170825. */ @Test public void test1170825() { XYSeries s1 = new XYSeries("Series1"); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(s1); try { /* XYSeries s = */ dataset.getSeries(1); } catch (IllegalArgumentException e) { // correct outcome } catch (IndexOutOfBoundsException e) { assertTrue(false); // wrong outcome } } /** * Some basic checks for the getSeries() method. */ @Test public void testGetSeries() { XYSeriesCollection c = new XYSeriesCollection(); XYSeries s1 = new XYSeries("s1"); c.addSeries(s1); assertEquals("s1", c.getSeries(0).getKey()); try { c.getSeries(-1); fail("Should have thrown IndexOutOfBoundsException on negative key"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } try { c.getSeries(1); fail("Should have thrown IndexOutOfBoundsException on key out of range"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } } /** * Some checks for the getSeries(Comparable) method. */ @Test public void testGetSeriesByKey() { XYSeriesCollection c = new XYSeriesCollection(); XYSeries s1 = new XYSeries("s1"); c.addSeries(s1); assertEquals("s1", c.getSeries("s1").getKey()); try { c.getSeries("s2"); fail("Should have thrown UnknownKeyException on unknown key"); } catch (UnknownKeyException e) { assertEquals("Key not found: s2", e.getMessage()); } try { c.getSeries(null); fail("Should have thrown IndexOutOfBoundsException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Some basic checks for the addSeries() method. */ @Test public void testAddSeries() { XYSeriesCollection c = new XYSeriesCollection(); XYSeries s1 = new XYSeries("s1"); c.addSeries(s1); // the dataset should prevent the addition of a series with the // same name as an existing series in the dataset XYSeries s2 = new XYSeries("s1"); try { c.addSeries(s2); fail("Should have thrown IllegalArgumentException on duplicate key"); } catch (IllegalArgumentException e) { assertEquals("This dataset already contains a series with the key s1", e.getMessage()); } assertEquals(1, c.getSeriesCount()); } /** * Some basic checks for the removeSeries() method. */ @Test public void testRemoveSeries() { XYSeriesCollection c = new XYSeriesCollection(); XYSeries s1 = new XYSeries("s1"); c.addSeries(s1); c.removeSeries(0); assertEquals(0, c.getSeriesCount()); c.addSeries(s1); try { c.removeSeries(-1); fail("Should have thrown IndexOutOfBoundsException on negative key"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds.", e.getMessage()); } try { c.removeSeries(1); fail("Should have thrown IndexOutOfBoundsException on key out of range"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds.", e.getMessage()); } } /** * Some tests for the indexOf() method. */ @Test public void testIndexOf() { XYSeries s1 = new XYSeries("S1"); XYSeries s2 = new XYSeries("S2"); XYSeriesCollection dataset = new XYSeriesCollection(); assertEquals(-1, dataset.indexOf(s1)); assertEquals(-1, dataset.indexOf(s2)); dataset.addSeries(s1); assertEquals(0, dataset.indexOf(s1)); assertEquals(-1, dataset.indexOf(s2)); dataset.addSeries(s2); assertEquals(0, dataset.indexOf(s1)); assertEquals(1, dataset.indexOf(s2)); dataset.removeSeries(s1); assertEquals(-1, dataset.indexOf(s1)); assertEquals(0, dataset.indexOf(s2)); XYSeries s2b = new XYSeries("S2"); assertEquals(0, dataset.indexOf(s2b)); } /** * Some checks for the getDomainBounds() method. */ @Test public void testGetDomainBounds() { XYSeriesCollection dataset = new XYSeriesCollection(); Range r = dataset.getDomainBounds(false); assertNull(r); r = dataset.getDomainBounds(true); assertNull(r); XYSeries series = new XYSeries("S1"); dataset.addSeries(series); r = dataset.getDomainBounds(false); assertNull(r); r = dataset.getDomainBounds(true); assertNull(r); series.add(1.0, 1.1); r = dataset.getDomainBounds(false); assertEquals(new Range(1.0, 1.0), r); r = dataset.getDomainBounds(true); assertEquals(new Range(0.5, 1.5), r); series.add(-1.0, -1.1); r = dataset.getDomainBounds(false); assertEquals(new Range(-1.0, 1.0), r); r = dataset.getDomainBounds(true); assertEquals(new Range(-1.5, 1.5), r); } /** * Some checks for the getRangeBounds() method. */ @Test public void testGetRangeBounds() { XYSeriesCollection dataset = new XYSeriesCollection(); Range r = dataset.getRangeBounds(false); assertNull(r); r = dataset.getRangeBounds(true); assertNull(r); XYSeries series = new XYSeries("S1"); dataset.addSeries(series); r = dataset.getRangeBounds(false); assertNull(r); r = dataset.getRangeBounds(true); assertNull(r); series.add(1.0, 1.1); r = dataset.getRangeBounds(false); assertEquals(new Range(1.1, 1.1), r); r = dataset.getRangeBounds(true); assertEquals(new Range(1.1, 1.1), r); series.add(-1.0, -1.1); r = dataset.getRangeBounds(false); assertEquals(new Range(-1.1, 1.1), r); r = dataset.getRangeBounds(true); assertEquals(new Range(-1.1, 1.1), r); } /** * A check that the dataset prevents renaming a series to the name of an * existing series in the dataset. */ @Test public void testRenameSeries() { XYSeries s1 = new XYSeries("S1"); XYSeries s2 = new XYSeries("S2"); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); try { s2.setKey("S1"); fail("Should have thrown IllegalArgumentException on negative key"); } catch (IllegalArgumentException e) { assertEquals("Duplicate key2", e.getMessage()); } } /** * A test to cover bug 3445507. The issue does not affect * XYSeriesCollection. */ @Test public void testBug3445507() { XYSeries s1 = new XYSeries("S1"); s1.add(1.0, null); s1.add(2.0, null); XYSeries s2 = new XYSeries("S2"); s1.add(1.0, 5.0); s1.add(2.0, 6.0); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); Range r = dataset.getRangeBounds(false); assertEquals(5.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } /** * Test that a series belonging to a collection can be renamed (in fact, * because of a bug this was not possible in JFreeChart 1.0.14). */ @Test public void testSeriesRename() { // first check that a valid renaming works XYSeries series1 = new XYSeries("A"); XYSeries series2 = new XYSeries("B"); XYSeriesCollection collection = new XYSeriesCollection(); collection.addSeries(series1); collection.addSeries(series2); series1.setKey("C"); assertEquals("C", collection.getSeries(0).getKey()); // next, check that setting a duplicate key fails try { series2.setKey("C"); fail("Expected an IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } assertEquals("B", series2.getKey()); // the series name should not // change because "C" is already the key for the other series in the // collection } }
package de.da_sense.moses.client; import android.app.ActionBar; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.MenuItem; import de.da_sense.moses.client.util.Log; /** * Represents the details of a userstudy. * * @author Sandra Amend * @author Wladimir Schmidt * @author Zijad Maksuti */ public class DetailActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // check orientation and screen size // only for devices with API Level 11 or higher if (isAtLeastHoneycomb() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE && getResources().getConfiguration().isLayoutSizeAtLeast( Configuration.SCREENLAYOUT_SIZE_LARGE)) { Log.d("DetailActivity", "orientation = landscape"); Log.d("DetailActivity", "layout at least size large"); // If the screen is now in landscape mode, we can show the // dialog in-line with the list so we don't need this activity. finish(); return; } // get the Detail Fragment to check later if it is null or not DetailFragment details = null; Log.d("DetailActivity", "savedInstanceState == null || details == null"); // during initial setup plug in the detail fragment details = new DetailFragment(); details.setRetainInstance(true); details.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction() .add(android.R.id.content, details).commit(); // get ActionBar and set AppIcon to direct to the "home screen" ActionBar ab = getActionBar(); ab.setDisplayHomeAsUpEnabled(true); } /** * @see com.actionbarsherlock.app.SherlockFragmentActivity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // application icon in action bar clicked // go back to list view (MainActivity) onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onSaveInstanceState(Bundle outState) { Log.d("DetailActivity", "onSaveInstanceState"); super.onSaveInstanceState(outState); } /** * @see android.app.Activity#onRestoreInstanceState(android.os.Bundle) */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { Log.d("DetailActivity", "onRestoreInstanceState"); super.onRestoreInstanceState(savedInstanceState); } /** * Helper method to check if we have at least API 11 or higher. * * @return */ @Deprecated public boolean isAtLeastHoneycomb() { String version = android.os.Build.VERSION.RELEASE; if (version.startsWith("1.") || version.startsWith("2.")) { return false; } else { return true; } } }
package br.eti.rslemos.brill; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import org.apache.commons.lang.ObjectUtils; import br.eti.rslemos.brill.rules.RuleFactory; import br.eti.rslemos.tagger.DefaultSentence; import br.eti.rslemos.tagger.Sentence; import br.eti.rslemos.tagger.Tagger; import br.eti.rslemos.tagger.Token; public class RulesetTrainer<T> { private final Tagger<T> baseTagger; private final List<RuleFactory<T>> ruleFactories; private final int threshold; public RulesetTrainer(Tagger<T> baseTagger, List<RuleFactory<T>> ruleFactories) { this(baseTagger, ruleFactories, 1); } public RulesetTrainer(Tagger<T> baseTagger, List<RuleFactory<T>> ruleFactories, int threshold) { if (threshold < 0) throw new IllegalArgumentException("Threshold must be non-negative"); this.baseTagger = baseTagger; this.ruleFactories = ruleFactories; this.threshold = threshold; } private transient List<Sentence<T>> proofCorpus; private transient List<Sentence<T>> trainingCorpus; private transient ScoreBoard<T> board; private transient ArrayList<Rule<T>> rules; public synchronized RuleBasedTagger<T> train(List<Sentence<T>> proofCorpus) { this.proofCorpus = Collections.unmodifiableList(proofCorpus); this.trainingCorpus = new ArrayList<Sentence<T>>(proofCorpus.size()); this.board = new ScoreBoard<T>(); this.rules = new ArrayList<Rule<T>>(); try { prepareTrainingCorpus(); discoverRules(); rules.trimToSize(); return new RuleBasedTagger<T>(baseTagger, rules); } finally { // dispose this.proofCorpus = null; this.trainingCorpus = null; this.board = null; this.rules = null; } } private void prepareTrainingCorpus() { for (Sentence<T> proofSentence : proofCorpus) { Sentence<T> trainingSentence = new DefaultSentence<T>(proofSentence); baseTagger.tag(trainingSentence); trainingCorpus.add(trainingSentence); } } private void discoverRules() { Rule<T> bestRule; while ((bestRule = discoverNextRule()) != null) { rules.add(bestRule); } } private Rule<T> discoverNextRule() { board.newRound(); produceAllPossibleRules(); Score<T> bestScore = selectBestRule(); if (bestScore.getScore() >= threshold) { board.discardDependentsOn(bestScore.rule); applyRule(bestScore.rule); return bestScore.rule; } else return null; } private void applyRule(Rule<T> bestRule) { for (Sentence<T> trainingSentence : trainingCorpus) RuleBasedTagger.applyRule(new DelayedContext<T>(new SentenceContext<T>(trainingSentence)), bestRule); } private void produceAllPossibleRules() { for (Pair<Sentence<T>, Sentence<T>> pair : pairOf(proofCorpus, trainingCorpus)) { produceAllPossibleRules(pair.x, pair.y); } } private void produceAllPossibleRules(Sentence<T> proofSentence, Sentence<T> trainingSentence) { Context<T> trainingContext = new SentenceContext<T>(trainingSentence); for (Token<T> proofToken : proofSentence) { Token<T> trainingToken = trainingContext.next(); if (!ObjectUtils.equals(proofToken.getTag(), trainingToken.getTag())) { Collection<Rule<T>> rules = invokeRuleFactories(trainingContext, proofToken); board.addTruePositives(rules); } } } private Collection<Rule<T>> invokeRuleFactories(Context<T> context, Token<T> target) { Collection<Rule<T>> rules = new LinkedHashSet<Rule<T>>(ruleFactories.size()); for (RuleFactory<T> factory : ruleFactories) rules.addAll(factory.create(context, target)); return rules; } private Score<T> selectBestRule() { Queue<Score<T>> rules = board.getRulesByPriority(); Score<T> bestScore = new Score<T>(null, null, Integer.MAX_VALUE); bestScore.dec(); while(!rules.isEmpty()) { Score<T> entry = rules.poll(); if (entry.getScore() > bestScore.getScore()) { computeNegativeScore(entry); if (entry.getScore() > bestScore.getScore()) { bestScore = entry; } } else break; // cut } return bestScore; } private void computeNegativeScore(Score<T> entry) { if (entry.initNegativeMatches()) { for (Pair<Sentence<T>, Sentence<T>> pair : pairOf(proofCorpus, trainingCorpus)) { computeNegativeScore(entry, pair.x, pair.y); } } } private void computeNegativeScore(Score<T> entry, Sentence<T> proofSentence, Sentence<T> trainingSentence) { Context<T> trainingContext = new SentenceContext<T>(trainingSentence); for (Token<T> proofToken : proofSentence) { trainingContext.next(); computeNegativeScore(entry, proofToken, trainingContext); } } private void computeNegativeScore(Score<T> score, Token<T> proofToken, Context<T> trainingSentence) { Rule<T> rule = score.rule; if (rule.matches(trainingSentence)) if (ObjectUtils.equals(rule.getFrom(), proofToken.getTag())) score.dec(); } private static class Score<T1> implements Comparable<Score<T1>> { public final Object roundCreated; public final Rule<T1> rule; private final int counter; private int positiveMatches = 0; private int negativeMatches = 0; private boolean init = false; protected Score(Object roundCreated, Rule<T1> rule, int counter) { this.roundCreated = roundCreated; this.rule = rule; this.counter = counter; } public void inc() { positiveMatches++; } public void dec() { negativeMatches++; } public boolean initNegativeMatches() { boolean oldInit = init; init = true; return !oldInit; } public int getScore() { return positiveMatches - negativeMatches; } public int compareTo(Score<T1> o) { int primaryCriteria = o.getScore() - getScore(); return primaryCriteria != 0 ? primaryCriteria : o.counter - counter; } } private static class ScoreBoard<T1> { private final HashMap<Rule<T1>, Score<T1>> rules = new HashMap<Rule<T1>, Score<T1>>(); private Object round; private int counter; public void addTruePositive(Rule<T1> rule) { Score<T1> score = rules.get(rule); if (score == null) { score = new Score<T1>(round, rule, counter); rules.put(rule, score); } if (round == score.roundCreated) score.inc(); } public void addTruePositives(Collection<Rule<T1>> rules) { for (Rule<T1> rule : rules) { addTruePositive(rule); } } public Object newRound() { return round = new Object(); } public Queue<Score<T1>> getRulesByPriority() { return new PriorityQueue<Score<T1>>(rules.values()); } public void discardDependentsOn(Rule<T1> rule) { for (Iterator<Rule<T1>> it = rules.keySet().iterator(); it.hasNext();) { Rule<T1> r = it.next(); // already covers the case where rule == bestRule, since a rule firing depends on its tags anyway if (r.firingDependsOnTag(rule.getFrom()) || r.firingDependsOnTag(rule.getTo())) it.remove(); } } } private static class Pair<X, Y> { public final X x; public final Y y; public Pair(X x, Y y) { this.x = x; this.y = y; } } private static <X, Y> Iterable<Pair<X, Y>> pairOf(final Iterable<X> x, final Iterable<Y> y) { return new Iterable<Pair<X, Y>>() { @Override public Iterator<Pair<X, Y>> iterator() { return pairOf(x.iterator(), y.iterator()); } }; } private static <X, Y> Iterator<Pair<X, Y>> pairOf(final Iterator<X> x, final Iterator<Y> y) { return new Iterator<Pair<X, Y>>() { @Override public boolean hasNext() { return x.hasNext() && y.hasNext(); } @Override public Pair<X, Y> next() { return new Pair<X, Y>(x.next(), y.next()); } @Override public void remove() { x.remove(); y.remove(); } }; } }
package br.eti.rslemos.brill; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.commons.lang.ObjectUtils; import br.eti.rslemos.brill.RuleBasedTagger.BufferingContext; import br.eti.rslemos.brill.rules.RuleFactory; public class RulesetTrainer { public static interface HaltingStrategy { void setTrainingContext(TrainingContext trainingContext); boolean updateAndTest(); } public static interface RuleSelectStrategy { void setTrainingContext(TrainingContext trainingContext); Rule selectBestRule(Set<Rule> possibleRules); } public static interface RuleProducingStrategy { Collection<Rule> produceAllPossibleRules(Context context, Token target); } private final Tagger baseTagger; private final HaltingStrategy haltingStrategy; private final RuleSelectStrategy ruleSelectStrategy; private final RuleProducingStrategy ruleFactoryStrategy; public RulesetTrainer(Tagger baseTagger, List<RuleFactory> ruleFactories) { this(baseTagger, new RuleFactoryStrategy(ruleFactories), new ThresholdHaltingStrategy(1), new ScoringRuleSelectStrategy(new BrillScoringStrategy())); } public RulesetTrainer(Tagger baseTagger, RuleProducingStrategy ruleFactoryStrategy, HaltingStrategy haltingStrategy, RuleSelectStrategy ruleSelectStrategy) { this.baseTagger = baseTagger; this.ruleFactoryStrategy = ruleFactoryStrategy; this.haltingStrategy = haltingStrategy; this.ruleSelectStrategy = ruleSelectStrategy; } public Tagger getBaseTagger() { return baseTagger; } public HaltingStrategy getHaltingStrategy() { return haltingStrategy; } public RuleSelectStrategy getRuleSelectStrategy() { return ruleSelectStrategy; } public RuleProducingStrategy getRuleFactoryStrategy() { return ruleFactoryStrategy; } public synchronized RuleBasedTagger train(List<List<Token>> proofCorpus) { TrainingContext trainingContext = new TrainingContext(proofCorpus); trainingContext.applyBaseTagger(); List<Rule> rules = trainingContext.discoverRules(); return new RuleBasedTagger(baseTagger, rules); } public class TrainingContext { public final List<List<Token>> proofCorpus; public final BufferingContext[] trainingCorpus; public TrainingContext(List<List<Token>> proofCorpus) { this.proofCorpus = proofCorpus; this.trainingCorpus = new BufferingContext[proofCorpus.size()]; } private void applyBaseTagger() { for (int i = 0; i < trainingCorpus.length; i++) { List<Token> proofSentence = proofCorpus.get(i); Token[] baseTaggedSentence = new DefaultToken[proofSentence .size()]; for (int j = 0; j < baseTaggedSentence.length; j++) { baseTaggedSentence[j] = new DefaultToken(proofSentence.get( j).getWord()); } baseTagger.tagSentence(Arrays.asList(baseTaggedSentence)); trainingCorpus[i] = RuleBasedTagger .prepareContext(baseTaggedSentence); } } private List<Rule> discoverRules() { try { ruleSelectStrategy.setTrainingContext(this); haltingStrategy.setTrainingContext(this); return discoverRules0(); } finally { ruleSelectStrategy.setTrainingContext(null); haltingStrategy.setTrainingContext(null); } } private List<Rule> discoverRules0() { LinkedList<Rule> rules = new LinkedList<Rule>(); boolean shouldTryMore; do { shouldTryMore = false; Rule bestRule = ruleSelectStrategy.selectBestRule(produceAllPossibleRules()); if (bestRule != null) { applyRule(bestRule); if (shouldTryMore = haltingStrategy.updateAndTest()) rules.add(bestRule); } } while (shouldTryMore); return rules; } private void applyRule(Rule bestRule) { for (BufferingContext trainingSentence : trainingCorpus) RuleBasedTagger.applyRule(trainingSentence, bestRule); } private Set<Rule> produceAllPossibleRules() { Set<Rule> allPossibleRules = new HashSet<Rule>(); int i = 0; for (List<Token> proofSentence : proofCorpus) { BufferingContext trainingSentence = trainingCorpus[i++]; try { for (Token proofToken : proofSentence) { Token trainingToken = trainingSentence.next(); if (!ObjectUtils.equals(proofToken.getTag(), trainingToken.getTag())) { Collection<Rule> localPossibleRules = ruleFactoryStrategy.produceAllPossibleRules(trainingSentence, proofToken); allPossibleRules.addAll(localPossibleRules); } } } finally { trainingSentence.reset(); } } return allPossibleRules; } } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.doccat; import java.util.ArrayList; import java.util.Collection; public class BagOfWordsFeatureGenerator implements FeatureGenerator { public Collection extractFeatures(String[] text) { Collection bagOfWords = new ArrayList(text.length); for (int i = 0; i < text.length; i++) { bagOfWords.add("bow=" + text[i]); } return bagOfWords; } }
package org.jivesoftware.openfire.handler; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.QName; import org.jivesoftware.openfire.*; import org.jivesoftware.openfire.auth.*; import org.jivesoftware.openfire.event.SessionEventDispatcher; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.session.LocalClientSession; import org.jivesoftware.openfire.session.Session; import org.jivesoftware.openfire.user.UserManager; import org.jivesoftware.openfire.user.UserNotFoundException; import org.jivesoftware.stringprep.Stringprep; import org.jivesoftware.stringprep.StringprepException; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.Log; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.packet.PacketError; import org.xmpp.packet.StreamError; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; /** * Implements the TYPE_IQ jabber:iq:auth protocol (plain only). Clients * use this protocol to authenticate with the server. A 'get' query * runs an authentication probe with a given user name. Return the * authentication form or an error indicating the user is not * registered on the server.<p> * * A 'set' query authenticates with information given in the * authentication form. An authenticated session may reset their * authentication information using a 'set' query. * * <h2>Assumptions</h2> * This handler assumes that the request is addressed to the server. * An appropriate TYPE_IQ tag matcher should be placed in front of this * one to route TYPE_IQ requests not addressed to the server to * another channel (probably for direct delivery to the recipient). * * @author Iain Shigeoka */ public class IQAuthHandler extends IQHandler implements IQAuthInfo { private boolean anonymousAllowed; private Element probeResponse; private IQHandlerInfo info; private String serverName; private UserManager userManager; private RoutingTable routingTable; /** * Clients are not authenticated when accessing this handler. */ public IQAuthHandler() { super("XMPP Authentication handler"); info = new IQHandlerInfo("query", "jabber:iq:auth"); probeResponse = DocumentHelper.createElement(QName.get("query", "jabber:iq:auth")); probeResponse.addElement("username"); if (AuthFactory.isPlainSupported()) { probeResponse.addElement("password"); } if (AuthFactory.isDigestSupported()) { probeResponse.addElement("digest"); } probeResponse.addElement("resource"); anonymousAllowed = JiveGlobals.getBooleanProperty("xmpp.auth.anonymous"); } public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException { JID from = packet.getFrom(); LocalClientSession session = (LocalClientSession) sessionManager.getSession(from); // If no session was found then answer an error (if possible) if (session == null) { Log.error("Error during authentication. Session not found in " + sessionManager.getPreAuthenticatedKeys() + " for key " + from); // This error packet will probably won't make it through IQ reply = IQ.createResultIQ(packet); reply.setChildElement(packet.getChildElement().createCopy()); reply.setError(PacketError.Condition.internal_server_error); return reply; } IQ response; boolean resourceBound = false; if (JiveGlobals.getBooleanProperty("xmpp.auth.iqauth",true)) { try { Element iq = packet.getElement(); Element query = iq.element("query"); Element queryResponse = probeResponse.createCopy(); if (IQ.Type.get == packet.getType()) { String username = query.elementText("username"); if (username != null) { queryResponse.element("username").setText(username); } response = IQ.createResultIQ(packet); response.setChildElement(queryResponse); // This is a workaround. Since we don't want to have an incorrect TO attribute // value we need to clean up the TO attribute and send directly the response. // The TO attribute will contain an incorrect value since we are setting a fake // JID until the user actually authenticates with the server. if (session.getStatus() != Session.STATUS_AUTHENTICATED) { response.setTo((JID)null); } } // Otherwise set query else { if (query.elements().isEmpty()) { // Anonymous authentication response = anonymousLogin(session, packet); resourceBound = session.getStatus() == Session.STATUS_AUTHENTICATED; } else { String username = query.elementText("username"); // Login authentication String password = query.elementText("password"); String digest = null; if (query.element("digest") != null) { digest = query.elementText("digest").toLowerCase(); } // If we're already logged in, this is a password reset if (session.getStatus() == Session.STATUS_AUTHENTICATED) { // Check that a new password has been specified if (password == null || password.trim().length() == 0) { response = IQ.createResultIQ(packet); response.setError(PacketError.Condition.not_allowed); response.setType(IQ.Type.error); } else { // Check if a user is trying to change his own password if (session.getUsername().equalsIgnoreCase(username)) { response = passwordReset(password, packet, username, session); } // Check if an admin is trying to set the password for another user else if (XMPPServer.getInstance().getAdmins() .contains(new JID(from.getNode(), from.getDomain(), null, true))) { response = passwordReset(password, packet, username, session); } else { // User not authorized to change the password of another user throw new UnauthorizedException(); } } } else { // it is an auth attempt response = login(username, query, packet, password, session, digest); resourceBound = session.getStatus() == Session.STATUS_AUTHENTICATED; } } } } catch (UserNotFoundException e) { response = IQ.createResultIQ(packet); response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.not_authorized); } catch (UnauthorizedException e) { response = IQ.createResultIQ(packet); response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.not_authorized); } catch (ConnectionException e) { response = IQ.createResultIQ(packet); response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.internal_server_error); } catch (InternalUnauthenticatedException e) { response = IQ.createResultIQ(packet); response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.internal_server_error); } } else { response = IQ.createResultIQ(packet); response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.not_authorized); } // Send the response directly since we want to be sure that we are sending it back // to the correct session. Any other session of the same user but with different // resource is incorrect. session.process(response); if (resourceBound) { // After the client has been informed, inform all listeners as well. SessionEventDispatcher.dispatchEvent(session, SessionEventDispatcher.EventType.resource_bound); } return null; } private IQ login(String username, Element iq, IQ packet, String password, LocalClientSession session, String digest) throws UnauthorizedException, UserNotFoundException, ConnectionException, InternalUnauthenticatedException { // Verify the validity of the username if (username == null || username.trim().length() == 0) { throw new UnauthorizedException("Invalid username (empty or null)."); } try { Stringprep.nodeprep(username); } catch (StringprepException e) { throw new UnauthorizedException("Invalid username: " + username, e); } // Verify that specified resource is not violating any string prep rule String resource = iq.elementText("resource"); if (resource != null) { try { resource = JID.resourceprep(resource); } catch (StringprepException e) { throw new UnauthorizedException("Invalid resource: " + resource, e); } } else { // Answer a not_acceptable error since a resource was not supplied IQ response = IQ.createResultIQ(packet); response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.not_acceptable); return response; } if (! JiveGlobals.getBooleanProperty("xmpp.auth.iqauth",true)) { throw new UnauthorizedException(); } username = username.toLowerCase(); // Verify that supplied username and password are correct (i.e. user authentication was successful) AuthToken token = null; if (password != null && AuthFactory.isPlainSupported()) { token = AuthFactory.authenticate(username, password); } else if (digest != null && AuthFactory.isDigestSupported()) { token = AuthFactory.authenticate(username, session.getStreamID().toString(), digest); } if (token == null) { throw new UnauthorizedException(); } // Verify if there is a resource conflict between new resource and existing one. // Check if a session already exists with the requested full JID and verify if // we should kick it off or refuse the new connection ClientSession oldSession = routingTable.getClientRoute(new JID(username, serverName, resource, true)); if (oldSession != null) { try { int conflictLimit = sessionManager.getConflictKickLimit(); if (conflictLimit == SessionManager.NEVER_KICK) { IQ response = IQ.createResultIQ(packet); response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.forbidden); return response; } int conflictCount = oldSession.incrementConflictCount(); if (conflictCount > conflictLimit) { // Send a stream:error before closing the old connection StreamError error = new StreamError(StreamError.Condition.conflict); oldSession.deliverRawText(error.toXML()); oldSession.close(); } else { IQ response = IQ.createResultIQ(packet); response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.forbidden); return response; } } catch (Exception e) { Log.error("Error during login", e); } } // Set that the new session has been authenticated successfully session.setAuthToken(token, resource); packet.setFrom(session.getAddress()); return IQ.createResultIQ(packet); } private IQ passwordReset(String password, IQ packet, String username, Session session) throws UnauthorizedException { IQ response; if (password == null || password.length() == 0) { throw new UnauthorizedException(); } else { try { userManager.getUser(username).setPassword(password); response = IQ.createResultIQ(packet); List<String> params = new ArrayList<String>(); params.add(username); params.add(session.toString()); Log.info(LocaleUtils.getLocalizedString("admin.password.update", params)); } catch (UserNotFoundException e) { throw new UnauthorizedException(); } } return response; } private IQ anonymousLogin(LocalClientSession session, IQ packet) { IQ response = IQ.createResultIQ(packet); if (anonymousAllowed) { // Verify that client can connect from his IP address boolean forbidAccess = false; try { String hostAddress = session.getConnection().getHostAddress(); if (!LocalClientSession.getAllowedAnonymIPs().isEmpty() && !LocalClientSession.getAllowedAnonymIPs().containsKey(hostAddress)) { byte[] address = session.getConnection().getAddress(); String range1 = (address[0] & 0xff) + "." + (address[1] & 0xff) + "." + (address[2] & 0xff) + ".*"; String range2 = (address[0] & 0xff) + "." + (address[1] & 0xff) + ".*.*"; String range3 = (address[0] & 0xff) + ".*.*.*"; if (!LocalClientSession.getAllowedAnonymIPs().containsKey(range1) && !LocalClientSession.getAllowedAnonymIPs().containsKey(range2) && !LocalClientSession.getAllowedAnonymIPs().containsKey(range3)) { forbidAccess = true; } } } catch (UnknownHostException e) { forbidAccess = true; } if (forbidAccess) { // Connection forbidden from that IP address response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.forbidden); } else { // Anonymous authentication allowed session.setAnonymousAuth(); response.setTo(session.getAddress()); Element auth = response.setChildElement("query", "jabber:iq:auth"); auth.addElement("resource").setText(session.getAddress().getResource()); } } else { // Anonymous authentication is not allowed response.setChildElement(packet.getChildElement().createCopy()); response.setError(PacketError.Condition.forbidden); } return response; } public boolean isAnonymousAllowed() { return anonymousAllowed; } public void setAllowAnonymous(boolean isAnonymous) throws UnauthorizedException { anonymousAllowed = isAnonymous; JiveGlobals.setProperty("xmpp.auth.anonymous", Boolean.toString(anonymousAllowed)); } public void initialize(XMPPServer server) { super.initialize(server); userManager = server.getUserManager(); routingTable = server.getRoutingTable(); serverName = server.getServerInfo().getXMPPDomain(); } public IQHandlerInfo getInfo() { return info; } }
package org.jivesoftware.wildfire.session; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.Log; import org.jivesoftware.wildfire.Connection; import org.jivesoftware.wildfire.SessionManager; import org.jivesoftware.wildfire.StreamID; import org.jivesoftware.wildfire.XMPPServer; import org.jivesoftware.wildfire.auth.AuthToken; import org.jivesoftware.wildfire.auth.UnauthorizedException; import org.jivesoftware.wildfire.net.SASLAuthentication; import org.jivesoftware.wildfire.net.SSLConfig; import org.jivesoftware.wildfire.net.SocketConnection; import org.jivesoftware.wildfire.privacy.PrivacyList; import org.jivesoftware.wildfire.privacy.PrivacyListManager; import org.jivesoftware.wildfire.user.PresenceEventDispatcher; import org.jivesoftware.wildfire.user.UserNotFoundException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmpp.packet.JID; import org.xmpp.packet.Packet; import org.xmpp.packet.Presence; import org.xmpp.packet.StreamError; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; /** * Represents a session between the server and a client. * * @author Gaston Dombiak */ public class ClientSession extends Session { private static final String ETHERX_NAMESPACE = "http://etherx.jabber.org/streams"; private static final String FLASH_NAMESPACE = "http: /** * Keep the list of IP address that are allowed to connect to the server. If the list is * empty then anyone is allowed to connect to the server.<p> * * Note: Key = IP address or IP range; Value = empty string. A hash map is being used for * performance reasons. */ private static Map<String,String> allowedIPs = new HashMap<String,String>(); private static Connection.TLSPolicy tlsPolicy; private static Connection.CompressionPolicy compressionPolicy; /** * The authentication token for this session. */ protected AuthToken authToken; /** * Flag indicating if this session has been initialized yet (upon first available transition). */ private boolean initialized; /** * Flag that indicates if the session was available ever. */ private boolean wasAvailable = false; private boolean offlineFloodStopped = false; private Presence presence = null; private int conflictCount = 0; /** * Privacy list that overrides the default privacy list. This list affects only this * session and only for the duration of the session. */ private PrivacyList activeList; /** * Default privacy list used for the session's user. This list is processed if there * is no active list set for the session. */ private PrivacyList defaultList; static { // Fill out the allowedIPs with the system property String allowed = JiveGlobals.getProperty("xmpp.client.login.allowed", ""); StringTokenizer tokens = new StringTokenizer(allowed, ", "); while (tokens.hasMoreTokens()) { String address = tokens.nextToken().trim(); allowedIPs.put(address, ""); } // Set the TLS policy stored as a system property String policyName = JiveGlobals.getProperty("xmpp.client.tls.policy", Connection.TLSPolicy.optional.toString()); tlsPolicy = Connection.TLSPolicy.valueOf(policyName); // Set the Compression policy stored as a system property policyName = JiveGlobals.getProperty("xmpp.client.compression.policy", Connection.CompressionPolicy.optional.toString()); compressionPolicy = Connection.CompressionPolicy.valueOf(policyName); } /** * Returns the list of IP address that are allowed to connect to the server. If the list is * empty then anyone is allowed to connect to the server. * * @return the list of IP address that are allowed to connect to the server. */ public static Map<String, String> getAllowedIPs() { return allowedIPs; } /** * Returns a newly created session between the server and a client. The session will * be created and returned only if correct name/prefix (i.e. 'stream' or 'flash') * and namespace were provided by the client. * * @param serverName the name of the server where the session is connecting to. * @param xpp the parser that is reading the provided XML through the connection. * @param connection the connection with the client. * @return a newly created session between the server and a client. * @throws org.xmlpull.v1.XmlPullParserException if an error occurs while parsing incoming data. */ public static Session createSession(String serverName, XmlPullParser xpp, Connection connection) throws XmlPullParserException { boolean isFlashClient = xpp.getPrefix().equals("flash"); connection.setFlashClient(isFlashClient); // Conduct error checking, the opening tag should be 'stream' // in the 'etherx' namespace if (!xpp.getName().equals("stream") && !isFlashClient) { throw new XmlPullParserException( LocaleUtils.getLocalizedString("admin.error.bad-stream")); } if (!xpp.getNamespace(xpp.getPrefix()).equals(ETHERX_NAMESPACE) && !(isFlashClient && xpp.getNamespace(xpp.getPrefix()).equals(FLASH_NAMESPACE))) { throw new XmlPullParserException(LocaleUtils.getLocalizedString( "admin.error.bad-namespace")); } if (!allowedIPs.isEmpty()) { boolean forbidAccess = false; String hostAddress = "Unknown"; // The server is using a whitelist so check that the IP address of the client // is authorized to connect to the server try { hostAddress = connection.getInetAddress().getHostAddress(); if (!allowedIPs.containsKey(hostAddress)) { byte[] address = connection.getInetAddress().getAddress(); String range1 = (address[0] & 0xff) + "." + (address[1] & 0xff) + "." + (address[2] & 0xff) + ".*"; String range2 = (address[0] & 0xff) + "." + (address[1] & 0xff) + ".*.*"; String range3 = (address[0] & 0xff) + ".*.*.*"; if (!allowedIPs.containsKey(range1) && !allowedIPs.containsKey(range2) && !allowedIPs.containsKey(range3)) { forbidAccess = true; } } } catch (UnknownHostException e) { forbidAccess = true; } if (forbidAccess) { // Client cannot connect from this IP address so end the stream and // TCP connection Log.debug("Closed connection to client attempting to connect from: " + hostAddress); // Include the not-authorized error in the response StreamError error = new StreamError(StreamError.Condition.not_authorized); connection.deliverRawText(error.toXML()); // Close the underlying connection connection.close(); return null; } } // Default language is English ("en"). String language = "en"; // Default to a version of "0.0". Clients written before the XMPP 1.0 spec may // not report a version in which case "0.0" should be assumed (per rfc3920 // section 4.4.1). int majorVersion = 0; int minorVersion = 0; for (int i = 0; i < xpp.getAttributeCount(); i++) { if ("lang".equals(xpp.getAttributeName(i))) { language = xpp.getAttributeValue(i); } if ("version".equals(xpp.getAttributeName(i))) { try { int[] version = decodeVersion(xpp.getAttributeValue(i)); majorVersion = version[0]; minorVersion = version[1]; } catch (Exception e) { Log.error(e); } } } // If the client supports a greater major version than the server, // set the version to the highest one the server supports. if (majorVersion > MAJOR_VERSION) { majorVersion = MAJOR_VERSION; minorVersion = MINOR_VERSION; } else if (majorVersion == MAJOR_VERSION) { // If the client supports a greater minor version than the // server, set the version to the highest one that the server // supports. if (minorVersion > MINOR_VERSION) { minorVersion = MINOR_VERSION; } } // Store language and version information in the connection. connection.setLanaguage(language); connection.setXMPPVersion(majorVersion, minorVersion); // Indicate the TLS policy to use for this connection if (!connection.isSecure()) { boolean hasCertificates = false; try { hasCertificates = SSLConfig.getKeyStore().size() > 0; } catch (Exception e) { Log.error(e); } if (Connection.TLSPolicy.required == tlsPolicy && !hasCertificates) { Log.error("Client session rejected. TLS is required but no certificates " + "were created."); return null; } // Set default TLS policy connection.setTlsPolicy(hasCertificates ? tlsPolicy : Connection.TLSPolicy.disabled); } else { // Set default TLS policy connection.setTlsPolicy(Connection.TLSPolicy.disabled); } // Indicate the compression policy to use for this connection connection.setCompressionPolicy(compressionPolicy); // Create a ClientSession for this user. Session session = SessionManager.getInstance().createClientSession(connection); // Build the start packet response StringBuilder sb = new StringBuilder(200); sb.append("<?xml version='1.0' encoding='"); sb.append(CHARSET); sb.append("'?>"); if (isFlashClient) { sb.append("<flash:stream xmlns:flash=\"http: } else { sb.append("<stream:stream "); } sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"jabber:client\" from=\""); sb.append(serverName); sb.append("\" id=\""); sb.append(session.getStreamID().toString()); sb.append("\" xml:lang=\""); sb.append(language); // Don't include version info if the version is 0.0. if (majorVersion != 0) { sb.append("\" version=\""); sb.append(majorVersion).append(".").append(minorVersion); } sb.append("\">"); connection.deliverRawText(sb.toString()); // If this is a "Jabber" connection, the session is now initialized and we can // return to allow normal packet parsing. if (majorVersion == 0) { return session; } // Otherwise, this is at least XMPP 1.0 so we need to announce stream features. sb = new StringBuilder(490); sb.append("<stream:features>"); if (connection.getTlsPolicy() != Connection.TLSPolicy.disabled) { sb.append("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\">"); if (connection.getTlsPolicy() == Connection.TLSPolicy.required) { sb.append("<required/>"); } sb.append("</starttls>"); } // Include available SASL Mechanisms sb.append(SASLAuthentication.getSASLMechanisms(session)); // Include Stream features String specificFeatures = session.getAvailableStreamFeatures(); if (specificFeatures != null) { sb.append(specificFeatures); } sb.append("</stream:features>"); connection.deliverRawText(sb.toString()); return session; } /** * Sets the list of IP address that are allowed to connect to the server. If the list is * empty then anyone is allowed to connect to the server. * * @param allowed the list of IP address that are allowed to connect to the server. */ public static void setAllowedIPs(Map<String, String> allowed) { allowedIPs = allowed; if (allowedIPs.isEmpty()) { JiveGlobals.deleteProperty("xmpp.client.login.allowed"); } else { // Iterate through the elements in the map. StringBuilder buf = new StringBuilder(); Iterator<String> iter = allowedIPs.keySet().iterator(); if (iter.hasNext()) { buf.append(iter.next()); } while (iter.hasNext()) { buf.append(", ").append(iter.next()); } JiveGlobals.setProperty("xmpp.client.login.allowed", buf.toString()); } } /** * Returns whether TLS is mandatory, optional or is disabled for clients. When TLS is * mandatory clients are required to secure their connections or otherwise their connections * will be closed. On the other hand, when TLS is disabled clients are not allowed to secure * their connections using TLS. Their connections will be closed if they try to secure the * connection. in this last case. * * @return whether TLS is mandatory, optional or is disabled. */ public static SocketConnection.TLSPolicy getTLSPolicy() { return tlsPolicy; } /** * Sets whether TLS is mandatory, optional or is disabled for clients. When TLS is * mandatory clients are required to secure their connections or otherwise their connections * will be closed. On the other hand, when TLS is disabled clients are not allowed to secure * their connections using TLS. Their connections will be closed if they try to secure the * connection. in this last case. * * @param policy whether TLS is mandatory, optional or is disabled. */ public static void setTLSPolicy(SocketConnection.TLSPolicy policy) { tlsPolicy = policy; JiveGlobals.setProperty("xmpp.client.tls.policy", tlsPolicy.toString()); } /** * Returns whether compression is optional or is disabled for clients. * * @return whether compression is optional or is disabled. */ public static SocketConnection.CompressionPolicy getCompressionPolicy() { return compressionPolicy; } /** * Sets whether compression is optional or is disabled for clients. * * @param policy whether compression is optional or is disabled. */ public static void setCompressionPolicy(SocketConnection.CompressionPolicy policy) { compressionPolicy = policy; JiveGlobals.setProperty("xmpp.client.compression.policy", compressionPolicy.toString()); } /** * Returns the Privacy list that overrides the default privacy list. This list affects * only this session and only for the duration of the session. * * @return the Privacy list that overrides the default privacy list. */ public PrivacyList getActiveList() { return activeList; } /** * Sets the Privacy list that overrides the default privacy list. This list affects * only this session and only for the duration of the session. * * @param activeList the Privacy list that overrides the default privacy list. */ public void setActiveList(PrivacyList activeList) { this.activeList = activeList; } /** * Returns the default Privacy list used for the session's user. This list is * processed if there is no active list set for the session. * * @return the default Privacy list used for the session's user. */ public PrivacyList getDefaultList() { return defaultList; } /** * Sets the default Privacy list used for the session's user. This list is * processed if there is no active list set for the session. * * * @param defaultList the default Privacy list used for the session's user. */ public void setDefaultList(PrivacyList defaultList) { this.defaultList = defaultList; } public ClientSession(String serverName, Connection connection, StreamID streamID) { super(serverName, connection, streamID); // Set an unavailable initial presence presence = new Presence(); presence.setType(Presence.Type.unavailable); } /** * Returns the username associated with this session. Use this information * with the user manager to obtain the user based on username. * * @return the username associated with this session * @throws UserNotFoundException if a user is not associated with a session * (the session has not authenticated yet) */ public String getUsername() throws UserNotFoundException { if (authToken == null) { throw new UserNotFoundException(); } return getAddress().getNode(); } /** * Sets the new Authorization Token for this session. The session is not yet considered fully * authenticated (i.e. active) since a resource has not been binded at this point. This * message will be sent after SASL authentication was successful but yet resource binding * is required. * * @param auth the authentication token obtained from SASL authentication. */ public void setAuthToken(AuthToken auth) { authToken = auth; } /** * Initialize the session with a valid authentication token and * resource name. This automatically upgrades the session's * status to authenticated and enables many features that are not * available until authenticated (obtaining managers for example). * * @param auth the authentication token obtained from the AuthFactory. * @param resource the resource this session authenticated under. */ public void setAuthToken(AuthToken auth, String resource) { setAddress(new JID(auth.getUsername(), getServerName(), resource)); authToken = auth; sessionManager.addSession(this); setStatus(Session.STATUS_AUTHENTICATED); // Set default privacy list for this session setDefaultList(PrivacyListManager.getInstance().getDefaultPrivacyList(auth.getUsername())); } /** * Initialize the session as an anonymous login. This automatically upgrades the session's * status to authenticated and enables many features that are not available until * authenticated (obtaining managers for example).<p> */ public void setAnonymousAuth() { // Anonymous users have a full JID. Use the random resource as the JID's node String resource = getAddress().getResource(); setAddress(new JID(resource, getServerName(), resource)); sessionManager.addAnonymousSession(this); setStatus(Session.STATUS_AUTHENTICATED); } /** * Returns the authentication token associated with this session. * * @return the authentication token associated with this session (can be null). */ public AuthToken getAuthToken() { return authToken; } /** * Flag indicating if this session has been initialized once coming * online. Session initialization occurs after the session receives * the first "available" presence update from the client. Initialization * actions include pushing offline messages, presence subscription requests, * and presence statuses to the client. Initialization occurs only once * following the first available presence transition. * * @return True if the session has already been initializsed */ public boolean isInitialized() { return initialized; } /** * Sets the initialization state of the session. * * @param isInit True if the session has been initialized * @see #isInitialized */ public void setInitialized(boolean isInit) { initialized = isInit; } /** * Returns true if the session was available ever. * * @return true if the session was available ever. */ public boolean wasAvailable() { return wasAvailable; } public boolean canFloodOfflineMessages() { if(offlineFloodStopped) { return false; } String username = getAddress().getNode(); for (ClientSession session : sessionManager.getSessions(username)) { if (session.isOfflineFloodStopped()) { return false; } } return true; } public boolean isOfflineFloodStopped() { return offlineFloodStopped; } public void setOfflineFloodStopped(boolean offlineFloodStopped) { this.offlineFloodStopped = offlineFloodStopped; } /** * Obtain the presence of this session. * * @return The presence of this session or null if not authenticated */ public Presence getPresence() { return presence; } /** * Set the presence of this session * * @param presence The presence for the session * @return The old priority of the session or null if not authenticated */ public Presence setPresence(Presence presence) { Presence oldPresence = this.presence; this.presence = presence; if (oldPresence.isAvailable() && !this.presence.isAvailable()) { // The client is no longer available sessionManager.sessionUnavailable(this); // Mark that the session is no longer initialized. This means that if the user sends // an available presence again the session will be initialized again thus receiving // offline messages and offline presence subscription requests setInitialized(false); // Notify listeners that the session is no longer available PresenceEventDispatcher.unavailableSession(this, presence); } else if (!oldPresence.isAvailable() && this.presence.isAvailable()) { // The client is available sessionManager.sessionAvailable(this); wasAvailable = true; // Notify listeners that the session is now available PresenceEventDispatcher.availableSession(this, presence); } else if (this.presence.isAvailable() && oldPresence.getPriority() != this.presence.getPriority()) { // The client has changed the priority of his presence sessionManager.changePriority(getAddress(), this.presence.getPriority()); // Notify listeners that the priority of the session/resource has changed PresenceEventDispatcher.presencePriorityChanged(this, presence); } else if (this.presence.isAvailable()) { // Notify listeners that the show or status value of the presence has changed PresenceEventDispatcher.presenceChanged(this, presence); } return oldPresence; } /** * Returns the number of conflicts detected on this session. * Conflicts typically occur when another session authenticates properly * to the user account and requests to use a resource matching the one * in use by this session. Administrators may configure the server to automatically * kick off existing sessions when their conflict count exceeds some limit including * 0 (old sessions are kicked off immediately to accommodate new sessions). Conflicts * typically signify the existing (old) session is broken/hung. * * @return The number of conflicts detected for this session */ public int getConflictCount() { return conflictCount; } public String getAvailableStreamFeatures() { // Offer authenticate and registration only if TLS was not required or if required // then the connection is already secured if (conn.getTlsPolicy() == Connection.TLSPolicy.required && !conn.isSecure()) { return null; } StringBuilder sb = new StringBuilder(200); // Include Stream Compression Mechanism if (conn.getCompressionPolicy() != Connection.CompressionPolicy.disabled && !conn.isCompressed()) { sb.append( "<compression xmlns=\"http://jabber.org/features/compress\"><method>zlib</method></compression>"); } if (getAuthToken() == null) { // Advertise that the server supports Non-SASL Authentication sb.append("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>"); // Advertise that the server supports In-Band Registration if (XMPPServer.getInstance().getIQRegisterHandler().isInbandRegEnabled()) { sb.append("<register xmlns=\"http://jabber.org/features/iq-register\"/>"); } } else { // If the session has been authenticated then offer resource binding // and session establishment sb.append("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"); sb.append("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>"); } return sb.toString(); } /** * Increments the conflict by one. */ public void incrementConflictCount() { conflictCount++; } /** * Returns true if the specified packet must not be blocked based on the active or default * privacy list rules. The active list will be tried first. If none was found then the * default list is going to be used. If no default list was defined for this user then * allow the packet to flow. * * @param packet the packet to analyze if it must be blocked. * @return true if the specified packet must be blocked. */ public boolean canProcess(Packet packet) { if (activeList != null) { // If a privacy list is active then make sure that the packet is not blocked return !activeList.shouldBlockPacket(packet); } else if (defaultList != null) { // There is no active list so check if there exists a default list and make // sure that the packet is not blocked return !defaultList.shouldBlockPacket(packet); } return true; } void deliver(Packet packet) throws UnauthorizedException { if (conn != null && !conn.isClosed()) { conn.deliver(packet); } } public String toString() { return super.toString() + " presence: " + presence; } }
package com.sometrik.framework; import java.util.ArrayList; import java.util.TreeMap; import android.content.Context; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; public class FWPicker extends Spinner implements NativeMessageHandler { private Context context; private ArrayAdapter<String> adapter; private ArrayList<Integer> numberList; private TreeMap<Integer, String> valueMap; private final int id; private native void pickerOptionSelected(int id, int position); public FWPicker(Context context) { super(context); adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item); valueMap = new TreeMap<Integer, String>(); numberList = new ArrayList<Integer>(); id = getId(); this.context = context; setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { pickerOptionSelected(id, position); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); } @Override public void handleMessage(NativeMessage message) { switch (message.getMessage()) { case ADD_OPTION: adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item); valueMap.put(message.getValue(), message.getTextValue()); numberList.add(message.getValue()); for (int i = 0; i < numberList.size(); i++) { adapter.add(valueMap.get(numberList.get(i))); } setAdapter(adapter); break; default: System.out.println("Message couldn't be handled by Picker"); break; } } @Override public void showView() { } @Override public int getElementId() { return getId(); } }
package com.sims.topaz; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.VisibleRegion; import com.sims.topaz.adapter.TagSuggestionAdapter; import com.sims.topaz.network.NetworkRestModule; import com.sims.topaz.network.interfaces.ErreurDelegate; import com.sims.topaz.network.interfaces.MessageDelegate; import com.sims.topaz.network.modele.ApiError; import com.sims.topaz.network.modele.Message; import com.sims.topaz.network.modele.Preview; import com.sims.topaz.utils.MyTypefaceSingleton; import com.sims.topaz.utils.SimsContext; import com.sims.topaz.utils.TagUtils; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; public class TagSearchFragment extends Fragment implements MessageDelegate, ErreurDelegate { private NetworkRestModule mNetworkModule; private GoogleMap mMap; private EditText text; public TagSearchFragment() { } public void setMap(GoogleMap map) { mMap = map; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNetworkModule = new NetworkRestModule(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_tag_search, container, false); Typeface face = MyTypefaceSingleton.getInstance().getTypeFace(); text = (EditText) view.findViewById(R.id.tag_search); text.setTypeface(face); text.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { //Toast.makeText(SimsContext.getContext(), s, Toast.LENGTH_SHORT).show(); } }); ImageView image = (ImageView) view.findViewById(R.id.tag_search_icon); image.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { executeSearch(text.getText()); } }); ListView tagList = (ListView) view.findViewById(R.id.tag_list); tagList.setAdapter(new TagSuggestionAdapter(getActivity(), R.layout.tag_suggestion_item, TagUtils.getAllTags())); return view; } public void executeSearch(CharSequence tx) { if( mMap != null && mNetworkModule != null ){ VisibleRegion visibleRegion = mMap.getProjection().getVisibleRegion(); try { mNetworkModule.getPreviewsByTag(visibleRegion.farLeft, visibleRegion.nearRight, URLEncoder.encode(tx.toString(), "utf8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } @Override public void afterPostMessage(Message message) { // TODO Auto-generated method stub } @Override public void afterGetMessage(Message message) { // TODO Auto-generated method stub } @Override public void afterGetPreviews(List<Preview> list) { Fragment f = PreviewListFragment.newInstance(list); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.setCustomAnimations(R.drawable.animation_bottom_up, R.drawable.animation_bottom_down); transaction.replace(R.id.preview_list_tag, f); transaction.addToBackStack(null); transaction.commit(); } @Override public void apiError(ApiError error) { //NetworkRestModule.resetHttpClient(); Toast.makeText(SimsContext.getContext(), "apiError", Toast.LENGTH_SHORT).show(); } @Override public void networkError() { Toast.makeText(SimsContext.getContext(), "networkError", Toast.LENGTH_SHORT).show(); } public EditText getEditText() { return text; } }
package jsettlers.graphics.startscreen; import java.util.Date; import java.util.List; /** * This connector provides data that is needed by the start screen. * * @author michael */ public interface IStartScreenConnector { /** * Gets a list of maps the user can play. * * @return */ List<? extends IMapItem> getMaps(); public interface IMapItem { String getName(); int getMinPlayers(); int getMaxPlayers(); /** * Creates a loadable game. This method should return fast. * <p> * It does not fail, but may return a map data provider that fails * loading. * * @return never null. */ // IMapDataProvider createLoadableGame(int players, long random); } /** * Gets the games a user may load * * @return A fixed list of games. */ List<? extends ILoadableGame> getLoadableGames(); public interface ILoadableGame { String getName(); Date getSaveTime(); } /** * Gets a list of network games that can be recovered. */ List<? extends IRecoverableGame> getRecoverableGames(); public interface IRecoverableGame extends INetworkGame { Date getSaveTime(); } /** * Gets a list of network games. * * @return The list of network games. */ INetworkGame[] getNetworkGames(); public interface INetworkGame { String getName(); String[] getPlayerNames(); } void setNetworkServer(String host); void addNetworkGameListener(INetworkGameListener gameListener); void removeNetworkGameListener(INetworkGameListener gameListener); public interface INetworkGameListener { void networkGamesChanged(); } /* - - - - - callbacks - - - - - */ /** * Called when the user starts a singleplayer game */ void startNewGame(IGameSettings game); public interface IGameSettings { IMapItem getMap(); int getPlayerCount(); } /** * Called when the user wants to load a game * * @param load * The game to load. A item of getLoadableGames(); */ void loadGame(ILoadableGame load); /** * Starts a network game * * @param game * @param name */ void startMatch(IGameSettings game, String matchName); void recoverNetworkGame(IRecoverableGame game); void joinNetworkGame(INetworkGame game); void exitGame(); }
package be.isach.samaritan.music; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class AudioFilesManager { public static void checkforSongsToConvert() { cleanMp4(); File directory = new File("/home/samaritan/music"); for (File file : directory.listFiles()) { if (file.getName().endsWith(".webm")) { convert(file); } } } private static void convert(File file) { // System.out.println("Trying to convert: " + file.getName()); // String spacedName = file.getName().replace(".webm", ".mp3"); // File webmFile = file.getAbsoluteFile(); // webmFile.renameTo(new File(webmFile.getAbsolutePath().replace(" ", ""))); // File mp3File = new File(webmFile.getAbsolutePath().replace(" ", "").replace(".webm", ".mp3")); // System.out.println("\nExists: " + webmFile.exists() + "\n"); try { String[] command = { "ffmpeg", "-i", // "\"" + file.getAbsolutePath() + "\"", // "\"" + file.getAbsolutePath().replace(".webm", ".mp3") + "\"" "music/a.webm", "music/a.mp3" }; System.out.println(Arrays.asList(command)); Process p = Runtime.getRuntime().exec(command); BufferedReader output = getOutput(p); BufferedReader error = getError(p); String ligne = ""; while ((ligne = output.readLine()) != null) { System.out.println(ligne); } while ((ligne = error.readLine()) != null) { System.out.println(ligne); } p.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } // mp3File.renameTo(new File(spacedName)); } private static BufferedReader getOutput(Process p) { return new BufferedReader(new InputStreamReader(p.getInputStream())); } private static BufferedReader getError(Process p) { return new BufferedReader(new InputStreamReader(p.getErrorStream())); } private static void cleanMp4() { File file = new File("/home/samaritan/music"); // Arrays.asList(file.listFiles()).stream().filter(file1 -> file1.getName().endsWith(".mp4")).forEach(File::delete); } }
package br.uff.ic.provviewer.GUI; import br.uff.ic.provviewer.Collapser; import br.uff.ic.utility.graph.Edge; import br.uff.ic.provviewer.Filter.Filters; import br.uff.ic.provviewer.Filter.PreFilters; import static br.uff.ic.provviewer.GUI.GuiFunctions.PanCameraToFirstVertex; import br.uff.ic.provviewer.GraphFrame; import br.uff.ic.provviewer.ImproveJUNGPerformance; import br.uff.ic.provviewer.Variables; import br.uff.ic.utility.Utils; import edu.uci.ics.jung.graph.DirectedGraph; import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse; import java.awt.RenderingHints; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.ToolTipManager; /** * Class to initialize the interface operations * * @author Kohwalter */ public class GuiInitialization { /** * Method to initialize the tool components * * @param variables * @param graph * @param graphFrame * @param Layouts * @param agentLabel interface check-box state agent label * @param activityLabel interface check-box state activity label * @param entityLabel interface check-box state for entity label * @param timeLabel interface check-box state for time label */ public static void initGraphComponent(Variables variables, DirectedGraph<Object, Edge> graph, JFrame graphFrame, JComboBox Layouts, boolean agentLabel, boolean activityLabel, boolean entityLabel, boolean timeLabel, boolean showID) { variables.initConfig = true; variables.graph = graph; variables.collapsedGraph = variables.graph; GuiFunctions.SetView(variables, Layouts, graphFrame); variables.updateNumberOfGraphs(); variables.guiBackground.InitBackground(variables, Layouts); GuiFunctions.MouseInteraction(variables); GuiTooltip.Tooltip(variables); GuiFunctions.VertexLabel(variables, agentLabel, activityLabel, entityLabel, timeLabel, showID); GuiFunctions.Stroke(variables); GuiFunctions.GraphPaint(variables); GuiFunctions.VertexShape(variables); InitFilters(variables); Utils.NormalizeTime(variables.graph, false); variables.jungPerformance.init(variables.view); ToolTipManager.sharedInstance().setInitialDelay(10); ToolTipManager.sharedInstance().setDismissDelay(50000); GraphFrame.vertexFilterList.setSelectedIndex(0); } /** * Method to update the features after openning a new file * @param variables * @param Layouts */ public static void ReInitializeAfterReadingFile(Variables variables, JComboBox Layouts) { variables.updateNumberOfGraphs(); GuiFunctions.Stroke(variables); GuiFunctions.GraphPaint(variables); GuiFunctions.VertexShape(variables); InitFilters(variables); Utils.NormalizeTime(variables.graph, false); variables.guiBackground.InitBackground(variables, Layouts); GraphFrame.edgeFilterList.setSelectedIndex(0); GraphFrame.vertexFilterList.setSelectedIndex(0); PanCameraToFirstVertex(variables); variables.config.resetVertexModeInitializations(); } /** * Method to initialize the tool's variables * * @param variables */ public static void InitVariables(Variables variables) { variables.mouse = new DefaultModalGraphMouse(); variables.filterCredits = false; variables = new Variables(); variables.collapser = new Collapser(); variables.filter = new Filters(); variables.prologIsInitialized = false; variables.initLayout = true; variables.initConfig = false; } /** * Method to initialize the tool's filters * * @param variables */ public static void InitFilters(Variables variables) { variables.filter.filteredGraph = variables.graph; // variables.filter.FilterInit(); PreFilters.PreFilter(); variables.filter.Filters(variables); } }
package com.akiban.sql.pg; import com.akiban.ais.model.AkibanInformationSchema; import com.akiban.sql.server.ServerServiceRequirements; import com.akiban.sql.server.ServerSessionBase; import com.akiban.sql.server.ServerSessionMonitor; import com.akiban.sql.server.ServerStatementCache; import com.akiban.sql.server.ServerTransaction; import com.akiban.sql.server.ServerValueDecoder; import com.akiban.sql.StandardException; import com.akiban.sql.parser.ParameterNode; import com.akiban.sql.parser.SQLParserException; import com.akiban.sql.parser.StatementNode; import com.akiban.qp.operator.QueryContext; import com.akiban.qp.operator.StoreAdapter; import com.akiban.qp.persistitadapter.PersistitAdapter; import com.akiban.server.api.DDLFunctions; import com.akiban.server.error.*; import com.akiban.server.service.monitor.MonitorStage; import static com.akiban.server.service.dxl.DXLFunctionsHook.DXLFunction; import com.akiban.util.tap.InOutTap; import com.akiban.util.tap.Tap; import com.persistit.exception.RollbackException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.*; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.*; import java.util.*; /** * Connection to a Postgres server client. * Runs in its own thread; has its own AkServer Session. * */ public class PostgresServerConnection extends ServerSessionBase implements PostgresServerSession, Runnable { private static final Logger logger = LoggerFactory.getLogger(PostgresServerConnection.class); private static final InOutTap READ_MESSAGE = Tap.createTimer("PostgresServerConnection: read message"); private static final InOutTap PROCESS_MESSAGE = Tap.createTimer("PostgresServerConnection: process message"); private final PostgresServer server; private boolean running = false, ignoreUntilSync = false; private Socket socket; private PostgresMessenger messenger; private OutputFormat outputFormat = OutputFormat.TABLE; private int sessionId, secret; private int version; private Map<String,PostgresStatement> preparedStatements = new HashMap<String,PostgresStatement>(); private Map<String,PostgresBoundQueryContext> boundPortals = new HashMap<String,PostgresBoundQueryContext>(); private ServerStatementCache<PostgresStatement> statementCache; private PostgresStatementParser[] unparsedGenerators; private PostgresStatementGenerator[] parsedGenerators; private Thread thread; private volatile String cancelForKillReason, cancelByUser; private static class GeneratedResult { public PostgresStatementGenerator generator; public PostgresStatement statement; public GeneratedResult(PostgresStatementGenerator generator, PostgresStatement statement) { this.generator = generator; this.statement = statement; } } public PostgresServerConnection(PostgresServer server, Socket socket, int sessionId, int secret, ServerServiceRequirements reqs) { super(reqs); this.server = server; this.socket = socket; this.sessionId = sessionId; this.secret = secret; this.sessionMonitor = new ServerSessionMonitor(PostgresServer.SERVER_TYPE, sessionId); sessionMonitor.setRemoteAddress(socket.getInetAddress().getHostAddress()); reqs.monitor().registerSessionMonitor(sessionMonitor); } public void start() { running = true; thread = new Thread(this); thread.start(); } public void stop() { running = false; // Can only wake up stream read by closing down socket. try { socket.close(); } catch (IOException ex) { } if ((thread != null) && (thread != Thread.currentThread())) { try { // Wait a bit, but don't hang up shutdown if thread is wedged. thread.join(500); if (thread.isAlive()) logger.warn("Connection " + sessionId + " still running."); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } thread = null; } } public void run() { try { createMessenger(); topLevel(); } catch (Exception ex) { if (running) logger.warn("Error in server", ex); } finally { try { socket.close(); } catch (IOException ex) { } } } protected void createMessenger() throws IOException { messenger = new PostgresMessenger(socket) { @Override public void beforeIdle() throws IOException { super.beforeIdle(); sessionMonitor.enterStage(MonitorStage.IDLE); } @Override public void afterIdle() throws IOException { sessionMonitor.leaveStage(); super.afterIdle(); } @Override public void idle() { if (cancelForKillReason != null) { String msg = cancelForKillReason; cancelForKillReason = null; if (cancelByUser != null) { msg += " by " + cancelByUser; cancelByUser = null; } throw new ConnectionTerminatedException(msg); } } }; } protected void topLevel() throws IOException, Exception { logger.info("Connect from {}" + socket.getRemoteSocketAddress()); boolean startupComplete = false; try { while (running) { READ_MESSAGE.in(); PostgresMessages type; try { type = messenger.readMessage(startupComplete); } catch (ConnectionTerminatedException ex) { logError(ErrorLogLevel.DEBUG, "About to terminate", ex); notifyClient(QueryContext.NotificationLevel.WARNING, ex.getCode(), ex.getShortMessage()); stop(); continue; } finally { READ_MESSAGE.out(); } PROCESS_MESSAGE.in(); if (ignoreUntilSync) { if ((type != PostgresMessages.EOF_TYPE) && (type != PostgresMessages.SYNC_TYPE)) continue; ignoreUntilSync = false; } long startNsec = System.nanoTime(); try { switch (type) { case EOF_TYPE: // EOF stop(); break; case SYNC_TYPE: readyForQuery(); break; case STARTUP_MESSAGE_TYPE: startupComplete = processStartupMessage(); break; case PASSWORD_MESSAGE_TYPE: processPasswordMessage(); break; case QUERY_TYPE: processQuery(); break; case PARSE_TYPE: processParse(); break; case BIND_TYPE: processBind(); break; case DESCRIBE_TYPE: processDescribe(); break; case EXECUTE_TYPE: processExecute(); break; case FLUSH_TYPE: processFlush(); break; case CLOSE_TYPE: processClose(); break; case TERMINATE_TYPE: processTerminate(); break; } } catch (QueryCanceledException ex) { InvalidOperationException nex = ex; boolean forKill = false; if (cancelForKillReason != null) { nex = new ConnectionTerminatedException(cancelForKillReason); nex.initCause(ex); cancelForKillReason = null; forKill = true; } logError(ErrorLogLevel.INFO, "Query canceled", nex); String msg = nex.getShortMessage(); if (cancelByUser != null) { if (!forKill) msg = "Query canceled"; msg += " by " + cancelByUser; cancelByUser = null; } sendErrorResponse(type, nex, nex.getCode(), msg); if (forKill) stop(); } catch (ConnectionTerminatedException ex) { logError(ErrorLogLevel.DEBUG, "Query terminated self", ex); sendErrorResponse(type, ex, ex.getCode(), ex.getShortMessage()); stop(); } catch (InvalidOperationException ex) { logError(ErrorLogLevel.WARN, "Error in query", ex); sendErrorResponse(type, ex, ex.getCode(), ex.getShortMessage()); } catch (RollbackException ex) { QueryRollbackException qe = new QueryRollbackException(); qe.initCause(ex); logError(ErrorLogLevel.INFO, "Query rollback", qe); sendErrorResponse(type, qe, qe.getCode(), qe.getMessage()); } catch (Exception ex) { logError(ErrorLogLevel.WARN, "Unexpected error in query", ex); String message = (ex.getMessage() == null ? ex.getClass().toString() : ex.getMessage()); sendErrorResponse(type, ex, ErrorCode.UNEXPECTED_EXCEPTION, message); } finally { long stopNsec = System.nanoTime(); if (logger.isTraceEnabled()) { logger.trace("Executed {}: {} usec", type, (stopNsec - startNsec) / 1000); } } PROCESS_MESSAGE.out(); } } finally { if (transaction != null) { transaction.abort(); transaction = null; } server.removeConnection(sessionId); reqs.monitor().deregisterSessionMonitor(sessionMonitor); } } private enum ErrorLogLevel { WARN, INFO, DEBUG }; private void logError(ErrorLogLevel level, String msg, Exception ex) { if (reqs.config().testing()) { level = ErrorLogLevel.DEBUG; } switch (level) { case DEBUG: logger.debug(msg, ex); break; case INFO: logger.info(msg, ex); break; case WARN: default: logger.warn(msg, ex); break; } } protected void sendErrorResponse(PostgresMessages type, Exception exception, ErrorCode errorCode, String message) throws Exception { if (type.errorMode() == PostgresMessages.ErrorMode.NONE) throw exception; else { messenger.beginMessage(PostgresMessages.ERROR_RESPONSE_TYPE.code()); messenger.write('S'); messenger.writeString((type.errorMode() == PostgresMessages.ErrorMode.FATAL) ? "FATAL" : "ERROR"); messenger.write('C'); messenger.writeString(errorCode.getFormattedValue()); messenger.write('M'); messenger.writeString(message); if (exception instanceof BaseSQLException) { int pos = ((BaseSQLException)exception).getErrorPosition(); if (pos > 0) { messenger.write('P'); messenger.writeString(Integer.toString(pos)); } } messenger.write(0); messenger.sendMessage(true); } if (type.errorMode() == PostgresMessages.ErrorMode.EXTENDED) ignoreUntilSync = true; else readyForQuery(); } protected void readyForQuery() throws IOException { messenger.beginMessage(PostgresMessages.READY_FOR_QUERY_TYPE.code()); char mode = 'I'; // Idle if (isTransactionActive()) mode = isTransactionRollbackPending() ? 'E' : 'T'; messenger.writeByte(mode); messenger.sendMessage(true); } protected boolean processStartupMessage() throws IOException { int version = messenger.readInt(); switch (version) { case PostgresMessenger.VERSION_CANCEL: processCancelRequest(); return false; case PostgresMessenger.VERSION_SSL: processSSLMessage(); return false; default: this.version = version; logger.debug("Version {}.{}", (version >> 16), (version & 0xFFFF)); } Properties clientProperties = new Properties(server.getProperties()); while (true) { String param = messenger.readString(); if (param.length() == 0) break; String value = messenger.readString(); clientProperties.put(param, value); } logger.debug("Properties: {}", clientProperties); setProperties(clientProperties); session = reqs.sessionService().createSession(); // TODO: Not needed right now and not a convenient time to // encounter schema lock from long-running DDL. // But see comment in initParser(): what if we wanted to warn // or error when schema does not exist? //updateAIS(null); if (Boolean.parseBoolean(properties.getProperty("require_password", "false"))) { messenger.beginMessage(PostgresMessages.AUTHENTICATION_TYPE.code()); messenger.writeInt(PostgresMessenger.AUTHENTICATION_CLEAR_TEXT); messenger.sendMessage(true); } else { String user = properties.getProperty("user"); logger.info("Login {}", user); authenticationOkay(user); } return true; } protected void processCancelRequest() throws IOException { int sessionId = messenger.readInt(); int secret = messenger.readInt(); PostgresServerConnection connection = server.getConnection(sessionId); if ((connection != null) && (secret == connection.secret)) { connection.cancelQuery(null, null); } stop(); // That's all for this connection. } protected void processSSLMessage() throws IOException { OutputStream raw = messenger.getOutputStream(); if (System.getProperty("javax.net.ssl.keyStore") == null) { // JSSE doesn't have a keystore; TLSv1 handshake is gonna fail. Deny support. raw.write('N'); raw.flush(); } else { // Someone seems to have configured for SSL. Wrap the // socket and start server mode negotiation. Client should // then use SSL socket to start regular server protocol. raw.write('S'); raw.flush(); SSLSocketFactory sslFactory = (SSLSocketFactory)SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket)sslFactory.createSocket(socket, socket.getLocalAddress().toString(), socket.getLocalPort(), true); socket = sslSocket; createMessenger(); sslSocket.setUseClientMode(false); sslSocket.startHandshake(); } } protected void processPasswordMessage() throws IOException { String user = properties.getProperty("user"); String pass = messenger.readString(); logger.info("Login {}/{}", user, pass); authenticationOkay(user); } protected void authenticationOkay(String user) throws IOException { Properties status = new Properties(); // This is enough to make the JDBC driver happy. status.put("client_encoding", properties.getProperty("client_encoding", "UTF8")); status.put("server_encoding", messenger.getEncoding()); status.put("server_version", "8.4.7"); // Not sure what the min it'll accept is. status.put("session_authorization", user); status.put("DateStyle", "ISO, MDY"); { messenger.beginMessage(PostgresMessages.AUTHENTICATION_TYPE.code()); messenger.writeInt(PostgresMessenger.AUTHENTICATION_OK); messenger.sendMessage(); } for (String prop : status.stringPropertyNames()) { messenger.beginMessage(PostgresMessages.PARAMETER_STATUS_TYPE.code()); messenger.writeString(prop); messenger.writeString(status.getProperty(prop)); messenger.sendMessage(); } { messenger.beginMessage(PostgresMessages.BACKEND_KEY_DATA_TYPE.code()); messenger.writeInt(sessionId); messenger.writeInt(secret); messenger.sendMessage(); } readyForQuery(); } protected void processQuery() throws IOException { long startTime = System.currentTimeMillis(); String sql = messenger.readString(); logger.info("Query: {}", sql); if (sql.length() == 0) { emptyQuery(); return; } sessionMonitor.startStatement(sql, startTime); PostgresQueryContext context = new PostgresQueryContext(this); updateAIS(context); PostgresStatement pstmt = null; if (statementCache != null) pstmt = statementCache.get(sql); if (pstmt == null) { for (PostgresStatementParser parser : unparsedGenerators) { // Try special recognition first; only allowed to turn // into one statement. pstmt = parser.parse(this, sql, null); if (pstmt != null) break; } } int rowsProcessed = 0; if (pstmt != null) { pstmt.sendDescription(context, false); rowsProcessed = executeStatement(pstmt, context, -1); } else { // Parse as a _list_ of statements and process each in turn. List<StatementNode> stmts; try { sessionMonitor.enterStage(MonitorStage.PARSE); stmts = parser.parseStatements(sql); } catch (SQLParserException ex) { throw new SQLParseException(ex); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } finally { sessionMonitor.leaveStage(); } for (StatementNode stmt : stmts) { GeneratedResult res = generateStatement(stmt, null, null); boolean success = false; ServerTransaction local = beforeExecute(res.statement); try { pstmt = generateStatementFinal(res, stmt, null, null); if ((statementCache != null) && (stmts.size() == 1)) statementCache.put(sql, pstmt); pstmt.sendDescription(context, false); rowsProcessed = executeStatement(pstmt, context, -1); success = true; } finally { afterExecute(pstmt, local, success); } } } readyForQuery(); sessionMonitor.endStatement(rowsProcessed); logger.debug("Query complete"); if (reqs.monitor().isQueryLogEnabled()) { reqs.monitor().logQuery(sessionMonitor); } } protected void processParse() throws IOException { String stmtName = messenger.readString(); String sql = messenger.readString(); short nparams = messenger.readShort(); int[] paramTypes = new int[nparams]; for (int i = 0; i < nparams; i++) paramTypes[i] = messenger.readInt(); sessionMonitor.startStatement(sql); logger.info("Parse: {}", sql); PostgresQueryContext context = new PostgresQueryContext(this); updateAIS(context); PostgresStatement pstmt = null; if (statementCache != null) pstmt = statementCache.get(sql); if (pstmt == null) { StatementNode stmt; List<ParameterNode> params; try { sessionMonitor.enterStage(MonitorStage.PARSE); stmt = parser.parseStatement(sql); params = parser.getParameterList(); } catch (SQLParserException ex) { throw new SQLParseException(ex); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } finally { sessionMonitor.leaveStage(); } GeneratedResult res = generateStatement(stmt, params, paramTypes); ServerTransaction local = beforeExecute(res.statement); boolean success = false; try { pstmt = generateStatementFinal(res, stmt, params, paramTypes); success = true; } finally { afterExecute(pstmt, local, success); } if (statementCache != null) statementCache.put(sql, pstmt); } preparedStatements.put(stmtName, pstmt); messenger.beginMessage(PostgresMessages.PARSE_COMPLETE_TYPE.code()); messenger.sendMessage(); } protected void processBind() throws IOException { String portalName = messenger.readString(); String stmtName = messenger.readString(); byte[][] params = null; boolean[] paramsBinary = null; { short nformats = messenger.readShort(); if (nformats > 0) { paramsBinary = new boolean[nformats]; for (int i = 0; i < nformats; i++) paramsBinary[i] = (messenger.readShort() == 1); } short nparams = messenger.readShort(); if (nparams > 0) { params = new byte[nparams][]; for (int i = 0; i < nparams; i++) { int len = messenger.readInt(); if (len < 0) continue; // Null byte[] param = new byte[len]; messenger.readFully(param, 0, len); params[i] = param; } } } boolean[] resultsBinary = null; boolean defaultResultsBinary = false; { short nresults = messenger.readShort(); if (nresults == 1) defaultResultsBinary = (messenger.readShort() == 1); else if (nresults > 0) { resultsBinary = new boolean[nresults]; for (int i = 0; i < nresults; i++) { resultsBinary[i] = (messenger.readShort() == 1); } defaultResultsBinary = resultsBinary[nresults-1]; } } PostgresStatement pstmt = preparedStatements.get(stmtName); PostgresBoundQueryContext bound = new PostgresBoundQueryContext(this, pstmt); if (params != null) { ServerValueDecoder decoder = new ServerValueDecoder(messenger.getEncoding()); PostgresType[] parameterTypes = null; boolean usePValues = false; if (pstmt instanceof PostgresBaseStatement) { PostgresDMLStatement dml = (PostgresDMLStatement)pstmt; parameterTypes = dml.getParameterTypes(); usePValues = dml.usesPValues(); } for (int i = 0; i < params.length; i++) { PostgresType pgType = null; if (parameterTypes != null) pgType = parameterTypes[i]; boolean binary = false; if ((paramsBinary != null) && (i < paramsBinary.length)) binary = paramsBinary[i]; if (usePValues) decoder.decodePValue(params[i], pgType, binary, bound, i); else decoder.decodeValue(params[i], pgType, binary, bound, i); } } bound.setColumnBinary(resultsBinary, defaultResultsBinary); boundPortals.put(portalName, bound); messenger.beginMessage(PostgresMessages.BIND_COMPLETE_TYPE.code()); messenger.sendMessage(); } protected void processDescribe() throws IOException{ byte source = messenger.readByte(); String name = messenger.readString(); PostgresStatement pstmt; PostgresQueryContext context; switch (source) { case (byte)'S': pstmt = preparedStatements.get(name); context = new PostgresQueryContext(this); break; case (byte)'P': { PostgresBoundQueryContext bound = boundPortals.get(name); pstmt = bound.getStatement(); context = bound; } break; default: throw new IOException("Unknown describe source: " + (char)source); } pstmt.sendDescription(context, true); } protected void processExecute() throws IOException { long startTime = System.currentTimeMillis(); String portalName = messenger.readString(); int maxrows = messenger.readInt(); PostgresBoundQueryContext context = boundPortals.get(portalName); PostgresStatement pstmt = context.getStatement(); logger.info("Execute: {}", pstmt); // TODO: save SQL in prepared statement and get it here. sessionMonitor.startStatement(null, startTime); int rowsProcessed = executeStatement(pstmt, context, maxrows); sessionMonitor.endStatement(rowsProcessed); logger.debug("Execute complete"); if (reqs.monitor().isQueryLogEnabled()) { reqs.monitor().logQuery(sessionMonitor); } } protected void processFlush() throws IOException { messenger.flush(); } protected void processClose() throws IOException { byte source = messenger.readByte(); String name = messenger.readString(); PostgresStatement pstmt; switch (source) { case (byte)'S': pstmt = preparedStatements.remove(name); break; case (byte)'P': pstmt = boundPortals.remove(name).getStatement(); break; default: throw new IOException("Unknown describe source: " + (char)source); } messenger.beginMessage(PostgresMessages.CLOSE_COMPLETE_TYPE.code()); messenger.sendMessage(); } protected void processTerminate() throws IOException { stop(); } public void cancelQuery(String forKillReason, String byUser) { this.cancelForKillReason = forKillReason; this.cancelByUser = byUser; // A running query checks session state for query cancelation during Cursor.next() calls. If the // query is stuck in a blocking operation, then thread interruption should unstick it. Either way, // the query should eventually throw QueryCanceledException which will be caught by topLevel(). if (session != null) { session.cancelCurrentQuery(true); } if (thread != null) { thread.interrupt(); } } public void waitAndStop() { // Wait a little bit for the connection to stop itself. for (int i = 0; i < 5; i++) { if (!running) return; try { Thread.sleep(50); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); break; } } // Force stop. stop(); } // When the AIS changes, throw everything away, since it might // point to obsolete objects. protected void updateAIS(PostgresQueryContext context) { boolean locked = false; try { if (context != null) { // If there is long-running DDL like creating an index, this is almost // always where other queries will lock. context.lock(DXLFunction.UNSPECIFIED_DDL_READ); locked = true; } DDLFunctions ddl = reqs.dxl().ddlFunctions(); AkibanInformationSchema newAIS = ddl.getAIS(session); if ((ais != null) && (ais.getGeneration() == newAIS.getGeneration())) return; // Unchanged. ais = newAIS; } finally { if (locked) { context.unlock(DXLFunction.UNSPECIFIED_DDL_READ); } } rebuildCompiler(); } protected void rebuildCompiler() { Object parserKeys = initParser(); PostgresOperatorCompiler compiler; String format = getProperty("OutputFormat", "table"); if (format.equals("table")) outputFormat = OutputFormat.TABLE; else if (format.equals("json")) outputFormat = OutputFormat.JSON; else if (format.equals("json_with_meta_data")) outputFormat = OutputFormat.JSON_WITH_META_DATA; else throw new InvalidParameterValueException(format); switch (outputFormat) { case TABLE: default: compiler = PostgresOperatorCompiler.create(this); break; case JSON: case JSON_WITH_META_DATA: compiler = PostgresJsonCompiler.create(this); break; } initAdapters(compiler); unparsedGenerators = new PostgresStatementParser[] { new PostgresEmulatedMetaDataStatementParser(this) }; parsedGenerators = new PostgresStatementGenerator[] { // Can be ordered by frequency so long as there is no overlap. compiler, new PostgresDDLStatementGenerator(this), new PostgresSessionStatementGenerator(this), new PostgresCallStatementGenerator(this), new PostgresExplainStatementGenerator(this), new PostgresServerStatementGenerator(this) }; statementCache = getStatementCache(); } protected ServerStatementCache<PostgresStatement> getStatementCache() { // Statement cache depends on some connection settings. return server.getStatementCache(Arrays.asList(parser.getFeatures(), defaultSchemaName, getProperty("OutputFormat", "table"), getBooleanProperty("cbo", true), getBooleanProperty("newtypes", false)), ais.getGeneration()); } @Override protected void sessionChanged() { if (parsedGenerators == null) return; // setAttribute() from generator's ctor. for (PostgresStatementParser parser : unparsedGenerators) { parser.sessionChanged(this); } for (PostgresStatementGenerator generator : parsedGenerators) { generator.sessionChanged(this); } statementCache = getStatementCache(); } protected GeneratedResult generateStatement(StatementNode stmt, List<ParameterNode> params, int[] paramTypes) { try { sessionMonitor.enterStage(MonitorStage.OPTIMIZE); for (PostgresStatementGenerator generator : parsedGenerators) { PostgresStatement pstmt = generator.generateInitial(this, stmt, params, paramTypes); if (pstmt != null) return new GeneratedResult(generator, pstmt); } } finally { sessionMonitor.leaveStage(); } throw new UnsupportedSQLException ("", stmt); } protected PostgresStatement generateStatementFinal(GeneratedResult generated, StatementNode stmt, List<ParameterNode> params, int[] paramTypes) { try { sessionMonitor.enterStage(MonitorStage.OPTIMIZE); return generated.generator.generateFinal(this, generated.statement, stmt, params, paramTypes); } finally { sessionMonitor.leaveStage(); } } protected int executeStatement(PostgresStatement pstmt, PostgresQueryContext context, int maxrows) throws IOException { PersistitAdapter persistitAdapter = null; if ((transaction != null) && // As opposed to WRITE_STEP_ISOLATED. (pstmt.getTransactionMode() == PostgresStatement.TransactionMode.WRITE)) { persistitAdapter = (PersistitAdapter)adapters.get(StoreAdapter.AdapterType.PERSISTIT_ADAPTER); persistitAdapter.withStepChanging(false); } ServerTransaction localTransaction = beforeExecute(pstmt); int rowsProcessed = 0; boolean success = false; try { session.setTimeoutAfterSeconds(getQueryTimeoutSec()); sessionMonitor.enterStage(MonitorStage.EXECUTE); rowsProcessed = pstmt.execute(context, maxrows); success = true; } finally { afterExecute(pstmt, localTransaction, success); if (persistitAdapter != null) persistitAdapter.withStepChanging(true); // Keep conservative default. sessionMonitor.leaveStage(); } return rowsProcessed; } protected void emptyQuery() throws IOException { messenger.beginMessage(PostgresMessages.EMPTY_QUERY_RESPONSE_TYPE.code()); messenger.sendMessage(); readyForQuery(); } @Override public Date currentTime() { Date override = server.getOverrideCurrentTime(); if (override != null) return override; else return super.currentTime(); } @Override public void notifyClient(QueryContext.NotificationLevel level, ErrorCode errorCode, String message) throws IOException { if (shouldNotify(level)) { Object state = messenger.suspendMessage(); messenger.beginMessage(PostgresMessages.NOTICE_RESPONSE_TYPE.code()); messenger.write('S'); switch (level) { case WARNING: messenger.writeString("WARN"); break; case INFO: messenger.writeString("INFO"); break; case DEBUG: messenger.writeString("DEBUG"); break; // Other possibilities are "NOTICE" and "LOG". } if (errorCode != null) { messenger.write('C'); messenger.writeString(errorCode.getFormattedValue()); } messenger.write('M'); messenger.writeString(message); messenger.write(0); messenger.sendMessage(true); messenger.resumeMessage(state); } } /* PostgresServerSession */ @Override public int getVersion() { return version; } @Override public PostgresMessenger getMessenger() { return messenger; } @Override public OutputFormat getOutputFormat() { return outputFormat; } @Override protected boolean propertySet(String key, String value) { if ("client_encoding".equals(key)) { messenger.setEncoding(value); return true; } if ("OutputFormat".equals(key) || "parserInfixBit".equals(key) || "parserInfixLogical".equals(key) || "parserDoubleQuoted".equals(key) || "columnAsFunc".equals(key) || "cbo".equals(key) || "newtypes".equals(key)) { if (parsedGenerators != null) rebuildCompiler(); return true; } return super.propertySet(key, value); } public PostgresServer getServer() { return server; } }
package com.ams.controller.admin; import com.alibaba.fastjson.JSONObject; import com.ams.entities.admin.*; import com.ams.service.admin.ProductService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; @Controller @RequestMapping(value = "/webservice") public class ServiceController extends BaseController { private static Logger logger = Logger.getLogger(ServiceController.class); @Autowired ProductService productService; @RequestMapping(value = "rest/save") public @ResponseBody ServiceResponse add(HttpServletRequest request, HttpServletResponse response, ModelMap model,@RequestBody ProductInfoTemp productInfo) { logger.debug(productInfo); ServiceResponse res = new ServiceResponse(); try { productInfo.setStatus("2"); //productService.saveProduct(productInfo); }catch (Exception e) { logger.error("", e); res.setCode(500); res.setMessage(e.getMessage()); } return res; } @RequestMapping(value = "rest/list") public @ResponseBody ServiceResponse list(HttpServletRequest request, HttpServletResponse response, ModelMap model, ServiceRequest serviceRequest) { logger.info(serviceRequest); ServiceResponse res = new ServiceResponse(); try { List<ProductInfo> list = productService.serviceQueryList(serviceRequest); logger.info(list.get(0)); res.setData(list); }catch (Exception e){ logger.error("",e); res.setCode(500); res.setMessage(e.getMessage()); } return res; } }
package com.behase.relumin.service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import com.behase.relumin.Constants; import com.behase.relumin.exception.ApiException; import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.behase.relumin.util.JedisUtils; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class NodeServiceImpl implements NodeService { private static final int OFFSET = 9999; @Autowired JedisPool dataStoreJedisPool; @Autowired ObjectMapper mapper; @Value("${redis.prefixKey}") private String redisPrefixKey; @Override public Map<String, String> getStaticsInfo(ClusterNode clusterNode) { try (Jedis jedis = JedisUtils.getJedisByHostAndPort(clusterNode.getHostAndPort())) { Map<String, String> result = JedisUtils.parseInfoResult(jedis.info()); return result; } } @SuppressWarnings("unchecked") @Override public Map<String, List<List<Object>>> getStaticsInfoHistory(String clusterName, String nodeId, List<String> fields, long start, long end) { if (end < start) { throw new InvalidParameterException("End time must be larger than start time."); } List<Map<String, String>> rangeResult = Lists.newArrayList(); int startIndex = 0; int endIndex = OFFSET; boolean validStart = true; boolean validEnd = true; while (true && (validStart || validEnd)) { log.debug("statics loop. startIndex : {}", startIndex); List<Map<String, String>> staticsList = getStaticsInfoHistoryFromRedis(clusterName, nodeId, fields, startIndex, endIndex); if (staticsList == null || staticsList.isEmpty()) { break; } for (Map<String, String> statics : staticsList) { long timestamp = Long.valueOf(statics.get("_timestamp")); if (timestamp > end) { validEnd = false; } else if (timestamp < start) { validStart = false; } else { rangeResult.add(statics); } } startIndex += OFFSET + 1; endIndex += OFFSET + 1; } Collections.reverse(rangeResult); long durationMillis = end - start; long thresholdMillis; if (durationMillis <= (long)1 * 24 * 60 * 60 * 1000) { // 1day thresholdMillis = Long.MIN_VALUE; } else if (durationMillis <= (long)7 * 24 * 60 * 60 * 1000) { // 7days thresholdMillis = 5 * 60 * 1000; } else if (durationMillis <= (long)30 * 24 * 60 * 60 * 1000) { // 30 days thresholdMillis = 30 * 60 * 1000; } else if (durationMillis <= (long)60 * 24 * 60 * 60 * 1000) { // 60 days thresholdMillis = 1 * 60 * 60 * 1000; } else if (durationMillis <= (long)120 * 24 * 60 * 60 * 1000) { // 120 days thresholdMillis = 2 * 60 * 60 * 1000; } else if (durationMillis <= (long)120 * 24 * 60 * 60 * 1000) { // 180 days thresholdMillis = 6 * 60 * 60 * 1000; } else if (durationMillis <= (long)365 * 24 * 60 * 60 * 1000) { // 1 years thresholdMillis = 12 * 60 * 60 * 1000; } else { thresholdMillis = 24 * 60 * 60 * 1000; } Map<String, List<List<Object>>> averageResult = Maps.newConcurrentMap(); fields.parallelStream().forEach(field -> { List<List<Object>> fieldAverageResult = Lists.newArrayList(); long preTimestamp = 0; BigDecimal sum = new BigDecimal(0); long sumTs = 0; int count = 0; for (Map<String, String> val : rangeResult) { long timestamp = Long.valueOf(val.get("_timestamp")); BigDecimal value; try { value = new BigDecimal(val.get(field)); } catch (Exception e) { break; } if (preTimestamp > timestamp) { continue; } if (preTimestamp == 0) { preTimestamp = timestamp; sum = value; sumTs = timestamp; count = 1; continue; } long curDurationMillis = timestamp - preTimestamp; if (curDurationMillis < thresholdMillis) { log.debug("Within threshold. value={}, curDurationSecs={}, thresholdSecs={}", value, curDurationMillis / 1000, thresholdMillis); sum = sum.add(value); sumTs += timestamp; count++; } else { BigDecimal averageValue = new BigDecimal(0); if (count != 0) { averageValue = sum.divide(new BigDecimal(count), 4, BigDecimal.ROUND_HALF_UP); } long averageTs = 0; if (count != 0) { averageTs = sumTs / count; } log.debug("ESCAPE threshold. averageValue={}, averageTs={}, sum={}, sumTs={}, sumCount={}", averageValue, averageTs, sum, sumTs, count); fieldAverageResult.add(Lists.newArrayList(averageTs, averageValue.doubleValue())); preTimestamp = 0; sum = new BigDecimal(0); sumTs = 0; count = 0; } } if (preTimestamp != 0) { BigDecimal averageValue = new BigDecimal(0); if (count != 0) { averageValue = sum.divide(new BigDecimal(count), 4, BigDecimal.ROUND_HALF_UP); } long averageTs = 0; if (count != 0) { averageTs = sumTs / count; } log.debug("ESCAPE threshold. averageValue={}, averageTs={}, sum={}, sumTs={}, sumCount={}", averageValue, averageTs, sum, sumTs, count); fieldAverageResult.add(Lists.newArrayList(averageTs, averageValue.doubleValue())); } averageResult.put(field, fieldAverageResult); }); return averageResult; } @Override public void shutdown(String hostAndPort) { try (Jedis jedis = JedisUtils.getJedisByHostAndPort(hostAndPort)) { try { jedis.ping(); } catch (Exception e) { log.warn("redis error.", e); throw new ApiException(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Failed to connect to Redis Cluster(%s). Please confirm.", hostAndPort), HttpStatus.BAD_REQUEST); } jedis.shutdown(); } } private List<Map<String, String>> getStaticsInfoHistoryFromRedis(String clusterName, String nodeId, List<String> fields, long startIndex, long endIndex) { List<Map<String, String>> result = Lists.newArrayList(); try (Jedis jedis = dataStoreJedisPool.getResource()) { List<String> rawResult = jedis.lrange(Constants.getNodeStaticsInfoRedisKey(redisPrefixKey, clusterName, nodeId), startIndex, endIndex); rawResult.forEach(v -> { try { Map<String, String> map = mapper.readValue(v, new TypeReference<Map<String, Object>>() { }); result.add(map); } catch (Exception e) { log.warn("Failed to parse json.", e); } }); } return filterGetStaticsInfoHistory(result, fields); } private List<Map<String, String>> filterGetStaticsInfoHistory(List<Map<String, String>> staticsInfos, List<String> fields) { List<String> copyedFields = new ArrayList<String>(fields); copyedFields.add("_timestamp"); return staticsInfos.stream().map(v -> { Map<String, String> item = Maps.newHashMap(); copyedFields.forEach(field -> { item.put(field, v.get(field)); }); return item; }).collect(Collectors.toList()); } }
package com.ecwid.consul.v1.agent.model; import com.google.gson.annotations.SerializedName; import java.util.List; import java.util.Map; /** * @author Vasily Vasilkov (vgv@ecwid.com) * @author Spencer Gibb (spencer@gibb.us) */ public class NewService { public static class Check { @SerializedName("Script") private String script; @SerializedName("Interval") private String interval; @SerializedName("TTL") private String ttl; @SerializedName("HTTP") private String http; @SerializedName("Method") private String method; @SerializedName("Header") private Map<String, List<String>> header; @SerializedName("TCP") private String tcp; @SerializedName("Timeout") private String timeout; @SerializedName("DeregisterCriticalServiceAfter") private String deregisterCriticalServiceAfter; @SerializedName("TLSSkipVerify") private Boolean tlsSkipVerify; @SerializedName("Status") private String status; public String getScript() { return script; } public void setScript(String script) { this.script = script; } public String getInterval() { return interval; } public void setInterval(String interval) { this.interval = interval; } public String getTtl() { return ttl; } public void setTtl(String ttl) { this.ttl = ttl; } public String getHttp() { return http; } public void setHttp(String http) { this.http = http; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Map<String, List<String>> getHeader() { return header; } public void setHeader(Map<String, List<String>> header) { this.header = header; } public String getTcp() { return tcp; } public void setTcp(String tcp) { this.tcp = tcp; } public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } public String getDeregisterCriticalServiceAfter() { return deregisterCriticalServiceAfter; } public void setDeregisterCriticalServiceAfter(String deregisterCriticalServiceAfter) { this.deregisterCriticalServiceAfter = deregisterCriticalServiceAfter; } public Boolean getTlsSkipVerify() { return tlsSkipVerify; } public void setTlsSkipVerify(Boolean tlsSkipVerify) { this.tlsSkipVerify = tlsSkipVerify; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "Check{" + "script='" + script + '\'' + ", interval='" + interval + '\'' + ", ttl='" + ttl + '\'' + ", http='" + http + '\'' + ", method='" + method + '\'' + ", header=" + header + ", tcp='" + tcp + '\'' + ", timeout='" + timeout + '\'' + ", deregisterCriticalServiceAfter='" + deregisterCriticalServiceAfter + '\'' + ", tlsSkipVerify=" + tlsSkipVerify + ", status='" + status + '\'' + '}'; } } @SerializedName("ID") private String id; @SerializedName("Name") private String name; @SerializedName("Tags") private List<String> tags; @SerializedName("Address") private String address; @SerializedName("Meta") private Map<String, String> meta; @SerializedName("Port") private Integer port; @SerializedName("EnableTagOverride") private Boolean enableTagOverride; @SerializedName("Check") private Check check; @SerializedName("Checks") private List<Check> checks; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Map<String, String> getMeta() { return meta; } public void setMeta(Map<String, String> meta) { this.meta = meta; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public Boolean getEnableTagOverride() { return enableTagOverride; } public void setEnableTagOverride(Boolean enableTagOverride) { this.enableTagOverride = enableTagOverride; } public Check getCheck() { return check; } public void setCheck(Check check) { this.check = check; } public List<Check> getChecks() { return checks; } public void setChecks(List<Check> checks) { this.checks = checks; } @Override public String toString() { return "NewService{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", tags=" + tags + ", address='" + address + '\'' + ", meta=" + meta + ", port=" + port + ", enableTagOverride=" + enableTagOverride + ", check=" + check + ", checks=" + checks + '}'; } }
package com.github.laboo.lwes.websocketserver; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.cli.*; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpointConfig; import org.glassfish.tyrus.server.Server; import org.lwes.emitter.MulticastEventEmitter; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.*; public class Main { public static int DEFAULT_PORT = 8887; private Server server; private CommandLine cl; private Thread t; private static int port = DEFAULT_PORT; private static Options options; public Main(int port) { System.out.println("help"); this.port = port; // TODO wtf is this map??? this.server = new Server("localhost", port, "/", new HashMap<String, Object>(), LwesWebSocketEndpoint.class); System.out.println("created"); } public Main(int port, CommandLine cl) { this(port); this.cl = cl; } public void start() throws DeploymentException { System.out.println("starting"); this.server.start(); } public void stop() { this.server.stop(); } public static CommandLine parseArgs(String[] args) throws org.apache.commons.cli.ParseException { options = new Options(); Option help = Option.builder("h") .required(false) .desc("Show help.") .longOpt("help") .build(); Option emit = Option.builder("e") .required(false) .desc("Emit events for testing purposes (false)") .longOpt("emit") .build(); Option port = Option.builder("p") .required(false) .hasArg() .type(Integer.class) .desc("TCP port to listen on for WebSocket connections (8887)") .longOpt("port") .build(); Option level = Option.builder("l") .required(false) .hasArg() .desc("Log level: trace, debug, info, warn, or error (warn)") .longOpt("log-level") .build(); Option mbs = Option.builder("m") .required(false) .hasArg() .desc("Log rollover MB trigger (5)") .longOpt("log-mbs") .build(); options.addOption(help); options.addOption(emit); options.addOption(port); options.addOption(level); options.addOption(mbs); // TODO log pattern DefaultParser parser = new DefaultParser(); return parser.parse(options, args); } public static void main(String[] args) throws UnknownHostException, org.apache.commons.cli.ParseException, DeploymentException { CommandLine cl = parseArgs(args); if (cl.hasOption("h")) { HelpFormatter formater = new HelpFormatter(); formater.printHelp("Main", options); return; } String port = cl.getOptionValue("port", String.valueOf(DEFAULT_PORT)); new Main(Integer.parseInt(port),cl).go(); } ExecutorService executor = Executors.newFixedThreadPool(5); public void go() throws org.apache.commons.cli.ParseException, DeploymentException { String mbs = cl.getOptionValue('m', String.valueOf(Log.DEFAULT_ROLLOVER_MBS)); Logger log = Log.getLogger(Integer.parseInt(mbs), Log.DEFAULT_PATTERN); String levelStr = this.cl.getOptionValue("l", Level.WARN.toString()); Level level = determineLogLevel(levelStr); log.setLevel(Level.ALL); log.info("Log level from here on out is " + level); log.setLevel(level); //Server server = new Server("localhost", 8025, "/websocket", LwesWebSocketEndpoint.class); this.start(); long count = 0; MulticastEventEmitter emitter = null; try { if (cl != null && cl.hasOption("e")) { emitter = new MulticastEventEmitter(); emitter.setESFFilePath("/path/to/esf/file"); emitter.setMulticastAddress(InetAddress.getByName("224.0.0.69")); emitter.setMulticastPort(9191); emitter.initialize(); } while (!Thread.currentThread().isInterrupted()) { if (cl != null && cl.hasOption("e")) { org.lwes.Event e = null; if (count % 2 == 0) { e = emitter.createEvent("Click", false); e.setString("url", "http: } else if (count % 3 == 0) { e = emitter.createEvent("Search", false); e.setString("term", "the thing I'm searching for"); e.setDouble("lat", 51.5033630); e.setDouble("lon", -0.1276250); } else { e = emitter.createEvent("Ad", false); e.setString("text", "Buy my product"); } e.setInt64("count", count++); emitter.emit(e); } Thread.sleep(1000); } } catch (IOException ioe) { log.error(ioe.toString()); } catch (InterruptedException ie) { log.info("Interrupted. Quitting."); } this.stop(); } private Level determineLogLevel(String levelStr) throws ParseException { if (levelStr.equalsIgnoreCase("TRACE")) { return Level.TRACE; } else if (levelStr.equalsIgnoreCase("DEBUG")) { return Level.DEBUG; } else if (levelStr.equalsIgnoreCase("INFO")) { return Level.INFO; } else if (levelStr.equalsIgnoreCase("WARN")) { return Level.WARN; } else if (levelStr.equalsIgnoreCase("ERROR")) { return Level.ERROR; } else { throw new ParseException("Level [" + levelStr + "] not valid." + " Choices are trace, debug, info, warn and error"); } } }
package com.github.piotr_rusin.yule.domain; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Version; import javax.validation.constraints.NotNull; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import org.hibernate.validator.constraints.NotBlank; import com.github.piotr_rusin.yule.validation.ExistingArticleConstraint; import com.github.piotr_rusin.yule.validation.StatusConstraintsFulfilled; /** * A class representing blog articles. * * @author Piotr Rusin <piotr.rusin88@gmail.com> */ @Entity @EntityListeners(ArticleListener.class) @Table(name = "articles") @StatusConstraintsFulfilled public class Article { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotBlank private String title; private String slug; private String introduction; private String content; @Column(name = "creation_date") @CreationTimestamp private Instant creationDate; @Column(name = "publication_date") private Instant publicationDate; @NotNull @Enumerated(EnumType.STRING) private ArticleStatus status = ArticleStatus.DRAFT; @Column(name = "modification_date") @UpdateTimestamp private Instant modificationDate; @Version private int version; @Column(name = "is_blog_post") private boolean post = true; protected Article() { } public Article(String title, String content) { this.title = title; this.content = content; } /** * Create a new article as a copy of an existing one. * * @param article is an article to copy */ public Article(Article article) { this.title = article.title; this.content = article.content; this.creationDate = article.creationDate; this.id = article.id; this.modificationDate = article.modificationDate; this.post = article.post; this.publicationDate = article.publicationDate; this.slug = article.slug; this.status = article.status; this.version = article.version; this.introduction = article.introduction; } public int getId() { return id; } public String getTitle() { return title; } /** * Set the title of the article. * * @param title * is the value to be set. It can't be null or empty. */ public void setTitle(String title) { this.title = title; } /** * Get the current value representing the article in URL addresses. * * @return the value, either a custom one or one generated by * {@link ArticleListener#makeSureHasSlug(Article) a * pre-persist and pre-update event handler} * @see #setSlug(String) */ public String getSlug() { return slug; } /** * Set a custom value representing the article in URL addresses. * * @param slug * is a value to be set as a slug. If it's null, and no * other value will be set before saving the article in * the database, a value based on the title at the time * of persist or update operation will be generated and * set instead. * @see ArticleListener#makeSureHasSlug(Article) */ public void setSlug(String slug) { this.slug = slug; } /** * Get a value used as an introduction to the article * * @return the custom introduction value, if set, otherwise a value * derived from the current content. If the content is not * null and has a <!--more--> tag, the part of the content * before the tag will be returned, otherwise the whole * content will. */ public String getIntroduction() { if (introduction != null) return introduction; if (content == null) return null; return content.split("<!--more } /** * Set a custom value to be used as an introduction to the article. * * @param value * is the value to be set * @see #getIntroduction() */ public void setIntroduction(String value) { introduction = value; } public String getContent() { return content; } /** * Set the content of the article. * * @param content * is a value to be set as the content. Using an invalid * value will result in leaving the article in an invalid * state. The choice of a correct value depends on * {@link Article#getStatus() the current status} of the * article. * @see ArticleStatus * @see StatusConstraintsFulfilled */ public void setContent(String content) { this.content = content; } public Instant getCreationDate() { return creationDate; } public Instant getPublicationDate() { return publicationDate; } /** * Set the publication date of the article * * @param publicationDate * is a publication date to be set. Using an incorrect * value will result in leaving the article object in an * invalid state. The choice of a correct value depends * on {@link Article#getStatus() the current status} of * the article. * @see ArticleStatus * @see StatusConstraintsFulfilled */ public void setPublicationDate(Instant publicationDate) { if (publicationDate != null) publicationDate = publicationDate.truncatedTo(ChronoUnit.MINUTES); this.publicationDate = publicationDate; } /** * Get the status of the article. * * @return the current status. * @see ArticleStatus */ public ArticleStatus getStatus() { return status; } /** * Set the status of the article * <p> * The status object may provide some additional constraints for its * owner, so setting it may leave the article in an invalid state. * * @param status * is a status value to be set * @see ArticleStatus * @see StatusConstraintsFulfilled */ public void setStatus(ArticleStatus status) { this.status = status; } public boolean isScheduledForPublication() { return status == ArticleStatus.SCHEDULED_FOR_PUBLICATION; } /** * Get status constraints violated by this article. * * @return a List containing all status constraints provided by the * status object of this article that are not fulfilled by * this article. */ public List<ExistingArticleConstraint> getViolatedStatusConstraints() { if (status == null) return Collections.emptyList(); return status.constraints .stream() .filter(c -> !c.isFulfilledFor(this)) .collect(Collectors.toList()); } public Instant getModificationDate() { return modificationDate; } /** * Get the version number of the article. * * @return a version number used by optimistic locking mechanism. */ public int getVersion() { return version; } /** * Check if the article is also a blog post. * <p> * All published articles on a blog are publicly accessible through * their URL addresses. * <p> * All articles that are also blog posts are additionally listed on * one of the pages of a blog, in reverse chronological order. * * @return true if the article is a blog post */ public boolean isPost() { return post; } /** * Set a value marking the article as a blog post. * * @param post * is true if the article is to become a blog post, false * otherwise */ public void setPost(boolean post) { this.post = post; } @Override public String toString() { return "Article [" + (title != null ? "title=" + title + ", " : "") + (creationDate != null ? "creationDate=" + creationDate + ", " : "") + (publicationDate != null ? "publicationDate=" + publicationDate + ", " : "") + (status != null ? "status=" + status + ", " : "") + "post=" + post + "]"; } }
package com.gruppe27.fellesprosjekt.common; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryonet.EndPoint; import com.gruppe27.fellesprosjekt.common.messages.*; import com.gruppe27.fellesprosjekt.common.serializers.LocalDateSerializer; import com.gruppe27.fellesprosjekt.common.serializers.LocalTimeSerializer; import java.time.LocalDate; import java.time.LocalTime; import java.util.HashSet; public class Network { public static final int PORT = 5000; public static void register(EndPoint endPoint) { Kryo kryo = endPoint.getKryo(); // -- COMMON -- kryo.register(Event.class); kryo.register(Group.class); kryo.register(HashSet.class); kryo.register(LocalDate.class, new LocalDateSerializer()); kryo.register(LocalTime.class, new LocalTimeSerializer()); kryo.register(Room.class); kryo.register(String.class); kryo.register(User.class); // -- MESSAGES -- kryo.register(AuthCompleteMessage.class); kryo.register(AuthCompleteMessage.Command.class); kryo.register(AuthMessage.class); kryo.register(AuthMessage.Command.class); kryo.register(ErrorMessage.class); kryo.register(EventMessage.class); kryo.register(EventMessage.Command.class); kryo.register(GeneralMessage.class); kryo.register(GeneralMessage.Command.class); kryo.register(InviteMessage.class); kryo.register(InviteMessage.Command.class); kryo.register(ParticipantStatusMessage.class); kryo.register(ParticipantStatusMessage.Command.class); kryo.register(RoomMessage.class); kryo.register(RoomMessage.Command.class); kryo.register(RoomRequestMessage.class); kryo.register(RoomRequestMessage.Command.class); kryo.register(TestMessage.class); kryo.register(UserMessage.class); kryo.register(UserMessage.Command.class); } }
package com.hsjawanda.gaeobjectify.util; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.Future; import java.util.logging.Logger; import lombok.AccessLevel; import lombok.NonNull; import lombok.Setter; import lombok.Singular; import lombok.experimental.Accessors; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.RetryOptions; import com.google.appengine.api.taskqueue.TaskHandle; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.common.base.CaseFormat; import com.google.common.collect.Range; /** * @author Harshdeep Jawanda <hsjawanda@gmail.com> * */ @Setter @Accessors(chain = true) public class TaskConfig<T> { @SuppressWarnings("unused") private static Logger LOG = Logger.getLogger(TaskConfig.class .getName()); @lombok.NonNull @Setter(AccessLevel.PRIVATE) private Class<T> taskClass; private String nameSuffix; private String queueName; private String host; private RetryOptions retryOptions; private long delayMillis; private boolean addTimestamp; private boolean useAutoNaming; @Singular() @Setter(AccessLevel.PRIVATE) private Map<String, String> strParams; @Singular @Setter(AccessLevel.PRIVATE) private Map<String, byte[]> byteParams; public static final Range<Long> DELAY_RANGE = Range.closed(1L, 60 * 60 * 1000L); public static final String MAPPING = Config.get("tasks.mapping").or("/task"); protected static final SimpleDateFormat TASK_DATE = new SimpleDateFormat( "yyyy-MM-dd_HH-mm-ss_SSS"); static { TasksHelper.TASK_DATE.setTimeZone(TimeZone.getTimeZone("IST")); } // private TaskConfig() {} public static <T> TaskConfig<T> create(@NonNull Class<T> cls) { final boolean useAutoNaming = false, addTimestamp = true; final String nameSuffix = null, queueName = null; TaskConfig<T> config = new TaskConfig<T>().setTaskClass(cls).setNameSuffix(nameSuffix) .setQueueName(queueName).setDelayMillis(500).setAddTimestamp(addTimestamp) .setUseAutoNaming(useAutoNaming).setStrParams(new HashMap<String, String>(2)) .setByteParams(new HashMap<String, byte[]>(1)); return config; } public TaskConfig<T> strParam(String key, String value) { if (key != null && null != value) { this.strParams.put(key, value); } return this; } public TaskConfig<T> byteParam(String key, byte[] value) { if (null != key && null != value) { this.byteParams.put(key, value); } return this; } private Future<TaskHandle> addToQueue(boolean async) throws IllegalArgumentException { Queue q = null; if (null == this.queueName) { q = QueueFactory.getDefaultQueue(); } else { q = QueueFactory.getQueue(this.queueName); } checkArgument(null != q, "Couldn't find a queue with name '" + this.queueName + "'."); String normalizedTaskName = normalizedTaskName(); TaskOptions taskOptions = TaskOptions.Builder.withUrl(taskUrl(normalizedTaskName)); if (null != this.retryOptions) { taskOptions = taskOptions.retryOptions(this.retryOptions); } if (null != this.host) { taskOptions = taskOptions.header("Host", this.host); } if (!this.useAutoNaming) { StringBuilder taskName = new StringBuilder(50).append(normalizedTaskName); if (isNotBlank(this.nameSuffix)) { taskName.append('_').append(defaultString(this.nameSuffix)); } if (this.addTimestamp) { TasksHelper.TASK_DATE.setTimeZone(Constants.IST); taskName.append('_').append(TasksHelper.TASK_DATE.format(new Date())); } taskOptions = taskOptions.taskName(taskName.toString()); } if (null != this.strParams) { for (String key : this.strParams.keySet()) { taskOptions = taskOptions.param(key, this.strParams.get(key)); } } if (null != this.byteParams) { for (String key : this.byteParams.keySet()) { taskOptions = taskOptions.param(key, this.byteParams.get(key)); } } if (DELAY_RANGE.contains(this.delayMillis)) { taskOptions = taskOptions.countdownMillis(this.delayMillis); } if (async) return q.addAsync(taskOptions); else { q.add(taskOptions); } return null; } public void addToQueue() { addToQueue(false); } public Future<TaskHandle> addToQueueAsync() { return addToQueue(true); } private String normalizedTaskName() { return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, this.taskClass.getSimpleName()); } private static String taskUrl(String normalizedName) { return Constants.pathJoiner.join(MAPPING, normalizedName); } }
package org.openlca.app.navigation; import java.util.Collection; import java.util.LinkedList; import java.util.Objects; import java.util.Optional; import java.util.Queue; import org.openlca.app.db.Database; import org.openlca.app.db.DatabaseDir; import org.openlca.app.navigation.elements.CategoryElement; import org.openlca.app.navigation.elements.INavigationElement; import org.openlca.app.navigation.elements.ModelElement; import org.openlca.app.navigation.elements.ModelTypeElement; import org.openlca.app.util.LibraryUtil; import org.openlca.core.database.CategoryDao; import org.openlca.core.database.Daos; import org.openlca.core.model.Category; import org.openlca.core.model.ImpactCategory; import org.openlca.core.model.ModelType; import org.openlca.core.model.Process; import org.openlca.core.model.RootEntity; import org.openlca.core.model.descriptors.RootDescriptor; public class CopyPaste { private enum Action { NONE, COPY, CUT } private static INavigationElement<?>[] cache = null; private static Action currentAction = Action.NONE; public static void copy(Collection<INavigationElement<?>> elements) { copy(elements.toArray(new INavigationElement<?>[0])); } public static void copy(INavigationElement<?>[] elements) { if (!isSupported(elements)) return; initialize(Action.COPY, elements); } public static void cut(Collection<INavigationElement<?>> elements) { cut(elements.toArray(new INavigationElement<?>[0])); } private static void cut(INavigationElement<?>[] elements) { if (!isSupported(elements)) return; initialize(Action.CUT, elements); var navigator = Navigator.getInstance(); for (var elem : cache) { elem.getParent().getChildren().remove(elem); if (navigator != null) { navigator.getCommonViewer().refresh(elem.getParent()); } } } public static boolean isSupported(INavigationElement<?> elem) { if (!(elem instanceof ModelElement) && !(elem instanceof CategoryElement)) return false; return elem.getLibrary().isEmpty(); } public static boolean isSupported(Collection<INavigationElement<?>> elements) { if (elements == null) return false; return isSupported(elements.toArray(new INavigationElement[0])); } public static boolean isSupported(INavigationElement<?>[] elements) { if (elements == null || elements.length == 0) return false; ModelType modelType = null; for (INavigationElement<?> element : elements) { if (!isSupported(element)) return false; ModelType currentModelType = getModelType(element); if (modelType == null) modelType = currentModelType; else if (currentModelType != modelType) return false; } return true; } private static ModelType getModelType(INavigationElement<?> e) { if (e instanceof ModelElement) return ((ModelElement) e).getContent().type; if (e instanceof CategoryElement) return ((CategoryElement) e).getContent().modelType; if (e instanceof ModelTypeElement) return ((ModelTypeElement) e).getContent(); return ModelType.UNKNOWN; } private static void initialize(Action action, INavigationElement<?>[] elements) { if (action == Action.CUT && currentAction == Action.CUT) { extendCache(elements); return; } if (currentAction == Action.CUT) restore(); cache = elements; currentAction = action; } private static void extendCache(INavigationElement<?>[] elements) { if (elements == null || elements.length == 0) return; if (cacheIsEmpty()) { cache = elements; return; } INavigationElement<?>[] newCache = new INavigationElement<?>[cache.length + elements.length]; System.arraycopy(cache, 0, newCache, 0, cache.length); System.arraycopy(elements, 0, newCache, cache.length, elements.length); cache = newCache; } private static void restore() { if (cacheIsEmpty()) return; for (INavigationElement<?> element : cache) { paste(element, element.getParent()); var modelRoot = Navigator.findElement(getModelType(element)); Navigator.refresh(modelRoot); } } public static void pasteTo(INavigationElement<?> categoryElement) { if (cacheIsEmpty()) return; if (!canPasteTo(categoryElement)) return; boolean started = false; try { Database.getWorkspaceIdUpdater().beginTransaction(); started = true; for (INavigationElement<?> element : cache) paste(element, categoryElement); } finally { if (started) Database.getWorkspaceIdUpdater().endTransaction(); clearCache(); } } public static void clearCache() { cache = null; currentAction = Action.NONE; INavigationElement<?> root = Navigator.findElement(Database.getActiveConfiguration()); Navigator.refresh(root); } public static boolean canMove(Collection<INavigationElement<?>> elements, INavigationElement<?> target) { return canMove(elements.toArray(new INavigationElement[0]), target); } private static boolean canMove(INavigationElement<?>[] elements, INavigationElement<?> target) { if (!isSupported(elements)) return false; if (!(target instanceof CategoryElement || target instanceof ModelTypeElement)) return false; return getModelType(target) == getModelType(elements[0]); } public static boolean canPasteTo(INavigationElement<?> element) { if (cacheIsEmpty()) return false; if (!(element instanceof CategoryElement || element instanceof ModelTypeElement)) return false; return getModelType(element) == getModelType(cache[0]); } private static void paste(INavigationElement<?> element, INavigationElement<?> category) { if (currentAction == Action.CUT) { if (element instanceof CategoryElement) move((CategoryElement) element, category); else if (element instanceof ModelElement) move((ModelElement) element, category); } else if (currentAction == Action.COPY) { if (element instanceof CategoryElement) { copy((CategoryElement) element, category); } else if (element instanceof ModelElement modElem) { copyTo(modElem, getCategory(category)); } } } private static Category getCategory(INavigationElement<?> element) { return element instanceof CategoryElement catElem ? catElem.getContent() : null; } private static void move(CategoryElement element, INavigationElement<?> categoryElement) { Category newParent = getCategory(categoryElement); Category oldParent = getCategory(element.getParent()); Category category = element.getContent(); if (Objects.equals(category, newParent)) return; if (isChild(newParent, category)) return; // do not create category cycles if (oldParent != null) oldParent.childCategories.remove(category); if (newParent != null) newParent.childCategories.add(category); category.category = newParent; CategoryDao dao = new CategoryDao(Database.get()); if (oldParent != null) { dao.update(oldParent); } if (newParent != null) { dao.update(newParent); } dao.update(category); } private static boolean isChild(Category category, Category parent) { if (category == null || parent == null) return false; Category p = category.category; while (p != null) { if (Objects.equals(p, parent)) return true; p = p.category; } return false; } private static void move(ModelElement element, INavigationElement<?> categoryElement) { RootDescriptor entity = element.getContent(); Category category = getCategory(categoryElement); Optional<Category> parent = Optional.ofNullable(category); Daos.root(Database.get(), entity.type).updateCategory(entity, parent); } private static void copy(CategoryElement element, INavigationElement<?> category) { Category parent = getCategory(category); Queue<CategoryElement> elements = new LinkedList<>(); elements.add(element); while (!elements.isEmpty()) { CategoryElement current = elements.poll(); Category catCopy = current.getContent().copy(); catCopy.name = catCopy.name + " (copy)"; catCopy.childCategories.clear(); catCopy.category = parent; if (parent == null) catCopy = Database.get().insert(catCopy); else { parent.childCategories.add(catCopy); parent = Database.get().update(parent); for (var child : parent.childCategories) { if (child.name.equals(catCopy.name)) { catCopy = child; break; } } } for (INavigationElement<?> child : current.getChildren()) if (child instanceof CategoryElement catElem) elements.add(catElem); else if (child instanceof ModelElement modElem) { copyTo(modElem, catCopy); } parent = catCopy; } } private static void copyTo(ModelElement e, Category category) { var d = e.getContent(); if (d == null) return; var dao = Daos.root(Database.get(), d.type); if (dao == null) return; var entity = dao.getForId(d.id); if (entity == null) return; if (entity.isFromLibrary()) { if (entity instanceof Process p) { LibraryUtil.fillExchangesOf(p); } else if (entity instanceof ImpactCategory i) { LibraryUtil.fillFactorsOf(i); } } var copy = (RootEntity) entity.copy(); copy.library = null; copy.category = category; copy.name = copy.name + " (copy)"; DatabaseDir.copyDir(entity, copy); Database.get().insert(copy); } public static boolean cacheIsEmpty() { return cache == null || cache.length == 0; } }
package com.lothrazar.terrariabuttons; import com.lothrazar.terrariabuttons.client.*; import com.lothrazar.terrariabuttons.util.Const; import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class EventHandler { @SuppressWarnings("unchecked") @SideOnly(Side.CLIENT) @SubscribeEvent public void onGuiPostInit(InitGuiEvent.Post event) { if(event.gui == null){return;}//probably doesnt ever happen //EntityPlayer p = Minecraft.getMinecraft().thePlayer; //TODO: get a blacklist//whitelist from config? /* //blacklist method if (event.gui instanceof GuiContainer && !(event.gui instanceof net.minecraft.client.gui.GuiMerchant) && !(event.gui instanceof net.minecraft.client.gui.GuiRepair) && !(event.gui instanceof net.minecraft.client.gui.inventory.GuiBeacon) && !(event.gui instanceof net.minecraft.client.gui.inventory.GuiInventory) //players inventory )*/ //System.out.println(event.gui.getClass().getName()); //whitelist method if(event.gui instanceof net.minecraft.client.gui.inventory.GuiChest || event.gui instanceof net.minecraft.client.gui.inventory.GuiDispenser || event.gui instanceof net.minecraft.client.gui.inventory.GuiBrewingStand || event.gui instanceof net.minecraft.client.gui.inventory.GuiBeacon || event.gui instanceof net.minecraft.client.gui.inventory.GuiCrafting || event.gui instanceof net.minecraft.client.gui.inventory.GuiFurnace || event.gui instanceof net.minecraft.client.gui.inventory.GuiScreenHorseInventory ) { int button_id = 256; // TODO: config for different locations - left right bottom top int x=0,y=0,padding = 6, ypadding = 24; System.out.println(ModConfig.position); if(ModConfig.position.equalsIgnoreCase(ModConfig.posLeft)) { x = padding; y = padding; } else if(ModConfig.position.equalsIgnoreCase(ModConfig.posRight)) { x = Minecraft.getMinecraft().displayWidth/2 - Const.btnWidth - padding;//align to right side y = padding; } //TODO: ... button does nothing for now event.buttonList.add(new GuiButtonLootAll(button_id++, x,y)); y += ypadding; event.buttonList.add(new GuiButtonDepositAll(button_id++, x,y)); y += ypadding; event.buttonList.add(new GuiButtonQuickStack(button_id++, x,y)); y += ypadding; event.buttonList.add(new GuiButtonRestock(button_id++, x,y)); //y += ypadding; //event.buttonList.add(new GuiButtonRename(button_id++, x,y)); } } }
package com.lsnare.film.worker; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class FilmCrewBatchWorker { public static final int RUN_INTERVAL = 30000; static Log log = LogFactory.getLog(FilmCrewBatchWorker.class); public static void main(String[] args) { while(true){ try { //check film records that need to be updated log.info("Processing film updates..."); //update all dirty records //sleep log.info("Film updates complete"); Thread.sleep(Integer.valueOf(System.getenv("FILM_CREW_BATCH_WORKER_RUN_INTERVAL"))); } catch (Exception e) { } } } }
package org.oryxeditor.buildapps.sscompress; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URLEncoder; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.json.JSONArray; import org.json.JSONObject; import org.apache.commons.codec.binary.Base64; public class SSCompressor { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { if(args.length < 1) throw new Exception("Missing argument! Usage: java SSCompressor <SSDirectory>"); //get stencil set directory from arguments String ssDirString = args[0]; //get stencil set configuration file File ssConf = new File(ssDirString + "/stencilsets.json"); if(!ssConf.exists()) throw new Exception("File " + ssDirString + "/stencilsets.json does not exist."); //read stencil set configuration StringBuffer jsonObjStr = readFile(ssConf); JSONArray jsonObj = new JSONArray(jsonObjStr.toString()); //iterate all stencil set configurations for(int i = 0; i < jsonObj.length(); i++) { JSONObject ssObj = jsonObj.getJSONObject(i); //get stencil set location if(ssObj.has("uri")) { String ssUri = ssObj.getString("uri"); File ssFile = new File(ssDirString + ssUri); if(!ssFile.exists()) throw new Exception("Stencil set " + ssDirString + ssUri + " that is referenced in stencil set configuration file does not exist."); String ssDir = ssFile.getParent(); //read stencil set file StringBuffer ssString = readFile(ssFile); // store copy of original stencilset file (w/o SVG includes) with postfix '-nosvg' int pIdx = ssUri.lastIndexOf('.'); File ssNoSvgFile = new File(ssDirString + ssUri.substring(0, pIdx) + "-nosvg" + ssUri.substring(pIdx)); writeFile(ssNoSvgFile, ssString.toString()); /*try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder document = builder.newDocumentBuilder(); document.parse(svgString.toString()); } catch(Exception e) { throw new Exception("File " + svgFile.getCanonicalPath() + " is not a valid XML file: " + e.getMessage()); }*/ //append file content to output json file (replacing existing json file) tempSS.append("\"view\":\""); tempSS.append(svgString.toString().replaceAll("[\\t\\n\\x0B\\f\\r]", " ").replaceAll("\"", "\\\\\"")); //newSS.append(filename); tempSS.append("\""); } tempSS.append(ssString.substring(lastIndex)); //write compressed stencil set file writeFile(ssFile, tempSS.toString()); System.out.println("Compressed stencil set file " + ssFile.getCanonicalPath()); } } } private static StringBuffer readFile(File file) throws Exception { FileInputStream fin = new FileInputStream(file); StringBuffer result = new StringBuffer(); String thisLine = ""; BufferedReader myInput = new BufferedReader(new InputStreamReader(fin)); while ((thisLine = myInput.readLine()) != null) { result.append(thisLine); result.append("\n"); } myInput.close(); fin.close(); return result; } private static void writeFile(File file, String text) throws Exception { FileOutputStream fos = new FileOutputStream(file); BufferedWriter myOutput = new BufferedWriter(new OutputStreamWriter(fos)); myOutput.write(text); myOutput.flush(); myOutput.close(); fos.close(); } /*private static String encodeBase64(String text) { byte[] encoded = Base64.encodeBase64(text.getBytes()); return new String(encoded); }*/ }
package com.minelittlepony.model; import com.minelittlepony.model.armour.ModelPonyArmor; import com.minelittlepony.model.armour.PonyArmor; import com.minelittlepony.model.capabilities.IModel; import com.minelittlepony.model.capabilities.IModelPart; import com.minelittlepony.model.components.PonySnout; import com.minelittlepony.model.components.PonyTail; import com.minelittlepony.pony.data.IPonyData; import com.minelittlepony.pony.data.Pony; import com.minelittlepony.pony.data.PonyData; import com.minelittlepony.pony.data.PonySize; import com.minelittlepony.render.AbstractPonyRenderer; import com.minelittlepony.render.PonyRenderer; import com.minelittlepony.render.plane.PlaneRenderer; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelPlayer; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.EnumHandSide; import net.minecraft.util.math.MathHelper; import java.util.Random; import static net.minecraft.client.renderer.GlStateManager.*; import static com.minelittlepony.model.PonyModelConstants.*; /** * Foundation class for all types of ponies. */ public abstract class AbstractPonyModel extends ModelPlayer implements IModel { protected boolean isSleeping; private boolean isFlying; private boolean isSwimming; private boolean headGear; /** * Associcated pony data. */ public IPonyData metadata = new PonyData(); /** * Vertical pitch whilst flying. */ public float motionPitch; /** * Flag indicating that this model is performing a rainboom (flight). */ protected boolean rainboom; public PlaneRenderer upperTorso; public PlaneRenderer neck; public IModelPart tail; public PonySnout snout; public AbstractPonyModel(boolean arms) { super(0, arms); } @Override public PonyArmor createArmour() { return new PonyArmor(new ModelPonyArmor(), new ModelPonyArmor()); } /** * Checks flying and speed conditions and sets rainboom to true if we're a species with wings and is going faaast. */ protected void checkRainboom(Entity entity, float swing) { rainboom = canFly() && Math.sqrt(entity.motionX * entity.motionX + entity.motionZ * entity.motionZ) > 0.4F; } public void updateLivingState(EntityLivingBase entity, Pony pony) { isSneak = entity.isSneaking(); isSleeping = entity.isPlayerSleeping(); isFlying = pony.isPegasusFlying(entity); isSwimming = pony.isSwimming(entity); headGear = pony.isWearingHeadgear(entity); } /** * Sets the model's various rotation angles. * * @param move Entity motion parameter - i.e. velocity in no specific direction used in bipeds to calculate step amount. * @param swing Degree to which each 'limb' swings. * @param ticks Total whole and partial ticks since the entity's existance. Used in animations together with {@code swing} and {@code move}. * @param headYaw Horizontal head motion in radians. * @param headPitch Vertical head motion in radians. * @param scale Scaling factor used to render this model. Determined by the return value of {@link RenderLivingBase.prepareScale}. Usually {@code 0.0625F}. * @param entity The entity we're being called for. */ @Override public void setRotationAngles(float move, float swing, float ticks, float headYaw, float headPitch, float scale, Entity entity) { checkRainboom(entity, swing); super.setRotationAngles(move, swing, ticks, headYaw, headPitch, scale, entity); float headRotateAngleY = isSleeping ? 1.4f : headYaw / 57.29578F; float headRotateAngleX = isSleeping ? 0.1f : headPitch / 57.29578F; headRotateAngleX = Math.min(headRotateAngleX, (float) (0.5f - Math.toRadians(motionPitch))); headRotateAngleX = Math.max(headRotateAngleX, (float) (-1.25f - Math.toRadians(motionPitch))); updateHeadRotation(headRotateAngleX, headRotateAngleY); shakeBody(move, swing, getWobbleAmount(), ticks); rotateLegs(move, swing, ticks, entity); if (!rainboom) { holdItem(swing); } swingItem(entity); if (isCrouching()) { adjustBody(BODY_ROTATE_ANGLE_X_SNEAK, BODY_RP_Y_SNEAK, BODY_RP_Z_SNEAK); sneakLegs(); setHead(0, 6, -2); } else if (isRiding) { adjustBodyRiding(); bipedLeftLeg.rotationPointZ = 15; bipedLeftLeg.rotationPointY = 10; bipedLeftLeg.rotateAngleX = -PI / 4; bipedLeftLeg.rotateAngleY = -PI / 5; bipedRightLeg.rotationPointZ = 15; bipedRightLeg.rotationPointY = 10; bipedRightLeg.rotateAngleX = -PI / 4; bipedRightLeg.rotateAngleY = PI / 5; bipedLeftArm.rotateAngleZ = -PI * 0.06f; bipedRightArm.rotateAngleZ = PI * 0.06f; } else { adjustBody(BODY_ROTATE_ANGLE_X_NOTSNEAK, BODY_RP_Y_NOTSNEAK, BODY_RP_Z_NOTSNEAK); bipedRightLeg.rotationPointY = FRONT_LEG_RP_Y_NOTSNEAK; bipedLeftLeg.rotationPointY = FRONT_LEG_RP_Y_NOTSNEAK; swingArms(ticks); setHead(0, 0, 0); } if (isSleeping) ponySleep(); animateWears(); snout.setGender(metadata.getGender()); } protected float getWobbleAmount() { if (swingProgress <= 0) { return 0; } return MathHelper.sin(MathHelper.sqrt(swingProgress) * PI * 2) * 0.04F; } protected void adjustBodyRiding() { adjustBodyComponents(BODY_ROTATE_ANGLE_X_RIDING, BODY_RP_Y_RIDING, BODY_RP_Z_RIDING); adjustNeck(BODY_ROTATE_ANGLE_X_NOTSNEAK, BODY_RP_Y_NOTSNEAK, BODY_RP_Z_NOTSNEAK); setHead(0, 0, 0); } /** * Sets the model's various rotation angles. * * @param move Entity motion parameter - i.e. velocity in no specific direction used in bipeds to calculate step amount. * @param swing Degree to which each 'limb' swings. * @param bodySwing Horizontal (Y) body rotation. * @param ticks Total whole and partial ticks since the entity's existance. Used in animations together with {@code swing} and {@code move}. */ protected void shakeBody(float move, float swing, float bodySwing, float ticks) { tail.setRotationAndAngles(rainboom, move, swing, bodySwing * 5, ticks); upperTorso.rotateAngleY = bodySwing; bipedBody.rotateAngleY = bodySwing; neck.rotateAngleY = bodySwing; } private void animateWears() { copyModelAngles(bipedLeftArm, bipedLeftArmwear); copyModelAngles(bipedRightArm, bipedRightArmwear); copyModelAngles(bipedLeftLeg, bipedLeftLegwear); copyModelAngles(bipedRightLeg, bipedRightLegwear); copyModelAngles(bipedBody, bipedBodyWear); } @Override public ModelRenderer getHead() { return bipedHead; } /** * Sets the head rotation point. */ protected void setHead(float posX, float posY, float posZ) { bipedHead.setRotationPoint(posX, posY, posZ); bipedHeadwear.setRotationPoint(posX, posY, posZ); } /** * Called to update the head rotation. * * @param x New rotation X * @param y New rotation Y */ protected void updateHeadRotation(float x, float y) { bipedHeadwear.rotateAngleY = bipedHead.rotateAngleY = y; bipedHeadwear.rotateAngleX = bipedHead.rotateAngleX = x; } /** * * Used to set the legs rotation based on walking/crouching animations. * * Takes the same parameters as {@link AbstractPonyModel.setRotationAndAngles} * */ protected void rotateLegs(float move, float swing, float ticks, Entity entity) { if (isFlying()) { rotateLegsInFlight(move, swing, ticks, entity); } else { rotateLegsOnGround(move, swing, ticks, entity); } bipedRightArm.rotateAngleZ = 0; bipedLeftArm.rotateAngleZ = 0; float sin = MathHelper.sin(bipedBody.rotateAngleY) * 5; float cos = MathHelper.cos(bipedBody.rotateAngleY) * 5; float spread = getLegSpread(); bipedRightArm.rotationPointZ = spread + sin; bipedLeftArm.rotationPointZ = spread - sin; float legRPX = cos - getLegOutset(); legRPX = metadata.getInterpolator().interpolate("legOffset", legRPX, 3); bipedRightArm.rotationPointX = -legRPX; bipedRightLeg.rotationPointX = -legRPX; bipedLeftArm.rotationPointX = legRPX; bipedLeftLeg.rotationPointX = legRPX; bipedRightArm.rotateAngleY += bipedBody.rotateAngleY; bipedLeftArm.rotateAngleY += bipedBody.rotateAngleY; bipedRightArm.rotationPointY = bipedLeftArm.rotationPointY = 8; bipedRightLeg.rotationPointZ = bipedLeftLeg.rotationPointZ = 10; } /** * Rotates legs in quopy fashion whilst flying. * * @param move Entity motion parameter - i.e. velocity in no specific direction used in bipeds to calculate step amount. * @param swing Degree to which each 'limb' swings. * @param ticks Total whole and partial ticks since the entity's existance. Used in animations together with {@code swing} and {@code move}. * @param entity The entity we're being called for. * */ protected void rotateLegsInFlight(float move, float swing, float ticks, Entity entity) { float armX = rainboom ? ROTATE_270 : MathHelper.sin(-swing / 2); float legX = rainboom ? ROTATE_90 : MathHelper.sin(swing / 2); bipedLeftArm.rotateAngleX = armX; bipedRightArm.rotateAngleX = armX; bipedLeftLeg.rotateAngleX = legX; bipedRightLeg.rotateAngleX = legX; bipedLeftArm.rotateAngleY = -0.2F; bipedLeftLeg.rotateAngleY = 0.2F; bipedRightArm.rotateAngleY = 0.2F; bipedRightLeg.rotateAngleY = -0.2F; } /** * Rotates legs in quopy fashion for walking. * * @param move Entity motion parameter - i.e. velocity in no specific direction used in bipeds to calculate step amount. * @param swing Degree to which each 'limb' swings. * @param ticks Total whole and partial ticks since the entity's existance. Used in animations together with {@code swing} and {@code move}. * @param entity The entity we're being called for. * */ protected void rotateLegsOnGround(float move, float swing, float ticks, Entity entity) { float angle = PI * (float) Math.pow(swing, 16); float baseRotation = move * 0.6662F; // magic number ahoy float scale = swing / 4; bipedLeftArm.rotateAngleX = MathHelper.cos(baseRotation + angle) * scale; bipedRightArm.rotateAngleX = MathHelper.cos(baseRotation + PI + angle / 2) * scale; bipedLeftLeg.rotateAngleX = MathHelper.cos(baseRotation + PI - (angle * 0.4f)) * scale; bipedRightLeg.rotateAngleX = MathHelper.cos(baseRotation + angle / 5) * scale; bipedLeftArm.rotateAngleY = 0; bipedRightArm.rotateAngleY = 0; bipedLeftLeg.rotateAngleY = 0; bipedRightLeg.rotateAngleY = 0; } protected float getLegOutset() { if (isSleeping) return 3.6f; if (isCrouching()) return 1; return 5; } protected float getLegSpread() { return rainboom ? 2 : 1; } /** * Adjusts legs as if holding an item. Delegates to the correct arm/leg/limb as neccessary. * * @param swing */ protected void holdItem(float swing) { boolean both = leftArmPose == ArmPose.ITEM && rightArmPose == ArmPose.ITEM; alignArmForAction(bipedLeftArm, leftArmPose, rightArmPose, both, swing, 1); alignArmForAction(bipedRightArm, rightArmPose, leftArmPose, both, swing, -1); } /** * Aligns an arm for the appropriate arm pose * * @param arm The arm model to align * @param pose The post to align to * @param both True if we have something in both hands * @param swing Degree to which each 'limb' swings. */ protected void alignArmForAction(ModelRenderer arm, ArmPose pose, ArmPose complement, boolean both, float swing, float reflect) { switch (pose) { case ITEM: float swag = 1; if (!isFlying && both) { swag -= (float)Math.pow(swing, 2); } float mult = 1 - swag/2; arm.rotateAngleX = arm.rotateAngleX * mult - (PI / 10) * swag; arm.rotateAngleZ = -reflect * (PI / 15); if (isSneak) { arm.rotationPointX -= reflect * 2; } case EMPTY: arm.rotateAngleY = 0; break; case BLOCK: arm.rotateAngleX = (arm.rotateAngleX / 2 - 0.9424779F) - 0.3F; arm.rotateAngleY = reflect * PI / 9; arm.rotationPointX += reflect; arm.rotationPointZ += 3; if (isSneak) { arm.rotationPointY += 4; } break; case BOW_AND_ARROW: aimBow(arm, swing); break; default: } } protected void aimBow(ModelRenderer arm, float ticks) { arm.rotateAngleX = ROTATE_270 + bipedHead.rotateAngleX + (MathHelper.sin(ticks * 0.067F) * 0.05F); arm.rotateAngleY = bipedHead.rotateAngleY - 0.06F; arm.rotateAngleZ = MathHelper.cos(ticks * 0.09F) * 0.05F + 0.05F; if (isSneak) { arm.rotationPointY += 4; } } /** * Animates arm swinging. Delegates to the correct arm/leg/limb as neccessary. * * @param entity The entity we are being called for. */ protected void swingItem(Entity entity) { if (swingProgress > 0 && !isSleeping) { EnumHandSide mainSide = getMainHand(entity); swingArm(getArmForSide(mainSide)); } } /** * Animates arm swinging. * * @param arm The arm to swing */ protected void swingArm(ModelRenderer arm) { float swing = 1 - (float)Math.pow(1 - swingProgress, 3); float deltaX = MathHelper.sin(swing * PI); float deltaZ = MathHelper.sin(swingProgress * PI); float deltaAim = deltaZ * (0.7F - bipedHead.rotateAngleX) * 0.75F; arm.rotateAngleX -= deltaAim + deltaX * 1.2F; arm.rotateAngleY += bipedBody.rotateAngleY * 2; arm.rotateAngleZ = -deltaZ * 0.4F; } /** * Animates the walking animation. * * @param ticks Total whole and partial ticks since the entity's existance. Used in animations together with {@code swing} and {@code move}. */ protected void swingArms(float ticks) { if (isSleeping) return; float cos = MathHelper.cos(ticks * 0.09F) * 0.05F + 0.05F; float sin = MathHelper.sin(ticks * 0.067F) * 0.05F; if (rightArmPose != ArmPose.EMPTY) { bipedRightArm.rotateAngleZ += cos; bipedRightArm.rotateAngleX += sin; } if (leftArmPose != ArmPose.EMPTY) { bipedLeftArm.rotateAngleZ += cos; bipedLeftArm.rotateAngleX += sin; } } protected void adjustBody(float rotateAngleX, float rotationPointY, float rotationPointZ) { adjustBodyComponents(rotateAngleX, rotationPointY, rotationPointZ); adjustNeck(rotateAngleX, rotationPointY, rotationPointZ); } protected void adjustBodyComponents(float rotateAngleX, float rotationPointY, float rotationPointZ) { bipedBody.rotateAngleX = rotateAngleX; bipedBody.rotationPointY = rotationPointY; bipedBody.rotationPointZ = rotationPointZ; upperTorso.rotateAngleX = rotateAngleX; upperTorso.rotationPointY = rotationPointY; upperTorso.rotationPointZ = rotationPointZ; } protected void adjustNeck(float rotateAngleX, float rotationPointY, float rotationPointZ) { neck.setRotationPoint(NECK_ROT_X + rotateAngleX, rotationPointY, rotationPointZ); } /** * Aligns legs to a sneaky position. */ protected void sneakLegs() { bipedRightArm.rotateAngleX -= SNEAK_LEG_X_ROTATION_ADJUSTMENT; bipedLeftArm.rotateAngleX -= SNEAK_LEG_X_ROTATION_ADJUSTMENT; bipedLeftLeg.rotationPointY = bipedRightLeg.rotationPointY = FRONT_LEG_RP_Y_SNEAK; } protected void ponySleep() { bipedRightArm.rotateAngleX = ROTATE_270; bipedLeftArm.rotateAngleX = ROTATE_270; bipedRightLeg.rotateAngleX = ROTATE_90; bipedLeftLeg.rotateAngleX = ROTATE_90; setHead(1, 2, isSneak ? -1 : 1); AbstractPonyRenderer.shiftRotationPoint(bipedRightArm, 0, 2, 6); AbstractPonyRenderer.shiftRotationPoint(bipedLeftArm, 0, 2, 6); AbstractPonyRenderer.shiftRotationPoint(bipedRightLeg, 0, 2, -8); AbstractPonyRenderer.shiftRotationPoint(bipedLeftLeg, 0, 2, -8); } public void init(float yOffset, float stretch) { boxList.clear(); initHead(yOffset, stretch); initBody(yOffset, stretch); initLegs(yOffset, stretch); initTail(yOffset, stretch); } protected void initHead(float yOffset, float stretch) { snout = new PonySnout(this); snout.init(yOffset, stretch); bipedHead = new PonyRenderer(this, 0, 0) .offset(HEAD_CENTRE_X, HEAD_CENTRE_Y, HEAD_CENTRE_Z) .around(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z - 2) .box(-4, -4, -4, 8, 8, 8, stretch) .tex(12, 16).box(-4, -6, 1, 2, 2, 2, stretch) .flip().box( 2, -6, 1, 2, 2, 2, stretch); bipedHeadwear = new PonyRenderer(this, 32, 0) .offset(HEAD_CENTRE_X, HEAD_CENTRE_Y, HEAD_CENTRE_Z) .around(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z - 2) .box(-4, -4, -4, 8, 8, 8, stretch + 0.5F); } protected void initTail(float yOffset, float stretch) { tail = new PonyTail(this); tail.init(yOffset, stretch); } /** * Creates the main torso and neck. */ protected void initBody(float yOffset, float stretch) { if (textureHeight == 64) { bipedBodyWear = new ModelRenderer(this, 16, 32); } bipedBody = new PonyRenderer(this, 16, 16) .around(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z) .box(-4, 4, -2, 8, 8, 4, stretch); bipedBodyWear.addBox(-4, 4, -2, 8, 8, 4, stretch + 0.25F); bipedBodyWear.setRotationPoint(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z); upperTorso = new PlaneRenderer(this, 24, 0); upperTorso.offset(BODY_CENTRE_X, BODY_CENTRE_Y, BODY_CENTRE_Z) .around(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z) .tex(24, 0) .addEastPlane( 4, -4, -4, 8, 8, stretch) .tex(4, 0) .addEastPlane( 4, -4, 4, 8, 4, stretch) .tex(56, 0) .addBottomPlane(-4, 4, -4, 8, 8, stretch) .tex(36, 16) .addBackPlane(-4, -4, 8, 8, 4, stretch) .addBackPlane(-4, 0, 8, 8, 4, stretch) .addBottomPlane(-4, 4, 4, 8, 4, stretch) .flipZ().tex(32, 20).addTopPlane(-4, -4, -4, 8, 12, stretch) .tex(24, 0).addWestPlane(-4, -4, -4, 8, 8, stretch) .tex(4, 0) .addWestPlane(-4, -4, 4, 8, 4, stretch) // Tail stub .child(0) .tex(32, 0).addTopPlane(-1, 2, 2, 2, 6, stretch) .addBottomPlane(-1, 4, 2, 2, 6, stretch) .addEastPlane( 1, 2, 2, 2, 6, stretch) .addBackPlane(-1, 2, 8, 2, 2, stretch) .flipZ().addWestPlane(-1, 2, 2, 2, 6, stretch) .rotate(0.5F, 0, 0); neck = new PlaneRenderer(this, 0, 16) .at(NECK_CENTRE_X, NECK_CENTRE_Y, NECK_CENTRE_Z) .rotate(NECK_ROT_X, 0, 0).around(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z) .addFrontPlane(0, 0, 0, 4, 4, stretch) .addBackPlane(0, 0, 4, 4, 4, stretch) .addEastPlane(4, 0, 0, 4, 4, stretch) .addWestPlane(0, 0, 0, 4, 4, stretch); } protected void preInitLegs() { bipedLeftArm = new ModelRenderer(this, 32, 48); bipedRightArm = new ModelRenderer(this, 40, 16); bipedLeftLeg = new ModelRenderer(this, 16, 48); bipedRightLeg = new ModelRenderer(this, 0, 16); } protected void preInitLegwear() { bipedLeftArmwear = new ModelRenderer(this, 48, 48); bipedRightArmwear = new ModelRenderer(this, 40, 32); bipedLeftLegwear = new ModelRenderer(this, 0, 48); bipedRightLegwear = new ModelRenderer(this, 0, 32); } protected void initLegs(float yOffset, float stretch) { preInitLegs(); preInitLegwear(); int armWidth = getArmWidth(); int armDepth = getArmDepth(); float rarmX = getLegRotationX(); float rarmY = getArmRotationY(); float armX = THIRDP_ARM_CENTRE_X; float armY = THIRDP_ARM_CENTRE_Y - 6; float armZ = BODY_CENTRE_Z / 2 - 1 - armDepth; bipedLeftArm .addBox(armX, armY, armZ, armWidth, 12, armDepth, stretch); bipedRightArm.addBox(armX - armWidth, armY, armZ, armWidth, 12, armDepth, stretch); bipedLeftLeg .addBox(armX, armY, armZ, armWidth, 12, armDepth, stretch); bipedRightLeg.addBox(armX - armWidth, armY, armZ, armWidth, 12, armDepth, stretch); bipedLeftArm .setRotationPoint( rarmX, yOffset + rarmY, 0); bipedRightArm.setRotationPoint(-rarmX, yOffset + rarmY, 0); bipedLeftLeg .setRotationPoint( rarmX, yOffset, 0); bipedRightLeg.setRotationPoint(-rarmX, yOffset, 0); bipedLeftArmwear.addBox(armX, armY, armZ, armWidth, 12, armDepth, stretch + 0.25f); bipedLeftArmwear.setRotationPoint(rarmX, yOffset + rarmY, 0); bipedRightArmwear.addBox(armX - armWidth, armY, armZ, armWidth, 12, armDepth, stretch + 0.25f); bipedRightArmwear.setRotationPoint(-rarmX, yOffset + rarmY, 0); bipedLeftLegwear.addBox(armX, armY, armZ, armWidth, 12, armDepth, stretch + 0.25f); bipedRightLegwear.setRotationPoint(rarmX, yOffset, 0); bipedRightLegwear.addBox(armX - armWidth, armY, armZ, armWidth, 12, armDepth, stretch + 0.25f); bipedRightLegwear.setRotationPoint(-rarmX, yOffset, 0); } protected int getArmWidth() { return 4; } protected int getArmDepth() { return 4; } protected float getLegRotationX() { return 3; } protected float getArmRotationY() { return 8; } public ArmPose getArmPoseForSide(EnumHandSide side) { return side == EnumHandSide.RIGHT ? rightArmPose : leftArmPose; } @Override public IPonyData getMetadata() { return metadata; } @Override public boolean isCrouching() { return !rainboom && isSneak && !isFlying; } @Override public boolean isGoingFast() { return rainboom; } @Override public boolean hasHeadGear() { return headGear; } @Override public boolean isFlying() { return isFlying && canFly(); } @Override public boolean isSwimming() { return isSwimming; } @Override public boolean isChild() { return metadata.getSize() == PonySize.FOAL || isChild; } @Override public float getSwingAmount() { return swingProgress; } /** * Sets the model's various rotation angles. * * @param entity The entity we're being called for. * @param move Entity motion parameter - i.e. velocity in no specific direction used in bipeds to calculate step amount. * @param swing Degree to which each 'limb' swings. * @param ticks Total whole and partial ticks since the entity's existance. Used in animations together with {@code swing} and {@code move}. * @param headYaw Horizontal head motion in radians. * @param headPitch Vertical head motion in radians. * @param scale Scaling factor used to render this model. Determined by the return value of {@link RenderLivingBase.prepareScale}. Usually {@code 0.0625F}. */ @Override public void render(Entity entity, float move, float swing, float ticks, float headYaw, float headPitch, float scale) { pushMatrix(); transform(BodyPart.HEAD); renderHead(entity, move, swing, ticks, headYaw, headPitch, scale); popMatrix(); pushMatrix(); transform(BodyPart.NECK); renderNeck(scale); popMatrix(); pushMatrix(); transform(BodyPart.BODY); renderBody(entity, move, swing, ticks, headYaw, headPitch, scale); popMatrix(); pushMatrix(); transform(BodyPart.LEGS); renderLegs(scale); popMatrix(); } /** * * Called to render the head. * * Takes the same parameters as {@link AbstractPonyModel.setRotationAndAngles} * */ protected void renderHead(Entity entity, float move, float swing, float ticks, float headYaw, float headPitch, float scale) { bipedHead.render(scale); bipedHeadwear.render(scale); bipedHead.postRender(scale); } protected void renderNeck(float scale) { GlStateManager.scale(0.9, 0.9, 0.9); neck.render(scale); } /** * * Called to render the head. * * Takes the same parameters as {@link AbstractPonyModel.setRotationAndAngles} * */ protected void renderBody(Entity entity, float move, float swing, float ticks, float headYaw, float headPitch, float scale) { bipedBody.render(scale); if (textureHeight == 64) { bipedBodyWear.render(scale); } upperTorso.render(scale); bipedBody.postRender(scale); tail.renderPart(scale); } protected void renderLegs(float scale) { if (!isSneak) bipedBody.postRender(scale); bipedLeftArm.render(scale); bipedRightArm.render(scale); bipedLeftLeg.render(scale); bipedRightLeg.render(scale); if (textureHeight == 64) { bipedLeftArmwear.render(scale); bipedRightArmwear.render(scale); bipedLeftLegwear.render(scale); bipedRightLegwear.render(scale); } } @Override public void transform(BodyPart part) { if (isRiding) translate(0, -0.4F, -0.2F); if (isSleeping) { rotate(90, 1, 0, 0); rotate(180, 0, 1, 0); } if (part == BodyPart.HEAD) { rotate(motionPitch, 1, 0, 0); } // TODO: Get these out of here if (isChild()) { transformFoal(part); } else if (metadata.getSize() == PonySize.LARGE) { transformLarge(part); } else if (metadata.getSize() == PonySize.TALL) { transformTall(part); } else { transformNormal(part); } } private void transformNormal(BodyPart part) { if (isSleeping) translate(0, -0.61F, 0.25F); switch (part) { case NECK: if (isCrouching()) translate(-0.03F, 0.03F, 0.1F); default: } } private void transformTall(BodyPart part) { if (isSleeping) translate(0, -0.5F, 0.25F); switch (part) { case HEAD: translate(0, -0.15F, 0.01F); if (isCrouching()) translate(0, 0.05F, 0); break; case NECK: translate(0, -0.09F, -0.01F); scale(1, 1.1F, 1); if (isCrouching()) translate(-0.02F, -0.02F, 0.1F); break; case BODY: case TAIL: translate(0, -0.1F, 0); scale(1, 1, 1); break; case LEGS: translate(0, -0.25F, 0.03F); scale(1, 1.18F, 1); if (rainboom) translate(0, 0.05F, 0); break; } } private void transformLarge(BodyPart part) { if (isSleeping) translate(0, -0.98F, 0.2F); switch (part) { case HEAD: translate(0, -0.17F, -0.04F); if (isSleeping) translate(0, 0, -0.1F); if (isCrouching()) translate(0, 0.15F, 0); break; case NECK: translate(0, -0.15F, -0.07F); if (isCrouching()) translate(-0.03F, 0.16F, 0.07F); break; case BODY: translate(0, -0.2F, -0.04F); scale(1.15F, 1.2F, 1.2F); break; case TAIL: translate(0, -0.2F, 0.08F); break; case LEGS: translate(0, -0.14F, 0); scale(1.15F, 1.12F, 1.15F); break; } } private void transformFoal(BodyPart part) { if (isCrouching()) translate(0, -0.12F, 0); if (isSleeping) translate(0, -1.48F, 0.25F); if (isRiding) translate(0, 0.1F, 0); switch (part) { case NECK: case HEAD: translate(0, 0.76F, 0); scale(0.9F, 0.9F, 0.9F); if (part == BodyPart.HEAD) break; if (isCrouching()) translate(0, -0.01F, 0.15F); break; case BODY: case TAIL: translate(0, 0.76F, -0.04F); scale(0.6F, 0.6F, 0.6F); break; case LEGS: translate(0, 0.89F, 0); scale(0.6F, 0.41F, 0.6F); if (isCrouching()) translate(0, 0.12F, 0); if (rainboom) translate(0, -0.08F, 0); break; } } /** * Copies this model's attributes from some other. */ @Override public void setModelAttributes(ModelBase model) { super.setModelAttributes(model); if (model instanceof AbstractPonyModel) { AbstractPonyModel pony = (AbstractPonyModel) model; isFlying = pony.isFlying; isSleeping = pony.isSleeping; metadata = pony.metadata; motionPitch = pony.motionPitch; rainboom = pony.rainboom; } } @Override public ModelRenderer getRandomModelBox(Random rand) { // grab one at random, but cycle through the list until you find one that's filled. // Return if you find one, or if you get back to where you started in which case there isn't any. int randomI = rand.nextInt(boxList.size()); int index = randomI; ModelRenderer result; do { result = boxList.get(randomI); if (!result.cubeList.isEmpty()) return result; index = (index + 1) % boxList.size(); } while (index != randomI); return result; } }
package com.minespaceships.mod.spaceship; import java.io.Serializable; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Scanner; import java.util.Set; import java.util.Vector; import javax.vecmath.Vector3d; import com.google.common.collect.ImmutableList; import com.minespaceships.mod.blocks.EngineBlock; import com.minespaceships.mod.blocks.NavigatorBlock; import com.minespaceships.mod.blocks.PhaserBlock; import com.minespaceships.mod.blocks.ShieldBlock; import com.minespaceships.mod.overhead.ChatRegisterEntity; import com.minespaceships.mod.worldanalysation.WorldMock; import com.minespaceships.util.BlockCopier; import com.minespaceships.util.Vec3Op; import energyStrategySystem.EnergyStrategySystem; import energyStrategySystem.IEnergyC; import net.minecraft.block.Block; import net.minecraft.block.BlockDoor; import net.minecraft.block.BlockDoor.EnumDoorHalf; import net.minecraft.block.BlockWallSign; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.IStringSerializable; import net.minecraft.util.Vec3; import net.minecraft.util.Vec3i; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.relauncher.Side; public class Spaceship implements Serializable{ private BlockPos origin; private World world; private BlockMap blockMap; private SpaceshipAssembler assembler; private EnergyStrategySystem energySystem; private boolean isResolved = true; private static final String positionsKey = "Positions"; private boolean canBeRemoved = true; public static final int maxShipSize = 27000; @Deprecated public Spaceship(final BlockPos minSpan, final BlockPos origin, final BlockPos maxSpan, World world){ this.origin = origin; this.world = world; setMeasurements(((BlockPos) minSpan).add(origin), ((BlockPos) maxSpan).add(origin)); initializeBase(); } @Deprecated public Spaceship(int[] originMeasurement){ world = (WorldServer)MinecraftServer.getServer().getEntityWorld(); readOriginMeasurementArray(originMeasurement); initializeBase(); } public Spaceship(BlockPos initial, World world) throws Exception{ blockMap = new BlockMap(initial); blockMap = SpaceshipMath.getConnectedPositions(initial, world, maxShipSize); if(blockMap == null){ throw new Exception("Ship is too huge or connected to the Ground"); } this.origin = initial; this.world = world; initializeBase(); } public Spaceship(BlockMap blocks, World world){ blockMap = blocks; this.world = world; initializeBase(); } public Spaceship(NBTTagCompound s, String firstKey, World world)throws Exception { this.world = world; //world needs to be loaded first to prevent null pointer this.readFromNBT(s, firstKey); this.origin = blockMap.getOrigin(); initializeBase(); } private void initializeBase(){ if(assembler == null){ assembler = new SpaceshipAssembler(blockMap.getOrigin()); refreshParts(); } energySystem = new EnergyStrategySystem(assembler, world); //Shipyard.getShipyard(world).addShip(this); } public BlockPos getOrigin(){ return origin; } public BlockPos getMaxPos(){ return blockMap.getMaxPos(); } public BlockPos getMinPos(){ return blockMap.getMinPos(); } public boolean canBeRemoved(){ return canBeRemoved; } public int getNavigatorCount(){ return assembler.getParts(NavigatorBlock.class).size(); } public ArrayList<BlockPos> getPositions(){ return blockMap.getPositions(); } public BlockMap getBlockMap(){ return blockMap; } @Deprecated public int[] getOriginMeasurementArray(){ BlockPos minSpan = Vec3Op.subtract(blockMap.getMinPos(), origin); BlockPos maxSpan = Vec3Op.subtract(blockMap.getMaxPos(), origin); int[] a = {minSpan.getX(), minSpan.getY(), minSpan.getZ(), origin.getX(), origin.getY(), origin.getZ(), maxSpan.getX(), maxSpan.getY(), maxSpan.getZ()}; return a; } @Deprecated public void readOriginMeasurementArray(int[] array){ try { BlockPos minSpan = new BlockPos(array[0], array[1], array[2]); BlockPos maxSpan = new BlockPos(array[6], array[7], array[8]); origin = new BlockPos(array[3], array[4], array[5]); setMeasurements(minSpan.add(origin), maxSpan.add(origin)); origin = new BlockPos(array[3], array[4], array[5]); } catch (ArrayIndexOutOfBoundsException ex) { System.out.println("Could not read OriginMeasurementArray (probably an error with NBT). Try creating a new World."); System.out.println("Printing Exception Stack:"); System.out.println(ex.getMessage()); } } @Deprecated private void setMeasurements(final BlockPos minPos, final BlockPos maxPos){ blockMap = new BlockMap(minPos); BlockPos span = Vec3Op.subtract(((BlockPos) maxPos), minPos); for(int x = 0; x <= span.getX(); x++){ for(int y = 0; y <= span.getY(); y++){ for(int z = 0; z <= span.getZ(); z++){ //if(!world.isAirBlock(new BlockPos(x,y,z).add(minPos))){ blockMap.add(new BlockPos(x,y,z).add(minPos)); } } } origin = Vec3Op.scale(span, 0.5); } public void activatePhasers(){ energySystem.changeAll(PhaserBlock.class, true); } public void deactivatePhasers(){ energySystem.changeAll(PhaserBlock.class, false); } public void activateShields(){ energySystem.changeAll(ShieldBlock.class, true); } public void deactivateShields(){ energySystem.changeAll(ShieldBlock.class, false); } public void activateEngines(){ energySystem.changeAll(EngineBlock.class, true); } public void deactivateEngines(){ energySystem.changeAll(EngineBlock.class, false); } public void setTarget(BlockPos position){ moveTo(Vec3Op.subtract(position, origin), 0, world); } public void setTarget(BlockPos position, World world){ moveTo(Vec3Op.subtract(position, origin), world); } public void moveTo(BlockPos addDirection) { moveTo(addDirection, world, 0); } public void moveTo(BlockPos addDirection, World world) { moveTo(addDirection, world, 0); } public void moveTo(BlockPos addDirection, int turn, World world) { moveTo(addDirection, world, turn); } private void moveTo(BlockPos addDirection, World world, final int turn){ if(!canMove(addDirection, world, turn)){ return; } /** * Moves the spaceship to a target position. * These method check also if the target position is a valid position. * @param position */ public void move(BlockPos position){ if(position == null){ throw new IllegalArgumentException("The target position can not be null"); } double x = position.getX(); double y = position.getY(); double z = position.getZ(); double maxWorldHeight = this.world.getHeight(); BlockPos maxShipHeight = getMaxPos(); BlockPos minShipHeight = getMinPos(); double shipHeight = maxShipHeight.getY()-minShipHeight.getY(); //Troubleshooting for the world height out of bounds. if(position.getY() >= maxWorldHeight){ this.setTarget(new BlockPos(x,(maxWorldHeight-shipHeight),z)); } if(position.getY() <= 0){ this.setTarget(new BlockPos(x,(0+shipHeight),z)); } //Valid position this.setTarget(new BlockPos(x,y,z)); } public boolean canMove(BlockPos addDirection, World targetWorld, int turn){ if(world != targetWorld){ return true; } double maxWorldHeight = this.world.getHeight(); BlockPos maxPos = getMaxPos(); BlockPos minPos = getMinPos(); BlockPos nextMaxPos = Turn.getRotatedPos(maxPos, origin, addDirection, turn); BlockPos nextMinPos = Turn.getRotatedPos(minPos, origin, addDirection, turn); if(nextMaxPos.getY() > maxWorldHeight || nextMinPos.getY() < 0){ return false; } return !isInsideShipRectangle(nextMaxPos) && !isInsideShipRectangle(nextMinPos); } public boolean isInsideShipRectangle(BlockPos pos){ BlockPos max = getMaxPos(); BlockPos min = getMinPos(); return pos.getX() >= min.getX() && pos.getY() >= min.getY() && pos.getZ() >= min.getZ() && pos.getX() < max.getX() && pos.getY() < max.getY() && pos.getZ() < max.getZ(); } public void readFromNBT(NBTTagCompound c, String firstKey){ String data = c.getString(firstKey+positionsKey); try { positionsFromString(data); } catch (Exception e) { e.printStackTrace(); } } public void writeToNBT(NBTTagCompound c, String firstKey){ c.setString(firstKey+positionsKey, positionsToString()); } }
package com.redhat.ceylon.compiler.js; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.js.GenerateJsVisitor.GenerateCallback; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Generic; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.tree.Tree; public class BmeGenerator { static void generateBme(final Tree.BaseMemberExpression bme, final GenerateJsVisitor gen, final boolean forInvoke) { Declaration decl = bme.getDeclaration(); if (decl != null) { String name = decl.getName(); String pkgName = decl.getUnit().getPackage().getQualifiedNameString(); // map Ceylon true/false/null directly to JS true/false/null if (Module.LANGUAGE_MODULE_NAME.equals(pkgName)) { if ("true".equals(name) || "false".equals(name) || "null".equals(name)) { gen.out(name); return; } } } String exp = gen.memberAccess(bme, null); if (decl == null && gen.isInDynamicBlock()) { gen.out("(typeof ", exp, "==='undefined'||", exp, "===null?"); gen.generateThrow("Undefined or null reference: " + exp, bme); gen.out(":", exp, ")"); } else { final boolean isCallable = !forInvoke && decl instanceof Method && gen.getTypeUtils().callable.equals(bme.getTypeModel().getDeclaration()); String who = isCallable && decl.isMember() ? gen.getMember(bme, decl, null) : null; if (who != null && who.isEmpty()) { who=null; } final boolean hasTparms = hasTypeParameters(bme); if (isCallable && (who != null || hasTparms)) { if (hasTparms) { //Method refs with type arguments must be passed as a special function printGenericMethodReference(gen, bme, who, exp); } else { //Member methods must be passed as JsCallables gen.out(GenerateJsVisitor.getClAlias(), "JsCallable(/*ESTEMERO*/", who, ",", exp, ")"); } } else { gen.out(exp); } } } static boolean hasTypeParameters(final Tree.StaticMemberOrTypeExpression expr) { return expr.getTypeArguments() != null && !expr.getTypeArguments().getTypeModels().isEmpty(); } /** Create a map with type arguments from the type parameter list in the expression's declaration and the * type argument list in the expression itself. */ static Map<TypeParameter, ProducedType> createTypeArguments(final Tree.StaticMemberOrTypeExpression expr) { List<TypeParameter> tparams = null; if (expr.getDeclaration() instanceof Generic) { tparams = ((Generic)expr.getDeclaration()).getTypeParameters(); } else { expr.addUnexpectedError("Getting type parameters from unidentified declaration type " + expr.getDeclaration()); return null; } final HashMap<TypeParameter, ProducedType> targs = new HashMap<>(); final Iterator<ProducedType> iter = expr.getTypeArguments().getTypeModels().iterator(); for (TypeParameter tp : tparams) { ProducedType pt = iter.hasNext() ? iter.next() : tp.getDefaultTypeArgument(); targs.put(tp, pt); } return targs; } static void printGenericMethodReference(final GenerateJsVisitor gen, final Tree.StaticMemberOrTypeExpression expr, final String who, final String member) { //Method refs with type arguments must be passed as a special function final String tmpargs = gen.getNames().createTempVariable(); gen.out("function(){var ", tmpargs, "=[].slice.call(arguments,0);", tmpargs, ".push("); TypeUtils.printTypeArguments(expr, createTypeArguments(expr), gen, true); gen.out(");return ", member, ".apply(", who==null?"null":who, ",", tmpargs, ");}"); } /** * Generates a write access to a member, as represented by the given expression. * The given callback is responsible for generating the assigned value. * If lhs==null and the expression is a BaseMemberExpression * then the qualified path is prepended. */ static void generateMemberAccess(Tree.StaticMemberOrTypeExpression expr, GenerateCallback callback, String lhs, final GenerateJsVisitor gen) { Declaration decl = expr.getDeclaration(); boolean paren = false; String plainName = null; if (decl == null && gen.isInDynamicBlock()) { plainName = expr.getIdentifier().getText(); } else if (GenerateJsVisitor.isNative(decl)) { // direct access to a native element plainName = decl.getName(); } if (plainName != null) { if ((lhs != null) && (lhs.length() > 0)) { gen.out(lhs, "."); } gen.out(plainName, "="); } else { boolean protoCall = gen.opts.isOptimize() && (gen.getSuperMemberScope(expr) != null); if (gen.accessDirectly(decl) && !(protoCall && gen.defineAsProperty(decl))) { // direct access, without setter gen.out(gen.memberAccessBase(expr, decl, true, lhs), "="); } else { // access through setter gen.out(gen.memberAccessBase(expr, decl, true, lhs), protoCall ? ".call(this," : "("); paren = true; } } callback.generateValue(); if (paren) { gen.out(")"); } } static void generateMemberAccess(final Tree.StaticMemberOrTypeExpression expr, final String strValue, final String lhs, final GenerateJsVisitor gen) { generateMemberAccess(expr, new GenerateCallback() { @Override public void generateValue() { gen.out(strValue); } }, lhs, gen); } }
package com.researchworx.cresco.dashboard; import com.google.gson.Gson; import com.researchworx.cresco.library.messaging.MsgEvent; import com.researchworx.cresco.library.plugin.core.CExecutor; import com.researchworx.cresco.library.utilities.CLogger; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.security.MessageDigest; import java.util.*; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; public class Executor extends CExecutor { private final CLogger logger; private Plugin mainPlugin; private Gson gson; Executor(Plugin plugin) { super(plugin); mainPlugin = plugin; this.logger = new CLogger(this.plugin.getMsgOutQueue(), this.plugin.getRegion(), this.plugin.getAgent(), this.plugin.getPluginID(), CLogger.Level.Trace); gson = new Gson(); } @Override public MsgEvent processExec(MsgEvent ce) { logger.trace("Processing Exec message"); switch (ce.getParam("action")) { case "repolist": return repoList(ce); default: logger.error("Unknown configtype found {} for {}:", ce.getParam("action"), ce.getMsgType().toString()); } return null; } private MsgEvent repoList(MsgEvent msg) { Map<String,List<Map<String,String>>> repoMap = new HashMap<>(); repoMap.put("plugins",getPluginInventory(mainPlugin.repoPath)); List<Map<String,String>> contactMap = getNetworkAddresses(); repoMap.put("server",contactMap); msg.setCompressedParam("repolist",gson.toJson(repoMap)); return msg; } private List<Map<String,String>> getNetworkAddresses() { List<Map<String,String>> contactMap = null; try { contactMap = new ArrayList<>(); String port = plugin.getConfig().getStringParam("port", "3445"); String protocol = "http"; String path = "/repository"; List<InterfaceAddress> interfaceAddressList = new ArrayList<>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (!networkInterface.getDisplayName().startsWith("veth") && !networkInterface.isLoopback() && networkInterface.supportsMulticast() && !networkInterface.isPointToPoint() && !networkInterface.isVirtual()) { logger.debug("Found Network Interface [" + networkInterface.getDisplayName() + "] initialized"); interfaceAddressList.addAll(networkInterface.getInterfaceAddresses()); } } for (InterfaceAddress inaddr : interfaceAddressList) { logger.debug("interface addresses " + inaddr); Map<String, String> serverMap = new HashMap<>(); String hostAddress = inaddr.getAddress().getHostAddress(); if (hostAddress.contains("%")) { String[] remoteScope = hostAddress.split("%"); hostAddress = remoteScope[0]; } serverMap.put("protocol", protocol); serverMap.put("ip", hostAddress); serverMap.put("port", port); serverMap.put("path", path); contactMap.add(serverMap); } //put hostname at top of list InetAddress addr = InetAddress.getLocalHost(); String hostAddress = addr.getHostAddress(); if (hostAddress.contains("%")) { String[] remoteScope = hostAddress.split("%"); hostAddress = remoteScope[0]; } Map<String,String> serverMap = new HashMap<>(); serverMap.put("protocol", protocol); serverMap.put("ip", hostAddress); serverMap.put("port", port); serverMap.put("path", path); contactMap.remove(contactMap.indexOf(serverMap)); contactMap.add(0,serverMap); //Use env var for host with hidden external addresses String externalIp = plugin.getConfig().getStringParam("externalip"); //externalIp = "128.163.202.50"; if(externalIp != null) { Map<String, String> serverMapExternal = new HashMap<>(); serverMapExternal.put("protocol", protocol); serverMapExternal.put("ip", externalIp); serverMapExternal.put("port", port); serverMapExternal.put("path", path); contactMap.add(0,serverMapExternal); } //test } catch (Exception ex) { logger.error("getNetworkAddresses ", ex.getMessage()); } return contactMap; } private List<Map<String,String>> getPluginInventory(String repoPath) { List<Map<String,String>> pluginFiles = null; try { File folder = new File(repoPath); if(folder.exists()) { pluginFiles = new ArrayList<>(); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { try{ String jarPath = listOfFiles[i].getAbsolutePath(); String jarFileName = listOfFiles[i].getName(); String pluginName = getPluginName(jarPath); String pluginMD5 = getJarMD5(jarPath); String pluginVersion = getPluginVersion(jarPath); //System.out.println(pluginName + " " + jarFileName + " " + pluginVersion + " " + pluginMD5); //pluginFiles.add(listOfFiles[i].getAbsolutePath()); Map<String,String> pluginMap = new HashMap<>(); pluginMap.put("pluginname",pluginName); pluginMap.put("jarfile",jarFileName); pluginMap.put("md5",pluginMD5); pluginMap.put("version",pluginVersion); pluginFiles.add(pluginMap); } catch(Exception ex) { } } } if(pluginFiles.isEmpty()) { pluginFiles = null; } } } catch(Exception ex) { pluginFiles = null; } return pluginFiles; } private String getPluginVersion(String jarFile) { String version = null; try{ //String jarFile = AgentEngine.class.getProtectionDomain().getCodeSource().getLocation().getPath(); //logger.debug("JARFILE:" + jarFile); //File file = new File(jarFile.substring(5, (jarFile.length() ))); File file = new File(jarFile); boolean calcHash = true; BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); long fileTime = attr.creationTime().toMillis(); FileInputStream fis = new FileInputStream(file); @SuppressWarnings("resource") JarInputStream jarStream = new JarInputStream(fis); Manifest mf = jarStream.getManifest(); Attributes mainAttribs = mf.getMainAttributes(); version = mainAttribs.getValue("Implementation-Version"); } catch(Exception ex) { ex.printStackTrace(); } return version; } private String getPluginName(String jarFile) { String version = null; try{ //String jarFile = AgentEngine.class.getProtectionDomain().getCodeSource().getLocation().getPath(); //logger.debug("JARFILE:" + jarFile); //File file = new File(jarFile.substring(5, (jarFile.length() ))); File file = new File(jarFile); boolean calcHash = true; BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); long fileTime = attr.creationTime().toMillis(); FileInputStream fis = new FileInputStream(file); @SuppressWarnings("resource") JarInputStream jarStream = new JarInputStream(fis); Manifest mf = jarStream.getManifest(); Attributes mainAttribs = mf.getMainAttributes(); version = mainAttribs.getValue("artifactId"); } catch(Exception ex) { ex.printStackTrace(); } return version; } private String getJarMD5(String pluginFile) { String jarString = null; try { Path path = Paths.get(pluginFile); byte[] data = Files.readAllBytes(path); MessageDigest m= MessageDigest.getInstance("MD5"); m.update(data); jarString = new BigInteger(1,m.digest()).toString(16); } catch(Exception e) { e.printStackTrace(); } return jarString; } }
package com.valkryst.VTerminal.misc; import lombok.NonNull; import java.awt.*; public final class ColorFunctions { // Prevent users from creating an instance. private ColorFunctions() {} /** * Shades a color by some factor, where a higher factor results in a darker * shade. * * @param color A color * @param shadeFactor The amount to shade by, from 0.0 to 1.0. * @return The shaded color. */ public static Color shade(final @NonNull Color color, double shadeFactor) { if (shadeFactor > 1.0) { shadeFactor = 1.0; } if (shadeFactor < 0.0) { shadeFactor = 0.0; } final int a = color.getAlpha(); double r = color.getRed(); double g = color.getGreen(); double b = color.getBlue(); r *= (1.0 - shadeFactor); g *= (1.0 - shadeFactor); b *= (1.0 - shadeFactor); return new Color((int) r, (int) g, (int) b, a); } /** * Tints a color by some factor, where a higher factor results in a lighter * tint. * * @param color A color. * @param tintFactor The amount to tint by, from 0.0 to 1.0. * @return The tinted color. */ public static Color tint(final @NonNull Color color, double tintFactor) { if (tintFactor > 1.0) { tintFactor = 1.0; } if (tintFactor < 0.0) { tintFactor = 0.0; } final int a = color.getAlpha(); double r = color.getRed(); double g = color.getGreen(); double b = color.getBlue(); r += ((255.0 - r) * tintFactor); g += ((255.0 - g) * tintFactor); b += ((255.0 - b) * tintFactor); return new Color((int) r, (int) g, (int) b, a); } /** * Blends two colors using the alpha blend algorithm. * * @param source The source color being blended onto the destination color. * @param destination The destination color. * @return The blended color. */ public static Color alphaBlend(final @NonNull Color source, final @NonNull Color destination) { return new Color(alphaBlend(source.getRGB(), destination.getRGB())); } /** * Blends two RGBA values using the alpha blend algorithm. * * @param sourceRGBA The source RGBA being blended onto the destination RGBA. * @param destinationRGBA The destination RGBA. * @return The blended RGBA value. */ public static int alphaBlend(final int sourceRGBA, final int destinationRGBA) { final int destinationA = (destinationRGBA >> 24) & 0xFF; final int destinationR = (destinationRGBA >> 16) & 0xFF; final int destinationG = (destinationRGBA >> 8) & 0xFF; final int destinationB = destinationRGBA & 0xFF; final int sourceA = (sourceRGBA >> 24) & 0xFF; final int sourceR = (sourceRGBA >> 16) & 0xFF; final int sourceG = (sourceRGBA >> 8) & 0xFF; final int sourceB = sourceRGBA & 0xFF; int alphaBlend = destinationA * (255 - sourceA) + sourceA; int redBlend = destinationR * (255 - sourceA) + (sourceR * sourceA); int greenBlend = destinationG * (255 - sourceA) + (sourceG * sourceA); int blueBlend = destinationB * (255 - sourceA) + (sourceB * sourceA); alphaBlend &= 0xFF; redBlend &= 0xFF; greenBlend &= 0xFF; blueBlend &= 0xFF; return (alphaBlend << 24) + (redBlend << 16) + (greenBlend << 8) + blueBlend; } }
package de.fraunhofer.iais.eis.biotope; import de.fraunhofer.iais.eis.biotope.exceptions.OMIRequestCreationException; import de.fraunhofer.iais.eis.biotope.exceptions.OMIRequestResponseException; import de.fraunhofer.iais.eis.biotope.exceptions.OMIRequestSendException; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.eclipse.rdf4j.model.Model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; @Component class NodeService { private final Logger logger = LoggerFactory.getLogger(NodeService.class); private final String CALLBACK_METHOD_PATH = "/callback"; private final String CB_DEFAULT_PROTOCOL = "http"; private final String CB_DEFAULT_PORT = "9090"; private final String CB_DEFAULT_HOSTNAME = "localhost"; private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); private Collection<OmiNode> omiNodes = new HashSet<>(); private String callbackUrl = CALLBACK_METHOD_PATH; @Autowired private OdfRdfConverter odfRdfConverter; @Autowired private OdfRdfRepository odfRdfRepository; public NodeService() { String protocol = System.getenv("CB_PROTOCOL"); protocol = protocol == null ? CB_DEFAULT_PROTOCOL : protocol; String hostname = System.getenv("CB_HOSTNAME"); hostname = hostname == null ? CB_DEFAULT_HOSTNAME : hostname; String port = System.getenv("CB_PORT"); port = port == null ? CB_DEFAULT_PORT : port; callbackUrl = protocol + "://" + hostname + ":" + port + CALLBACK_METHOD_PATH; } public void addNode(OmiNode omiNode) { omiNodes.add(omiNode); } public void subscribe(OmiNode omiNode) { logger.debug("subscribing omiNode " + omiNode.toString()); String subscriptionRequest = createSubscriptionRequest(omiNode.getSubscriptionXMLRequest()); HttpResponse response = sendRequest(omiNode.getUrl(), subscriptionRequest); omiNode.setSubscriptionId(getSubscriptionRequestId(response)); } private String createSubscriptionRequest(String subscriptionXMLRequest) { try { DocumentBuilder db = dbf.newDocumentBuilder(); InputStream is = new ByteArrayInputStream(subscriptionXMLRequest.getBytes()); Document doc = db.parse(is); doc.getChildNodes(); Attr ttl = doc.createAttribute("ttl"); ttl.setValue("-1"); Attr interval = doc.createAttribute("interval"); interval.setValue("-1"); Attr callback = doc.createAttribute("callback"); logger.info("setting callback to: '" +callbackUrl+ "'"); callback.setValue(callbackUrl); Node envelopeNode = doc.getElementsByTagName("omi:omiEnvelope").item(0); envelopeNode.getAttributes().setNamedItem(ttl); Node readNode = doc.getElementsByTagName("omi:read").item(0); readNode.getAttributes().setNamedItem(interval); readNode.getAttributes().setNamedItem(callback); return serializeDocument(doc); } catch (TransformerException | SAXException | ParserConfigurationException | IOException e) { throw new OMIRequestCreationException("Error creating O-MI subscription request", e); } } private String serializeDocument(Document doc) throws TransformerException { StringWriter writer = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); writer.flush(); return writer.toString(); } private HttpResponse sendRequest(URL url, String request) { CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost post = new HttpPost(url.toURI()); post.setEntity(new StringEntity(request)); return client.execute(post); } catch (URISyntaxException | IOException e) { throw new OMIRequestSendException("Error sending O-MI request", e); } } private String getSubscriptionRequestId(HttpResponse subscriptionResponse) { int httpStatus = subscriptionResponse.getStatusLine().getStatusCode(); if (httpStatus != HttpStatus.SC_OK) { throw new OMIRequestResponseException("HTTP response status: " +httpStatus); } try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(subscriptionResponse.getEntity().getContent()); Node returnNode = doc.getElementsByTagName("omi:return").item(0); int omiStatus = getOmiDocumentReturnCode(doc); String omiDescription = returnNode.getAttributes().getNamedItem("description").getNodeValue(); if (omiStatus != HttpStatus.SC_OK) { throw new OMIRequestResponseException("O-MI response status: " +omiStatus+ ", description: '" +omiDescription+ "'"); } String subscriptionId = doc.getElementsByTagName("omi:requestID").item(0).getTextContent(); logger.info("Subscription sent successfully"); return subscriptionId; } catch (SAXException | ParserConfigurationException | IOException e) { throw new OMIRequestCreationException("Error parsing O-MI response", e); } } private int getOmiDocumentReturnCode(Document doc) { Node returnNode = doc.getElementsByTagName("omi:return").item(0); return Integer.parseInt(returnNode.getAttributes().getNamedItem("returnCode").getNodeValue()); } public void persistOmiMessageContent(String omiMessage) { logger.info("O-MI value changed"); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream(omiMessage.getBytes(StandardCharsets.UTF_8))); int omiRetCode = getOmiDocumentReturnCode(doc); if (omiRetCode == HttpStatus.SC_OK) { String odfStructure = innerXml(doc.getElementsByTagName("omi:msg").item(0)); persistOdfStructure(odfStructure); } else { logger.warn("O-MI message has error code " +omiRetCode+ ". Ignoring the message."); } } catch (SAXException | ParserConfigurationException | IOException e) { throw new OMIRequestCreationException("Error parsing O-MI message", e); } } private String innerXml(Node node) { DOMImplementationLS lsImpl = (DOMImplementationLS)node.getOwnerDocument().getImplementation().getFeature("LS", "3.0"); LSSerializer lsSerializer = lsImpl.createLSSerializer(); lsSerializer.getDomConfig().setParameter("xml-declaration", false); NodeList childNodes = node.getChildNodes(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < childNodes.getLength(); i++) { Node childNode = childNodes.item(i); if (childNode.getTextContent().trim().isEmpty()) continue; sb.append(lsSerializer.writeToString(childNodes.item(i))); } return sb.toString(); } private void persistOdfStructure(String odfStructure) { Model odfData = odfRdfConverter.odf2rdf(new ByteArrayInputStream(odfStructure.getBytes(StandardCharsets.UTF_8))); odfRdfRepository.persist(odfData); } public Collection<OmiNode> getOmiNodes() { return omiNodes; } public void baselineSync(OmiNode omiNode) { HttpResponse response = sendRequest(omiNode.getUrl(), omiNode.getSubscriptionXMLRequest()); try { String odfContent = IOUtils.toString(response.getEntity().getContent(), Charset.defaultCharset()); persistOmiMessageContent(odfContent); } catch (IOException e) { throw new OMIRequestResponseException("Error reading O-MI response conent"); } } }
package de.impelon.disenchanter; import net.minecraftforge.common.config.Config; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; @Config(modid = DisenchanterMain.MODID, category = "") public class DisenchanterConfig { @Config.Name("experience_jar") public static final ExperienceJarSection experienceJar = new ExperienceJarSection(); public static class ExperienceJarSection { @Config.Name("JarDefaultExperienceCapacity") @Config.Comment("How many experience points should the jar of experience store at most by default?") @Config.RangeInt(min = 0) public int jarDefaultExperienceCapacity = 1024; @Config.Name("JarUpgradeCapacityChange") @Config.Comment("By how many experience points should the capacity be changed when upgrading a jar of experience?") public int jarUpgradeCapacityChange = 512; @Config.Name("JarUpgradeMaxCapacity") @Config.Comment("What should be the maximal capacity of experience points obtainable via upgrades be for the jar of experience?") public int jarUpgradeMaxCapacity = 2048; }; @Config.RequiresMcRestart @Config.Name("crafting") public static final CraftingSection crafting = new CraftingSection(); public static class CraftingSection { @Config.Name("EnableDisenchantmentTableRecipe") @Config.Comment("Should the recipe for the normal disenchantment table be available?") public boolean enableDisenchantmentTableRecipe = true; @Config.Name("EnableAutomaticTableUpgradeRecipe") @Config.Comment("Should the recipe for the automatic-upgrade (disenchantment table) be available?") public boolean enableAutomaticTableUpgradeRecipe = true; @Config.Name("EnableBulkDisenchantingTableUpgradeRecipe") @Config.Comment("Should the recipe for the bulk-disenchanting-upgrade (disenchantment table) be available?") public boolean enableBulkDisenchantingTableUpgradeRecipe = true; @Config.Name("EnableCyclingTableUpgradeRecipe") @Config.Comment("Should the recipe for the cycling-upgrade (disenchantment table) be available?") public boolean enableCyclingTableUpgradeRecipe = true; @Config.Name("EnableVoidingTableUpgradeRecipe") @Config.Comment("Should the recipe for the voiding-upgrade (disenchantment table) be available?") public boolean enableVoidingTableUpgradeRecipe = true; @Config.Name("EnableClearTableRecipe") @Config.Comment("Should the recipe for clearing all upgrades from a disenchantment table be available?") public boolean enableClearTableRecipe = true; @Config.Name("EnableJarRecipe") @Config.Comment("Should the recipe for the jar of experience be available?") public boolean enableJarRecipe = true; @Config.Name("EnableOverloadJarUpgradeRecipe") @Config.Comment("Should the recipe for the overload-upgrade (jar of experience) be available?") public boolean enableOverloadJarUpgradeRecipe = true; @Config.Name("EnableCapacityJarUpgradeRecipe") @Config.Comment("Should the recipe for upgrading the capacity (jar of experience) be available?") public boolean enableCapacityJarUpgradeRecipe = true; @Config.Name("EnableClearJarRecipe") @Config.Comment("Should the recipe for clearing all upgrades from a jar of experience be available?") public boolean enableClearJarRecipe = true; } @Config.Name("disenchanting") public static final DisenchantingSection disenchanting = new DisenchantingSection(); public static class DisenchantingSection { @Config.Name("FlatDamage") @Config.Comment("How much flat damage should be dealt to items when disenchanting?") public int flatDamage = 10; @Config.Name("MaxDurabilityDamage") @Config.Comment("How much of the item's maximum durability should be dealt as damage to items when disenchanting?") public double maxDurabilityDamage = 0.025; @Config.Name("MaxDurabilityDamageReducible") @Config.Comment({"How much of the item's maximum durability should be dealt as reducible damage to items when disenchanting?", "This can be reduced by surrounding the disenchantment table with blocks that increase the enchanting level for the enchanting table (e.g. bookshelves)."}) public double maxDurabilityDamageReducible = 0.2; @Config.Name("MachineDamageMultiplier") @Config.Comment("By how much should the damage be multiplied when using an automatic disenchantment table?") public double machineDamageMultiplier = 2.5; @Config.Name("DestroyNonDamageableItems") @Config.Comment("Should non-damageable items like books be destroyed when disenchanted?") public boolean destroyNonDamageableItems = false; @Config.Name("EnchantmentLossChance") @Config.Comment("What should the probability be that an enchantment is lost when disenchanting?") @Config.RangeDouble(min = 0.0, max = 1.0) public double enchantmentLossChance = 0.0; @Config.Name("RepairCostMultiplier") @Config.Comment({"By how much should the repair cost of the item (f.e. used by anvils) be multiplied when disenchanting?", "0.5 is halving the repair cost (using an anvil doubles the repair cost); 1.0 leaves the cost unchanged."}) @Config.RangeDouble(min = 0.0) public double repairCostMultiplier = 0.5; @Config.Name("FlatExperience") @Config.Comment({"When converting an enchantment to XP, a flat amount of experience points will be added.", "What should that amount be?"}) public int flatExperience = 0; @Config.Name("MinEnchantabilityExperience") @Config.Comment({"When converting an enchantment to XP, experience points relative to the enchantment's minimum enchantability will be added.", "What percentage of the enchantability should be used?"}) public double minEnchantabilityExperience = 0.33; @Config.Name("MaxEnchantabilityExperience") @Config.Comment({"When converting an enchantment to XP, experience points relative to the enchantment's maximum enchantability will be added.", "What percentage of the enchantability should be used?"}) public double maxEnchantabilityExperience = 0.15; @Config.Name("AutomaticDisenchantingProcessTicks") @Config.Comment("How many ticks should the disenchanting process last when using an automatic disenchantment table?") @Config.RangeInt(min = 1) public int ticksAutomaticDisenchantingProcess = 100; @Config.Name("CyclingDisenchantingTicks") @Config.Comment("How many ticks should the cycling disenchantment table wait before switching to a new enchantment?") @Config.RangeInt(min = 1) public int ticksCyclingDisenchanting = 60; @Config.Name("DisabledItems") @Config.Comment({"Which items should not be disenchantable?", "Entries are of the format `modid:itemid`; for example minecraft:dirt", "Java Regex can be used with a `[r]`-prefix; for example [r]minecraft:.* to ban all vanilla items."}) public String[] disabledItems = {}; @Config.Name("DisabledEnchantments") @Config.Comment({"Which enchantments should be ignored when disenchanting?", "Entries are of the format `modid:enchantid`; for example minecraft:bane_of_arthropods", "Java Regex can be used with a `[r]`-prefix; for example [r]minecraft:.* to ban all vanilla enchantments."}) public String[] disabledEnchantments = {}; @Config.Name("DisableCurses") @Config.Comment("Should curse-enchantments -like curse of vanishing- be ignored when disenchanting?") public boolean disableCurses = false; @Config.Name("EnableTCBehaviour") @Config.Comment({"Should items from Tinkers Construct be handled differently?", "Enchantments will not be able to be removed from these items."}) public boolean enableTCBehaviour = true; }; @Config.Name("visual") public static final VisualSection visual = new VisualSection(); public static class VisualSection { @Config.Name("BookRendererYOffset") @Config.Comment({"How should the book be positioned above the disenchantment table compared to the regular enchanting table?", "0.0 is the same as the enchanting table.", "You will probably want to set this to about 0.1, if you want to disable BookRendererFlipped."}) public double bookRendererYOffset = 0.4; @Config.Name("BookRendererFlipped") @Config.Comment("Should the book above the disenchantment table be flipped upside-down?") public boolean bookRendererFlipped = true; @Config.Name("BookRendererHidden") @Config.Comment("Should the book above the disenchantment table be completely hidden?") public boolean bookRendererHidden = false; @Config.Name("ShowUpgradesInGUI") @Config.Comment("Should the different upgrades of a disenchantment table be listed when viewing the GUI of said table?") public boolean showUpgradesInGUI = true; @Config.Name("DescriptionInGUIColor") @Config.Comment("What color should be used for additional descriptions (f.e. list of table upgrades) shown in the GUI of a disenchantment table?") public int descriptionInGUIColor = 11184810; }; @Mod.EventBusSubscriber private static class EventHandler { /** * Inject the new values and save to the config file when the config has been changed from the GUI. * * @param event The event */ @SubscribeEvent public static void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { if (event.getModID().equals(DisenchanterMain.MODID)) { ConfigManager.sync(DisenchanterMain.MODID, Config.Type.INSTANCE); } } } }
package de.ninam.projects.launcher; import ch.ntb.usb.Device; import ch.ntb.usb.USB; import ch.ntb.usb.USBException; public class LauncherService { private final byte[] CMD_STOP = new byte[]{0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; private final byte[] CMD_LED_ON = new byte[]{0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; private final byte[] CMD_LED_OFF = new byte[]{0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; private final byte[] CMD_UP = new byte[]{0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; private final byte[] CMD_DOWN = new byte[]{0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; private final byte[] CMD_LEFT = new byte[]{0x02, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; private final byte[] CMD_RIGHT = new byte[]{0x02, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; private final byte[] CMD_FIRE = new byte[]{0x02, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; private Device rocketLauncher = null; public LauncherService() { rocketLauncher = USB.getDevice((short) 0x2123, (short) 0x1010); // Vendor ID, Product ID try { rocketLauncher.open(1, 0, -1); // Open the device (Configuration(default), Interface(Control), AlternativeConfig(None)) } catch (USBException ex) { throw new RuntimeException("launcher not available"); } } public void stop() { execute(CMD_STOP, 100); } public void ledOn() { execute(CMD_LED_ON, 100); } public void ledOff() { execute(CMD_LED_OFF, 100); } public void up() { execute(CMD_UP, 100); } public void down() { execute(CMD_DOWN, 100); } public void left() { execute(CMD_LEFT, 100); } public void right() { execute(CMD_RIGHT, 100); } public void launch() { execute(CMD_FIRE, 3300); } public void rightdown() { up(); up(); up(); } public void rightup() { rightdown(); rightdown(); } public void leftdown() { rightdown(); left(); left(); } public void leftup() { rightdown(); up(); left(); } public void algorithmus() { rightup(); launch(); down(); down(); launch(); left(); left(); launch(); right(); up(); launch(); } /** * zero position. */ public void zero() { execute(CMD_DOWN, 3000); execute(CMD_LEFT, 6000); execute(CMD_RIGHT, 3000); execute(CMD_UP, 200); } /** * executes a command * * @param cmd command * @param time that the command shall be executed */ private void execute(byte[] cmd, int time) { try { if (rocketLauncher.isOpen()) { rocketLauncher.controlMsg(0x21, 0x09, 0, 0, cmd, cmd.length, 2000, false); long waitUntil = System.currentTimeMillis() + time; while (waitUntil > System.currentTimeMillis()) { //Burn Time and let the Launcher execute. } rocketLauncher.controlMsg(0x21, 0x09, 0, 0, CMD_STOP, CMD_STOP.length, 2000, false); } } catch (Exception e) { e.printStackTrace(); } } }
package de.otto.edison.vault; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnJava; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Conditional; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.util.Properties; import static de.otto.edison.vault.VaultClient.vaultClient; import static java.lang.Boolean.parseBoolean; @Component public class VaultPropertiesReader extends PropertySourcesPlaceholderConfigurer { protected Environment environment; private Logger LOG = LoggerFactory.getLogger(VaultPropertiesReader.class); protected VaultTokenFactory vaultTokenFactory = new VaultTokenFactory(); @Override public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException { if (vaultEnabled()) { setProperties(fetchPropertiesFromVault()); } super.postProcessBeanFactory(beanFactory); } @Override public void setEnvironment(final Environment environment) { this.environment = environment; super.setEnvironment(environment); } public boolean vaultEnabled() { final String vaultEnabled = environment.getProperty("edison.vault.enabled"); return vaultEnabled != null && parseBoolean(vaultEnabled); } protected VaultClient getVaultClient() { final String vaultSecretPath = environment.getProperty("edison.vault.secret-path"); final String tokenEnvironment = environment.getProperty("edison.vault.environment-token"); final String tokenFile = environment.getProperty("edison.vault.file-token"); final String vaultAppId = environment.getProperty("edison.vault.appid"); final String vaultUserId = environment.getProperty("edison.vault.userid"); String vaultBaseUrl = environment.getProperty("edison.vault.base-url"); if (StringUtils.isEmpty(vaultBaseUrl)) { vaultBaseUrl = VaultClient.getVaultAddrFromEnv(); } VaultToken vaultToken = vaultTokenFactory.createVaultToken(); if (!StringUtils.isEmpty(tokenEnvironment)) { LOG.info("read token from env variable '{}'", tokenEnvironment); vaultToken.readTokenFromEnv(tokenEnvironment); } else if (!StringUtils.isEmpty(tokenFile)) { LOG.info("read token from file '{}'", tokenFile); vaultToken.readTokenFromFile(tokenFile); } else { LOG.info("get token from login"); vaultToken.readTokenFromLogin(vaultBaseUrl, vaultAppId, vaultUserId); } return vaultClient(vaultBaseUrl, vaultSecretPath, vaultToken); } public Properties fetchPropertiesFromVault() { final Properties vaultProperties = new Properties(); final VaultClient vaultClient = getVaultClient(); for (final String key : fetchVaultPropertyKeys()) { final String trimmedKey = key.trim(); vaultProperties.setProperty(trimmedKey, vaultClient.read(trimmedKey)); } return vaultProperties; } private String[] fetchVaultPropertyKeys() { final String vaultPropertyKeys = environment.getProperty("edison.vault.properties"); if (StringUtils.isEmpty(vaultPropertyKeys)) { return new String[0]; } return vaultPropertyKeys.split(","); } }
package de.retest.recheck.ignore; import static de.retest.recheck.configuration.ProjectConfiguration.FILTER_FOLDER; import static de.retest.recheck.configuration.ProjectConfiguration.RETEST_PROJECT_CONFIG_FOLDER; import java.io.IOException; import java.net.URI; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystemNotFoundException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.tuple.Pair; import de.retest.recheck.configuration.ProjectConfiguration; import lombok.extern.slf4j.Slf4j; @Slf4j public class SearchFilterFiles { public static final String FILTER_EXTENSION = ".filter"; public static final String FILTER_JS_EXTENSION = ".filter.js"; private static final String FILTER_DIR_NAME = "filter"; private static final String WEB_FILTER_RESOURCE = "/" + FILTER_DIR_NAME + "/web/"; private static final List<String> defaultWebFilter = Arrays.asList( WEB_FILTER_RESOURCE + "positioning.filter", WEB_FILTER_RESOURCE + "style-attributes.filter", WEB_FILTER_RESOURCE + "invisible-attributes.filter", WEB_FILTER_RESOURCE + "content.filter" ); private SearchFilterFiles() {} /** * @return The default filter files from the JAR. */ public static List<Pair<String, FilterLoader>> getDefaultFilterFiles() { return defaultWebFilter.stream() .map( SearchFilterFiles.class::getResource ) .filter( Objects::nonNull ) .map( URL::toExternalForm ) .map( URI::create ) .map( SearchFilterFiles::loadFilterFromUri ) .filter( Objects::nonNull ) .collect( Collectors.toList() ); } private static Pair<String, FilterLoader> loadFilterFromUri( final URI uri ) { try { final Path path = Paths.get( uri ); return Pair.of( getFileName( path ), FilterLoader.load( path ) ); } catch ( final FileSystemNotFoundException e ) { return createFileSystemAndLoadFilter( uri ); } } private static Pair<String, FilterLoader> createFileSystemAndLoadFilter( final URI uri ) { try ( final FileSystem fs = FileSystems.newFileSystem( uri, Collections.emptyMap() ) ) { final Path path = fs.provider().getPath( uri ); return Pair.of( getFileName( path ), FilterLoader.provide( path ) ); } catch ( final IOException e ) { log.error( "Could not load filter at '{}'", uri, e ); return null; } } /** * @return The project filter files from the filter folder. */ public static List<Pair<String, FilterLoader>> getProjectFilterFiles() { return ProjectConfiguration.getInstance().getProjectConfigFolder() .map( path -> path.resolve( FILTER_FOLDER ) ) .map( SearchFilterFiles::loadFiltersFromDirectory ) .orElse( Collections.emptyList() ); } /** * @return The user filter files from the user's home. */ public static List<Pair<String, FilterLoader>> getUserFilterFiles() { final Path userFilterFolder = Paths.get( System.getProperty( "user.home" ), RETEST_PROJECT_CONFIG_FOLDER, FILTER_DIR_NAME ); if ( Files.exists( userFilterFolder ) ) { return loadFiltersFromDirectory( userFilterFolder ); } return Collections.emptyList(); } private static List<Pair<String, FilterLoader>> loadFiltersFromDirectory( final Path directory ) { try ( final Stream<Path> paths = Files.walk( directory ) ) { return paths.filter( Files::isRegularFile ) .filter( isFilterFile() ) .map( path -> Pair.of( getFileName( path ), FilterLoader.load( path ) ) ) .collect( Collectors.toList() ); } catch ( final NoSuchFileException e ) { log.warn( "No filter folder found at '{}': {}", directory, e.getMessage() ); } catch ( final IOException e ) { log.error( "Exception accessing project filter folder '{}'.", directory, e ); } return Collections.emptyList(); } private static Predicate<? super Path> isFilterFile() { return file -> file.toString().endsWith( FILTER_EXTENSION ) || file.toString().endsWith( FILTER_JS_EXTENSION ); } /** * @return Mapping from file names to filter. In the case of duplicates, specific filters are preferred over generic * filters (i.e. project filer over user filter over default filter). */ public static Map<String, Filter> toFileNameFilterMapping() { // Concat from specific to generic. return Stream.of( getProjectFilterFiles(), getUserFilterFiles(), getDefaultFilterFiles() ) .flatMap( List::stream ) .collect( Collectors.toMap( // Use the file name as key. Pair::getLeft, // Use the loaded filter as value. pair -> { final FilterLoader loader = pair.getRight(); try { return loader.load(); } catch ( final IOException e ) { log.error( "Could not load filter for name '{}'.", pair.getLeft(), e ); return Filter.FILTER_NOTHING; } }, // Prefer specific over generic filters (due to concat order). ( specificFilter, genericFilter ) -> specificFilter ) ); } private static String getFileName( final Path path ) { return path.getFileName().toString(); } public static Filter getFilterByName( final String name ) { final Filter filter = toFileNameFilterMapping().get( name ); if ( filter == null ) { final Optional<String> projectFilterDir = ProjectConfiguration.getInstance().getProjectConfigFolder() .map( path -> path.resolve( FILTER_FOLDER ) ) .map( Path::toAbsolutePath ) .map( Path::toString ); throw projectFilterDir.isPresent() ? new FilterNotFoundException( name, projectFilterDir.get() ) : new FilterNotFoundException( name ); } return filter; } }
package de.tum.in.www1.artemis.service; import java.security.SecureRandom; import java.time.Duration; import java.time.ZonedDateTime; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import de.tum.in.www1.artemis.domain.Exercise; import de.tum.in.www1.artemis.domain.ProgrammingExercise; import de.tum.in.www1.artemis.domain.User; import de.tum.in.www1.artemis.domain.enumeration.InitializationState; import de.tum.in.www1.artemis.domain.exam.Exam; import de.tum.in.www1.artemis.domain.exam.ExerciseGroup; import de.tum.in.www1.artemis.domain.exam.StudentExam; import de.tum.in.www1.artemis.domain.participation.Participation; import de.tum.in.www1.artemis.repository.ExamRepository; import de.tum.in.www1.artemis.repository.StudentExamRepository; import de.tum.in.www1.artemis.service.dto.StudentDTO; import de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException; import de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException; /** * Service Implementation for managing Course. */ @Service public class ExamService { private final Logger log = LoggerFactory.getLogger(ExamService.class); private CourseService courseService; private final UserService userService; private final ExamRepository examRepository; private final StudentExamRepository studentExamRepository; private final ParticipationService participationService; private final ProgrammingExerciseService programmingExerciseService; public ExamService(ExamRepository examRepository, StudentExamRepository studentExamRepository, UserService userService, ParticipationService participationService, ProgrammingExerciseService programmingExerciseService) { this.examRepository = examRepository; this.studentExamRepository = studentExamRepository; this.userService = userService; this.participationService = participationService; this.programmingExerciseService = programmingExerciseService; } @Autowired // break the dependency cycle public void setCourseService(CourseService courseService) { this.courseService = courseService; } /** * Save an exam. * * @param exam the entity to save * @return the persisted entity */ public Exam save(Exam exam) { log.debug("Request to save exam : {}", exam); return examRepository.save(exam); } /** * Get one exam by id. * * @param examId the id of the entity * @return the entity */ @NotNull public Exam findOne(Long examId) { log.debug("Request to get exam : {}", examId); return examRepository.findById(examId).orElseThrow(() -> new EntityNotFoundException("Exam with id: \"" + examId + "\" does not exist")); } /** * Get one exam by id with exercise groups. * * @param examId the id of the entity * @return the exam with exercise groups */ @NotNull public Exam findOneWithExerciseGroups(Long examId) { log.debug("Request to get exam with exercise groups : {}", examId); return examRepository.findWithExerciseGroupsById(examId).orElseThrow(() -> new EntityNotFoundException("Exam with id: \"" + examId + "\" does not exist")); } /** * Get one exam by id with exercise groups and exercises. * * @param examId the id of the entity * @return the exam with exercise groups */ @NotNull public Exam findOneWithExerciseGroupsAndExercises(Long examId) { log.debug("Request to get exam with exercise groups : {}", examId); return examRepository.findWithExerciseGroupsAndExercisesById(examId).orElseThrow(() -> new EntityNotFoundException("Exam with id: \"" + examId + "\" does not exist")); } /** * Get one exam by id with registered users. * * @param examId the id of the entity * @return the exam with registered users */ @NotNull public Exam findOneWithRegisteredUsers(Long examId) { log.debug("Request to get exam with registered users : {}", examId); return examRepository.findWithRegisteredUsersById(examId).orElseThrow(() -> new EntityNotFoundException("Exam with id: \"" + examId + "\" does not exist")); } /** * Get one exam by id with registered users and exercise groups. * * @param examId the id of the entity * @return the exam with registered users and exercise groups */ @NotNull public Exam findOneWithRegisteredUsersAndExerciseGroupsAndExercises(Long examId) { log.debug("Request to get exam with registered users and registered students : {}", examId); return examRepository.findWithRegisteredUsersAndExerciseGroupsAndExercisesById(examId) .orElseThrow(() -> new EntityNotFoundException("Exam with id: \"" + examId + "\" does not exist")); } /** * Get all exams for the given course. * * @param courseId the id of the course * @return the list of all exams */ public List<Exam> findAllByCourseId(Long courseId) { log.debug("REST request to get all exams for Course : {}", courseId); return examRepository.findByCourseId(courseId); } /** * Get the exam of a course with exercise groups and student exams * @param examId {Long} The courseId of the course which contains the exam * @return The exam */ public Exam findOneWithExercisesGroupsAndStudentExamsByExamId(Long examId) { log.debug("REST request to get the exam with student exams and exercise groups for Id : {}", examId); return examRepository.findOneWithEagerExercisesGroupsAndStudentExams(examId); } /** * Delete the exam by id. * * @param examId the id of the entity */ public void delete(Long examId) { log.debug("Request to delete exam : {}", examId); examRepository.deleteById(examId); } /** * Filters the visible exams (excluding the ones that are not visible yet) * * @param exams a set of exams (e.g. the ones of a course) * @return only the visible exams */ public Set<Exam> filterVisibleExams(Set<Exam> exams) { return exams.stream().filter(Exam::isVisibleToStudents).collect(Collectors.toSet()); } /** * Generates the student exams randomly based on the exam configuration and the exercise groups * * @param examId the id of the exam * @return the list of student exams with their corresponding users */ public List<StudentExam> generateStudentExams(Long examId) { List<StudentExam> studentExams = new ArrayList<>(); SecureRandom random = new SecureRandom(); // Delete all existing student exams via orphan removal Exam examWithExistingStudentExams = examRepository.findWithStudentExamsById(examId).get(); studentExamRepository.deleteInBatch(examWithExistingStudentExams.getStudentExams()); Exam exam = examRepository.findWithExercisesRegisteredUsersStudentExamsById(examId).get(); // Check that the start and end date of the exam is set if (exam.getStartDate() == null || exam.getEndDate() == null) { throw new BadRequestAlertException("The start and end date must be set for the exam", "Exam", "artemisApp.exam.validation.startAndEndMustBeSet"); } // Determine the default working time by computing the duration between start and end date of the exam Integer defaultWorkingTime = Math.toIntExact(Duration.between(exam.getStartDate(), exam.getEndDate()).toSeconds()); // Ensure that all exercise groups have at least one exercise for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) { if (exerciseGroup.getExercises().isEmpty()) { throw new BadRequestAlertException("All exercise groups must have at least one exercise", "Exam", "artemisApp.exam.validation.atLeastOneExercisePerExerciseGroup"); } } // Check that numberOfExercisesInExam is set if (exam.getNumberOfExercisesInExam() == null) { throw new BadRequestAlertException("The number of exercises in the exam is not set.", "Exam", "artemisApp.exam.validation.numberOfExercisesInExamNotSet"); } List<ExerciseGroup> exerciseGroups = exam.getExerciseGroups(); // Check that there are enough exercise groups if (exerciseGroups.size() < exam.getNumberOfExercisesInExam()) { throw new BadRequestAlertException("The number of exercise groups is too small", "Exam", "artemisApp.exam.validation.tooFewExerciseGroups"); } long numberOfOptionalExercises = exam.getNumberOfExercisesInExam() - exerciseGroups.stream().filter(ExerciseGroup::getIsMandatory).count(); // Check that there are not too much mandatory exercise groups if (numberOfOptionalExercises < 0) { throw new BadRequestAlertException("The number of mandatory exercise groups is too large", "Exam", "artemisApp.exam.validation.tooManyMandatoryExerciseGroups"); } // Prepare indices of mandatory and optional exercise groups to preserve order of exercise groups List<Integer> indicesOfMandatoryExerciseGroups = new ArrayList<>(); List<Integer> indicesOfOptionalExerciseGroups = new ArrayList<>(); for (int i = 0; i < exam.getExerciseGroups().size(); i++) { if (Boolean.TRUE.equals(exam.getExerciseGroups().get(i).getIsMandatory())) { indicesOfMandatoryExerciseGroups.add(i); } else { indicesOfOptionalExerciseGroups.add(i); } } for (User registeredUser : exam.getRegisteredUsers()) { // Create one student exam per user StudentExam studentExam = new StudentExam(); studentExam.setWorkingTime(defaultWorkingTime); studentExam.setExam(exam); studentExam.setUser(registeredUser); // Add a random exercise for each exercise group if the index of the exercise group is in assembledIndices List<Integer> assembledIndices = assembleIndicesListWithRandomSelection(indicesOfMandatoryExerciseGroups, indicesOfOptionalExerciseGroups, numberOfOptionalExercises); for (Integer index : assembledIndices) { // We get one random exercise from all preselected exercise groups studentExam.addExercise(selectRandomExercise(random, exerciseGroups.get(index))); } // Apply random exercise order if (Boolean.TRUE.equals(exam.getRandomizeExerciseOrder())) { Collections.shuffle(studentExam.getExercises()); } studentExams.add(studentExam); } studentExams = studentExamRepository.saveAll(studentExams); // TODO: make sure the student exams still contain non proxy users return studentExams; } /** * Add multiple users to the students of the exam so that they can access the exam * The passed list of UserDTOs must include the registration number (the other entries are currently ignored and can be left out) * Note: registration based on other user attributes (e.g. email, name, login) is currently NOT supported * * This method first tries to find the student in the internal Artemis user database (because the user is most probably already using Artemis). * In case the user cannot be found, we additionally search the (TUM) LDAP in case it is configured properly. * * @param courseId the id of the course * @param examId the id of the exam * @param studentDtos the list of students (with at least registration number) who should get access to the exam * @return the list of students who could not be registered for the exam, because they could NOT be found in the Artemis database and could NOT be found in the TUM LDAP */ public List<StudentDTO> registerStudentsForExam(@PathVariable Long courseId, @PathVariable Long examId, @RequestBody List<StudentDTO> studentDtos) { var course = courseService.findOne(courseId); var exam = findOneWithRegisteredUsers(examId); List<StudentDTO> notFoundStudentsDtos = new ArrayList<>(); for (var studentDto : studentDtos) { var registrationNumber = studentDto.getRegistrationNumber(); try { // 1) we use the registration number and try to find the student in the Artemis user database Optional<User> optionalStudent = userService.findUserWithGroupsAndAuthoritiesByRegistrationNumber(registrationNumber); if (optionalStudent.isPresent()) { var student = optionalStudent.get(); // we only need to add the student to the course group, if the student is not yet part of it, otherwise the student cannot access the exam (within the course) if (!student.getGroups().contains(course.getStudentGroupName())) { userService.addUserToGroup(student, course.getStudentGroupName()); } exam.addUser(student); continue; } // 2) if we cannot find the student, we use the registration number and try to find the student in the (TUM) LDAP, create it in the Artemis DB and in a potential // external user management system optionalStudent = userService.createUserFromLdap(registrationNumber); if (optionalStudent.isPresent()) { var student = optionalStudent.get(); // the newly created student needs to get the rights to access the course, otherwise the student cannot access the exam (within the course) userService.addUserToGroup(student, course.getStudentGroupName()); exam.addUser(student); continue; } // 3) if we cannot find the user in the (TUM) LDAP, we report this to the client log.warn("User with registration number " + registrationNumber + " not found in Artemis user database and not found in (TUM) LDAP"); } catch (Exception ex) { log.warn("Error while processing user with registration number " + registrationNumber + ": " + ex.getMessage(), ex); } notFoundStudentsDtos.add(studentDto); } examRepository.save(exam); return notFoundStudentsDtos; } /** * Sets the transient attribute numberOfRegisteredUsers for all given exams * * @param exams Exams for which to compute and set the number of registered users */ public void setNumberOfRegisteredUsersForExams(List<Exam> exams) { List<Long> examIds = exams.stream().map(Exam::getId).collect(Collectors.toList()); List<long[]> examIdAndRegisteredUsersCountPairs = examRepository.countRegisteredUsersByExamIds(examIds); Map<Long, Integer> registeredUsersCountMap = convertListOfCountsIntoMap(examIdAndRegisteredUsersCountPairs); exams.forEach(exam -> exam.setNumberOfRegisteredUsers(registeredUsersCountMap.get(exam.getId()).longValue())); } /** * Converts List<[examId, registeredUsersCount]> into Map<examId -> registeredUsersCount> * * @param examIdAndRegisteredUsersCountPairs list of pairs (examId, registeredUsersCount) * @return map of exam id to registered users count */ private Map<Long, Integer> convertListOfCountsIntoMap(List<long[]> examIdAndRegisteredUsersCountPairs) { return examIdAndRegisteredUsersCountPairs.stream().collect(Collectors.toMap(examIdAndRegisteredUsersCountPair -> examIdAndRegisteredUsersCountPair[0], // examId examIdAndRegisteredUsersCountPair -> Math.toIntExact(examIdAndRegisteredUsersCountPair[1]) // registeredUsersCount )); } private List<Integer> assembleIndicesListWithRandomSelection(List<Integer> mandatoryIndices, List<Integer> optionalIndices, Long numberOfOptionalExercises) { // Add all mandatory indices List<Integer> indices = new ArrayList<>(mandatoryIndices); // Add as many optional indices as numberOfOptionalExercises if (numberOfOptionalExercises > 0) { Collections.shuffle(optionalIndices); indices = Stream.concat(indices.stream(), optionalIndices.stream().limit(numberOfOptionalExercises)).collect(Collectors.toList()); } // Sort the indices to preserve the original order Collections.sort(indices); return indices; } private Exercise selectRandomExercise(SecureRandom random, ExerciseGroup exerciseGroup) { List<Exercise> exercises = new ArrayList<>(exerciseGroup.getExercises()); int randomIndex = random.nextInt(exercises.size()); return exercises.get(randomIndex); } /** * Starts all the exercises of all the student exams of an exam * * @param examId exam to which the student exams belong * @return number of generated Participations */ public Integer startExercises(Long examId) { var exam = examRepository.findWithStudentExamsExercisesParticipationsSubmissionsById(examId) .orElseThrow(() -> new EntityNotFoundException("Exam with id: \"" + examId + "\" does not exist")); var studentExams = exam.getStudentExams(); List<Participation> generatedParticipations = new ArrayList<>(); for (StudentExam studentExam : studentExams) { User student = studentExam.getUser(); for (Exercise exercise : studentExam.getExercises()) { // we start the exercise if no participation was found that was already fully initialized if (exercise.getStudentParticipations().stream() .noneMatch(studentParticipation -> studentParticipation.getParticipant().equals(student) && studentParticipation.getInitializationState() != null && studentParticipation.getInitializationState().hasCompletedState(InitializationState.INITIALIZED))) { try { if (exercise instanceof ProgrammingExercise) { // Load lazy property final var programmingExercise = programmingExerciseService.findWithTemplateParticipationAndSolutionParticipationById(exercise.getId()); ((ProgrammingExercise) exercise).setTemplateParticipation(programmingExercise.getTemplateParticipation()); } // this will create initial (empty) submissions for quiz, text, modeling and file upload var participation = participationService.startExercise(exercise, student, true); generatedParticipations.add(participation); } catch (Exception ex) { log.warn("Start exercise for student exam {} and exercise {} and student {}", studentExam.getId(), exercise.getId(), student.getId()); } } } } return generatedParticipations.size(); } /** * Returns the latest individual exam end date as determined by the working time of the student exams. * <p> * If no student exams are available, the exam end date is returned. * * @param examId the id of the exam * @return the latest end date or the exam end date if no student exams are found. May return <code>null</code>, if the exam has no start/end date. * @throws EntityNotFoundException if no exam with the given examId can be found */ public ZonedDateTime getLatestIndiviudalExamEndDate(Long examId) { return getLatestIndiviudalExamEndDate(findOne(examId)); } /** * Returns the latest individual exam end date as determined by the working time of the student exams. * <p> * If no student exams are available, the exam end date is returned. * * @param exam the exam * @return the latest end date or the exam end date if no student exams are found. May return <code>null</code>, if the exam has no start/end date. */ public ZonedDateTime getLatestIndiviudalExamEndDate(Exam exam) { if (exam.getStartDate() == null) return null; var maxWorkingTime = studentExamRepository.findMaxWorkingTimeByExamId(exam.getId()); return maxWorkingTime.map(timeInSeconds -> exam.getStartDate().plusSeconds(timeInSeconds)).orElse(exam.getEndDate()); } /** * Returns all individual exam end dates as determined by the working time of the student exams. * <p> * If no student exams are available, an empty set returned. * * @param examId the id of the exam * @return a set of all end dates. May return an empty set, if the exam has no start/end date or student exams cannot be found. * @throws EntityNotFoundException if no exam with the given examId can be found */ public Set<ZonedDateTime> getAllIndiviudalExamEndDates(Long examId) { return getAllIndiviudalExamEndDates(findOne(examId)); } /** * Returns all individual exam end dates as determined by the working time of the student exams. * <p> * If no student exams are available, an empty set returned. * * @param exam the exam * @return a set of all end dates. May return an empty set, if the exam has no start/end date or student exams cannot be found. */ public Set<ZonedDateTime> getAllIndiviudalExamEndDates(Exam exam) { if (exam.getStartDate() == null) return null; var workingTimes = studentExamRepository.findAllDistinctWorkingTimesByExamId(exam.getId()); return workingTimes.stream().map(timeInSeconds -> exam.getStartDate().plusSeconds(timeInSeconds)).collect(Collectors.toSet()); } }
package estivate.converter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import estivate.core.Converter; import lombok.extern.slf4j.Slf4j; /** * Format sample: "picto-(\\w)?\\.png" * * @author Benoit Theunissen * */ @Slf4j public class RegexExtractorConvertor implements Converter { public static final Map<String, Pattern> PATTERNS = new HashMap<String, Pattern>(); public boolean canConvert(Object value, Class<?> targetType) { return targetType.isAssignableFrom(int.class) || targetType.isAssignableFrom(int[].class) || targetType.isAssignableFrom(String.class) || targetType.isAssignableFrom(String[].class); } public Object convert(Object value, Class<?> targetType, String format) { Pattern compile = getPattern(format); Matcher matcher = compile.matcher(value.toString()); List<String> matches = new ArrayList<String>(); while (matcher.find()) { int groupCount = matcher.groupCount(); for (int i = 0; i < groupCount; i++) { String current = matcher.group(i + 1); log.debug("matching: {}", current); matches.add(current); } } if (matches.isEmpty()) { throw new RuntimeException("Expression '" + format + "' cant match '" + value.toString() + "'"); } if (targetType.isAssignableFrom(int.class)) { return Integer.parseInt(matches.get(0)); } if (targetType.isAssignableFrom(int[].class)) { int[] result = new int[matches.size()]; int idx = 0; for (String match : matches) { result[idx++] = Integer.parseInt(match); } return result; } if (targetType.isAssignableFrom(String[].class)) { return matches.toArray(new String[] {}); } return matches.get(0); } private Pattern getPattern(String format) { Pattern pattern = PATTERNS.get(format); if (pattern == null) { pattern = Pattern.compile(format); PATTERNS.put(format, pattern); } return pattern; } }
package eu.openanalytics.shinyproxy; import eu.openanalytics.containerproxy.util.BadRequestException; import javax.servlet.http.HttpServletRequest; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AppRequestInfo { private static final Pattern APP_INSTANCE_PATTERN = Pattern.compile(".*?/(app_i|app_direct_i)/([^/]*)/([^/]*)(/?.*)"); private static final Pattern APP_PATTERN = Pattern.compile(".*?/(app|app_direct)/([^/]*)(/?.*)"); private static final Pattern INSTANCE_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_.-]*$"); private final String appName; private final String appInstance; private final String subPath; public AppRequestInfo(String appName, String appInstance, String subPath) { this.appName = appName; this.appInstance = appInstance; this.subPath = subPath; } public static AppRequestInfo fromRequestOrException(HttpServletRequest request) { AppRequestInfo result = fromURI(request.getRequestURI()); if (result == null) { throw new BadRequestException("Error parsing URL."); } return result; } public static AppRequestInfo fromURI(String uri) { Matcher appMatcher = APP_PATTERN.matcher(uri); Matcher appInstanceMatcher = APP_INSTANCE_PATTERN.matcher(uri); if (appInstanceMatcher.matches()) { String appName = appInstanceMatcher.group(2); if (appName == null || appName.trim().equals("")) { throw new BadRequestException("Error parsing URL: name of app not found in URL."); } String appInstance = appInstanceMatcher.group(3); if (appInstance == null || appInstance.trim().equals("")) { throw new BadRequestException("Error parsing URL: name of instance not found in URL."); } if (appInstance.length() > 64 || !INSTANCE_NAME_PATTERN.matcher(appInstance).matches()) { throw new BadRequestException("Error parsing URL: name of instance contains invalid characters or is too long."); } String subPath = appInstanceMatcher.group(4); if (subPath == null || subPath.trim().equals("")) { subPath = null; } else { subPath = subPath.trim(); } return new AppRequestInfo(appName, appInstance, subPath); } else if (appMatcher.matches()) { String appName = appMatcher.group(2); if (appName == null || appName.trim().equals("")) { throw new BadRequestException("Error parsing URL: name of app not found in URL."); } String appInstance = "_"; String subPath = appMatcher.group(3); if (subPath == null || subPath.trim().equals("")) { subPath = null; } else { subPath = subPath.trim(); } return new AppRequestInfo(appName, appInstance, subPath); } else { return null; } } public String getAppInstance() { return appInstance; } public String getAppInstanceDisplayName() { if (appInstance.equals("_")) { return "Default"; } return appInstance; } public String getAppName() { return appName; } public String getSubPath() { return subPath; } }
package com.doit.bigfish; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Wellcome to BigFish Application ! - DEV" ); } }
package fr.lteconsulting.pomexplorer; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; import java.util.Set; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.Status; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; public class GitRepository { private final Path path; private final Set<Project> projects = new HashSet<>(); private Repository repository; public GitRepository( Path path ) { this.path = path; } public Path getPath() { return path; } public void addProject( Project project ) { projects.add( project ); } public Set<Project> getProjects() { return projects; } @Override public boolean equals( Object obj ) { if( !(obj instanceof GitRepository) ) return false; return path.equals( ((GitRepository) obj).path ); } @Override public int hashCode() { return path.hashCode(); } public void getStatus( StringBuilder log, boolean details ) { ensureOpen(); Status status; try( Git git = Git.open( Paths.get( path.toString(), ".git" ).toFile() ) ) { status = git.status().call(); int nb = status.getAdded().size() + status.getChanged().size() + status.getConflicting().size() + status.getMissing().size() + status.getModified().size() + status.getRemoved().size(); log.append( (nb > 0 ? "[*] " : "[ ] ") + path.toAbsolutePath().toString() + (nb > 0 ? (" <b>(" + nb + " changes</b>)") : "") + "<br/>" ); if( details ) { log.append( "<br/>" ); if (!status.getAdded().isEmpty()) log.append("Added: " + status.getAdded() + "<br/>"); if (!status.getChanged().isEmpty()) log.append("Changed: " + status.getChanged() + "<br/>"); if (!status.getConflicting().isEmpty()) { log.append("Conflicting: " + status.getConflicting() + "<br/>"); log.append("ConflictingStageState: " + status.getConflictingStageState() + "<br/>"); } if (!status.getMissing().isEmpty()) log.append("Missing: " + status.getMissing() + "<br/>"); if (!status.getModified().isEmpty()) log.append("Modified: " + status.getModified() + "<br/>"); if (!status.getRemoved().isEmpty()) log.append("Removed: " + status.getRemoved() + "<br/>"); if (!status.getUntracked().isEmpty()) log.append("Untracked: " + status.getUntracked() + "<br/>"); if (!status.getUntrackedFolders().isEmpty()) log.append("UntrackedFolders: " + status.getUntrackedFolders() + "<br/>"); log.append( "<br/>" ); } } catch( Exception e ) { throw new RuntimeException( e ); } closeRepo(); } private void ensureOpen() { if( repository != null ) return; FileRepositoryBuilder builder = new FileRepositoryBuilder(); try { repository = builder.setGitDir( path.toFile() ).readEnvironment().findGitDir().setWorkTree( path.toFile() ).build(); } catch( IOException e ) { e.printStackTrace(); } } private void closeRepo() { repository.close(); repository = null; } }
package info.faceland.strife.managers; import info.faceland.strife.data.BlockData; import info.faceland.strife.util.LogUtil; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.UUID; public class BlockManager { private final Map<UUID, BlockData> blockDataMap = new HashMap<>(); private final Random random = new Random(); private static final double FLAT_BLOCK_S = 10; private static final double PERCENT_BLOCK_S = 0.1; private static final long DEFAULT_BLOCK_MILLIS = 10000; private static final double MAX_BLOCK_CHANCE = 0.6; public boolean attemptBlock(UUID uuid, double maximumBlock, boolean isBlocking) { updateStoredBlock(uuid, maximumBlock); double blockChance = Math.min(blockDataMap.get(uuid).getStoredBlock() / 100, MAX_BLOCK_CHANCE); if (isBlocking) { blockChance *= 2; } LogUtil.printDebug("Block chance: " + blockChance); if (random.nextDouble() > blockChance) { return false; } reduceStoredBlock(uuid, isBlocking); return true; } public long getMillisSinceBlock(UUID uuid) { return System.currentTimeMillis() - blockDataMap.get(uuid).getLastHit(); } public double getSecondsSinceBlock(UUID uuid) { return ((double) getMillisSinceBlock(uuid)) / 1000; } private void updateStoredBlock(UUID uuid, double maximumBlock) { if (blockDataMap.get(uuid) == null) { BlockData data = new BlockData(System.currentTimeMillis() - DEFAULT_BLOCK_MILLIS, 0); blockDataMap.put(uuid, data); } double block = blockDataMap.get(uuid).getStoredBlock(); block += (FLAT_BLOCK_S + PERCENT_BLOCK_S * maximumBlock) * getSecondsSinceBlock(uuid); blockDataMap.get(uuid).setStoredBlock(Math.min(block, maximumBlock)); blockDataMap.get(uuid).setLastHit(System.currentTimeMillis()); LogUtil.printDebug("New block before clamp: " + block); } private void reduceStoredBlock(UUID uuid, boolean isBlocking) { BlockData data = blockDataMap.get(uuid); LogUtil.printDebug("Pre reduction block: " + data.getStoredBlock()); data.setStoredBlock(Math.max(0, data.getStoredBlock() - (isBlocking ? 50 : 100))); LogUtil.printDebug("Post reduction block: " + data.getStoredBlock()); } }
package com.cjt2325.cameralibrary; import android.hardware.Camera; import android.hardware.Camera.Size; import android.util.Log; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * 445263848@qq.com. */ public class CameraParamUtil { private static final String TAG = "JCameraView"; private CameraSizeComparator sizeComparator = new CameraSizeComparator(); private static CameraParamUtil cameraParamUtil = null; private CameraParamUtil() { } public static CameraParamUtil getInstance() { if (cameraParamUtil == null) { cameraParamUtil = new CameraParamUtil(); return cameraParamUtil; } else { return cameraParamUtil; } } public Size getPreviewSize(List<Camera.Size> list, int th, float rate) { Collections.sort(list, sizeComparator); int i = 0; for (Size s : list) { if ((s.width > th) && equalRate(s, rate)) { Log.i(TAG, "MakeSure Preview :w = " + s.width + " h = " + s.height); break; } i++; } if (i == list.size()) { return getBestSize(list, rate); } else { return list.get(i); } } public Size getPictureSize(List<Camera.Size> list, int th, float rate) { Collections.sort(list, sizeComparator); int i = 0; for (Size s : list) { if ((s.width > th) && equalRate(s, rate)) { Log.i(TAG, "MakeSure Picture :w = " + s.width + " h = " + s.height); break; } i++; } if (i == list.size()) { return getBestSize(list, rate); } else { return list.get(i); } } public Size getBestSize(List<Camera.Size> list, float rate) { float previewDisparity = 100; int index = 0; for (int i = 0; i < list.size(); i++) { Size cur = list.get(i); float prop = (float) cur.width / (float) cur.height; if (Math.abs(rate - prop) < previewDisparity) { previewDisparity = Math.abs(rate - prop); index = i; } } return list.get(index); } public boolean equalRate(Size s, float rate) { float r = (float) (s.width) / (float) (s.height); if (Math.abs(r - rate) <= 0.2) { return true; } else { return false; } } public boolean isSupportedFocusMode(List<String> focusList, String focusMode) { for (int i = 0; i < focusList.size(); i++) { if (focusMode.equals(focusList.get(i))) { Log.i(TAG, "FocusMode supported " + focusMode); return true; } } Log.i(TAG, "FocusMode not supported " + focusMode); return false; } public boolean isSupportedPictureFormats(List<Integer> supportedPictureFormats, int jpeg) { for (int i = 0; i < supportedPictureFormats.size(); i++) { if (jpeg == supportedPictureFormats.get(i)) { Log.i(TAG, "Formats supported " + jpeg); return true; } } Log.i(TAG, "Formats not supported " + jpeg); return false; } public class CameraSizeComparator implements Comparator<Size> { public int compare(Size lhs, Size rhs) { if (lhs.width == rhs.width) { return 0; } else if (lhs.width > rhs.width) { return 1; } else { return -1; } } } }
package mondrian.olap.fun; import junit.framework.TestCase; import org.apache.commons.collections.ComparatorUtils; import org.apache.commons.collections.comparators.ReverseComparator; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Random; /** * <code>PartialSortTest</code> is a unit test for the partial-sort algorithm * {@link FunUtil#partialSort}, which supports MDX functions like TopCount and * BottomCount. No MDX here; there are tests of TopCount etc in FunctionTest. * * @author Marc Berkowitz * @since Nov 2008 * @version $Id$ */ public class PartialSortTest extends TestCase { final Random random = new Random(); // subroutines // returns a new array of random integers private Integer[] newRandomIntegers(int length, int minValue, int maxValue) { final int delta = maxValue - minValue; Integer[] vec = new Integer[length]; for (int i = 0; i < length; i++) { vec[i] = minValue + random.nextInt(delta); } return vec; } // calls partialSort() for natural ascending or descending order private void doPartialSort(Object[] items, boolean descending, int limit) { Comparator comp = ComparatorUtils.naturalComparator(); if (descending) { comp = ComparatorUtils.reversedComparator(comp); } FunUtil.partialSort(items, comp, limit); } // predicate: checks that results have been partially sorted; simplest case, on int[] private static boolean isPartiallySorted(int[] vec, int limit, boolean descending) { // elements {0 <= i < limit} are sorted for (int i = 1; i < limit; i++) { int delta = vec[i] - vec[i - 1]; if (descending) { if (delta > 0) { return false; } } else { if (delta < 0) { return false; } } } // elements {limit <= i} are just bigger or smaller than the bound vec[limit - 1]; int bound = vec[limit - 1]; for (int i = limit; i < vec.length; i++) { int delta = vec[i] - bound; if (descending) { if (delta > 0) { return false; } } else { if (delta < 0) { return false; } } } return true; } // same predicate generalized: uses natural comparison private static <T extends Comparable> boolean isPartiallySorted( T [] vec, int limit, boolean descending) { return isPartiallySorted( vec, limit, ComparatorUtils.naturalComparator(), descending); } // same predicate generalized: uses a given Comparator private static <T> boolean isPartiallySorted( T[] vec, int limit, Comparator<? super T> order, boolean descending) { return isPartiallySorted(vec, limit, order, descending, null); } // Same predicate generalized: uses two Comparators, a sort key (ascending or // descending), and a tie-breaker (always ascending). This is a contrivance to // verify a stable partial sort, on a special input array. private static <T> boolean isPartiallySorted( T[] vec, int limit, Comparator<? super T> order, boolean descending, Comparator<? super T> tieBreaker) { // elements {0 <= i < limit} are sorted for (int i = 1; i < limit; i++) { int delta = order.compare(vec[i], vec[i - 1]); if (delta == 0) { if (tieBreaker != null && tieBreaker.compare(vec[i], vec[i - 1]) < 0) { return false; } } else if (descending) { if (delta > 0) { return false; } } else { if (delta < 0) { return false; } } } // elements {limit <= i} are just bigger or smaller than the bound vec[limit - 1]; T bound = vec[limit - 1]; for (int i = limit; i < vec.length; i++) { int delta = order.compare(vec[i], bound); if (descending) { if (delta > 0) { return false; } } else { if (delta < 0) { return false; } } } return true; } // validate the predicate isPartiallySorted() public void testPredicate1() { int errct = 0; int size = 10 * 1000; int[] vec = new int[size]; // all sorted, ascending int key = 0; for (int i = 0; i < size; i++) { vec[i] = key; key += i % 3; } if (isPartiallySorted(vec, size, true)) { errct++; } if (!isPartiallySorted(vec, size, false)) { errct++; } // partially sorted, ascending key = 0; int limit = 2000; for (int i = 0; i < limit; i++) { vec[i] = key; key += i % 3; } for (int i = limit; i < size; i++) { vec[i] = 2 * key + random.nextInt(1000); } if (isPartiallySorted(vec, limit, true)) { errct++; } if (!isPartiallySorted(vec, limit, false)) { errct++; } // all sorted, descending; key = 2 * size; for (int i = 0; i < size; i++) { vec[i] = key; key -= i % 3; } if (!isPartiallySorted(vec, size, true)) { errct++; } if (isPartiallySorted(vec, size, false)) { errct++; } // partially sorted, descending key = 2 * size; limit = 2000; for (int i = 0; i < limit; i++) { vec[i] = key; key -= i % 3; } for (int i = limit; i < size; i++) { vec[i] = key - random.nextInt(size); } if (!isPartiallySorted(vec, limit, true)) { errct++; } if (isPartiallySorted(vec, limit, false)) { errct++; } assertTrue(errct == 0); } // same as testPredicate() but boxed public void testPredicate2() { int errct = 0; int size = 10 * 1000; Integer[] vec = new Integer[size]; Random random = new Random(); // all sorted, ascending int key = 0; for (int i = 0; i < size; i++) { vec[i] = key; key += i % 3; } if (isPartiallySorted(vec, size, true)) { errct++; } if (!isPartiallySorted(vec, size, false)) { errct++; } // partially sorted, ascending key = 0; int limit = 2000; for (int i = 0; i < limit; i++) { vec[i] = key; key += i % 3; } for (int i = limit; i < size; i++) { vec[i] = 2 * key + random.nextInt(1000); } if (isPartiallySorted(vec, limit, true)) { errct++; } if (!isPartiallySorted(vec, limit, false)) { errct++; } // all sorted, descending; key = 2 * size; for (int i = 0; i < size; i++) { vec[i] = key; key -= i % 3; } if (!isPartiallySorted(vec, size, true)) { errct++; } if (isPartiallySorted(vec, size, false)) { errct++; } // partially sorted, descending key = 2 * size; limit = 2000; for (int i = 0; i < limit; i++) { vec[i] = key; key -= i % 3; } for (int i = limit; i < size; i++) { vec[i] = key - random.nextInt(size); } if (!isPartiallySorted(vec, limit, true)) { errct++; } if (isPartiallySorted(vec, limit, false)) { errct++; } assertTrue(errct == 0); } public void testQuick() { final int length = 40; final int limit = 4; Integer vec[] = newRandomIntegers(length, 0, length); // sort descending doPartialSort(vec, true, limit); assertTrue(isPartiallySorted(vec, limit, true)); } public void testOnAlreadySorted() { final int length = 200; final int limit = 8; Integer vec[] = new Integer[length]; for (int i = 0; i < length; i++) { vec[i] = i; } // sort ascending doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); } public void testOnAlreadyReverseSorted() { final int length = 200; final int limit = 8; Integer vec[] = new Integer[length]; for (int i = 0; i < length; i++) { vec[i] = length - i; } // sort ascending doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); } // tests partial sort on arras of random integers private void randomIntegerTests(int length, int limit) { Integer vec[] = newRandomIntegers(length, 0, length); // sort descending doPartialSort(vec, true, limit); assertTrue(isPartiallySorted(vec, limit, true)); // sort ascending vec = newRandomIntegers(length, 0, length); doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); // both again with a wider range of values vec = newRandomIntegers(length, 10, 4 * length); doPartialSort(vec, true, limit); assertTrue(isPartiallySorted(vec, limit, true)); vec = newRandomIntegers(length, 10, 4 * length); doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); // and again with a narrower range values vec = newRandomIntegers(length, 0, length / 10); doPartialSort(vec, true, limit); assertTrue(isPartiallySorted(vec, limit, true)); vec = newRandomIntegers(length, 0, length / 10); doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); } // test correctness public void testOnRandomIntegers() { randomIntegerTests(100, 20); randomIntegerTests(50000, 10); randomIntegerTests(50000, 500); randomIntegerTests(50000, 12000); } // test with large vector public void testOnManyRandomIntegers() { randomIntegerTests(1000 * 1000, 5000); randomIntegerTests(1000 * 1000, 10); } public void longTest() { int count = 128; while (count testOnRandomIntegers(); } } // Test stable partial sort, Test input; a vector of itens with an explicit // index; sort should not pernute the index. static class Item { final int index; final int key; Item(int index, int key) { this.index = index; this.key = key; } static final Comparator<Item> byIndex = new Comparator<Item>() { public int compare(Item x, Item y) { return x.index - y.index; } }; static final Comparator<Item> byKey = new Comparator<Item>() { public int compare(Item x, Item y) { return x.key - y.key; } }; // returns true iff VEC is partially sorted 1st by key (ascending or // descending), 2nd by index (always ascending) static boolean isStablySorted(Item[] vec, int limit, boolean desc) { return isPartiallySorted(vec, limit, byKey, desc, byIndex); } } // returns a new array of partially sorted Items private Item[] newPartlySortedItems(int length, int limit, boolean desc) { Item[] vec = new Item[length]; int factor = desc? -1 : 1; int key = desc ? (2 * length) : 0; int i; for (i = 0; i < limit; i++) { vec[i] = new Item(i, key); key += factor * (i % 3); // stutter } for (; i < length; i++) { vec[i] = new Item(i, key + factor * random.nextInt(length)); } return vec; } // returns a new array of random Items private Item[] newRandomItems(int length, int minKey, int maxKey) { final int delta = maxKey - minKey; Item[] vec = new Item[length]; for (int i = 0; i < length; i++) { vec[i] = new Item(i, minKey + random.nextInt(delta)); } return vec; } // just glue private Item[] doStablePartialSort(Item[] vec, boolean desc, int limit) { Comparator<Item> comp = Item.byKey; if (desc) { comp = new ReverseComparator(comp); } List<Item> sorted = FunUtil.stablePartialSort(Arrays.asList(vec), comp, limit); return sorted.toArray(new Item[0]); } public void testPredicateIsStablySorted() { Item[] vec = newPartlySortedItems(24 ,4, false); assertTrue(Item.isStablySorted(vec, 4, false)); assertFalse(Item.isStablySorted(vec, 4, true)); vec = newPartlySortedItems(24 ,8, true); assertTrue(Item.isStablySorted(vec, 4, true)); assertFalse(Item.isStablySorted(vec, 4, false)); vec = newPartlySortedItems(1000, 100, true); assertTrue(Item.isStablySorted(vec, 100, true)); assertTrue(Item.isStablySorted(vec, 20, true)); assertTrue(Item.isStablySorted(vec, 4, true)); } public void testStableQuick() { final int length = 40; final int limit = 4; Item vec[] = newRandomItems(length, 0, length); // sort descending vec = doStablePartialSort(vec, true, limit); assertTrue(Item.isStablySorted(vec, limit, true)); } // tests stable partial sort on arras of random Items private void randomItemTests(int length, int limit) { Item vec[] = newRandomItems(length, 0, length); // sort descending vec = doStablePartialSort(vec, true, limit); assertTrue(Item.isStablySorted(vec, limit, true)); // sort ascending vec = newRandomItems(length, 0, length); vec = doStablePartialSort(vec, false, limit); assertTrue(Item.isStablySorted(vec, limit, false)); // both again with a wider range of values vec = newRandomItems(length, 10, 4 * length); vec = doStablePartialSort(vec, true, limit); assertTrue(Item.isStablySorted(vec, limit, true)); vec = newRandomItems(length, 10, 4 * length); vec = doStablePartialSort(vec, false, limit); assertTrue(Item.isStablySorted(vec, limit, false)); // and again with a narrower range values vec = newRandomItems(length, 0, length / 10); vec = doStablePartialSort(vec, true, limit); assertTrue(Item.isStablySorted(vec, limit, true)); vec = newRandomItems(length, 0, length / 10); vec = doStablePartialSort(vec, false, limit); assertTrue(Item.isStablySorted(vec, limit, false)); } public void testStableOnRandomItems() { randomItemTests(100, 20); randomItemTests(50000, 10); randomItemTests(50000, 500); randomItemTests(50000, 12000); } // Compares elapsed time of full sort (mergesort), partial sort, and stable // partial sort on the same input set. private void speedTest(int length, int limit) { System.out.println("sorting the max " + limit + " of " + length + " random Integers"); // random input, 3 copies Integer[] vec1 = newRandomIntegers(length, 0, length / 5); // repeated keys Integer[] vec2 = new Integer[length]; Integer[] vec3 = new Integer[length]; System.arraycopy(vec1, 0, vec2, 0, length); System.arraycopy(vec1, 0, vec3, 0, length); // full sort vec1 long now = System.currentTimeMillis(); Arrays.sort(vec1); long dt = System.currentTimeMillis() - now; System.out.println(" full mergesort took " + dt + " msecs"); // partial sort vec2 now = System.currentTimeMillis(); doPartialSort(vec2, true, limit); dt = System.currentTimeMillis() - now; System.out.println(" partial quicksort took " + dt + " msecs"); // stable partial sort vec3 Comparator comp = new ReverseComparator(ComparatorUtils.naturalComparator()); List<Integer> vec3List = Arrays.asList(vec3); now = System.currentTimeMillis(); FunUtil.stablePartialSort(vec3List, comp, limit); dt = System.currentTimeMillis() - now; System.out.println(" stable partial quicksort took " + dt + " msecs"); } // compare speed on different sizes of input public void _testSpeed() { speedTest(60, 2); // tiny speedTest(600, 12); // small speedTest(600, 200); speedTest(16000, 4); // medium speedTest(16000, 160); speedTest(400 * 400, 4); // large // speedTest(1600 * 1600, 4); // very large needs bigger heap } } // End PartialSortTest.java
package net.afterlifelochie.fontbox.render; import java.util.ArrayList; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import net.afterlifelochie.fontbox.document.Element; import net.afterlifelochie.fontbox.layout.DocumentProcessor; import net.afterlifelochie.fontbox.layout.ObjectBounds; import net.afterlifelochie.fontbox.layout.PageCursor; import net.afterlifelochie.fontbox.layout.components.Page; import net.minecraft.client.gui.GuiScreen; public abstract class BookGUI extends GuiScreen { /** * The page-up mode. * * @author AfterLifeLochie */ public static enum UpMode { /** One-up (one page) mode */ ONEUP(1), /** Two-up (two page) mode */ TWOUP(2); /** The number of pages in this mode */ public final int pages; UpMode(int pages) { this.pages = pages; } } /** * Page layout container * * @author AfterLifeLochie * */ public static class Layout { public int x, y; /** * Create a new Layout container for rendering the page on screen. * * @param x * The x-coordinate to render at * @param y * The y-coordinate to render at */ public Layout(int x, int y) { this.x = x; this.y = y; } } /** The renderer's UpMode */ protected final UpMode mode; /** The page layout grid */ protected final Layout[] layout; /** The list of pages */ protected ArrayList<Page> pages; /** The list of cursors */ protected ArrayList<PageCursor> cursors; /** The current page pointer */ protected int ptr = 0; /** * <p> * Create a new Book rendering context on top of the existing Minecraft GUI * system. The book rendering properties are set through the constructor and * control how many and where pages are rendered. * </p> * * @param mode * The page mode, usually ONEUP or TWOUP. * @param layout * The layout array which specifies where the pages should be * rendered. The number of elements in the array must match the * number of pages required by the UpMode specified. */ public BookGUI(UpMode mode, Layout[] layout) { if (layout == null) throw new IllegalArgumentException("Layout cannot be null!"); if (mode == null) throw new IllegalArgumentException("Mode cannot be null!"); if (layout.length != mode.pages) throw new IllegalArgumentException("Expected " + mode.pages + " pages for mode " + mode); this.mode = mode; this.layout = layout; } /** * <p> * Updates the pages currently being rendered. * </p> * <p> * If the page read pointer is currently beyond the end of the new page * count (ie, the number of pages has reduced), the pointer will be reset to * the beginning of the book. * </p> * * @param pages * The new list of pages */ public void changePages(ArrayList<Page> pages) { if (ptr >= pages.size()) { ptr = 0; onPageChanged(this, ptr); } this.pages = pages; } /** * <p> * Updates the cursors currently being rendered. Used for debugging only. * </p> * <p> * If the cursor parameter is not null, the matching cursor for each page * will be displayed. If the cursor parameter is null, no cursors will be * rendered on the page. * </p> * * @param cursors * The list of cursors, or null if no cursors should be rendered */ public void changeCursors(ArrayList<PageCursor> cursors) { this.cursors = cursors; } @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); } @Override public void updateScreen() { super.updateScreen(); } @Override public void drawScreen(int mx, int my, float frames) { super.drawScreen(mx, my, frames); drawBackground(mx, my, frames); try { if (this.pages != null) { for (int i = 0; i < mode.pages; i++) { Layout where = layout[i]; int what = ptr + i; if (pages.size() <= what) break; Page page = pages.get(ptr + i); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); if (this.cursors != null && what < cursors.size()) { PageCursor cursor = cursors.get(what); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glColor4f(1.0f, 0.0f, 0.0f, 0.5f); GLUtils.drawDefaultRect(where.x, where.y, page.width * 0.44f, page.height * 0.44f, zLevel); GL11.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); GLUtils.drawDefaultRect(where.x + (cursor.x * 0.44f), where.y + (cursor.y * 0.44f), 1.0, 1.0, zLevel); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_TEXTURE_2D); } renderPage(page, where.x, where.y, zLevel, mx, my, frames); } } } catch (RenderException err) { err.printStackTrace(); } drawForeground(mx, my, frames); } /** * Called when the current page is changed * * @param gui * The current GUI * @param whatPtr * The new page pointer value */ public abstract void onPageChanged(BookGUI gui, int whatPtr); /** * <p> * Draw the background layer of the interface. You must leave the opengl * state such that the layout (0, 0) will be drawn in the current place. * </p> * * @param mx * The mouse x-coordinate * @param my * The mouse y-coordinate * @param frame * The partial frames rendered */ public abstract void drawBackground(int mx, int my, float frame); /** * <p> * Draw the foreground layer of the interface. The opengl state is such that * the layout coordinates (0, 0) are in the top-left corner of the written * text. * </p> * * @param mx * The mouse x-coordinate * @param my * The mouse y-coordinate * @param frame * The partial frames rendered */ public abstract void drawForeground(int mx, int my, float frame); /** * Advance to the next page */ protected void next() { if (ptr + mode.pages < pages.size()) { ptr += mode.pages; onPageChanged(this, ptr); } } /** * Go to a page * * @param where * The page pointer */ protected void go(int where) { where = where - (where % mode.pages); if (ptr != where && 0 <= where - mode.pages && where + mode.pages < pages.size()) { ptr = where; onPageChanged(this, ptr); } } /** * Reverse to the previous page */ protected void previous() { if (0 <= ptr - mode.pages) { ptr -= mode.pages; onPageChanged(this, ptr); } } @Override protected void keyTyped(char val, int code) { super.keyTyped(val, code); if (code == Keyboard.KEY_LEFT) previous(); if (code == Keyboard.KEY_RIGHT) next(); } @Override protected void mouseClicked(int mx, int my, int button) { super.mouseClicked(mx, my, button); for (int i = 0; i < mode.pages; i++) { Layout where = layout[i]; int which = ptr + i; if (pages.size() <= which) break; Page page = pages.get(ptr + i); int mouseX = mx - where.x, mouseY = my - where.y; if (mouseX >= 0 && mouseY >= 0 && mouseX <= page.width && mouseY <= page.height) { Element elem = DocumentProcessor.getElementAt(page, mouseX, mouseY); if (elem != null) elem.clicked(this, mouseX, mouseY); } } } @Override protected void mouseMovedOrUp(int mx, int my, int button) { super.mouseMovedOrUp(mx, my, button); } @Override protected void mouseClickMove(int mx, int my, int button, long ticks) { super.mouseClickMove(mx, my, button, ticks); } private void renderPage(Page page, float x, float y, float z, int mx, int my, float frame) throws RenderException { GL11.glPushMatrix(); GL11.glTranslatef(x, y, z); /* * TODO: Draw this to a displaylist, then recall the displaylist later * on. This saves us recomputing a lot of values per frame and thus * prevents avoidable performance reductions. */ int count = page.elements.size(); for (int i = 0; i < count; i++) { page.elements.get(i).render(this, mx, my, frame); if (this.cursors != null) { ObjectBounds bounds = page.elements.get(i).bounds(); if (bounds != null) { GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glColor4f(0.0f, 0.0f, 1.0f, 0.5f); GL11.glPushMatrix(); GL11.glTranslatef(bounds.x * 0.44f, bounds.y * 0.44f, 0); GLUtils.drawDefaultRect(0, 0, bounds.width * 0.44f, bounds.height * 0.44f, zLevel); GL11.glPopMatrix(); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_TEXTURE_2D); } } } GL11.glPopMatrix(); } }
package net.atos.entng.rss.parser; import net.atos.entng.rss.model.Feed; import net.atos.entng.rss.model.Item; import org.vertx.java.core.Handler; import org.vertx.java.core.json.JsonObject; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class RssParserHandler extends DefaultHandler { private StringBuffer buffer; private Feed feed; private Item item; private final Handler<JsonObject> handler; private boolean parent; public RssParserHandler(Handler<JsonObject> handler) { super(); this.handler = handler; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{ if(qName != null){ if(qName.equals("channel")){ parent = true; feed = new Feed(); }else if(qName.equals("rss")){ buffer = new StringBuffer(); }else if(qName.equals("item")){ parent = false; item = new Item(); }else { buffer = new StringBuffer(); } } } @Override public void endElement(String uri, String localName, String qName) throws SAXException{ if(qName != null){ if(qName.equals("rss")){ }else if(qName.equals("item")){ if(item != null && feed != null){ feed.addItem(item); item = null; } buffer = null; }else if(qName.equals("title")){ if(buffer != null){ if(parent){ if(feed != null) feed.setTitle(buffer.toString().trim()); }else{ if(item != null) item.setTitle(buffer.toString().trim()); } buffer = null; } }else if(qName.equals("link")){ if(buffer != null){ if(parent){ if(feed != null) feed.setLink(buffer.toString().trim()); }else{ if(item != null) item.setLink(buffer.toString().trim()); } buffer = null; } }else if(qName.equals("description")){ if(buffer != null){ if(parent){ if(feed != null) feed.setDescription(buffer.toString().trim()); }else{ if(item != null) item.setDescription(buffer.toString().trim()); } buffer = null; } }else if(qName.equals("pubDate")){ if(buffer != null){ if(parent){ if(feed != null) feed.setPubDate(buffer.toString().trim()); }else{ if(item != null) item.setPubDate(buffer.toString().trim()); } buffer = null; } }else if(qName.equals("language")){ if(buffer != null && feed != null){ feed.setLanguage(buffer.toString().trim()); buffer = null; } } } } @Override public void characters(char[] ch,int start, int length) throws SAXException{ String lecture = new String(ch,start,length); if(buffer != null) buffer.append(lecture); } @Override public void endDocument() throws SAXException { JsonObject results = (feed != null) ? feed.toJson() : new JsonObject(); results.putNumber("status", 200); handler.handle(results); } }
package camelinaction; import org.apache.camel.jsonpath.JsonPath; /** * A bean that acts as a customer service */ public class CustomerService { /** * Is it a gold customer. * <p/> * Notice that we can use any kind of Camel bean parameter binding, so we can bind the message @Body, @Header and so on. */ public boolean isGold(@JsonPath("$.order.customerId") int customerId) { // its a gold customer if the customer id is < 1000 return customerId < 1000; } /** * Is it a silver customer. * <p/> * Notice that we can use any kind of Camel bean parameter binding, so we can bind the message @Body, @Header and so on. */ public boolean isSilver(@JsonPath("$.order.customerId") int customerId) { // its a silver customer if the customer id is between 1000 and 4999 return customerId >= 1000 && customerId < 5000; } }
package nl.ekholabs.escode.action; import java.awt.Frame; import java.io.File; import java.util.Optional; import javax.swing.JFileChooser; public class SelectFileAction { private final Frame parent; public SelectFileAction(final Frame parent) { this.parent = parent; } public Optional<File> openFile() { final JFileChooser chooser = new JFileChooser(); final int result = chooser.showOpenDialog(parent); if (result == JFileChooser.APPROVE_OPTION) { final Optional<File> file = Optional.of(chooser.getSelectedFile()); return file; } return Optional.empty(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.wur.plantbreeding.gff2RDF.object; /** * This class represent Markers information. * It can be used for both genetic or physical marker. * @author Pierre-Yves Chibon -- py@chibon.fr */ public class Marker { /** Name of the marker. */ private String name = ""; /** * ID of the marker, if not empty it will be used for the URI, otherwise * the name will be. */ private String id = ""; /** SGN markers have their own identifier which we use in one query. */ private String sgnid = ""; /** * Position of the marker either on the genetic map or on the physical map. */ private String position; /** The Chromosome of the gene on the genome. */ private String chromosome; /** Start position of the gene on the genome. */ private int start; /** Stop position of the gene on the genome. */ private int stop; /** * Boolean reflecting wether the marker is located on a genetic map (true) * or a physical map (false). * Default is genetic == true */ protected boolean genetic; /** * Ask wether the marker is located on a genetic map (true) or on a physical * map (false). * @return a boolean */ public final boolean isGenetic() { return genetic; } /** * Set the boolean wether the marker is located on a genetic map (true) or * on a physical map (false). * @param tmpgenetic a boolean */ public final void setGenetic(final boolean tmpgenetic) { this.genetic = tmpgenetic; } /** * Get the name of the marker. * @return the name of the marker */ public final String getName() { return name; } /** * Set the name of the marker. * @param tmpname name of the marker */ public final void setName(final String tmpname) { this.name = tmpname; } /** * Set the chromosome of the marker. * @param tmpchr name of the chromosome */ public final void setChromosome(final String tmpchr) { this.chromosome = tmpchr; } /** * Get the chromosome on which the marker is located. * @return the chromosome of the marker */ public final String getChromosome() { return this.chromosome; } /** * Set the position of the marker, either on the genetic map or on the * physical map. * @param tmppos position of the marker */ public final void setPosition(final String tmppos) { this.position = tmppos; } /** * Set the position of the marker, either on the genetic map or on the * physical map. * @param tmppos position of the marker */ public final void setPosition(final int tmppos) { this.position = Integer.toString(tmppos); } /** * Return the position of the marker either on the genetic map or on the * physical map. * @return position of the marker */ public final String getPosition() { return this.position; } /** * Retrieve the start position of the gene on the genome. * @return a int of the start position */ public final int getStart() { return start; } /** * Set the start position of the gene on the genome. * @param tmpstart a int of the start position */ public final void setStart(final int tmpstart) { this.start = tmpstart; } /** * Set the start position of the gene on the genome. * @param tmpstart a int of the start position */ public final void setStart(final String tmpstart) { this.start = (int) Double.parseDouble(tmpstart); } /** * Retrieve the stop position of the gene on the genome. * @return a int of the stop position */ public final int getStop() { return stop; } /** * Set the stop position of the gene on the genome. * @param tmpstop a int of the start position */ public final void setStop(final int tmpstop) { this.stop = tmpstop; } /** * Set the stop position of the gene on the genome. * @param tmpstop a int of the start position */ public final void setStop(final String tmpstop) { this.stop = (int) Double.parseDouble(tmpstop); } /** * Return the id of the marker if this one is not empty, otherwise returns * the name. * @return a String which is either the id if it is set or the name. */ public String getId() { if (this.id == null || this.id.isEmpty()){ return this.name; } else { return this.id; } } /** * Set the id of the marker to be used in the URI. * @param idtmp a String of the marker identifier. */ public void setId(String idtmp) { this.id = idtmp; } /** * Retrieve the SGN Identifier used for this marker. * @return a String of the SGN identifier. */ public String getSgnid() { return sgnid; } /** * Set the SGN identifier of this marker. * @param sgnidtmp a String of the SGN identifier. */ public void setSgnid(String sgnidtmp) { this.sgnid = sgnidtmp; } }
package no.stelar7.api.r4j.impl.lol.raw; import no.stelar7.api.r4j.basic.utils.Pair; import no.stelar7.api.r4j.pojo.lol.staticdata.realm.Realm; import no.stelar7.api.r4j.basic.calling.*; import no.stelar7.api.r4j.basic.constants.api.*; import no.stelar7.api.r4j.pojo.lol.staticdata.champion.*; import no.stelar7.api.r4j.pojo.lol.staticdata.item.*; import no.stelar7.api.r4j.pojo.lol.staticdata.language.LanguageStrings; import no.stelar7.api.r4j.pojo.lol.staticdata.map.*; import no.stelar7.api.r4j.pojo.lol.staticdata.mastery.*; import no.stelar7.api.r4j.pojo.lol.staticdata.perk.*; import no.stelar7.api.r4j.pojo.lol.staticdata.profileicon.*; import no.stelar7.api.r4j.pojo.lol.staticdata.rune.*; import no.stelar7.api.r4j.pojo.lol.staticdata.summonerspell.*; import java.util.*; import java.util.Map.Entry; public final class DDragonAPI { private static final DDragonAPI INSTANCE = new DDragonAPI(); public static DDragonAPI getInstance() { return DDragonAPI.INSTANCE; } private DDragonAPI() { // Hide public constructor } public Map<Integer, StaticChampion> getChampions(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_CHAMPION_MANY); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getDD() : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_CHAMPION_MANY, data); if (chl.isPresent()) { return ((StaticChampionList) chl.get()).getData(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } StaticChampionList list = (StaticChampionList) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_CHAMPION_MANY, data); return list.getData(); } catch (ClassCastException e) { return Collections.emptyMap(); } } public List<StaticChampion> getChampionsFromId(List<Integer> freeChampionIds) { Map<Integer, StaticChampion> all = getChampions(); List<StaticChampion> champs = new ArrayList<>(); for (Integer id : freeChampionIds) { StaticChampion champ = all.get(id); if (champ != null) { champs.add(champ); } } return champs; } public List<StaticChampion> getChampionsFromId(List<Integer> freeChampionIds, String version, String locale) { Map<Integer, StaticChampion> all = getChampions(version, locale); List<StaticChampion> champs = new ArrayList<>(); for (Integer id : freeChampionIds) { StaticChampion champ = all.get(id); if (champ != null) { champs.add(champ); } } return champs; } public Map<Integer, StaticChampion> getChampions() { return getChampions(null, null); } public StaticChampion getChampion(int id, String version, String locale) { return getChampions(version, locale).get(id); } public StaticChampion getChampion(int id) { return getChampion(id, null, null); } public Map<Integer, Item> getItems(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_ITEMS); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getDD() : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_ITEMS, data); if (chl.isPresent()) { return ((ItemList) chl.get()).getData(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } ItemList list = (ItemList) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_ITEMS, data); return list.getData(); } catch (ClassCastException e) { return Collections.emptyMap(); } } public Map<Integer, Item> getItems() { return getItems(null, null); } public Item getItem(int id, String version, String locale) { return getItems(version, locale).get(id); } public Item getItem(int id) { return getItem(id, null, null); } public Map<String, String> getLanguageStrings(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_LANGUAGE_STRINGS); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getDD() : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_LANGUAGE_STRINGS, data); if (chl.isPresent()) { return ((LanguageStrings) chl.get()).getData(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } LanguageStrings list = (LanguageStrings) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_LANGUAGE_STRINGS, data); return list.getData(); } catch (ClassCastException e) { return Collections.emptyMap(); } } public Map<String, String> getLanguageStrings() { return getLanguageStrings(null, null); } /** * Returns a list of possible locales * * @return a list of strings avaliable in this language */ public List<String> getLanguages() { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_LANGUAGES); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, ""); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, ""); // add some basic data so its cached Map<String, Object> data = new TreeMap<>(); data.put("platform", Platform.UNKNOWN); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_LANGUAGES, data); if (chl.isPresent()) { return (List<String>) chl.get(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyList(); } List<String> list = (List<String>) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_LANGUAGES, data); return list; } catch (ClassCastException e) { return Collections.emptyList(); } } public Map<String, MapDetails> getMaps(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_MAPS); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getDD() : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_MAPS, data); if (chl.isPresent()) { return ((MapData) chl.get()).getData(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } MapData list = (MapData) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_MAPS, data); return list.getData(); } catch (ClassCastException e) { return Collections.emptyMap(); } } public Map<String, MapDetails> getMaps() { return getMaps(null, null); } public Map<Integer, StaticMastery> getMasteries(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_MASTERIES); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getN().get("mastery") : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_MASTERIES, data); if (chl.isPresent()) { return ((StaticMasteryList) chl.get()).getData(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } StaticMasteryList list = (StaticMasteryList) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_MASTERIES, data); return list.getData(); } catch (ClassCastException e) { return Collections.emptyMap(); } } public Map<Integer, StaticMastery> getMasteries() { return getMasteries(null, null); } public Map<String, List<List<MasteryTreeItem>>> getMasteryTree(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_MASTERIES); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getN().get("mastery") : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_MASTERIES, data); if (chl.isPresent()) { return ((StaticMasteryList) chl.get()).getTree(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } StaticMasteryList list = (StaticMasteryList) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_MASTERIES, data); return list.getTree(); } catch (ClassCastException e) { return Collections.emptyMap(); } } public Map<String, List<List<MasteryTreeItem>>> getMasteryTree() { return getMasteryTree(null, null); } public StaticMastery getMastery(int id, String version, String locale) { return getMasteries(version, locale).get(id); } public StaticMastery getMastery(int id) { return getMastery(id, null, null); } public Map<Long, ProfileIconDetails> getProfileIcons(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_PROFILEICONS); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getDD() : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_PROFILEICONS, data); if (chl.isPresent()) { return ((ProfileIconData) chl.get()).getData(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } ProfileIconData list = (ProfileIconData) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_PROFILEICONS, data); return list.getData(); } catch (ClassCastException e) { return Collections.emptyMap(); } } public Map<Long, ProfileIconDetails> getProfileIcons() { return getProfileIcons(null, null); } /** * Always returns euw */ public Realm getRealm() { return getRealm(Platform.EUW1); } public Realm getRealm(Platform region) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withURLParameter(Constants.REGION_PLACEHOLDER, region.getRealmValue()) .withEndpoint(URLEndpoint.DDRAGON_REALMS); Map<String, Object> data = new TreeMap<>(); data.put("platform", region); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_REALMS, data); if (chl.isPresent()) { return (Realm) chl.get(); } try { Realm list = (Realm) builder.build(); data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_REALMS, data); return list; } catch (ClassCastException e) { return null; } } public Map<Integer, StaticRune> getRunes(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_RUNES); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getN().get("rune") : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_RUNES, data); if (chl.isPresent()) { return ((StaticRuneList) chl.get()).getData(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } StaticRuneList list = (StaticRuneList) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_RUNES, data); return list.getData(); } catch (ClassCastException e) { return Collections.emptyMap(); } } public Map<Integer, StaticRune> getRunes() { return getRunes(null, null); } public StaticRune getRune(int id, String version, String locale) { return getRunes(version, locale).get(id); } public StaticRune getRune(int id) { return getRune(id, null, null); } public Map<Integer, StaticSummonerSpell> getSummonerSpells(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_SUMMONER_SPELLS); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getDD() : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_SUMMONER_SPELLS, data); if (chl.isPresent()) { return ((StaticSummonerSpellList) chl.get()).getData(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } StaticSummonerSpellList list = (StaticSummonerSpellList) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_SUMMONER_SPELLS, data); return list.getData(); } catch (ClassCastException e) { return Collections.emptyMap(); } } public Map<Integer, StaticSummonerSpell> getSummonerSpells() { return getSummonerSpells(null, null); } public StaticSummonerSpell getSummonerSpell(int id, String version, String locale) { return getSummonerSpells(version, locale).get(id); } public StaticSummonerSpell getSummonerSpell(int id) { return getSummonerSpell(id, null, null); } public List<String> getVersions() { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_VERSIONS); // add some basic data so its cached Map<String, Object> data = new TreeMap<>(); data.put("platform", Platform.UNKNOWN); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_VERSIONS, data); if (chl.isPresent()) { return (List<String>) chl.get(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyList(); } List<String> list = (List<String>) ret; data.put("value", list); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_VERSIONS, data); return list; } catch (ClassCastException e) { return Collections.emptyList(); } } public Map<Integer, StaticPerk> getPerks(String version, String locale) { Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_PERKS, data); if (chl.isPresent()) { return (Map<Integer, StaticPerk>) chl.get(); } Map<Integer, StaticPerk> perks = new HashMap<>(); for (Entry<Integer, PerkPath> path : getPerkPaths(version, locale).entrySet()) { for (PerkSlot slot : path.getValue().getSlots()) { for (StaticPerk perk : slot.getRunes()) { perks.put(perk.getId(), perk); } } } data.put("value", perks); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_PERKS, data); return perks; } public Map<Integer, StaticPerk> getPerks() { return getPerks(null, null); } public StaticPerk getPerk(int id, String version, String locale) { return getPerks(version, locale).get(id); } public StaticPerk getPerk(int id) { return getPerk(id, null, null); } public Map<Integer, PerkPath> getPerkPaths(String version, String locale) { DataCallBuilder builder = new DataCallBuilder() .withLimiters(false) .withProxy(Constants.DDRAGON_PROXY) .withEndpoint(URLEndpoint.DDRAGON_PERKPATHS); builder.withURLParameter(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getDD() : version); builder.withURLParameter(Constants.LOCALE_PLACEHOLDER, locale == null ? "en_US" : locale); Map<String, Object> data = new TreeMap<>(); data.put("version", version); data.put("locale", locale); Optional<?> chl = DataCall.getCacheProvider().get(URLEndpoint.DDRAGON_PERKPATHS, data); if (chl.isPresent()) { return (Map<Integer, PerkPath>) chl.get(); } try { Object ret = builder.build(); if (ret instanceof Pair) { return Collections.emptyMap(); } List<PerkPath> list = (List<PerkPath>) ret; Map<Integer, PerkPath> paths = new HashMap<>(); for (PerkPath path : list) { paths.put(path.getId(), path); } data.put("value", paths); DataCall.getCacheProvider().store(URLEndpoint.DDRAGON_PERKPATHS, data); return paths; } catch (ClassCastException e) { return Collections.emptyMap(); } } public Map<Integer, PerkPath> getPerkPaths() { return getPerkPaths(null, null); } public PerkPath getPerkPath(int id, String version, String locale) { return getPerkPaths(version, locale).get(id); } public PerkPath getPerkPath(int id) { return getPerkPath(id, null, null); } public String getTarball(String version) { return "https://ddragon.leagueoflegends.com/cdn/dragontail-{version}.tgz".replace(Constants.VERSION_PLACEHOLDER, version == null ? getRealm().getDD() : version); } public String getTarball() { return getTarball(null); } }
package nonapi.io.github.classgraph.json; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.concurrent.atomic.AtomicBoolean; /** Utils for Java serialization and deserialization. */ public final class JSONUtils { /** * JSON object key name for objects that are linked to from more than one object. Key name is only used if the * class that a JSON object was serialized from does not have its own id field annotated with {@link Id}. */ static final String ID_KEY = "__ID"; /** JSON object reference id prefix. */ static final String ID_PREFIX = "[ /** JSON object reference id suffix. */ static final String ID_SUFFIX = "]"; private static final String[] JSON_CHAR_REPLACEMENTS = new String[256]; // private static MethodHandle canAccessMethodHandle = null; // private static Method canAccessMethod = null; private static MethodHandle isAccessibleMethodHandle = null; private static Method isAccessibleMethod = null; private static MethodHandle trySetAccessibleMethodHandle = null; private static Method trySetAccessibleMethod = null; static { for (int c = 0; c < 256; c++) { if (c == 32) { c = 127; } final int nibble1 = c >> 4; final char hexDigit1 = nibble1 <= 9 ? (char) ('0' + nibble1) : (char) ('A' + nibble1 - 10); final int nibble0 = c & 0xf; final char hexDigit0 = nibble0 <= 9 ? (char) ('0' + nibble0) : (char) ('A' + nibble0 - 10); JSON_CHAR_REPLACEMENTS[c] = "\\u00" + Character.toString(hexDigit1) + Character.toString(hexDigit0); } JSON_CHAR_REPLACEMENTS['"'] = "\\\""; JSON_CHAR_REPLACEMENTS['\\'] = "\\\\"; JSON_CHAR_REPLACEMENTS['\n'] = "\\n"; JSON_CHAR_REPLACEMENTS['\r'] = "\\r"; JSON_CHAR_REPLACEMENTS['\t'] = "\\t"; JSON_CHAR_REPLACEMENTS['\b'] = "\\b"; JSON_CHAR_REPLACEMENTS['\f'] = "\\f"; final Lookup lookup = MethodHandles.lookup(); // try { // // JDK 9+: use AccessibleObject::canAccess(instance) // canAccessMethodHandle = lookup.findVirtual(AccessibleObject.class, "canAccess", // MethodType.methodType(boolean.class, Object.class)); // // Ignore // try { // canAccessMethod = AccessibleObject.class.getDeclaredMethod("canAccess"); // } catch (NoSuchMethodException | SecurityException e1) { // // Ignore try { // JDK 7/8: use AccessibleObject::isAccessible() isAccessibleMethodHandle = lookup.findVirtual(AccessibleObject.class, "isAccessible", MethodType.methodType(boolean.class)); } catch (NoSuchMethodException | IllegalAccessException e) { // Ignore } try { isAccessibleMethod = AccessibleObject.class.getDeclaredMethod("isAccessible", Object.class); } catch (NoSuchMethodException | SecurityException e1) { // Ignore } try { // JDK 9+: use AccessibleObject::trySetAccessible() rather than // AccessibleObject::setAccessible(true) trySetAccessibleMethodHandle = lookup.findVirtual(AccessibleObject.class, "trySetAccessible", MethodType.methodType(boolean.class)); } catch (NoSuchMethodException | IllegalAccessException e) { // Ignore } try { trySetAccessibleMethod = AccessibleObject.class.getDeclaredMethod("trySetAccessible"); } catch (NoSuchMethodException | SecurityException e1) { // Ignore } } /** Lookup table for fast indenting. */ private static final String[] INDENT_LEVELS = new String[17]; static { final StringBuilder buf = new StringBuilder(); for (int i = 0; i < INDENT_LEVELS.length; i++) { INDENT_LEVELS[i] = buf.toString(); buf.append(' '); } } /** * Constructor. */ private JSONUtils() { // Cannot be constructed } /** * Escape a string to be surrounded in double quotes in JSON. * * @param unsafeStr * the unsafe str * @param buf * the buf */ static void escapeJSONString(final String unsafeStr, final StringBuilder buf) { if (unsafeStr == null) { return; } // Fast path boolean needsEscaping = false; for (int i = 0, n = unsafeStr.length(); i < n; i++) { final char c = unsafeStr.charAt(i); if (c > 0xff || JSON_CHAR_REPLACEMENTS[c] != null) { needsEscaping = true; break; } } if (!needsEscaping) { buf.append(unsafeStr); return; } // Slow path for (int i = 0, n = unsafeStr.length(); i < n; i++) { final char c = unsafeStr.charAt(i); if (c > 0xff) { buf.append("\\u"); final int nibble3 = ((c) & 0xf000) >> 12; buf.append(nibble3 <= 9 ? (char) ('0' + nibble3) : (char) ('A' + nibble3 - 10)); final int nibble2 = ((c) & 0xf00) >> 8; buf.append(nibble2 <= 9 ? (char) ('0' + nibble2) : (char) ('A' + nibble2 - 10)); final int nibble1 = ((c) & 0xf0) >> 4; buf.append(nibble1 <= 9 ? (char) ('0' + nibble1) : (char) ('A' + nibble1 - 10)); final int nibble0 = ((c) & 0xf); buf.append(nibble0 <= 9 ? (char) ('0' + nibble0) : (char) ('A' + nibble0 - 10)); } else { final String replacement = JSON_CHAR_REPLACEMENTS[c]; if (replacement == null) { buf.append(c); } else { buf.append(replacement); } } } } /** * Escape a string to be surrounded in double quotes in JSON. * * @param unsafeStr * The string to escape. * @return The escaped string. */ public static String escapeJSONString(final String unsafeStr) { final StringBuilder buf = new StringBuilder(unsafeStr.length() * 2); escapeJSONString(unsafeStr, buf); return buf.toString(); } /** * Indent (depth * indentWidth) spaces. * * @param depth * the depth * @param indentWidth * the indent width * @param buf * the buf */ static void indent(final int depth, final int indentWidth, final StringBuilder buf) { final int maxIndent = INDENT_LEVELS.length - 1; for (int d = depth * indentWidth; d > 0;) { final int n = Math.min(d, maxIndent); buf.append(INDENT_LEVELS[n]); d -= n; } } static Object getFieldValue(final Object containingObj, final Field field) throws IllegalArgumentException, IllegalAccessException { final Class<?> fieldType = field.getType(); if (fieldType == Integer.TYPE) { return field.getInt(containingObj); } else if (fieldType == Long.TYPE) { return field.getLong(containingObj); } else if (fieldType == Short.TYPE) { return field.getShort(containingObj); } else if (fieldType == Double.TYPE) { return field.getDouble(containingObj); } else if (fieldType == Float.TYPE) { return field.getFloat(containingObj); } else if (fieldType == Boolean.TYPE) { return field.getBoolean(containingObj); } else if (fieldType == Byte.TYPE) { return field.getByte(containingObj); } else if (fieldType == Character.TYPE) { return field.getChar(containingObj); } else { return field.get(containingObj); } } /** * Return true for classes that can be equal to a basic value type (types that can be converted directly to and * from string representation). * * @param cls * the class * @return true, if the class is a basic value type */ static boolean isBasicValueType(final Class<?> cls) { return cls == String.class || cls == Integer.class || cls == Integer.TYPE || cls == Long.class || cls == Long.TYPE || cls == Short.class || cls == Short.TYPE || cls == Float.class || cls == Float.TYPE || cls == Double.class || cls == Double.TYPE || cls == Byte.class || cls == Byte.TYPE || cls == Character.class || cls == Character.TYPE || cls == Boolean.class || cls == Boolean.TYPE || cls.isEnum() || cls == Class.class; } /** * Return true for types that can be converted directly to and from string representation. * * @param type * the type * @return true, if the type is a basic value type */ static boolean isBasicValueType(final Type type) { if (type instanceof Class<?>) { return isBasicValueType((Class<?>) type); } else if (type instanceof ParameterizedType) { return isBasicValueType(((ParameterizedType) type).getRawType()); } else { return false; } } /** * Return true for objects that can be converted directly to and from string representation. * * @param obj * the object * @return true, if the object is null or of basic value type */ static boolean isBasicValueType(final Object obj) { return obj == null || obj instanceof String || obj instanceof Integer || obj instanceof Boolean || obj instanceof Long || obj instanceof Float || obj instanceof Double || obj instanceof Short || obj instanceof Byte || obj instanceof Character || obj.getClass().isEnum() || obj instanceof Class; } /** * Return true for objects that are collections or arrays (i.e. objects that are convertible to a JSON array). * * @param obj * the object * @return true, if the object is a collection or array */ static boolean isCollectionOrArray(final Object obj) { final Class<?> cls = obj.getClass(); return Collection.class.isAssignableFrom(cls) || cls.isArray(); } static Class<?> getRawType(final Type type) { if (type instanceof Class<?>) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) type).getRawType(); } else { throw new IllegalArgumentException("Illegal type: " + type); } } /** * Return true if the field is accessible, or can be made accessible (and make it accessible if so). * * @param fieldOrConstructor * the field or constructor * @return true if accessible */ static boolean isAccessibleOrMakeAccessible(final AccessibleObject fieldOrConstructor) { // Test if field or constructor is already accessible final AtomicBoolean accessible = new AtomicBoolean(false); // // TODO: this method needs to take an object instance reference before canAccess can be used // if (canAccessMethodHandle != null) { // // JDK 9+: use canAccess(instance) // try { // accessible.set((Boolean) canAccessMethodHandle.invokeExact(fieldOrConstructor, instance)); // } catch (Throwable e) { // // Ignore // if (canAccessMethod != null) { // accessible.set((Boolean) canAccessMethod.invoke(fieldOrConstructor, instance)); if (!accessible.get()) { if (isAccessibleMethodHandle != null) { // JDK 7/8: use isAccessible (deprecated in JDK 9+) try { // Have to use double casting and wrap in new Object[] due to Animal Sniffer bug: final Object invokeResult = isAccessibleMethodHandle .invoke(new Object[] { fieldOrConstructor }); accessible.set((Boolean) invokeResult); } catch (final Throwable e) { // Ignore } } else if (isAccessibleMethod != null) { // JDK 7/8: use isAccessible (deprecated in JDK 9+) try { accessible.set((Boolean) isAccessibleMethod.invoke(fieldOrConstructor)); } catch (final Throwable e) { // Ignore } } } // Only set accessible if field or constructor is not yet accessible if (!accessible.get()) { if (trySetAccessibleMethodHandle != null) { try { // Have to use double casting and wrap in new Object[] due to Animal Sniffer bug: final Object invokeResult = trySetAccessibleMethodHandle .invoke(new Object[] { fieldOrConstructor }); accessible.set((Boolean) invokeResult); } catch (final Throwable e) { // Ignore } } else if (trySetAccessibleMethod != null) { try { accessible.set((Boolean) trySetAccessibleMethod.invoke(fieldOrConstructor)); } catch (final Throwable e) { // Ignore } } if (!accessible.get()) { try { fieldOrConstructor.setAccessible(true); accessible.set(true); } catch (final Throwable t) { // Ignore } } if (!accessible.get()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { if (trySetAccessibleMethodHandle != null) { try { // Have to use double casting and wrap in new Object[] due to Animal Sniffer bug: final Object invokeResult = trySetAccessibleMethodHandle .invoke(new Object[] { fieldOrConstructor }); accessible.set((Boolean) invokeResult); } catch (final Throwable e) { // Ignore } } else if (trySetAccessibleMethod != null) { try { accessible.set((Boolean) trySetAccessibleMethod.invoke(fieldOrConstructor)); } catch (final Throwable e) { // Ignore } } if (!accessible.get()) { try { fieldOrConstructor.setAccessible(true); accessible.set(true); } catch (final Throwable t) { // Ignore } } return null; } }); } } return accessible.get(); } /** * Check if a field is serializable. Don't serialize transient, final, synthetic, or inaccessible fields. * * <p> * N.B. Tries to set field to accessible, which will require an "opens" declarations from modules that want to * allow this introspection. * * @param field * the field * @param onlySerializePublicFields * if true, only serialize public fields * @return true if the field is serializable */ static boolean fieldIsSerializable(final Field field, final boolean onlySerializePublicFields) { final int modifiers = field.getModifiers(); if ((!onlySerializePublicFields || Modifier.isPublic(modifiers)) && !Modifier.isTransient(modifiers) && !Modifier.isFinal(modifiers) && ((modifiers & 0x1000 /* synthetic */) == 0)) { return JSONUtils.isAccessibleOrMakeAccessible(field); } return false; } }
package se.sics.cooja.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.security.AccessControlException; import java.util.Enumeration; import java.util.Properties; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import se.sics.cooja.GUI; import se.sics.cooja.MoteType; import se.sics.cooja.Plugin; import se.sics.cooja.ProjectConfig; import se.sics.cooja.Simulation; import se.sics.cooja.dialogs.CompileContiki; import se.sics.cooja.dialogs.MessageList; import se.sics.cooja.dialogs.MessageList.MessageContainer; import se.sics.cooja.plugins.ScriptRunner; public class ExecuteJAR { private static Logger logger = Logger.getLogger(ExecuteJAR.class); public final static String SIMCONFIG_FILENAME = "simulation.csc"; public final static String EXTERNALTOOLS_FILENAME = "exttools.config"; public final static String FIRMWARE_SUFFIX = ".sky"; public static void main(String[] args) { try { if ((new File(GUI.LOG_CONFIG_FILE)).exists()) { DOMConfigurator.configure(GUI.LOG_CONFIG_FILE); } else { DOMConfigurator.configure(GUI.class.getResource("/" + GUI.LOG_CONFIG_FILE)); } } catch (AccessControlException e) { BasicConfigurator.configure(); } if (args.length > 0) { /* Generate executable JAR */ if (args.length != 1) { throw new RuntimeException( "Bad command line arguments: specify only one simulation config!" ); } generate(new File(args[0])); } else { /* Run simulation */ execute(); } } private static void generate(File config) { if (!config.exists()) { throw new RuntimeException( "Simulation config not found: " + config.getAbsolutePath() ); } /* Load simulation */ logger.info("Loading " + config); Simulation s = GUI.quickStartSimulationConfig(config, false); if (s == null) { throw new RuntimeException( "Error when creating simulation" ); } s.stopSimulation(); try { buildExecutableJAR(s.getGUI(), new File(config.getName() + ".jar")); } catch (RuntimeException e) { } System.exit(1); } final static boolean OVERWRITE = false; private static void execute() { String executeDir = null; try { executeDir = new File( ExecuteJAR.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getName(); if (!executeDir.endsWith(".jar")) { logger.fatal("Not a proper JAR archive: " + executeDir); System.exit(1); } executeDir = executeDir.substring(0, executeDir.length()-".jar".length()); new File(executeDir).mkdir(); } catch (URISyntaxException e1) { logger.fatal("Can't access JAR file name: " + e1.getMessage()); System.exit(1); } /* Unpack JAR dependencies - only when they do not already exist! */ try { InputStream inputStream; File diskFile = new File(executeDir, SIMCONFIG_FILENAME); if (OVERWRITE || !diskFile.exists()) { logger.info("Unpacking simulation config: " + SIMCONFIG_FILENAME + " -> " + diskFile.getName()); inputStream = GUI.class.getResourceAsStream("/" + SIMCONFIG_FILENAME); byte[] fileData = ArrayUtils.readFromStream(inputStream); if (fileData == null) { logger.info("Failed extracting file (read fail)"); System.exit(1); } boolean ok = ArrayUtils.writeToFile(diskFile, fileData); if (!ok) { logger.info("Failed extracting file (write fail)"); System.exit(1); } } else { logger.info("Skip: simulation config already exists: " + diskFile); } diskFile = new File(executeDir, EXTERNALTOOLS_FILENAME); if (OVERWRITE || !diskFile.exists()) { logger.info("Unpacking external tools config: " + EXTERNALTOOLS_FILENAME + " -> " + diskFile.getName()); inputStream = GUI.class.getResourceAsStream("/" + EXTERNALTOOLS_FILENAME); byte[] fileData = ArrayUtils.readFromStream(inputStream); if (fileData == null) { logger.info("Failed extracting file (read fail)"); System.exit(1); } boolean ok = ArrayUtils.writeToFile(diskFile, fileData); if (!ok) { logger.info("Failed extracting file (write fail)"); System.exit(1); } } else { logger.info("Skip: external tools config already exists: " + diskFile); } GUI.externalToolsUserSettingsFile = diskFile; int firmwareCounter = 0; while (true) { File firmwareFile = new File(firmwareCounter + FIRMWARE_SUFFIX); diskFile = new File(executeDir, firmwareCounter + FIRMWARE_SUFFIX); firmwareCounter++; if (OVERWRITE || !diskFile.exists()) { logger.info("Unpacking firmware file: " + firmwareFile.getName() + " -> " + diskFile.getName()); inputStream = GUI.class.getResourceAsStream("/" + firmwareFile.getName()); if (inputStream == null) { /* Not available in simulation */ break; } byte[] fileData = ArrayUtils.readFromStream(inputStream); if (fileData == null) { logger.info("Failed extracting file (read fail)"); System.exit(1); } boolean ok = ArrayUtils.writeToFile(diskFile, fileData); if (!ok) { logger.info("Failed extracting file (write fail)"); System.exit(1); } } else { logger.info("Skip: firmware files already exist: " + diskFile); break; } } } catch (Exception e) { logger.fatal("Error when unpacking executable JAR: " + e.getMessage()); return; } logger.info("Starting simulation"); GUI.setLookAndFeel(); GUI.quickStartSimulationConfig(new File(executeDir, SIMCONFIG_FILENAME), false); } /** * Builds executable JAR from current simulation * * @param gui GUI. Must contain simulation * @param outputFile Output file */ public static boolean buildExecutableJAR(GUI gui, File outputFile) { String executeDir = null; executeDir = outputFile.getName(); if (!executeDir.endsWith(".jar")) { throw new RuntimeException("Not a proper JAR archive: " + executeDir); } executeDir = executeDir.substring(0, executeDir.length()-".jar".length()); Simulation simulation = gui.getSimulation(); if (simulation == null) { throw new RuntimeException( "No simulation active" ); } /* Check dependencies: mote type */ for (MoteType t: simulation.getMoteTypes()) { if (!t.getClass().getName().contains("SkyMoteType")) { throw new RuntimeException( "You simulation contains the mote type: " + GUI.getDescriptionOf(t.getClass()) + "\n" + "Only the Sky Mote Type is currently supported.\n" ); } logger.info("Checking mote types: '" + GUI.getDescriptionOf(t.getClass()) + "'"); } /* Check dependencies: Contiki Test Editor */ boolean hasTestEditor = false; for (Plugin startedPlugin : gui.getStartedPlugins()) { if (startedPlugin instanceof ScriptRunner) { hasTestEditor = true; break; } } logger.info("Checking that Contiki Test Editor exists: " + hasTestEditor); if (!hasTestEditor) { throw new RuntimeException( "The simulation needs at least one active Contiki Test Editor plugin.\n" + "The plugin is needed to control the non-visualized simulation." ); } /* Create temporary directory */ File workingDir; try { workingDir = File.createTempFile("cooja", ".tmp"); workingDir.delete(); workingDir.mkdir(); logger.info("Creating temporary directory: " + workingDir.getAbsolutePath()); } catch (IOException e1) { throw (RuntimeException) new RuntimeException( "Error when creating temporary directory: " + e1.getMessage() ).initCause(e1); } /* Unpacking project JARs */ ProjectConfig config = gui.getProjectConfig(); String[] projectJARs = config.getStringArrayValue(GUI.class.getName() + ".JARFILES"); for (String jar: projectJARs) { /* Locate project */ File project = config.getUserProjectDefining(GUI.class, "JARFILES", jar); File jarFile = new File(project, jar); if (!jarFile.exists()) { jarFile = new File(project, "lib/" + jar); } if (!jarFile.exists()) { throw new RuntimeException( "Project JAR could not be found: " + jarFile.getAbsolutePath() ); } logger.info("Unpacking project JAR " + jar + " (" + project + ")"); try { Process unjarProcess = Runtime.getRuntime().exec( new String[] { "jar", "xf", jarFile.getAbsolutePath()}, null, workingDir ); unjarProcess.waitFor(); } catch (Exception e1) { throw (RuntimeException) new RuntimeException( "Error unpacking JAR file: " + e1.getMessage() ).initCause(e1); } } /* Unpacking COOJA core JARs */ String[] coreJARs = new String[] { "tools/cooja/lib/jdom.jar", "tools/cooja/lib/log4j.jar", "tools/cooja/dist/cooja.jar" }; for (String jar: coreJARs) { File jarFile = new File(GUI.getExternalToolsSetting("PATH_CONTIKI"), jar); if (!jarFile.exists()) { throw new RuntimeException( "Project JAR could not be found: " + jarFile.getAbsolutePath() ); } logger.info("Unpacking core JAR " + jar); try { Process unjarProcess = Runtime.getRuntime().exec( new String[] { "jar", "xf", jarFile.getAbsolutePath()}, null, workingDir ); unjarProcess.waitFor(); } catch (Exception e1) { throw (RuntimeException) new RuntimeException( "Error unpacking JAR file: " + e1.getMessage() ).initCause(e1); } } /* Prepare simulation config */ Element rootElement = gui.extractSimulationConfig(); logger.info("Extracting simulation configuration"); logger.info("Simconfig: Stripping project references"); rootElement.removeChildren("project"); /* Remove project references */ for (Object simElement : rootElement.getChildren()) { if (((Element) simElement).getName().equals("simulation")) { int firmwareCounter = 0; for (Object moteTypeElement : ((Element)simElement).getChildren()) { if (((Element) moteTypeElement).getName().equals("motetype")) { logger.info("Simconfig: Stripping source references"); logger.info("Simconfig: Stripping build commands"); ((Element)moteTypeElement).removeChildren("source"); /* Remove source references */ ((Element)moteTypeElement).removeChildren("commands"); /* Remove build commands */ for (Object pathElement : ((Element)moteTypeElement).getChildren()) { if (((Element) pathElement).getName().equals("firmware")) { String newName = (firmwareCounter++) + FIRMWARE_SUFFIX; /* Copy firmwares, and update firmware references */ String firmwarePath = ((Element)pathElement).getText(); File firmwareFile = gui.restorePortablePath(new File(firmwarePath)); if (!firmwareFile.exists()) { throw new RuntimeException( "Firmware file does not exist: " + firmwareFile ); } logger.info("Simconfig: Copying firmware file: " + firmwareFile.getAbsolutePath()); byte[] data = ArrayUtils.readFromFile(firmwareFile); if (data == null) { throw new RuntimeException( "Error when reading firmware file: " + firmwareFile ); } boolean ok = ArrayUtils.writeToFile(new File(workingDir, newName), data); if (!ok) { throw new RuntimeException( "Error when writing firmware file: " + firmwareFile ); } logger.info("Simconfig: Update firmware path reference: " + firmwareFile.getAbsolutePath() + " -> " + (executeDir + "/" + newName)); ((Element)pathElement).setText(executeDir + "/" + newName); } } } } } } /* Save simulation config */ File configFile = new File(workingDir, SIMCONFIG_FILENAME); try { Document doc = new Document(rootElement); FileOutputStream out = new FileOutputStream(configFile); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, out); out.close(); } catch (Exception e1) { throw (RuntimeException) new RuntimeException( "Error when writing simulation configuration: " + configFile ).initCause(e1); } logger.info("Wrote simulation configuration: " + configFile.getName()); /* Export external tools config (without projects) */ try { File externalToolsConfig = new File(workingDir, EXTERNALTOOLS_FILENAME); FileOutputStream out = new FileOutputStream(externalToolsConfig); Properties differingSettings = new Properties(); Enumeration<Object> keyEnum = GUI.currentExternalToolsSettings.keys(); while (keyEnum.hasMoreElements()) { String key = (String) keyEnum.nextElement(); String defaultSetting = GUI.getExternalToolsDefaultSetting(key, ""); String currentSetting = GUI.currentExternalToolsSettings.getProperty(key, ""); if (key.equals("DEFAULT_PROJECTDIRS")) { differingSettings.setProperty(key, ""); } else if (!defaultSetting.equals(currentSetting)) { differingSettings.setProperty(key, currentSetting); } } differingSettings.store(out, "COOJA External Tools (User specific)"); out.close(); logger.info("Wrote external tools config: " + externalToolsConfig.getName()); } catch (Exception e2) { throw (RuntimeException) new RuntimeException( "Error when writing external tools configuration: " + e2.getMessage() ).initCause(e2); } /* Delete existing META-INF dir */ File metaInfDir = new File(workingDir, "META-INF"); if (metaInfDir.exists() && metaInfDir.isDirectory()) { if (!deleteDirectory(metaInfDir)) { if (!deleteDirectory(metaInfDir)) { deleteDirectory(metaInfDir); } } } /* Prepare JAR manifest */ File manifestFile = new File(workingDir, "manifest.tmp"); if (manifestFile.exists()) { manifestFile.delete(); } StringBuilder sb = new StringBuilder(); sb.append("Manifest-Version: 1.0\r\n"); sb.append("Main-Class: " + ExecuteJAR.class.getName() + "\r\n"); sb.append("Class-path: .\r\n"); StringUtils.saveToFile(manifestFile, sb.toString()); logger.info("Wrote manifest file: " + manifestFile.getName()); /* Build executable JAR */ if (outputFile.exists()) { outputFile.delete(); } logger.info("Building executable JAR: " + outputFile); MessageList errors = new MessageList(); try { CompileContiki.compile( "jar cfm " + outputFile.getAbsolutePath() + " manifest.tmp *", null, outputFile, workingDir, null, null, errors, true ); } catch (Exception e) { logger.warn("Building executable JAR error: " + e.getMessage()); MessageContainer[] err = errors.getMessages(); for (int i=0; i < err.length; i++) { logger.fatal(">> " + err[i]); } /* Forward exception */ throw (RuntimeException) new RuntimeException("Error when building executable JAR: " + e.getMessage()).initCause(e); } /* Delete temporary working directory */ logger.info("Deleting temporary files in: " + workingDir.getAbsolutePath()); if (!deleteDirectory(workingDir)) { if (!deleteDirectory(workingDir)) { deleteDirectory(workingDir); } } /* We are done! */ logger.info("Done! To run simulation: > java -jar " + outputFile.getName()); return true; } private static boolean deleteDirectory(File path) { if(path.exists()) { File[] files = path.listFiles(); for(File file: files) { if(file.isDirectory()) { deleteDirectory(file); } else { file.delete(); } } } return(path.delete()); } }
package org.ektorp.http; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.io.input.ReaderInputStream; import org.apache.commons.lang.RandomStringUtils; import org.ektorp.*; import org.ektorp.impl.StdCouchDbConnector; import org.ektorp.impl.StdCouchDbInstance; import org.ektorp.impl.StdObjectMapperFactory; import org.ektorp.impl.StreamedCouchDbConnector; import org.ektorp.support.CouchDbDocument; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.io.StringReader; import java.util.*; /* throws: Exception in thread "main" org.ektorp.DbAccessException: java.net.SocketException: Connection reset at org.ektorp.util.Exceptions.propagate(Exceptions.java:19) at org.ektorp.http.StdHttpClient.executeRequest(StdHttpClient.java:102) at org.ektorp.http.StdHttpClient.executePutPost(StdHttpClient.java:88) at org.ektorp.http.StdHttpClient.post(StdHttpClient.java:43) at org.ektorp.http.RestTemplate.post(RestTemplate.java:53) at org.ektorp.impl.StdCouchDbConnector.queryView(StdCouchDbConnector.java:284) at BulkTest.main(BulkTest.java:83) Caused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:185) at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:149) at org.apache.http.impl.io.SocketInputBuffer.fillBuffer(SocketInputBuffer.java:110) at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:260) at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:98) at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:252) at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:281) at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:233) at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:209) at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:298) at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:483) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554) at org.ektorp.http.StdHttpClient.executeRequest(StdHttpClient.java:96) 5 more */ @Ignore public class BulkTest { private final static Logger LOG = LoggerFactory.getLogger(StdCouchDbInstance.class); private HttpClient httpClient; private StdCouchDbConnector stdCouchDbConnector; private StreamedCouchDbConnector streamedCouchDbConnector; private CouchDbInstance dbInstance; private ObjectMapper mapper; private boolean createDatabaseIfNeeded = true; private boolean deleteDatabaseIfNeeded = false; @Before public void setUp() { StdHttpClient.Builder builder = new StdHttpClient.Builder(); // read the configuration from the System properties (if you want to target another host like Cloudant) final String serverHost = System.getProperty("serverHost"); final String serverPort = System.getProperty("serverPort"); final String serverUsername = System.getProperty("serverUsername"); final String serverPassword = System.getProperty("serverPassword"); final String proxyHost = System.getProperty("proxyHost"); final String proxyPort = System.getProperty("proxyPort"); builder = builder.cleanupIdleConnections(true).caching(false).enableSSL(false); if (serverHost != null) { builder = builder.host(serverHost); builder = builder.socketTimeout(10000).connectionTimeout(5000); } if (serverPort != null) { builder = builder.port(Integer.parseInt(serverPort)); } if (serverUsername != null) { builder = builder.username(serverUsername); } if (serverPassword != null) { builder = builder.password(serverPassword); } if (proxyHost != null && proxyPort != null) { builder = builder.proxy(proxyHost).proxyPort(Integer.parseInt(proxyPort)); } httpClient = builder.build(); dbInstance = new StdCouchDbInstance(httpClient); String databasePath = this.getClass().getSimpleName() + "-DataBase"; if (deleteDatabaseIfNeeded) { if (dbInstance.checkIfDbExists(databasePath)) { dbInstance.deleteDatabase(databasePath); } } if (createDatabaseIfNeeded) { if (!dbInstance.checkIfDbExists(databasePath)) { dbInstance.createDatabase(databasePath); } } else { if (!dbInstance.checkIfDbExists(databasePath)) { throw new IllegalStateException("Database does not exists"); } } stdCouchDbConnector = new StdCouchDbConnector(databasePath, dbInstance, new StdObjectMapperFactory()); streamedCouchDbConnector = new StreamedCouchDbConnector(databasePath, dbInstance, new StdObjectMapperFactory()); mapper = new ObjectMapper(); } @After public void tearDown() { if (httpClient != null) { httpClient.shutdown(); } } @Test public void shouldDoUpdateInBulkWithOneSmallInputStreamWithStdCouchDbConnector() throws Exception { doUpdateInBulkWithOneSmallInputStream(stdCouchDbConnector); } @Test public void shouldDoUpdateInBulkWithOneSmallInputStreamWithStreamedCouchDbConnector() throws Exception { doUpdateInBulkWithOneSmallInputStream(streamedCouchDbConnector); } @Test public void shouldUpdateInBulkWithOneElementWithStdCouchDbConnector() throws Exception { doUpdateInBulkWithOneElement(stdCouchDbConnector); } @Test public void shouldUpdateInBulkWithOneElementWithStreamedCouchDbConnector() throws Exception { doUpdateInBulkWithOneElement(streamedCouchDbConnector); } @Test public void shouldUpdateInBulkWithManyElementsWithStdCouchDbConnector() throws Exception { doUpdateInBulkWithManyElements(stdCouchDbConnector); } @Test public void shouldUpdateInBulkWithManyElementsWithStreamedCouchDbConnector() throws Exception { doUpdateInBulkWithManyElements(streamedCouchDbConnector); } public void doUpdateInBulkWithOneElement(CouchDbConnector db) throws Exception { final int iterationsCount = 100; // create document "myid" try { db.create("myid", mapper.readTree("{\"i\":0}")); } catch (UpdateConflictException ex) { LOG.info("already exists - ignore : " + "myid"); } long start = System.currentTimeMillis(); for (int i = 1; i <= iterationsCount; i++) { LOG.info("Round " + i + " of " + iterationsCount); JsonNode doc = db.get(JsonNode.class, "myid"); Collection<JsonNode> docList = Collections.singleton(doc); List<DocumentOperationResult> bulkResult = db.executeBulk(docList); if (!bulkResult.isEmpty()) { throw new Exception("Got DocumentOperationResult " + bulkResult); } } long rt = System.currentTimeMillis() - start; LOG.info("Running time: " + rt + " ms"); } public void doUpdateInBulkWithManyElements(CouchDbConnector db) { final int iterationsCount = 20; final int elementsCount = 200; final List<String> allDocIds = new ArrayList<String>(); for (int i = 0; i < elementsCount; i++) { String currentId = "TestDocumentBean-" + i; allDocIds.add(currentId); } final Map<String, String> currentRevisionById = new HashMap<String, String>(); if (!deleteDatabaseIfNeeded) { for (String id : allDocIds) { try { String currentRevisionId; currentRevisionId = db.getCurrentRevision(id); currentRevisionById.put(id, currentRevisionId); } catch (DocumentNotFoundException e) { // should never occur LOG.info("DocumentNotFoundException when searching for revision of document " + id, e); } } LOG.info("currentRevisionById = " + currentRevisionById); } for (int i = 0; i < elementsCount; i++) { String currentId = "TestDocumentBean-" + i; TestDocumentBean bean = new TestDocumentBean(RandomStringUtils.randomAlphanumeric(32), RandomStringUtils.randomAlphanumeric(16), System.currentTimeMillis(), 0); String currentRevision = currentRevisionById.get(currentId); if (currentRevision != null) { bean.setId(currentId); bean.setRevision(currentRevision); db.update(bean); } else { db.create(currentId, bean); } } final ViewQuery q = new ViewQuery().allDocs().includeDocs(true).keys(allDocIds); long start = System.currentTimeMillis(); long bulkOpsTotalDuration = 0; for (int i = 1; i <= iterationsCount; i++) { LOG.info("Round " + i + " of " + iterationsCount); List<TestDocumentBean> docList = db.queryView(q, TestDocumentBean.class); for (TestDocumentBean b : docList) { // check version is as expected if (b.version != i - 1) { throw new IllegalStateException("Bean state is not as expected : " + b); } b.version = i; } long bulkOpStart = System.currentTimeMillis(); List<DocumentOperationResult> bulkResult = db.executeBulk(docList); bulkOpsTotalDuration += (System.currentTimeMillis() - bulkOpStart); if (!bulkResult.isEmpty()) { throw new RuntimeException("Got DocumentOperationResult " + bulkResult); } } List<TestDocumentBean> docList = db.queryView(q, TestDocumentBean.class); for (TestDocumentBean b : docList) { // check version is as expected if (b.version != iterationsCount) { throw new IllegalStateException("Bean state is not as expected : " + b); } } long rt = System.currentTimeMillis() - start; LOG.info("Running time: " + rt + " ms, bulkOpsTotalDuration = " + bulkOpsTotalDuration + " ms"); } public void doUpdateInBulkWithOneSmallInputStream(CouchDbConnector db) throws Exception { final int iterationsCount = 100; // create or update the document, with initial "i" value of 0 final String id = "myid"; ObjectNode originalJsonObject = (ObjectNode) mapper.readTree("{\"i\":0}"); String currentRevisionId; try { currentRevisionId = db.getCurrentRevision(id); } catch (DocumentNotFoundException e) { currentRevisionId = null; } if (currentRevisionId == null) { db.create("myid", originalJsonObject); } else { originalJsonObject.put("_id", id); originalJsonObject.put("_rev", currentRevisionId); db.update(originalJsonObject); } long start = System.currentTimeMillis(); long bulkOpsTotalDuration = 0; for (int i = 1; i <= iterationsCount; i++) { LOG.info("Round " + i + " of " + iterationsCount); ObjectNode doc = db.get(ObjectNode.class, "myid"); int iFieldValue = doc.get("i").asInt(); if (iFieldValue != i - 1) { throw new IllegalStateException("Bean state is not as expected : " + doc); } doc.put("i", i); InputStream bulkDocumentAsInputStream = new ReaderInputStream(new StringReader("[" + mapper.writeValueAsString(doc) + "]")); long bulkOpStart = System.currentTimeMillis(); List<DocumentOperationResult> bulkResult = db.executeBulk(bulkDocumentAsInputStream); bulkOpsTotalDuration += (System.currentTimeMillis() - bulkOpStart); if (!bulkResult.isEmpty()) { throw new Exception("Got DocumentOperationResult " + bulkResult); } } long rt = System.currentTimeMillis() - start; LOG.info("Running time: " + rt + " ms, bulkOpsTotalDuration = " + bulkOpsTotalDuration + " ms"); } public static class TestDocumentBean extends CouchDbDocument { private String lastName; private String firstName; private Long dateOfBirth; private int version; public TestDocumentBean() { } public TestDocumentBean(String lastName, String firstName, Long dateOfBirth, int version) { this.lastName = lastName; this.firstName = firstName; this.dateOfBirth = dateOfBirth; this.version = version; } } }