answer
stringlengths
17
10.2M
package com.smidur.aventon.model; public class SnapToRoadService { SnappedPoints[] snappedPoints; public SnappedPoints[] getSnappedPoints() { return snappedPoints; } public void setSnappedPoints(SnappedPoints[] snappedPoints) { this.snappedPoints = snappedPoints; } }
package com.wehelp.wehelp.classes; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.wehelp.wehelp.services.IServiceArrayResponseCallback; import com.wehelp.wehelp.services.IServiceErrorCallback; import com.wehelp.wehelp.services.IServiceResponseCallback; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; public class ServiceContainer { private RequestQueue requestQueue; private Context context; private String baseUrl; private SharedPreferences sharedPreferences; public static final String TAG = "WeHelpTag"; public ServiceContainer(Context context, SharedPreferences sharedPreferences) { this.context = context; this.baseUrl = "http: this.sharedPreferences = sharedPreferences; } public Context getContext() { return this.context; } public RequestQueue getRequestQueue() { if (this.requestQueue == null) { this.requestQueue = Volley.newRequestQueue(this.context); } return this.requestQueue; } public <T> void addToRequestQueue(Request<T> request, String tag) { request.setTag(TextUtils.isEmpty(tag) ? TAG : tag); VolleyLog.d("Request added to queue: %s", request.getUrl()); this.getRequestQueue().add(request); } public <T> void addToRequestQueue(Request<T> request) { request.setTag(TAG); VolleyLog.d("Request added to queue: %s", request.getUrl()); this.getRequestQueue().add(request); } public void cancelPendingRequests(Object tag) { if (this.requestQueue != null) { this.requestQueue.cancelAll(tag); } } public void PostRequest(String url, Map<String, String> params, final IServiceResponseCallback responseCallback, final IServiceErrorCallback errorCallback) { String resource = this.baseUrl + url; JsonObjectRequest postRequest = new JsonObjectRequest(resource, new JSONObject(params), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("WeHelpWS", response.toString()); responseCallback.execute(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("WeHelpWs.Error", error.toString()); errorCallback.execute(error); } } ) { @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { int mStatusCode = response.statusCode; return super.parseNetworkResponse(response); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Authorization", "Bearer " + GetAccessToken()); return params; } }; postRequest.setRetryPolicy(new DefaultRetryPolicy( 50000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); this.addToRequestQueue(postRequest); } public void PostRequest(String url, JSONObject jsonObject, final IServiceResponseCallback responseCallback, final IServiceErrorCallback errorCallback) { String resource = this.baseUrl + url; JsonObjectRequest postRequest = new JsonObjectRequest(resource, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("WeHelpWS", response.toString()); responseCallback.execute(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("WeHelpWs.Error", error.toString()); errorCallback.execute(error); } } ) { @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { int mStatusCode = response.statusCode; return super.parseNetworkResponse(response); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Authorization", "Bearer " + GetAccessToken()); return params; } }; postRequest.setRetryPolicy(new DefaultRetryPolicy( 50000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); this.addToRequestQueue(postRequest); } public void GetRequest(String url, final IServiceResponseCallback responseCallback, final IServiceErrorCallback errorCallback) { String resource = this.baseUrl + url; JsonObjectRequest getRequest = new JsonObjectRequest(resource, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("WeHelpWS", response.toString()); responseCallback.execute(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("WeHelpWs.Error", error.toString()); errorCallback.execute(error); } } ) { @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { int mStatusCode = response.statusCode; return super.parseNetworkResponse(response); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Authorization", "Bearer " + GetAccessToken()); return params; } }; getRequest.setRetryPolicy(new DefaultRetryPolicy( 50000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); this.addToRequestQueue(getRequest); } public void GetArrayRequest(String url, final IServiceArrayResponseCallback responseCallback, final IServiceErrorCallback errorCallback) { String resource = this.baseUrl + url; JsonArrayRequest getRequest = new JsonArrayRequest(resource, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("WeHelpWS", response.toString()); responseCallback.execute(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("WeHelpWs.Error", error.toString()); errorCallback.execute(error); } }) { @Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { int mStatusCode = response.statusCode; return super.parseNetworkResponse(response); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Authorization", "Bearer " + GetAccessToken()); return params; } }; getRequest.setRetryPolicy(new DefaultRetryPolicy( 50000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); this.addToRequestQueue(getRequest); } public String GetAccessToken() { //SharedPreferences sharedPreferences = this.context.getSharedPreferences("com.wehelp.wehelp", Context.MODE_PRIVATE); return sharedPreferences.getString("WEHELP_ACCESS_TOKEN", ""); } public void SaveAccessToken(String accessToken, String refreshToken) { //SharedPreferences sharedPreferences = this.context.getSharedPreferences("com.wehelp.wehelp", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("WEHELP_ACCESS_TOKEN", accessToken); editor.putString("WEHELP_REFRESH_TOKEN", refreshToken); editor.commit(); } }
package de.danoeh.antennapod.view; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.core.util.Consumer; import androidx.core.view.ViewCompat; import com.google.android.material.snackbar.Snackbar; import de.danoeh.antennapod.R; import de.danoeh.antennapod.core.util.Converter; import de.danoeh.antennapod.core.util.IntentUtils; import de.danoeh.antennapod.core.util.NetworkUtils; import de.danoeh.antennapod.core.util.ShareUtils; import de.danoeh.antennapod.core.util.playback.Timeline; public class ShownotesWebView extends WebView implements View.OnLongClickListener { private static final String TAG = "ShownotesWebView"; /** * URL that was selected via long-press. */ private String selectedUrl; private Consumer<Integer> timecodeSelectedListener; private Runnable pageFinishedListener; public ShownotesWebView(Context context) { super(context); setup(); } public ShownotesWebView(Context context, AttributeSet attrs) { super(context, attrs); setup(); } public ShownotesWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setup(); } private void setup() { setBackgroundColor(Color.TRANSPARENT); if (!NetworkUtils.networkAvailable()) { getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // Use cached resources, even if they have expired } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } getSettings().setUseWideViewPort(false); getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); getSettings().setLoadWithOverviewMode(true); setOnLongClickListener(this); setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Timeline.isTimecodeLink(url) && timecodeSelectedListener != null) { timecodeSelectedListener.accept(Timeline.getTimecodeLinkTime(url)); } else { IntentUtils.openInBrowser(getContext(), url); } return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); Log.d(TAG, "Page finished"); if (pageFinishedListener != null) { pageFinishedListener.run(); } } }); } @Override public boolean onLongClick(View v) { WebView.HitTestResult r = getHitTestResult(); if (r != null && r.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) { Log.d(TAG, "Link of webview was long-pressed. Extra: " + r.getExtra()); selectedUrl = r.getExtra(); showContextMenu(); return true; } selectedUrl = null; return false; } public boolean onContextItemSelected(MenuItem item) { if (selectedUrl == null) { return false; } switch (item.getItemId()) { case R.id.open_in_browser_item: IntentUtils.openInBrowser(getContext(), selectedUrl); break; case R.id.share_url_item: ShareUtils.shareLink(getContext(), selectedUrl); break; case R.id.copy_url_item: ClipData clipData = ClipData.newPlainText(selectedUrl, selectedUrl); android.content.ClipboardManager cm = (android.content.ClipboardManager) getContext() .getSystemService(Context.CLIPBOARD_SERVICE); cm.setPrimaryClip(clipData); Snackbar s = Snackbar.make(this, R.string.copied_url_msg, Snackbar.LENGTH_LONG); ViewCompat.setElevation(s.getView(), 100); s.show(); break; case R.id.go_to_position_item: if (Timeline.isTimecodeLink(selectedUrl) && timecodeSelectedListener != null) { timecodeSelectedListener.accept(Timeline.getTimecodeLinkTime(selectedUrl)); } else { Log.e(TAG, "Selected go_to_position_item, but URL was no timecode link: " + selectedUrl); } break; default: selectedUrl = null; return false; } selectedUrl = null; return true; } @Override protected void onCreateContextMenu(ContextMenu menu) { super.onCreateContextMenu(menu); if (selectedUrl == null) { return; } if (Timeline.isTimecodeLink(selectedUrl)) { menu.add(Menu.NONE, R.id.go_to_position_item, Menu.NONE, R.string.go_to_position_label); menu.setHeaderTitle(Converter.getDurationStringLong(Timeline.getTimecodeLinkTime(selectedUrl))); } else { Uri uri = Uri.parse(selectedUrl); final Intent intent = new Intent(Intent.ACTION_VIEW, uri); if (IntentUtils.isCallable(getContext(), intent)) { menu.add(Menu.NONE, R.id.open_in_browser_item, Menu.NONE, R.string.open_in_browser_label); } menu.add(Menu.NONE, R.id.copy_url_item, Menu.NONE, R.string.copy_url_label); menu.add(Menu.NONE, R.id.share_url_item, Menu.NONE, R.string.share_url_label); menu.setHeaderTitle(selectedUrl); } } public void setTimecodeSelectedListener(Consumer<Integer> timecodeSelectedListener) { this.timecodeSelectedListener = timecodeSelectedListener; } public void setPageFinishedListener(Runnable pageFinishedListener) { this.pageFinishedListener = pageFinishedListener; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(Math.max(getMeasuredWidth(), getMinimumWidth()), Math.max(getMeasuredHeight(), getMinimumHeight())); } }
package edu.utexas.ee360p_teamproject; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { ///comment super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
package johnteee.imageasyncloader; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import android.util.Log; import android.view.animation.AnimationUtils; import android.widget.ImageView; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; class ImageAsyncHelper { private static final int MIB_IN_BYTES = 1024 * 1024; private Handler uiHandler = new Handler(Looper.getMainLooper()); private ConcurrentHashMap<String, Long> viewTimeOrderMap; private int cacheSize; private BitmapCacheWithARC resBitmapCache; ImageAsyncHelper() { this(30); } ImageAsyncHelper(float cacheSizeInMiB) { this.cacheSize = (int) (cacheSizeInMiB * MIB_IN_BYTES); init(); } private void init() { resBitmapCache = new BitmapCacheWithARC(cacheSize); viewTimeOrderMap = new ConcurrentHashMap<>(); } public void loadImageResAsync(final Context context, final ImageView imageView, final int resId, final int req_width, final int req_height) { final String keyOfView = getKeyOfObject(imageView); final long myOperatingExactTimestamp = System.currentTimeMillis(); viewTimeOrderMap.put(keyOfView, myOperatingExactTimestamp); BitmapDrawable bitmapDrawable = resBitmapCache.get(getDrawableKeyByResId(resId)); if (!(ImageUtils.isBitmapDrawableEmptyOrRecycled(bitmapDrawable))) { setImageBitmapOnUiThread(imageView, bitmapDrawable, myOperatingExactTimestamp, false); return; } // Avoid recycling ImageViews displayed wrong images. setImageBitmapOnUiThread(imageView, null, myOperatingExactTimestamp, false); AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { BitmapDrawable existingBitmapDrawable = resBitmapCache.get(getDrawableKeyByResId(resId)); if (! ImageUtils.isBitmapDrawableEmptyOrRecycled(existingBitmapDrawable)) { return null; } Bitmap newBitmap = ImageUtils.decodeSampledBitmapFromResource(context.getResources(), resId, req_width, req_height); BitmapDrawable newBitmapDrawable = new BitmapDrawable(context.getResources(), newBitmap); resBitmapCache.putWithARC(getDrawableKeyByResId(resId), newBitmapDrawable); setImageBitmapOnUiThread(imageView, newBitmapDrawable, myOperatingExactTimestamp); return null; } }; asyncTask.execute(); } @NonNull private String getDrawableKeyByResId(int resId) { return "drawable_" + resId; } private String getKeyOfObject(Object object) { String value = Objects.toString(object); Log.d("test", value); return value; } private void setImageBitmapOnUiThread(final ImageView imageView, final BitmapDrawable bitmapDrawable, final long myOperatingExactTimestamp) { setImageBitmapOnUiThread(imageView, bitmapDrawable, myOperatingExactTimestamp, true); } /** * * @param imageView * @param bitmapDrawable * @param myOperatingExactTimestamp To avoid the disorder problems of imageview updating. */ private void setImageBitmapOnUiThread(final ImageView imageView, final BitmapDrawable bitmapDrawable, final long myOperatingExactTimestamp, final boolean withAnimation) { uiHandler.post(new Runnable() { @Override public void run() { String keyOfView = getKeyOfObject(imageView); Long lastTimestamp = viewTimeOrderMap.get(keyOfView); if (lastTimestamp == null || myOperatingExactTimestamp >= lastTimestamp) { resBitmapCache.doThingsWithARCSafe(new Runnable() { @Override public void run() { Drawable oldDrawable = imageView.getDrawable(); if (bitmapDrawable == oldDrawable) { return; } resBitmapCache.changeDrawableARCAndCheck(oldDrawable, -1); if (bitmapDrawable == null || (! ImageUtils.isBitmapDrawableEmptyOrRecycled(bitmapDrawable))) { imageView.setImageDrawable(bitmapDrawable); resBitmapCache.changeDrawableARCAndCheck(bitmapDrawable, 1); if (withAnimation) { imageView.startAnimation(AnimationUtils.loadAnimation(imageView.getContext(), android.R.anim.fade_in)); } } } }); } } }); } public void terminate() { resBitmapCache.terminate(); viewTimeOrderMap.clear(); } }
package me.devsaki.hentoid.util.network; import android.content.Context; import android.net.Uri; import android.text.TextUtils; import android.util.Pair; import android.webkit.CookieManager; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import androidx.annotation.NonNull; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import me.devsaki.hentoid.BuildConfig; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import timber.log.Timber; /** * Helper for HTTP protocol operations */ public class HttpHelper { public static final int DEFAULT_REQUEST_TIMEOUT = 30000; // 30 seconds // Keywords of the HTTP protocol public static final String HEADER_ACCEPT_KEY = "accept"; public static final String HEADER_COOKIE_KEY = "cookie"; public static final String HEADER_REFERER_KEY = "referer"; public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_USER_AGENT = "User-Agent"; public static final String POST_MIME_TYPE = "application/x-www-form-urlencoded"; public static final Set<String> COOKIES_STANDARD_ATTRS = new HashSet<>(); // To display sites with desktop layouts public static final String DESKTOP_USER_AGENT_PATTERN = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) %s Safari/537.36"; public static String defaultUserAgent = null; public static String defaultChromeAgent = null; public static int defaultChromeVersion = -1; // Error messages public static final String AGENT_INIT_ISSUE = "Call initUserAgents first to initialize them !"; static { // Can't be done on the variable initializer as Set.of is only available since API R COOKIES_STANDARD_ATTRS.addAll(Arrays.asList("expires", "max-age", "domain", "path", "secure", "httponly", "samesite")); } private HttpHelper() { throw new IllegalStateException("Utility class"); } /** * Read an HTML resource from the given URL and retrieve it as a Document * * @param url URL to read the resource from * @return HTML resource read from the given URL represented as a Document * @throws IOException in case something bad happens when trying to access the online resource */ @Nullable public static Document getOnlineDocument(String url) throws IOException { return getOnlineDocument(url, null, true, true); } /** * Read an HTML resource from the given URL, using the given headers and agent and retrieve it as a Document * * @param url URL to read the resource from * @param headers Headers to use when building the request * @param useHentoidAgent True if the Hentoid User-Agent has to be used; false if a neutral User-Agent has to be used * @return HTML resource read from the given URL represented as a Document * @throws IOException in case something bad happens when trying to access the online resource */ @Nullable public static Document getOnlineDocument(String url, List<Pair<String, String>> headers, boolean useHentoidAgent, boolean useWebviewAgent) throws IOException { ResponseBody resource = getOnlineResource(url, headers, true, useHentoidAgent, useWebviewAgent).body(); if (resource != null) { return Jsoup.parse(resource.string()); } return null; } @Nullable public static Document postOnlineDocument( String url, List<Pair<String, String>> headers, boolean useHentoidAgent, boolean useWebviewAgent, @NonNull final String body, @NonNull final String mimeType) throws IOException { ResponseBody resource = postOnlineResource(url, headers, true, useHentoidAgent, useWebviewAgent, body, mimeType).body(); if (resource != null) { return Jsoup.parse(resource.string()); } return null; } /** * Read a resource from the given URL with HTTP GET, using the given headers and agent * * @param url URL to read the resource from * @param headers Headers to use when building the request * @param useHentoidAgent True if the Hentoid User-Agent has to be used; false if a neutral User-Agent has to be used * @return HTTP response * @throws IOException in case something bad happens when trying to access the online resource */ public static Response getOnlineResource(@NonNull String url, @Nullable List<Pair<String, String>> headers, boolean useMobileAgent, boolean useHentoidAgent, boolean useWebviewAgent) throws IOException { Request.Builder requestBuilder = buildRequest(url, headers, useMobileAgent, useHentoidAgent, useWebviewAgent); Request request = requestBuilder.get().build(); return OkHttpClientSingleton.getInstance(DEFAULT_REQUEST_TIMEOUT).newCall(request).execute(); } public static Response getOnlineResourceFast(@NonNull String url, @Nullable List<Pair<String, String>> headers, boolean useMobileAgent, boolean useHentoidAgent, boolean useWebviewAgent) throws IOException { Request.Builder requestBuilder = buildRequest(url, headers, useMobileAgent, useHentoidAgent, useWebviewAgent); Request request = requestBuilder.get().build(); return OkHttpClientSingleton.getInstance(2000, 10000).newCall(request).execute(); } /** * Read a resource from the given URL with HTTP POST, using the given headers and agent * * @param url URL to read the resource from * @param headers Headers to use when building the request * @param useHentoidAgent True if the Hentoid User-Agent has to be used; false if a neutral User-Agent has to be used * @param body Body of the resource to post * @return HTTP response * @throws IOException in case something bad happens when trying to access the online resource */ public static Response postOnlineResource( @NonNull String url, @Nullable List<Pair<String, String>> headers, boolean useMobileAgent, boolean useHentoidAgent, boolean useWebviewAgent, @NonNull final String body, @NonNull final String mimeType) throws IOException { Request.Builder requestBuilder = buildRequest(url, headers, useMobileAgent, useHentoidAgent, useWebviewAgent); Request request = requestBuilder.post(RequestBody.create(body, MediaType.parse(mimeType))).build(); return OkHttpClientSingleton.getInstance(DEFAULT_REQUEST_TIMEOUT).newCall(request).execute(); } /** * Build an HTTP request using the given arguments * * @param url URL to read the resource from * @param headers Headers to use when building the request * @param useMobileAgent True if a mobile User-Agent has to be used; false if a desktop User-Agent has to be used * @param useHentoidAgent True if the Hentoid User-Agent has to be used; false if a neutral User-Agent has to be used * @return HTTP request built with the given arguments */ private static Request.Builder buildRequest(@NonNull String url, @Nullable List<Pair<String, String>> headers, boolean useMobileAgent, boolean useHentoidAgent, boolean useWebviewAgent) { Request.Builder requestBuilder = new Request.Builder().url(url); if (headers != null) for (Pair<String, String> header : headers) if (header.second != null) requestBuilder.addHeader(header.first, header.second); requestBuilder.header(HEADER_USER_AGENT, useMobileAgent ? getMobileUserAgent(useHentoidAgent, useWebviewAgent) : getDesktopUserAgent(useHentoidAgent, useWebviewAgent)); return requestBuilder; } /** * Convert the given OkHttp {@link Response} into a {@link WebResourceResponse} * * @param resp OkHttp {@link Response} * @return The {@link WebResourceResponse} converted from the given OkHttp {@link Response} */ public static WebResourceResponse okHttpResponseToWebkitResponse(@NonNull final Response resp, @NonNull final InputStream is) { final String contentTypeValue = resp.header(HEADER_CONTENT_TYPE); WebResourceResponse result; Map<String, String> responseHeaders = okHttpHeadersToWebResourceHeaders(resp.headers().toMultimap()); String message = resp.message(); if (message.trim().isEmpty()) message = "None"; if (contentTypeValue != null) { Pair<String, String> details = cleanContentType(contentTypeValue); result = new WebResourceResponse(details.first, details.second, resp.code(), message, responseHeaders, is); } else { result = new WebResourceResponse("application/octet-stream", null, resp.code(), message, responseHeaders, is); } return result; } /** * "Flatten"" HTTP headers from an OkHttp-compatible structure to a Webkit-compatible structure * to be used with {@link android.webkit.WebResourceRequest} or {@link android.webkit.WebResourceResponse} * * @param okHttpHeaders HTTP Headers structured according to the convention used by OkHttp * @return "Flattened" HTTP headers structured according to the convention used by Webkit */ private static Map<String, String> okHttpHeadersToWebResourceHeaders(@NonNull final Map<String, List<String>> okHttpHeaders) { Map<String, String> result = new HashMap<>(); for (Map.Entry<String, List<String>> entry : okHttpHeaders.entrySet()) { List<String> values = entry.getValue(); if (values != null) result.put(entry.getKey(), TextUtils.join(getValuesSeparatorFromHttpHeader(entry.getKey()), values)); } return result; } /** * Convert request HTTP headers from a Webkit-compatible structure to an OkHttp-compatible structure * and enrich them with current cookies * * @param webkitRequestHeaders HTTP request Headers structured according to the convention used by Webkit * @param url Corresponding URL * @return HTTP request Headers structured according to the convention used by OkHttp */ public static List<Pair<String, String>> webkitRequestHeadersToOkHttpHeaders(@Nullable final Map<String, String> webkitRequestHeaders, @Nullable String url) { List<Pair<String, String>> result = new ArrayList<>(); if (webkitRequestHeaders != null) for (Map.Entry<String, String> entry : webkitRequestHeaders.entrySet()) result.add(new Pair<>(entry.getKey(), entry.getValue())); if (url != null) addCurrentCookiesToHeader(url, result); return result; } /** * Add current cookies of the given URL to the given headers structure * * @param url URL to get cookies for * @param headers Structure to populate */ public static void addCurrentCookiesToHeader(@NonNull final String url, @NonNull List<Pair<String, String>> headers) { String cookieStr = getCookies(url); if (!cookieStr.isEmpty()) headers.add(new Pair<>(HEADER_COOKIE_KEY, cookieStr)); } /** * Get the values separator used inside the given HTTP header key * * @param header key of the HTTP header * @return Values separator used inside the given HTTP header key */ private static String getValuesSeparatorFromHttpHeader(@NonNull final String header) { String separator = ", "; // HTTP spec if (header.equalsIgnoreCase("set-cookie") || header.equalsIgnoreCase("www-authenticate") || header.equalsIgnoreCase("proxy-authenticate")) separator = "\n"; // Special case : commas may appear in these headers => use a newline delimiter return separator; } /** * Process the value of a "Content-Type" HTTP header and return its parts * * @param rawContentType Value of the "Content-type" header * @return Pair containing * - The content-type (MIME-type) as its first value * - The charset, if it has been transmitted, as its second value (may be null) */ public static Pair<String, String> cleanContentType(@NonNull String rawContentType) { if (rawContentType.contains("charset=")) { final String[] contentTypeAndEncoding = rawContentType.replace("; ", ";").split(";"); final String contentType = contentTypeAndEncoding[0]; final String charset = contentTypeAndEncoding[1].split("=")[1]; return new Pair<>(contentType, charset); } else return new Pair<>(rawContentType, null); } /** * Return the extension of the file located at the given URI, without the leading '.' * * @param uri Location of the file * @return Extension of the file located at the given URI, without the leading '.' */ public static String getExtensionFromUri(String uri) { UriParts parts = new UriParts(uri); return parts.getExtension(); } /** * Extract the domain from the given URI * * @param uriStr URI to parse, in String form * @return Domain of the URI; null if no domain found */ public static String getDomainFromUri(@NonNull String uriStr) { Uri uri = Uri.parse(uriStr); String result = uri.getHost(); if (result != null && result.startsWith("www")) result = result.substring(4); return (null == result) ? "" : result; } /** * Parse the given cookie String * * @param cookiesStr Cookie string, as set in HTTP headers * @return Parsed cookies (key and value of each cookie; key only if there's no value) */ public static Map<String, String> parseCookies(@NonNull String cookiesStr) { Map<String, String> result = new HashMap<>(); String[] cookiesParts = cookiesStr.split(";"); for (String cookie : cookiesParts) { cookie = cookie.trim(); // Don't use split as the value of the cookie may contain an '=' int equalsIndex = cookie.indexOf('='); if (equalsIndex > -1) result.put(cookie.substring(0, equalsIndex), cookie.substring(equalsIndex + 1)); else result.put(cookie, ""); } return result; } /** * Strip the given cookie string from the standard parameters * i.e. only return the cookie values * * @param cookieStr The cookie as a string, using the format of the 'Set-Cookie' HTTP response header * @return Cookie string without the standard parameters */ public static String stripParams(@NonNull String cookieStr) { Map<String, String> cookies = parseCookies(cookieStr); List<String> namesToSet = new ArrayList<>(); for (Map.Entry<String, String> entry : cookies.entrySet()) { if (!COOKIES_STANDARD_ATTRS.contains(entry.getKey().toLowerCase())) namesToSet.add(entry.getKey() + "=" + entry.getValue()); } return TextUtils.join("; ", namesToSet); } /** * Set session cookies for the given URL, keeping existing cookies if they are still active * * @param url Url to set the cookies for * @param cookieStr The cookie as a string, using the format of the 'Set-Cookie' HTTP response header */ public static void setCookies(String url, String cookieStr) { /* Check if given cookies are already registered Rationale : setting any cookie programmatically will set it as a _session_ cookie. It's not smart to do that if the very same cookie is already set for a longer lifespan. */ Map<String, String> cookies = parseCookies(cookieStr); Map<String, String> names = new HashMap<>(); List<String> paramsToSet = new ArrayList<>(); List<String> namesToSet = new ArrayList<>(); for (Map.Entry<String, String> entry : cookies.entrySet()) { if (COOKIES_STANDARD_ATTRS.contains(entry.getKey().toLowerCase())) { if (entry.getValue().isEmpty()) paramsToSet.add(entry.getKey()); else paramsToSet.add(entry.getKey() + "=" + entry.getValue()); } else names.put(entry.getKey(), entry.getValue()); } CookieManager mgr = CookieManager.getInstance(); String existingCookiesStr = mgr.getCookie(url); if (existingCookiesStr != null) { Map<String, String> existingCookies = parseCookies(existingCookiesStr); for (Map.Entry<String, String> entry : names.entrySet()) { String key = entry.getKey(); String value = (null == entry.getValue()) ? "" : entry.getValue(); String existingValue = existingCookies.get(key); if (null == existingValue || !existingValue.equals(value)) namesToSet.add(key + "=" + value); } } else { for (Map.Entry<String, String> name : names.entrySet()) namesToSet.add(name.getKey() + "=" + name.getValue()); } if (namesToSet.isEmpty()) { Timber.v("No new cookie to set %s", url); return; } StringBuilder cookieStrToSet = new StringBuilder(); cookieStrToSet.append(TextUtils.join("; ", namesToSet)); for (String param : paramsToSet) cookieStrToSet.append("; ").append(param); mgr.setCookie(url, cookieStrToSet.toString()); Timber.v("Setting cookie for %s : %s", url, cookieStrToSet.toString()); mgr.flush(); } public static String fixUrl(final String url, @NonNull final String baseUrl) { if (null == url || url.isEmpty()) return ""; if (url.startsWith("//")) return "https:" + url; if (!url.startsWith("http")) { String sourceUrl = baseUrl; if (sourceUrl.endsWith("/")) sourceUrl = sourceUrl.substring(0, sourceUrl.length() - 1); if (url.startsWith("/")) return sourceUrl + url; else return sourceUrl + "/" + url; } else return url; } /** * Parse the parameters of the given Uri into a map * * @param uri Uri to parse the paramaters from * @return Parsed parameters, where each key is the parameters name and each corresponding value their respective value */ public static Map<String, String> parseParameters(@NonNull final Uri uri) { Map<String, String> result = new HashMap<>(); Set<String> keys = uri.getQueryParameterNames(); for (String k : keys) result.put(k, uri.getQueryParameter(k)); return result; } /** * Get current cookie headers for the given URL * * @param url URL to get cookies from * @return Raw cookies string for the given URL */ public static String getCookies(@NonNull final String url) { String result = CookieManager.getInstance().getCookie(url); if (result != null) return HttpHelper.stripParams(result); else return ""; } /** * Get current cookie headers for the given URL * If the app doesn't have any, load the given URL to get them * * @param url URL to get cookies from * @param headers Headers to call the URL with * @param useMobileAgent True if mobile agent should be used * @param useHentoidAgent True if Hentoid user agent should be used * @param useWebviewAgent True if webview user agent should be used * @return Raw cookies string for the given URL */ public static String getCookies(@NonNull String url, @Nullable List<Pair<String, String>> headers, boolean useMobileAgent, boolean useHentoidAgent, boolean useWebviewAgent) { String result = getCookies(url); if (result != null) return result; else return peekCookies(url, headers, useMobileAgent, useHentoidAgent, useWebviewAgent); } /** * Get cookie headers set by the page at the given URL by calling that page * * @param url URL to peek cookies from * @return Raw cookies string */ public static String peekCookies(@NonNull final String url) { return peekCookies(url, null, true, false, true); } /** * Get cookie headers set by the page at the given URL by calling that page * * @param url URL to peek cookies from * @param headers Headers to call the URL with * @param useMobileAgent True if mobile user agent should be used * @param useHentoidAgent True if Hentoid user agent should be used * @param useWebviewAgent True if webview user agent should be used * @return Raw cookies string for the given URL */ public static String peekCookies(@NonNull String url, @Nullable List<Pair<String, String>> headers, boolean useMobileAgent, boolean useHentoidAgent, boolean useWebviewAgent) { try { Response response = getOnlineResourceFast(url, headers, useMobileAgent, useHentoidAgent, useWebviewAgent); List<String> cookielist = response.headers("Set-Cookie"); if (cookielist.isEmpty()) cookielist = response.headers("Set-Cookie"); return TextUtils.join("; ", cookielist); } catch (IOException e) { Timber.e(e); } return ""; } /** * Initialize the app's user agents * * @param context Context to be used */ public static void initUserAgents(@NonNull final Context context) { String chromeString = "Chrome/"; defaultUserAgent = WebSettings.getDefaultUserAgent(context); if (defaultUserAgent.contains(chromeString)) { int chromeIndex = defaultUserAgent.indexOf(chromeString); int spaceIndex = defaultUserAgent.indexOf(' ', chromeIndex); int dotIndex = defaultUserAgent.indexOf('.', chromeIndex); String version = defaultUserAgent.substring(chromeIndex + chromeString.length(), dotIndex); defaultChromeVersion = Integer.parseInt(version); defaultChromeAgent = defaultUserAgent.substring(chromeIndex, spaceIndex); } Timber.i("defaultUserAgent = %s", defaultUserAgent); Timber.i("defaultChromeAgent = %s", defaultChromeAgent); Timber.i("defaultChromeVersion = %s", defaultChromeVersion); } /** * Get the app's mobile user agent * * @param withHentoid True if the Hentoid user-agent has to appear * @return The app's mobile user agent */ public static String getMobileUserAgent(boolean withHentoid, boolean withWebview) { return getDefaultUserAgent(withHentoid, withWebview); } /** * Get the app's desktop user agent * * @param withHentoid True if the Hentoid user-agent has to appear * @return The app's desktop user agent */ public static String getDesktopUserAgent(boolean withHentoid, boolean withWebview) { if (null == defaultChromeAgent) throw new RuntimeException(AGENT_INIT_ISSUE); String result = String.format(DESKTOP_USER_AGENT_PATTERN, defaultChromeAgent); if (withHentoid) result += " Hentoid/v" + BuildConfig.VERSION_NAME; if (!withWebview) result = cleanWebViewAgent(result); return result; } /** * Get the app's default user agent * * @param withHentoid True if the Hentoid user-agent has to appear * @return The app's default user agent */ public static String getDefaultUserAgent(boolean withHentoid, boolean withWebview) { if (null == defaultUserAgent) throw new RuntimeException(AGENT_INIT_ISSUE); String result = defaultUserAgent; if (withHentoid) result += " Hentoid/v" + BuildConfig.VERSION_NAME; if (!withWebview) result = cleanWebViewAgent(result); return result; } public static String cleanWebViewAgent(@NonNull final String agent) { String result = agent; int buildIndex = result.indexOf(" Build/"); if (buildIndex > -1) { int closeIndex = result.indexOf(")", buildIndex); int separatorIndex = result.indexOf(";", buildIndex); int firstIndex = Math.min(closeIndex, separatorIndex); result = result.substring(0, buildIndex) + result.substring(firstIndex); } int versionIndex = result.indexOf(" Version/"); if (versionIndex > -1) { int closeIndex = result.indexOf(" ", versionIndex + 1); result = result.substring(0, versionIndex) + result.substring(closeIndex); } return result.replace("; wv", ""); } /** * Get the app's Chrome version * * @return The app's Chrome version */ public static int getChromeVersion() { if (-1 == defaultChromeVersion) throw new RuntimeException(AGENT_INIT_ISSUE); return defaultChromeVersion; } public static class UriParts { private String path; private String fileName; private String extension; private String query; public UriParts(String uri) { String theUri = uri.toLowerCase(); String uriNoParams = theUri; int paramsIndex = theUri.lastIndexOf('?'); if (paramsIndex > -1) { uriNoParams = theUri.substring(0, paramsIndex); query = theUri.substring(paramsIndex + 1); } else { query = ""; } int pathIndex = uriNoParams.lastIndexOf('/'); if (pathIndex > -1) path = theUri.substring(0, pathIndex); else path = theUri; int extIndex = uriNoParams.lastIndexOf('.'); // No extensions detected if (extIndex < 0 || extIndex < pathIndex) { extension = ""; fileName = uriNoParams.substring(pathIndex + 1); } else { extension = uriNoParams.substring(extIndex + 1); fileName = uriNoParams.substring(pathIndex + 1, extIndex); } } public String toUri() { StringBuilder result = new StringBuilder(path); result.append("/").append(fileName); if (!extension.isEmpty()) result.append(".").append(extension); if (!query.isEmpty()) result.append("?").append(query); return result.toString(); } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getFileNameNoExt() { return fileName; } public String getExtension() { return extension; } public void setExtension(String extension) { this.extension = extension; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public void setFileNameNoExt(@NonNull final String fileName) { this.fileName = fileName; } } }
package org.mozilla.focus.fragment; import android.content.Intent; import android.graphics.drawable.TransitionDrawable; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import org.mozilla.focus.R; import org.mozilla.focus.activity.SettingsActivity; import org.mozilla.focus.menu.BrowserMenu; import org.mozilla.focus.open.OpenWithFragment; import org.mozilla.focus.utils.Browsers; import org.mozilla.focus.utils.ViewUtils; import org.mozilla.focus.utils.IntentUtils; import org.mozilla.focus.web.IWebView; /** * Fragment for displaying the browser UI. */ public class BrowserFragment extends Fragment implements View.OnClickListener { public static final String FRAGMENT_TAG = "browser"; private static final int ANIMATION_DURATION = 300; private static final String ARGUMENT_URL = "url"; public static BrowserFragment create(String url) { Bundle arguments = new Bundle(); arguments.putString(ARGUMENT_URL, url); BrowserFragment fragment = new BrowserFragment(); fragment.setArguments(arguments); return fragment; } private TransitionDrawable backgroundTransition; private TextView urlView; private IWebView webView; private ProgressBar progressView; private View lockView; private View menuView; private View forwardButton; private View backButton; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_browser, container, false); final String url = getArguments().getString(ARGUMENT_URL); urlView = (TextView) view.findViewById(R.id.url); urlView.setText(url); urlView.setOnClickListener(this); backgroundTransition = (TransitionDrawable) view.findViewById(R.id.urlbar).getBackground(); final View refreshButton = view.findViewById(R.id.refresh); if (refreshButton != null) { refreshButton.setOnClickListener(this); } if ((forwardButton = view.findViewById(R.id.forward)) != null) { forwardButton.setOnClickListener(this); } if ((backButton = view.findViewById(R.id.back)) != null) { backButton.setOnClickListener(this); } lockView = view.findViewById(R.id.lock); progressView = (ProgressBar) view.findViewById(R.id.progress); view.findViewById(R.id.erase).setOnClickListener(this); menuView = view.findViewById(R.id.menu); menuView.setOnClickListener(this); webView = (IWebView) view.findViewById(R.id.webview); webView.setCallback(new IWebView.Callback() { @Override public void onPageStarted(final String url) { lockView.setVisibility(View.GONE); progressView.announceForAccessibility(getString(R.string.accessibility_announcement_loading)); urlView.setText(url); backgroundTransition.resetTransition(); progressView.setVisibility(View.VISIBLE); updateToolbarButtonStates(); } @Override public void onPageFinished(boolean isSecure) { backgroundTransition.startTransition(ANIMATION_DURATION); progressView.announceForAccessibility(getString(R.string.accessibility_announcement_loading_finished)); progressView.setVisibility(View.INVISIBLE); if (isSecure) { lockView.setVisibility(View.VISIBLE); } updateToolbarButtonStates(); } @Override public void onProgress(int progress) { progressView.setProgress(progress); } @Override public void handleExternalUrl(final String url) { final String fallback = IntentUtils.handleExternalUri(getActivity(), url); if (fallback != null) { webView.loadUrl(fallback); } } }); webView.loadUrl(url); return view; } @Override public void onClick(View view) { switch (view.getId()) { case R.id.menu: BrowserMenu menu = new BrowserMenu(getActivity(), this); menu.show(menuView); break; case R.id.url: getActivity().getSupportFragmentManager() .beginTransaction() .add(R.id.container, UrlInputFragment.create(urlView.getText().toString())) .addToBackStack("url_entry") .commit(); break; case R.id.erase: webView.cleanup(); getActivity().getSupportFragmentManager() .beginTransaction() .setCustomAnimations(0, R.anim.erase_animation) .replace(R.id.container, HomeFragment.create(), HomeFragment.FRAGMENT_TAG) .commit(); ViewUtils.showBrandedSnackbar(getActivity().findViewById(android.R.id.content), R.string.feedback_erase, getResources().getInteger(R.integer.erase_snackbar_delay)); break; case R.id.back: webView.goBack(); break; case R.id.forward: webView.goForward(); break; case R.id.refresh: webView.reload(); break; case R.id.share: final Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, webView.getUrl()); startActivity(shareIntent); break; case R.id.settings: final Intent settingsIntent = new Intent(getActivity(), SettingsActivity.class); startActivity(settingsIntent); break; case R.id.open_default: { final Browsers browsers = new Browsers(getContext(), webView.getUrl()); final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webView.getUrl())); intent.setPackage(browsers.getDefaultBrowser().packageName); startActivity(intent); break; } case R.id.open_firefox: { final Browsers browsers = new Browsers(getContext(), webView.getUrl()); if (browsers.isInstalled(Browsers.KnownBrowser.FIREFOX)) { final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webView.getUrl())); intent.setPackage(Browsers.KnownBrowser.FIREFOX.packageName); startActivity(intent); } else { final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + Browsers.KnownBrowser.FIREFOX)); startActivity(intent); } break; } case R.id.open_select_browser: { final Browsers browsers = new Browsers(getContext(), webView.getUrl()); final OpenWithFragment fragment = OpenWithFragment.newInstance( browsers.getInstalledBrowsers(), webView.getUrl()); fragment.show(getFragmentManager(),OpenWithFragment.FRAGMENT_TAG); break; } } } @Override public void onDetach() { super.onDetach(); webView.setCallback(null); } private void updateToolbarButtonStates() { if (forwardButton == null || backButton == null) { return; } final boolean canGoForward = webView.canGoForward(); final boolean canGoBack = webView.canGoBack(); forwardButton.setEnabled(canGoForward); forwardButton.setAlpha(canGoForward ? 1.0f : 0.5f); backButton.setEnabled(canGoBack); backButton.setAlpha(canGoBack ? 1.0f : 0.5f); } public String getUrl() { return webView.getUrl(); } public boolean canGoForward() { return webView.canGoForward(); } public boolean canGoBack() { return webView.canGoBack(); } public void goBack() { webView.goBack(); } }
package org.wikipedia.search; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.collection.LruCache; import androidx.fragment.app.Fragment; import org.apache.commons.lang3.StringUtils; import org.wikipedia.Constants.InvokeSource; import org.wikipedia.LongPressHandler; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.activity.FragmentUtil; import org.wikipedia.analytics.SearchFunnel; import org.wikipedia.dataclient.ServiceFactory; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.history.HistoryEntry; import org.wikipedia.page.PageTitle; import org.wikipedia.util.StringUtil; import org.wikipedia.views.GoneIfEmptyTextView; import org.wikipedia.views.ViewUtil; import org.wikipedia.views.WikiErrorView; import java.util.ArrayList; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.disposables.CompositeDisposable; import io.reactivex.rxjava3.schedulers.Schedulers; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.wikipedia.util.L10nUtil.setConditionalLayoutDirection; public class SearchResultsFragment extends Fragment { public interface Callback { void onSearchResultCopyLink(@NonNull PageTitle title); void onSearchResultAddToList(@NonNull PageTitle title, @NonNull InvokeSource source); void onSearchResultShareLink(@NonNull PageTitle title); void onSearchProgressBar(boolean enabled); void navigateToTitle(@NonNull PageTitle item, boolean inNewTab, int position); void setSearchText(@NonNull CharSequence text); @NonNull SearchFunnel getFunnel(); } private static final int BATCH_SIZE = 20; private static final int DELAY_MILLIS = 300; private static final int MAX_CACHE_SIZE_SEARCH_RESULTS = 4; /** * Constant to ease in the conversion of timestamps from nanoseconds to milliseconds. */ private static final int NANO_TO_MILLI = 1_000_000; @BindView(R.id.search_results_display) View searchResultsDisplay; @BindView(R.id.search_results_container) View searchResultsContainer; @BindView(R.id.search_results_list) ListView searchResultsList; @BindView(R.id.search_error_view) WikiErrorView searchErrorView; @BindView(R.id.search_empty_view) View searchEmptyView; @BindView(R.id.search_suggestion) TextView searchSuggestion; private Unbinder unbinder; private final LruCache<String, List<SearchResult>> searchResultsCache = new LruCache<>(MAX_CACHE_SIZE_SEARCH_RESULTS); private String currentSearchTerm = ""; @Nullable private SearchResults lastFullTextResults; @NonNull private final List<SearchResult> totalResults = new ArrayList<>(); private CompositeDisposable disposables = new CompositeDisposable(); @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_search_results, container, false); unbinder = ButterKnife.bind(this, view); SearchResultAdapter adapter = new SearchResultAdapter(inflater); searchResultsList.setAdapter(adapter); searchErrorView.setBackClickListener((v) -> requireActivity().finish()); searchErrorView.setRetryClickListener((v) -> { searchErrorView.setVisibility(View.GONE); startSearch(currentSearchTerm, true); }); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); new LongPressHandler(searchResultsList, HistoryEntry.SOURCE_SEARCH, new SearchResultsFragmentLongPressHandler()); } @Override public void onDestroyView() { searchErrorView.setRetryClickListener(null); unbinder.unbind(); unbinder = null; disposables.clear(); super.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); } @OnClick(R.id.search_suggestion) void onSuggestionClick(View view) { Callback callback = callback(); String suggestion = (String) searchSuggestion.getTag(); if (callback != null && suggestion != null) { callback.getFunnel().searchDidYouMean(getSearchLanguageCode()); callback.setSearchText(suggestion); startSearch(suggestion, true); } } public void show() { searchResultsDisplay.setVisibility(View.VISIBLE); } public void hide() { searchResultsDisplay.setVisibility(View.GONE); } public boolean isShowing() { return searchResultsDisplay.getVisibility() == View.VISIBLE; } public void setLayoutDirection(@NonNull String langCode) { setConditionalLayoutDirection(searchResultsList, langCode); } /** * Kick off a search, based on a given search term. * @param term Phrase to search for. * @param force Whether to "force" starting this search. If the search is not forced, the * search may be delayed by a small time, so that network requests are not sent * too often. If the search is forced, the network request is sent immediately. */ public void startSearch(@Nullable String term, boolean force) { if (!force && StringUtils.equals(currentSearchTerm, term)) { return; } cancelSearchTask(); currentSearchTerm = term; if (isBlank(term)) { clearResults(); return; } List<SearchResult> cacheResult = searchResultsCache.get(getSearchLanguageCode() + "-" + term); if (cacheResult != null && !cacheResult.isEmpty()) { clearResults(); displayResults(cacheResult); return; } searchResultsDisplay.postDelayed(() -> doTitlePrefixSearch(term), force ? 0 : DELAY_MILLIS); } private void doTitlePrefixSearch(final String searchTerm) { cancelSearchTask(); final long startTime = System.nanoTime(); updateProgressBar(true); disposables.add(ServiceFactory.get(WikiSite.forLanguageCode(getSearchLanguageCode())).prefixSearch(searchTerm, BATCH_SIZE, searchTerm) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> { if (response != null && response.query() != null && response.query().pages() != null) { // noinspection ConstantConditions return new SearchResults(response.query().pages(), WikiSite.forLanguageCode(getSearchLanguageCode()), response.continuation(), response.suggestion()); } // A prefix search query with no results will return the following: // "batchcomplete": true, // "query": { // "search": [] // Just return an empty SearchResults() in this case. return new SearchResults(); }) .doAfterTerminate(() -> updateProgressBar(false)) .subscribe(results -> { searchErrorView.setVisibility(View.GONE); handleResults(results, searchTerm, startTime); }, caught -> { searchEmptyView.setVisibility(View.GONE); searchErrorView.setVisibility(View.VISIBLE); searchErrorView.setError(caught); searchResultsContainer.setVisibility(View.GONE); logError(false, startTime); })); } private void handleResults(@NonNull SearchResults results, @NonNull String searchTerm, long startTime) { List<SearchResult> resultList = results.getResults(); // To ease data analysis and better make the funnel track with user behaviour, // only transmit search results events if there are a nonzero number of results if (!resultList.isEmpty()) { clearResults(); displayResults(resultList); log(resultList, startTime); } handleSuggestion(results.getSuggestion()); // add titles to cache... searchResultsCache.put(getSearchLanguageCode() + "-" + searchTerm, resultList); // scroll to top, but post it to the message queue, because it should be done // after the data set is updated. searchResultsList.post(() -> { if (!isAdded()) { return; } searchResultsList.setSelectionAfterHeaderView(); }); if (resultList.isEmpty()) { // kick off full text search if we get no results doFullTextSearch(currentSearchTerm, null, true); } } private void handleSuggestion(@Nullable String suggestion) { if (suggestion != null) { searchSuggestion.setText(StringUtil.fromHtml("<u>" + getString(R.string.search_did_you_mean, suggestion) + "</u>")); searchSuggestion.setTag(suggestion); searchSuggestion.setVisibility(View.VISIBLE); } else { searchSuggestion.setVisibility(View.GONE); } } private void cancelSearchTask() { updateProgressBar(false); disposables.clear(); } private void doFullTextSearch(final String searchTerm, final Map<String, String> continueOffset, final boolean clearOnSuccess) { final long startTime = System.nanoTime(); updateProgressBar(true); disposables.add(ServiceFactory.get(WikiSite.forLanguageCode(getSearchLanguageCode())).fullTextSearch(searchTerm, BATCH_SIZE, continueOffset != null ? continueOffset.get("continue") : null, continueOffset != null ? continueOffset.get("gsroffset") : null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> { if (response.query() != null) { // noinspection ConstantConditions return new SearchResults(response.query().pages(), WikiSite.forLanguageCode(getSearchLanguageCode()), response.continuation(), null); } // A 'morelike' search query with no results will just return an API warning: // "batchcomplete": true, // "warnings": { // "search": { // "warnings": "No valid titles provided to 'morelike'." // Just return an empty SearchResults() in this case. return new SearchResults(); }) .doAfterTerminate(() -> updateProgressBar(false)) .subscribe(results -> { List<SearchResult> resultList = results.getResults(); cache(resultList, searchTerm); log(resultList, startTime); if (clearOnSuccess) { clearResults(false); } searchErrorView.setVisibility(View.GONE); // full text special: SearchResultsFragment.this.lastFullTextResults = results; displayResults(resultList); }, throwable -> { // If there's an error, just log it and let the existing prefix search results be. logError(true, startTime); })); } private void clearResults() { clearResults(true); } private void updateProgressBar(boolean enabled) { Callback callback = callback(); if (callback != null) { callback.onSearchProgressBar(enabled); } } private void clearResults(boolean clearSuggestion) { searchResultsContainer.setVisibility(View.GONE); searchEmptyView.setVisibility(View.GONE); searchErrorView.setVisibility(View.GONE); if (clearSuggestion) { searchSuggestion.setVisibility(View.GONE); } lastFullTextResults = null; totalResults.clear(); getAdapter().notifyDataSetChanged(); } private BaseAdapter getAdapter() { return (BaseAdapter) searchResultsList.getAdapter(); } /** * Displays results passed to it as search suggestions. * * @param results List of results to display. If null, clears the list of suggestions & hides it. */ private void displayResults(List<SearchResult> results) { for (SearchResult newResult : results) { boolean contains = false; for (SearchResult result : totalResults) { if (newResult.getPageTitle().equals(result.getPageTitle())) { contains = true; break; } } if (!contains) { totalResults.add(newResult); } } if (totalResults.isEmpty()) { searchEmptyView.setVisibility(View.VISIBLE); searchResultsContainer.setVisibility(View.GONE); } else { searchEmptyView.setVisibility(View.GONE); searchResultsContainer.setVisibility(View.VISIBLE); } getAdapter().notifyDataSetChanged(); } private class SearchResultsFragmentLongPressHandler implements org.wikipedia.LongPressHandler.ListViewOverflowMenuListener { private int lastPositionRequested; @Override public PageTitle getTitleForListPosition(int position) { lastPositionRequested = position; return ((SearchResult) getAdapter().getItem(position)).getPageTitle(); } @Override public void onOpenLink(PageTitle title, HistoryEntry entry) { Callback callback = callback(); if (callback != null) { callback.navigateToTitle(title, false, lastPositionRequested); } } @Override public void onOpenInNewTab(PageTitle title, HistoryEntry entry) { Callback callback = callback(); if (callback != null) { callback.navigateToTitle(title, true, lastPositionRequested); } } @Override public void onCopyLink(PageTitle title) { Callback callback = callback(); if (callback != null) { callback.onSearchResultCopyLink(title); } } @Override public void onShareLink(PageTitle title) { Callback callback = callback(); if (callback != null) { callback.onSearchResultShareLink(title); } } @Override public void onAddToList(@NonNull PageTitle title, @NonNull InvokeSource source) { Callback callback = callback(); if (callback != null) { callback.onSearchResultAddToList(title, source); } } } private final class SearchResultAdapter extends BaseAdapter implements View.OnClickListener, View.OnLongClickListener { private final LayoutInflater inflater; SearchResultAdapter(LayoutInflater inflater) { this.inflater = inflater; } @Override public int getCount() { return totalResults.size(); } @Override public Object getItem(int position) { return totalResults.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.item_search_result, parent, false); convertView.setFocusable(true); convertView.setOnClickListener(this); convertView.setOnLongClickListener(this); } TextView pageTitleText = convertView.findViewById(R.id.page_list_item_title); SearchResult result = (SearchResult) getItem(position); ImageView searchResultItemImage = convertView.findViewById(R.id.page_list_item_image); GoneIfEmptyTextView descriptionText = convertView.findViewById(R.id.page_list_item_description); TextView redirectText = convertView.findViewById(R.id.page_list_item_redirect); View redirectArrow = convertView.findViewById(R.id.page_list_item_redirect_arrow); if (TextUtils.isEmpty(result.getRedirectFrom())) { redirectText.setVisibility(View.GONE); redirectArrow.setVisibility(View.GONE); descriptionText.setText(result.getPageTitle().getDescription()); } else { redirectText.setVisibility(View.VISIBLE); redirectArrow.setVisibility(View.VISIBLE); redirectText.setText(getString(R.string.search_redirect_from, result.getRedirectFrom())); descriptionText.setVisibility(View.GONE); } // highlight search term within the text StringUtil.boldenKeywordText(pageTitleText, result.getPageTitle().getDisplayText(), currentSearchTerm); searchResultItemImage.setVisibility((result.getPageTitle().getThumbUrl() == null) ? View.GONE : View.VISIBLE); ViewUtil.loadImageWithRoundedCorners(searchResultItemImage, result.getPageTitle().getThumbUrl()); // ...and lastly, if we've scrolled to the last item in the list, then // continue searching! if (position == (totalResults.size() - 1) && WikipediaApp.getInstance().isOnline()) { if (lastFullTextResults == null) { // the first full text search doFullTextSearch(currentSearchTerm, null, false); } else if (lastFullTextResults.getContinuation() != null && !lastFullTextResults.getContinuation().isEmpty()) { // subsequent full text searches doFullTextSearch(currentSearchTerm, lastFullTextResults.getContinuation(), false); } } convertView.setTag(position); return convertView; } @Override public void onClick(View v) { Callback callback = callback(); int position = (int) v.getTag(); if (callback != null && position < totalResults.size()) { callback.navigateToTitle(totalResults.get(position).getPageTitle(), false, position); } } @Override public boolean onLongClick(View v) { return false; } } private void cache(@NonNull List<SearchResult> resultList, @NonNull String searchTerm) { String cacheKey = getSearchLanguageCode() + "-" + searchTerm; List<SearchResult> cachedTitles = searchResultsCache.get(cacheKey); if (cachedTitles != null) { cachedTitles.addAll(resultList); searchResultsCache.put(cacheKey, cachedTitles); } } private void log(@NonNull List<SearchResult> resultList, long startTime) { // To ease data analysis and better make the funnel track with user behaviour, // only transmit search results events if there are a nonzero number of results if (callback() != null && !resultList.isEmpty()) { // noinspection ConstantConditions callback().getFunnel().searchResults(true, resultList.size(), displayTime(startTime), getSearchLanguageCode()); } } private void logError(boolean fullText, long startTime) { if (callback() != null) { // noinspection ConstantConditions callback().getFunnel().searchError(fullText, displayTime(startTime), getSearchLanguageCode()); } } private int displayTime(long startTime) { return (int) ((System.nanoTime() - startTime) / NANO_TO_MILLI); } @Nullable private Callback callback() { return FragmentUtil.getCallback(this, Callback.class); } private String getSearchLanguageCode() { return ((SearchFragment) getParentFragment()).getSearchLanguageCode(); } }
package org.worshipsongs.fragment; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import org.worshipsongs.CommonConstants; import org.worshipsongs.R; import org.worshipsongs.activity.FavouriteSongsActivity; import org.worshipsongs.adapter.TitleAdapter; import org.worshipsongs.listener.SongContentViewListener; import org.worshipsongs.registry.ITabFragment; import org.worshipsongs.service.FavouriteService; import org.worshipsongs.service.PopupMenuService; import org.worshipsongs.utils.CommonUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Author : Madasamy * Version : 3.x */ public class ServicesFragment extends Fragment implements TitleAdapter.TitleAdapterListener<String>, AlertDialogFragment.DialogListener, ITabFragment { private FavouriteService favouriteService = new FavouriteService(); private List<String> services = new ArrayList<>(); private Parcelable state; private ListView serviceListView; private TitleAdapter<String> titleAdapter; private TextView infoTextView; private PopupMenuService popupMenuService = new PopupMenuService(); public static ServicesFragment newInstance() { return new ServicesFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // favouriteService = new FavouriteService(); if (savedInstanceState != null) { state = savedInstanceState.getParcelable(CommonConstants.STATE_KEY); } setHasOptionsMenu(true); initSetUp(); } private void initSetUp() { services = favouriteService.findNames(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.songs_layout, container, false); setInfoTextView(view); setListView(view); return view; } private void setInfoTextView(View view) { infoTextView = (TextView) view.findViewById(R.id.info_text_view); infoTextView.setText(getString(R.string.favourite_info_message_)); infoTextView.setLineSpacing(0, 1.2f); infoTextView.setVisibility(services.isEmpty() ? View.VISIBLE : View.GONE); } private void setListView(View view) { serviceListView = (ListView) view.findViewById(R.id.song_list_view); titleAdapter = new TitleAdapter<String>((AppCompatActivity) getActivity(), R.layout.songs_layout); titleAdapter.setTitleAdapterListener(this); titleAdapter.addObjects(services); serviceListView.setAdapter(titleAdapter); } @Override public void onSaveInstanceState(Bundle outState) { if (this.isAdded()) { outState.putParcelable(CommonConstants.STATE_KEY, serviceListView.onSaveInstanceState()); } super.onSaveInstanceState(outState); } @Override public void onResume() { super.onResume(); initSetUp(); refreshListView(); } //Adapter listener methods @Override public void setViews(Map<String, Object> objects, final String text) { TextView titleTextView = (TextView) objects.get(CommonConstants.TITLE_KEY); titleTextView.setText(text); titleTextView.setOnLongClickListener(new TextViewLongClickListener(text)); titleTextView.setOnClickListener(new TextViewOnClickListener(text)); ImageView optionsImageView = (ImageView) objects.get(CommonConstants.OPTIONS_IMAGE_KEY); optionsImageView.setVisibility(View.VISIBLE); optionsImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { popupMenuService.shareFavouritesInSocialMedia(view, text); } }); } //Dialog Listener method @Override public void onClickPositiveButton(Bundle bundle, String tag) { String favouriteName = bundle.getString(CommonConstants.NAME_KEY, ""); favouriteService.remove(favouriteName); services.clear(); initSetUp(); titleAdapter.addObjects(services); infoTextView.setVisibility(services.isEmpty() ? View.VISIBLE : View.GONE); } @Override public void onClickNegativeButton() { // Do nothing } //Tab choices and reorder methods @Override public int defaultSortOrder() { return 4; } @Override public String getTitle() { return "playlists"; } @Override public boolean checked() { return true; } @Override public void setListenerAndBundle(SongContentViewListener songContentViewListener, Bundle bundle) { } private class TextViewLongClickListener implements View.OnLongClickListener { private String serviceName; TextViewLongClickListener(String serviceName) { this.serviceName = serviceName; } @Override public boolean onLongClick(View v) { Bundle bundle = new Bundle(); bundle.putString(CommonConstants.TITLE_KEY, getString(R.string.delete)); bundle.putString(CommonConstants.MESSAGE_KEY, getString(R.string.message_delete_playlist, serviceName)); bundle.putString(CommonConstants.NAME_KEY, serviceName); AlertDialogFragment alertDialogFragment = AlertDialogFragment.newInstance(bundle); alertDialogFragment.setDialogListener(ServicesFragment.this); alertDialogFragment.show(getActivity().getFragmentManager(), "DeleteConfirmationDialog"); return false; } } private class TextViewOnClickListener implements View.OnClickListener { private String serviceName; TextViewOnClickListener(String serviceName) { this.serviceName = serviceName; } @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), FavouriteSongsActivity.class); intent.putExtra(CommonConstants.SERVICE_NAME_KEY, serviceName); startActivity(intent); } } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { if (getActivity() != null) { CommonUtils.hideKeyboard(getActivity()); } initSetUp(); refreshListView(); } } private void refreshListView() { if (state != null) { serviceListView.onRestoreInstanceState(state); } else if (titleAdapter != null) { titleAdapter.addObjects(services); infoTextView.setVisibility(services.isEmpty() ? View.VISIBLE : View.GONE); } } }
package org.odk.collect.android.activities; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.location.LocationManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.text.SpannableStringBuilder; import android.util.Log; import android.util.Pair; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.ContextThemeWrapper; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.framework.CommCareActivity; import org.commcare.android.framework.SessionActivityRegistration; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.logic.BarcodeScanListenerDefaultImpl; import org.commcare.android.util.FormUploadUtil; import org.commcare.android.util.SessionUnavailableException; import org.commcare.android.util.StringUtils; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.dalvik.activities.CommCareHomeActivity; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns; import org.commcare.dalvik.odk.provider.InstanceProviderAPI; import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns; import org.commcare.dalvik.utils.UriToFilePath; import org.javarosa.core.model.Constants; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.locale.Localizer; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.model.xform.XFormsModule; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathTypeMismatchException; import org.odk.collect.android.application.Collect; import org.odk.collect.android.jr.extensions.IntentCallout; import org.odk.collect.android.jr.extensions.PollSensorAction; import org.odk.collect.android.listeners.AdvanceToNextListener; import org.odk.collect.android.listeners.FormLoaderListener; import org.odk.collect.android.listeners.FormSaveCallback; import org.odk.collect.android.listeners.FormSavedListener; import org.odk.collect.android.listeners.WidgetChangedListener; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.logic.PropertyManager; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.preferences.PreferencesActivity.ProgressBarMode; import org.odk.collect.android.tasks.FormLoaderTask; import org.odk.collect.android.tasks.SaveToDiskTask; import org.odk.collect.android.utilities.Base64Wrapper; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.GeoUtils; import org.odk.collect.android.views.ODKView; import org.odk.collect.android.views.ResizingImageView; import org.odk.collect.android.widgets.DateTimeWidget; import org.odk.collect.android.widgets.ImageWidget; import org.odk.collect.android.widgets.IntentWidget; import org.odk.collect.android.widgets.QuestionWidget; import org.odk.collect.android.widgets.TimeWidget; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.crypto.spec.SecretKeySpec; /** * FormEntryActivity is responsible for displaying questions, animating transitions between * questions, and allowing the user to enter data. * * @author Carl Hartung (carlhartung@gmail.com) */ public class FormEntryActivity extends FragmentActivity implements AnimationListener, FormLoaderListener, FormSavedListener, FormSaveCallback, AdvanceToNextListener, OnGestureListener, WidgetChangedListener { private static final String TAG = FormEntryActivity.class.getSimpleName(); // Defines for FormEntryActivity private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private static final boolean EVALUATE_CONSTRAINTS = true; private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false; // Request codes for returning data from specified intent. public static final int IMAGE_CAPTURE = 1; public static final int BARCODE_CAPTURE = 2; public static final int AUDIO_CAPTURE = 3; public static final int VIDEO_CAPTURE = 4; public static final int LOCATION_CAPTURE = 5; private static final int HIERARCHY_ACTIVITY = 6; public static final int IMAGE_CHOOSER = 7; public static final int AUDIO_CHOOSER = 8; public static final int VIDEO_CHOOSER = 9; public static final int INTENT_CALLOUT = 10; private static final int HIERARCHY_ACTIVITY_FIRST_START = 11; public static final int SIGNATURE_CAPTURE = 12; // Extra returned from gp activity public static final String LOCATION_RESULT = "LOCATION_RESULT"; // Identifies the gp of the form used to launch form entry private static final String KEY_FORMPATH = "formpath"; public static final String KEY_INSTANCEDESTINATION = "instancedestination"; public static final String TITLE_FRAGMENT_TAG = "odk_title_fragment"; public static final String KEY_FORM_CONTENT_URI = "form_content_uri"; public static final String KEY_INSTANCE_CONTENT_URI = "instance_content_uri"; public static final String KEY_AES_STORAGE_KEY = "key_aes_storage"; public static final String KEY_HEADER_STRING = "form_header"; public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management"; public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled"; private static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved"; /** * Intent extra flag to track if this form is an archive. Used to trigger * return logic when this activity exits to the home screen, such as * whether to redirect to archive view or sync the form. */ public static final String IS_ARCHIVED_FORM = "is-archive-form"; // Identifies whether this is a new form, or reloading a form after a screen // rotation (or similar) private static final String NEWFORM = "newform"; private static final int MENU_LANGUAGES = Menu.FIRST; private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1; private static final int MENU_SAVE = Menu.FIRST + 2; private static final int MENU_PREFERENCES = Menu.FIRST + 3; private static final int PROGRESS_DIALOG = 1; private static final int SAVING_DIALOG = 2; private String mFormPath; // Path to a particular form instance public static String mInstancePath; private String mInstanceDestination; private GestureDetector mGestureDetector; private SecretKeySpec symetricKey = null; public static FormController mFormController; private Animation mInAnimation; private Animation mOutAnimation; private ViewGroup mViewPane; private View mCurrentView; private AlertDialog mRepeatDialog; private AlertDialog mAlertDialog; private boolean mIncompleteEnabled = true; // used to limit forward/backward swipes to one per question private boolean mBeenSwiped; private FormLoaderTask mFormLoaderTask; private SaveToDiskTask mSaveToDiskTask; private Uri formProviderContentURI = FormsColumns.CONTENT_URI; private Uri instanceProviderContentURI = InstanceColumns.CONTENT_URI; private static String mHeaderString; // Was the form saved? Used to set activity return code. private boolean hasSaved = false; private BroadcastReceiver mLocationServiceIssueReceiver; // marked true if we are in the process of saving a form because the user // database & key session are expiring. Being set causes savingComplete to // broadcast a form saving intent. private boolean savingFormOnKeySessionExpiration = false; enum AnimationType { LEFT, RIGHT, FADE } @Override @SuppressLint("NewApi") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addBreadcrumbBar(); // must be at the beginning of any activity that can be called from an external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } setupUI(); // Load JavaRosa modules. needed to restore forms. new XFormsModule().registerModule(); // needed to override rms property manager org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager( getApplicationContext())); boolean isNewForm = loadStateFromBundle(savedInstanceState); // Check to see if this is a screen flip or a new form load. Object data = this.getLastCustomNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask) data; } else if (!isNewForm) { // Screen orientation change refreshCurrentView(); } else { mFormController = null; mInstancePath = null; Intent intent = getIntent(); if (intent != null) { loadIntentFormData(intent); setTitleToLoading(); Uri uri = intent.getData(); final String contentType = getContentResolver().getType(uri); Uri formUri; boolean isInstanceReadOnly = false; try { switch (contentType) { case InstanceColumns.CONTENT_ITEM_TYPE: Pair<Uri, Boolean> instanceAndStatus = getInstanceUri(uri); formUri = instanceAndStatus.first; isInstanceReadOnly = instanceAndStatus.second; break; case FormsColumns.CONTENT_ITEM_TYPE: formUri = uri; mFormPath = getFormPath(uri); break; default: Log.e(TAG, "unrecognized URI"); CommCareHomeActivity.createErrorDialog(this, "unrecognized URI: " + uri, EXIT); return; } } catch (FormQueryException e) { CommCareHomeActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } if(formUri == null) { Log.e(TAG, "unrecognized URI"); CommCareActivity.createErrorDialog(this, "couldn't locate FormDB entry for the item at: " + uri, EXIT); return; } mFormLoaderTask = new FormLoaderTask(this, symetricKey, isInstanceReadOnly); mFormLoaderTask.execute(formUri); showDialog(PROGRESS_DIALOG); } } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { /* * EventLog accepts only proper Strings as input, but prior to this version, * Android would try to send SpannedStrings to it, thus crashing the app. * This makes sure the title is actually a String. * This fixes bug 174626. */ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 && item.getTitleCondensed() != null) { if (BuildConfig.DEBUG) { Log.v(TAG, "Selected item is: " + item); } item.setTitleCondensed(item.getTitleCondensed().toString()); } return super.onMenuItemSelected(featureId, item); } @Override public void formSaveCallback() { // note that we have started saving the form savingFormOnKeySessionExpiration = true; // start saving form, which will call the key session logout completion // function when it finishes. saveDataToDisk(EXIT, false, null, true); } private void registerFormEntryReceiver() { //BroadcastReceiver for: // a) An unresolvable xpath expression encountered in PollSensorAction.onLocationChanged // b) Checking if GPS services are not available mLocationServiceIssueReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { context.removeStickyBroadcast(intent); String action = intent.getAction(); if (GeoUtils.ACTION_CHECK_GPS_ENABLED.equals(action)) { handleNoGpsBroadcast(context); } else if (PollSensorAction.XPATH_ERROR_ACTION.equals(action)) { handleXpathErrorBroadcast(intent); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(PollSensorAction.XPATH_ERROR_ACTION); filter.addAction(GeoUtils.ACTION_CHECK_GPS_ENABLED); registerReceiver(mLocationServiceIssueReceiver, filter); } private void handleNoGpsBroadcast(Context context) { LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Set<String> providers = GeoUtils.evaluateProviders(manager); if (providers.isEmpty()) { DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { if (i == DialogInterface.BUTTON_POSITIVE) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } } }; GeoUtils.showNoGpsDialog(this, onChangeListener); } } private void handleXpathErrorBroadcast(Intent intent) { String problemXpath = intent.getStringExtra(PollSensorAction.KEY_UNRESOLVED_XPATH); CommCareActivity.createErrorDialog(FormEntryActivity.this, "There is a bug in one of your form's XPath Expressions \n" + problemXpath, EXIT); } /** * Setup Activity's UI */ private void setupUI() { setContentView(R.layout.screen_form_entry); setNavBarVisibility(); ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!"done".equals(v.getTag())) { FormEntryActivity.this.showNextView(); } else { triggerUserFormComplete(); } } }); prevButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!"quit".equals(v.getTag())) { FormEntryActivity.this.showPreviousView(); } else { FormEntryActivity.this.triggerUserQuitInput(); } } }); mViewPane = (ViewGroup)findViewById(R.id.form_entry_pane); mBeenSwiped = false; mAlertDialog = null; mCurrentView = null; mInAnimation = null; mOutAnimation = null; mGestureDetector = new GestureDetector(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_FORMPATH, mFormPath); outState.putBoolean(NEWFORM, false); outState.putString(KEY_FORM_CONTENT_URI, formProviderContentURI.toString()); outState.putString(KEY_INSTANCE_CONTENT_URI, instanceProviderContentURI.toString()); outState.putString(KEY_INSTANCEDESTINATION, mInstanceDestination); outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled); outState.putBoolean(KEY_HAS_SAVED, hasSaved); outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod); if(symetricKey != null) { try { outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded())); } catch (ClassNotFoundException e) { // we can't really get here anyway, since we couldn't have decoded the string to begin with throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key"); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (resultCode == RESULT_CANCELED) { if (requestCode == HIERARCHY_ACTIVITY_FIRST_START) { // They pressed 'back' on the first hierarchy screen, so we should assume they want // to back out of form entry all together finishReturnInstance(false); } else if (requestCode == INTENT_CALLOUT){ processIntentResponse(intent, true); } // request was canceled, so do nothing return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra(BarcodeScanListenerDefaultImpl.SCAN_RESULT); ((ODKView) mCurrentView).setBinaryData(sb); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case INTENT_CALLOUT: processIntentResponse(intent); break; case IMAGE_CAPTURE: processCaptureResponse(true); break; case SIGNATURE_CAPTURE: processCaptureResponse(false); break; case IMAGE_CHOOSER: processImageChooserResponse(intent); break; case AUDIO_CAPTURE: case VIDEO_CAPTURE: case AUDIO_CHOOSER: case VIDEO_CHOOSER: processChooserResponse(intent); break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); ((ODKView) mCurrentView).setBinaryData(sl); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case HIERARCHY_ACTIVITY: // We may have jumped to a new index in hierarchy activity, so refresh refreshCurrentView(false); break; } } /** * Performs any necessary relocating and scaling of an image coming from either a * SignatureWidget or ImageWidget (capture or choose) * * @param originalImage the image file returned by the image capture or chooser intent * @param shouldScale if false, indicates that the image is from a signature capture, so should * not attempt to scale * @return the image file that should be displayed on the device screen when this question * widget is in view */ private File moveAndScaleImage(File originalImage, boolean shouldScale) throws IOException { // We want to save our final image file in the instance folder for this form, so that it // gets sent to HQ with the form String instanceFolder = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); String extension = FileUtils.getExtension(originalImage.getAbsolutePath()); String imageFilename = System.currentTimeMillis() + "." + extension; String finalFilePath = instanceFolder + imageFilename; boolean savedScaledImage = false; if (shouldScale) { ImageWidget currentWidget = (ImageWidget)getPendingWidget(); int maxDimen = currentWidget.getMaxDimen(); if (maxDimen != -1) { savedScaledImage = FileUtils.scaleImage(originalImage, finalFilePath, maxDimen); } } if (!savedScaledImage) { // If we didn't create a scaled image and save it to the final path, then relocate the // original image from the temp filepath to our final path File finalFile = new File(finalFilePath); if (!originalImage.renameTo(finalFile)) { throw new IOException("Failed to rename " + originalImage.getAbsolutePath() + " to " + finalFile.getAbsolutePath()); } else { return finalFile; } } else { // Otherwise, relocate the original image to a raw/ folder, so that we still have access // to the unmodified version String rawDirPath = instanceFolder + "/raw"; File rawDir = new File(rawDirPath); if (!rawDir.exists()) { rawDir.mkdir(); } File rawImageFile = new File (rawDirPath + "/" + imageFilename); if (!originalImage.renameTo(rawImageFile)) { throw new IOException("Failed to rename " + originalImage.getAbsolutePath() + " to " + rawImageFile.getAbsolutePath()); } else { return rawImageFile; } } } /** * Processes the return from an image capture intent, launched by either an ImageWidget or * SignatureWidget * * @param isImage true if this was from an ImageWidget, false if it was a SignatureWidget */ private void processCaptureResponse(boolean isImage) { /* We saved the image to the tempfile_path, but we really want it to be in: * /sdcard/odk/instances/[current instance]/something.[jpg/png/etc] so we move it there * before inserting it into the content provider. Once the android image capture bug gets * fixed, (read, we move on from Android 1.6) we want to handle images the audio and * video */ // The intent is empty, but we know we saved the image to the temp file File originalImage = ImageWidget.TEMP_FILE_FOR_IMAGE_CAPTURE; try { File unscaledFinalImage = moveAndScaleImage(originalImage, isImage); saveImageWidgetAnswer(unscaledFinalImage); } catch (IOException e) { e.printStackTrace(); showCustomToast(Localization.get("image.capture.not.saved"), Toast.LENGTH_LONG); } } private void processImageChooserResponse(Intent intent) { /* We have a saved image somewhere, but we really want it to be in: * /sdcard/odk/instances/[current instance]/something.[jpg/png/etc] so we move it there * before inserting it into the content provider. Once the android image capture bug gets * fixed, (read, we move on from Android 1.6) we want to handle images the audio and * video */ // get gp of chosen file Uri selectedImage = intent.getData(); File originalImage = new File(FileUtils.getPath(this, selectedImage)); if (originalImage.exists()) { try { File unscaledFinalImage = moveAndScaleImage(originalImage, true); saveImageWidgetAnswer(unscaledFinalImage); } catch (IOException e) { e.printStackTrace(); showCustomToast(Localization.get("image.selection.not.saved"), Toast.LENGTH_LONG); } } else { // The user has managed to select a file from the image browser that doesn't actually // exist on the file system anymore showCustomToast(Localization.get("invalid.image.selection"), Toast.LENGTH_LONG); } } private void saveImageWidgetAnswer(File unscaledFinalImage) { // Add the new image to the Media content provider so that the viewing is fast in Android 2.0+ ContentValues values = new ContentValues(6); values.put(Images.Media.TITLE, unscaledFinalImage.getName()); values.put(Images.Media.DISPLAY_NAME, unscaledFinalImage.getName()); values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.DATA, unscaledFinalImage.getAbsolutePath()); Uri imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); Log.i(TAG, "Inserting image returned uri = " + imageURI.toString()); ((ODKView) mCurrentView).setBinaryData(imageURI); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } private void processChooserResponse(Intent intent) { // For audio/video capture/chooser, we get the URI from the content provider // then the widget copies the file and makes a new entry in the content provider. Uri media = intent.getData(); String binaryPath = UriToFilePath.getPathFromUri(CommCareApplication._(), media); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { // don't let the user select a file that won't be included in the // upload to the server ((ODKView) mCurrentView).clearAnswer(); Toast.makeText(FormEntryActivity.this, Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); } else { ((ODKView) mCurrentView).setBinaryData(media); } saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } // Search the the current view's widgets for one that has registered a pending callout with // the form controller private QuestionWidget getPendingWidget() { FormIndex pendingIndex = mFormController.getPendingCalloutFormIndex(); if (pendingIndex == null) { return null; } for (QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) { if (q.getFormId().equals(pendingIndex)) { return q; } } return null; } private void processIntentResponse(Intent response){ processIntentResponse(response, false); } private void processIntentResponse(Intent response, boolean cancelled) { // keep track of whether we should auto advance boolean advance = false; boolean quick = false; IntentWidget pendingIntentWidget = (IntentWidget)getPendingWidget(); TreeReference context; if (mFormController.getPendingCalloutFormIndex() != null) { context = mFormController.getPendingCalloutFormIndex().getReference(); } else { context = null; } if(pendingIntentWidget != null) { //Set our instance destination for binary data if needed String destination = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); //get the original intent callout IntentCallout ic = pendingIntentWidget.getIntentCallout(); quick = "quick".equals(ic.getAppearance()); //And process it advance = ic.processResponse(response, context, new File(destination)); ic.setCancelled(cancelled); } refreshCurrentView(); // auto advance if we got a good result and are in quick mode if(advance && quick){ showNextView(); } } private void updateFormRelevencies(){ saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); if(!(mCurrentView instanceof ODKView)){ throw new RuntimeException("Tried to update form relevency not on compound view"); } ODKView oldODKV = (ODKView)mCurrentView; FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts(); Set<FormEntryPrompt> used = new HashSet<>(); ArrayList<QuestionWidget> oldWidgets = oldODKV.getWidgets(); ArrayList<Integer> removeList = new ArrayList<>(); for(int i=0;i<oldWidgets.size();i++){ QuestionWidget oldWidget = oldWidgets.get(i); boolean stillRelevent = false; for(FormEntryPrompt prompt : newValidPrompts) { if(prompt.getIndex().equals(oldWidget.getPrompt().getIndex())) { stillRelevent = true; used.add(prompt); } } if(!stillRelevent){ removeList.add(i); } } // remove "atomically" to not mess up iterations oldODKV.removeQuestionsFromIndex(removeList); //Now go through add add any new prompts that we need for(int i = 0 ; i < newValidPrompts.length; ++i) { FormEntryPrompt prompt = newValidPrompts[i]; if(used.contains(prompt)) { //nothing to do here continue; } oldODKV.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i); } } private static class NavigationDetails { public int totalQuestions = 0; public int completedQuestions = 0; public boolean relevantBeforeCurrentScreen = false; public boolean isFirstScreen = false; public int answeredOnScreen = 0; public int requiredOnScreen = 0; public int relevantAfterCurrentScreen = 0; public FormIndex currentScreenExit = null; } private NavigationDetails calculateNavigationStatus() { NavigationDetails details = new NavigationDetails(); FormIndex userFormIndex = mFormController.getFormIndex(); FormIndex currentFormIndex = FormIndex.createBeginningOfFormIndex(); mFormController.expandRepeats(currentFormIndex); int event = mFormController.getEvent(currentFormIndex); try { // keep track of whether there is a question that exists before the // current screen boolean onCurrentScreen = false; while (event != FormEntryController.EVENT_END_OF_FORM) { int comparison = currentFormIndex.compareTo(userFormIndex); if (comparison == 0) { onCurrentScreen = true; details.currentScreenExit = mFormController.getNextFormIndex(currentFormIndex, true); } if (onCurrentScreen && currentFormIndex.equals(details.currentScreenExit)) { onCurrentScreen = false; } // Figure out if there are any events before this screen (either // new repeat or relevant questions are valid) if (event == FormEntryController.EVENT_QUESTION || event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) { // Figure out whether we're on the last screen if (!details.relevantBeforeCurrentScreen && !details.isFirstScreen) { // We got to the current screen without finding a // relevant question, // I guess we're on the first one. if (onCurrentScreen && !details.relevantBeforeCurrentScreen) { details.isFirstScreen = true; } else { // We're using the built in steps (and they take // relevancy into account) // so if there are prompts they have to be relevant details.relevantBeforeCurrentScreen = true; } } } if (event == FormEntryController.EVENT_QUESTION) { FormEntryPrompt[] prompts = mFormController.getQuestionPrompts(currentFormIndex); if (!onCurrentScreen && details.currentScreenExit != null) { details.relevantAfterCurrentScreen += prompts.length; } details.totalQuestions += prompts.length; // Current questions are complete only if they're answered. // Past questions are always complete. // Future questions are never complete. if (onCurrentScreen) { for (FormEntryPrompt prompt : prompts) { if (this.mCurrentView instanceof ODKView) { ODKView odkv = (ODKView) this.mCurrentView; prompt = getOnScreenPrompt(prompt, odkv); } boolean isAnswered = prompt.getAnswerValue() != null || prompt.getDataType() == Constants.DATATYPE_NULL; if (prompt.isRequired()) { details.requiredOnScreen++; if (isAnswered) { details.answeredOnScreen++; } } if (isAnswered) { details.completedQuestions++; } } } else if (comparison < 0) { // For previous questions, consider all "complete" details.completedQuestions += prompts.length; // TODO: This doesn't properly capture state to // determine whether we will end up out of the form if // we hit back! // Need to test _until_ we get a question that is // relevant, then we can skip the relevancy tests } } else if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) { // If we've already passed the current screen, this repeat // junction is coming up in the future and we will need to // know // about it if (!onCurrentScreen && details.currentScreenExit != null) { details.totalQuestions++; details.relevantAfterCurrentScreen++; } else { // Otherwise we already passed it and it no longer // affects the count } } currentFormIndex = mFormController.getNextFormIndex(currentFormIndex, FormController.STEP_INTO_GROUP, false); event = mFormController.getEvent(currentFormIndex); } } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); } // Set form back to correct state mFormController.jumpToIndex(userFormIndex); return details; } /** * Update progress bar's max and value, and the various buttons and navigation cues * associated with navigation * * @param view ODKView to update */ private void updateNavigationCues(View view) { updateFloatingLabels(view); ProgressBarMode mode = PreferencesActivity.getProgressBarMode(this); setNavBarVisibility(); if(mode == ProgressBarMode.None) { return; } NavigationDetails details = calculateNavigationStatus(); if(mode == ProgressBarMode.ProgressOnly && view instanceof ODKView) { ((ODKView)view).updateProgressBar(details.completedQuestions, details.totalQuestions); return; } ProgressBar progressBar = (ProgressBar)this.findViewById(R.id.nav_prog_bar); ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev); if(!details.relevantBeforeCurrentScreen) { prevButton.setImageResource(R.drawable.icon_close_darkwarm); prevButton.setTag("quit"); } else { prevButton.setImageResource(R.drawable.icon_chevron_left_brand); prevButton.setTag("back"); } //Apparently in Android 2.3 setting the drawable resource for the progress bar //causes it to lose it bounds. It's a bit cheaper to keep them around than it //is to invalidate the view, though. Rect bounds = progressBar.getProgressDrawable().getBounds(); //Save the drawable bound Log.i("Questions", "Total questions: " + details.totalQuestions + " | Completed questions: " + details.completedQuestions); if (BuildConfig.DEBUG && ((bounds.width() == 0 && bounds.height() == 0) || progressBar.getVisibility() != View.VISIBLE)) { Log.e(TAG, "Invisible ProgressBar! Its visibility is: " + progressBar.getVisibility() + ", its bounds are: " + bounds); } progressBar.setMax(details.totalQuestions); if(details.relevantAfterCurrentScreen == 0 && (details.requiredOnScreen == details.answeredOnScreen || details.requiredOnScreen < 1)) { nextButton.setImageResource(R.drawable.icon_chevron_right_attnpos); //TODO: _really_? This doesn't seem right nextButton.setTag("done"); progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_full)); Log.i("Questions","Form complete"); // if we get here, it means we don't have any more relevant questions after this one, so we mark it as complete progressBar.setProgress(details.totalQuestions); // completely fills the progressbar } else { nextButton.setImageResource(R.drawable.icon_chevron_right_brand); //TODO: _really_? This doesn't seem right nextButton.setTag("next"); progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_modern)); progressBar.setProgress(details.completedQuestions); } progressBar.getProgressDrawable().setBounds(bounds); //Set the bounds to the saved value //We should probably be doing this based on the widgets, maybe, not the model? Hard to call. updateBadgeInfo(details.requiredOnScreen, details.answeredOnScreen); } private void setNavBarVisibility() { //Make sure the nav bar visibility is set int navBarVisibility = PreferencesActivity.getProgressBarMode(this).useNavigationBar() ? View.VISIBLE : View.GONE; View nav = this.findViewById(R.id.nav_pane); if(nav.getVisibility() != navBarVisibility) { nav.setVisibility(navBarVisibility); this.findViewById(R.id.nav_badge_border_drawer).setVisibility(navBarVisibility); this.findViewById(R.id.nav_badge).setVisibility(navBarVisibility); } } enum FloatingLabel { good ("floating-good", R.drawable.label_floating_good, R.color.cc_attention_positive_text), caution ("floating-caution", R.drawable.label_floating_caution, R.color.cc_light_warm_accent_color), bad ("floating-bad", R.drawable.label_floating_bad, R.color.cc_attention_negative_color); final String label; final int resourceId; final int colorId; FloatingLabel(String label, int resourceId, int colorId) { this.label = label; this.resourceId = resourceId; this.colorId = colorId; } public String getAppearance() { return label;} public int getBackgroundDrawable() { return resourceId; } public int getColorId() { return colorId; } } private void updateFloatingLabels(View currentView) { //TODO: this should actually be set up to scale per screen size. ArrayList<Pair<String, FloatingLabel>> smallLabels = new ArrayList<>(); ArrayList<Pair<String, FloatingLabel>> largeLabels = new ArrayList<>(); FloatingLabel[] labelTypes = FloatingLabel.values(); if(currentView instanceof ODKView) { for(QuestionWidget widget : ((ODKView)currentView).getWidgets()) { String hint = widget.getPrompt().getAppearanceHint(); if(hint == null) { continue; } for(FloatingLabel type : labelTypes) { if(type.getAppearance().equals(hint)) { String widgetText = widget.getPrompt().getQuestionText(); if(widgetText != null && widgetText.length() < 15) { smallLabels.add(new Pair<>(widgetText, type)); } else { largeLabels.add(new Pair<>(widgetText, type)); } } } } } final ViewGroup parent = (ViewGroup)this.findViewById(R.id.form_entry_label_layout); parent.removeAllViews(); int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()); int minHeight = 7 * pixels; //Ok, now go ahead and add all of the small labels for(int i = 0 ; i < smallLabels.size(); i = i + 2 ) { if(i + 1 < smallLabels.size()) { LinearLayout.LayoutParams lpp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); final LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.HORIZONTAL); layout.setLayoutParams(lpp); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1); TextView left = (TextView)View.inflate(this, R.layout.component_floating_label, null); left.setLayoutParams(lp); left.setText(smallLabels.get(i).first + "; " + smallLabels.get(i + 1).first); left.setBackgroundResource(smallLabels.get(i).second.resourceId); left.setPadding(pixels, 2 * pixels, pixels, 2 * pixels); left.setTextColor(smallLabels.get(i).second.colorId); left.setMinimumHeight(minHeight); layout.addView(left); parent.addView(layout); } else { largeLabels.add(smallLabels.get(i)); } } for(int i = 0 ; i < largeLabels.size(); ++i ) { final TextView view = (TextView)View.inflate(this, R.layout.component_floating_label, null); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); view.setLayoutParams(lp); view.setPadding(pixels, 2 * pixels, pixels, 2 * pixels); view.setText(largeLabels.get(i).first); view.setBackgroundResource(largeLabels.get(i).second.resourceId); view.setTextColor(largeLabels.get(i).second.colorId); view.setMinimumHeight(minHeight); parent.addView(view); } } private void updateBadgeInfo(int requiredOnScreen, int answeredOnScreen) { View badgeBorder = this.findViewById(R.id.nav_badge_border_drawer); TextView badge = (TextView)this.findViewById(R.id.nav_badge); //If we don't need this stuff, just bail if(requiredOnScreen <= 1) { //Hide all badge related items badgeBorder.setVisibility(View.INVISIBLE); badge.setVisibility(View.INVISIBLE); return; } //Otherwise, update badge stuff badgeBorder.setVisibility(View.VISIBLE); badge.setVisibility(View.VISIBLE); if(requiredOnScreen - answeredOnScreen == 0) { //Unicode checkmark badge.setText("\u2713"); badge.setBackgroundResource(R.drawable.badge_background_complete); } else { badge.setBackgroundResource(R.drawable.badge_background); badge.setText(String.valueOf(requiredOnScreen - answeredOnScreen)); } } /** * Takes in a form entry prompt that is obtained generically and if there * is already one on screen (which, for isntance, may have cached some of its data) * returns the object in use currently. */ private FormEntryPrompt getOnScreenPrompt(FormEntryPrompt prompt, ODKView view) { FormIndex index = prompt.getIndex(); for(QuestionWidget widget : view.getWidgets()) { if(widget.getFormId().equals(index)) { return widget.getPrompt(); } } return prompt; } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView() { refreshCurrentView(true); } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView(boolean animateLastView) { if(mFormController == null) { throw new RuntimeException("Form state is lost! Cannot refresh current view. This shouldn't happen, please submit a bug report."); } int event = mFormController.getEvent(); // When we refresh, repeat dialog state isn't maintained, so step back to the previous // question. // Also, if we're within a group labeled 'field list', step back to the beginning of that // group. // That is, skip backwards over repeat prompts, groups that are not field-lists, // repeat events, and indexes in field-lists that is not the containing group. while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT || (event == FormEntryController.EVENT_GROUP && !mFormController.indexIsInFieldList()) || event == FormEntryController.EVENT_REPEAT || (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) { event = mFormController.stepToPreviousEvent(); } //If we're at the beginning of form event, but don't show the screen for that, we need //to get the next valid screen if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { this.showNextView(true); } else if(event == FormEntryController.EVENT_END_OF_FORM) { // TODO PLM: don't animate this view change (just like showNextView doesn't animate above) showPreviousView(); } else { View current = createView(event); showView(current, AnimationType.FADE, animateLastView); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.removeItem(MENU_LANGUAGES); menu.removeItem(MENU_HIERARCHY_VIEW); menu.removeItem(MENU_SAVE); menu.removeItem(MENU_PREFERENCES); if(mIncompleteEnabled) { menu.add(0, MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)).setIcon( android.R.drawable.ic_menu_save); } menu.add(0, MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)).setIcon( R.drawable.ic_menu_goto); boolean hasMultipleLanguages = (!(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1)); menu.add(0, MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language)) .setIcon(R.drawable.ic_menu_start_conversation) .setEnabled(hasMultipleLanguages); menu.add(0, MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.general_preferences)).setIcon( android.R.drawable.ic_menu_preferences); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_LANGUAGES: createLanguageDialog(); return true; case MENU_SAVE: // don't exit saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null, false); return true; case MENU_HIERARCHY_VIEW: if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY); return true; case MENU_PREFERENCES: Intent pref = new Intent(this, PreferencesActivity.class); startActivity(pref); return true; case android.R.id.home: triggerUserQuitInput(); return true; } return super.onOptionsItemSelected(item); } /** * @return true If the current index of the form controller contains questions */ private boolean currentPromptIsQuestion() { return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController .getEvent() == FormEntryController.EVENT_GROUP); } private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) { return saveAnswersForCurrentScreen(evaluateConstraints, true, false); } /** * Attempt to save the answer(s) in the current screen to into the data model. * * @param failOnRequired Whether or not the constraint evaluation * should return false if the question is only * required. (this is helpful for incomplete * saves) * @param headless running in a process that can't display graphics * @return false if any error occurs while saving (constraint violated, * etc...), true otherwise. */ private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { // only try to save if the current event is a question or a field-list // group boolean success = true; if ((mFormController.getEvent() == FormEntryController.EVENT_QUESTION) || ((mFormController.getEvent() == FormEntryController.EVENT_GROUP) && mFormController.indexIsInFieldList())) { if (mCurrentView instanceof ODKView) { HashMap<FormIndex, IAnswerData> answers = ((ODKView)mCurrentView).getAnswers(); // Sort the answers so if there are multiple errors, we can // bring focus to the first one List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, new Comparator<FormIndex>() { @Override public int compare(FormIndex arg0, FormIndex arg1) { return arg0.compareTo(arg1); } }); for (FormIndex index : indexKeys) { // Within a group, you can only save for question events if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { createConstraintToast(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } else { String viewType; if (mCurrentView == null || mCurrentView.getClass() == null) { viewType = "null"; } else { viewType = mCurrentView.getClass().toString(); } Log.w(TAG, "Unknown view type rendered while current event was question or group! View type: " + viewType); } } return success; } /** * Clears the answer on the screen. */ private void clearAnswer(QuestionWidget qw) { qw.clearAnswer(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer)); menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt)); } @Override public boolean onContextItemSelected(MenuItem item) { // We don't have the right view here, so we store the View's ID as the // item ID and loop through the possible views to find the one the user // clicked on. for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) { if (item.getItemId() == qw.getId()) { createClearDialog(qw); } } return super.onContextItemSelected(item); } /** * If we're loading, then we pass the loading thread to our next instance. */ @Override public Object onRetainCustomNonConfigurationInstance() { // if a form is loading, pass the loader task if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) return mFormLoaderTask; // if a form is writing to disk, pass the save to disk task if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED) return mSaveToDiskTask; // mFormEntryController is static so we don't need to pass it. if (mFormController != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } return null; } private String getHeaderString() { if(mHeaderString != null) { //Localization? return mHeaderString; } else { return StringUtils.getStringRobust(this, R.string.app_name) + " > " + mFormController.getFormTitle(); } } /** * Creates a view given the View type and an event */ private View createView(int event) { setTitle(getHeaderString()); ODKView odkv; // should only be a group here if the event_group is a field-list try { odkv = new ODKView(this, mFormController.getQuestionPrompts(), mFormController.getGroupsForCurrentIndex(), mFormController.getWidgetFactory(), this); Log.i(TAG, "created view for group"); } catch (RuntimeException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); // this is badness to avoid a crash. // really a next view should increment the formcontroller, create the view // if the view is null, then keep the current view and pop an error. return new View(this); } // Makes a "clear answer" menu pop up on long-click of // select-one/select-multiple questions for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly() && !mFormController.isFormReadOnly() && (qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_ONE || qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_MULTI)) { registerForContextMenu(qw); } } updateNavigationCues(odkv); return odkv; } @SuppressLint("NewApi") @Override public boolean dispatchTouchEvent(MotionEvent mv) { //We need to ignore this even if it's processed by the action //bar (if one exists) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar bar = getActionBar(); if (bar != null) { View customView = bar.getCustomView(); if (customView != null) { if (customView.dispatchTouchEvent(mv)) { return true; } } } } boolean handled = mGestureDetector.onTouchEvent(mv); return handled || super.dispatchTouchEvent(mv); } /** * Determines what should be displayed on the screen. Possible options are: a question, an ask * repeat dialog, or the submit screen. Also saves answers to the data model after checking * constraints. */ private void showNextView() { showNextView(false); } private void showNextView(boolean resuming) { if (currentPromptIsQuestion()) { if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) { // A constraint was violated so a dialog should be showing. return; } } if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) { int event; try{ group_skip: do { event = mFormController.stepToNextEvent(FormController.STEP_OVER_GROUP); switch (event) { case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_END_OF_FORM: View next = createView(event); if(!resuming) { showView(next, AnimationType.RIGHT); } else { showView(next, AnimationType.FADE, false); } break group_skip; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); break group_skip; case FormEntryController.EVENT_GROUP: //We only hit this event if we're at the _opening_ of a field //list, so it seems totally fine to do it this way, technically //though this should test whether the index is the field list //host. if (mFormController.indexIsInFieldList() && mFormController.getQuestionPrompts().length != 0) { View nextGroupView = createView(event); if(!resuming) { showView(nextGroupView, AnimationType.RIGHT); } else { showView(nextGroupView, AnimationType.FADE, false); } break group_skip; } // otherwise it's not a field-list group, so just skip it break; case FormEntryController.EVENT_REPEAT: Log.i(TAG, "repeat: " + mFormController.getFormIndex().getReference()); // skip repeats break; case FormEntryController.EVENT_REPEAT_JUNCTURE: Log.i(TAG, "repeat juncture: " + mFormController.getFormIndex().getReference()); // skip repeat junctures until we implement them break; default: Log.w(TAG, "JavaRosa added a new EVENT type and didn't tell us... shame on them."); break; } } while (event != FormEntryController.EVENT_END_OF_FORM); }catch(XPathTypeMismatchException e){ Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); } } else { mBeenSwiped = false; } } /** * Determines what should be displayed between a question, or the start screen and displays the * appropriate view. Also saves answers to the data model without checking constraints. */ private void showPreviousView() { // The answer is saved on a back swipe, but question constraints are ignored. if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } FormIndex startIndex = mFormController.getFormIndex(); FormIndex lastValidIndex = startIndex; if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) { int event = mFormController.stepToPreviousEvent(); //Step backwards until we either find a question, the beginning of the form, //or a field list with valid questions inside while (event != FormEntryController.EVENT_BEGINNING_OF_FORM && event != FormEntryController.EVENT_QUESTION && !(event == FormEntryController.EVENT_GROUP && mFormController.indexIsInFieldList() && mFormController .getQuestionPrompts().length != 0)) { event = mFormController.stepToPreviousEvent(); lastValidIndex = mFormController.getFormIndex(); } //check if we're at the beginning and not doing the whole "First screen" thing if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { //If so, we can't go all the way back here, so we've gotta hit the last index that was valid mFormController.jumpToIndex(lastValidIndex); //Did we jump at all? (not sure how we could have, but there might be a mismatch) if(lastValidIndex.equals(startIndex)) { //If not, don't even bother changing the view. //NOTE: This needs to be the same as the //exit condition below, in case either changes mBeenSwiped = false; FormEntryActivity.this.triggerUserQuitInput(); return; } //We might have walked all the way back still, which isn't great, //so keep moving forward again until we find it if(lastValidIndex.isBeginningOfFormIndex()) { //there must be a repeat between where we started and the beginning of hte form, walk back up to it this.showNextView(true); return; } } View next = createView(event); showView(next, AnimationType.LEFT); } else { //NOTE: this needs to match the exist condition above //when there is no start screen mBeenSwiped = false; FormEntryActivity.this.triggerUserQuitInput(); } } /** * Displays the View specified by the parameter 'next', animating both the current view and next * appropriately given the AnimationType. Also updates the progress bar. */ private void showView(View next, AnimationType from) { showView(next, from, true); } private void showView(View next, AnimationType from, boolean animateLastView) { switch (from) { case RIGHT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out); break; case LEFT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out); break; case FADE: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out); break; } if (mCurrentView != null) { if(animateLastView) { mCurrentView.startAnimation(mOutAnimation); } mViewPane.removeView(mCurrentView); } mInAnimation.setAnimationListener(this); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); mCurrentView = next; mViewPane.addView(mCurrentView, lp); mCurrentView.startAnimation(mInAnimation); FrameLayout header = (FrameLayout)findViewById(R.id.form_entry_header); TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label)); header.setVisibility(View.GONE); groupLabel.setVisibility(View.GONE); if (mCurrentView instanceof ODKView) { ((ODKView) mCurrentView).setFocus(this); SpannableStringBuilder groupLabelText = ((ODKView) mCurrentView).getGroupLabel(); if(groupLabelText != null && !groupLabelText.toString().trim().equals("")) { groupLabel.setText(groupLabelText); header.setVisibility(View.VISIBLE); groupLabel.setVisibility(View.VISIBLE); } } else { InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0); } } // Hopefully someday we can use managed dialogs when the bugs are fixed /** * Creates and displays a dialog displaying the violated constraint. */ private void createConstraintToast(FormIndex index, String constraintText, int saveStatus, boolean requestFocus) { switch (saveStatus) { case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: if (constraintText == null) { constraintText = StringUtils.getStringRobust(this, R.string.invalid_answer_error); } break; case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: constraintText = StringUtils.getStringRobust(this, R.string.required_answer_error); break; } boolean displayed = false; //We need to see if question in violation is on the screen, so we can show this cleanly. for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) { if(index.equals(q.getFormId())) { q.notifyInvalid(constraintText, requestFocus); displayed = true; break; } } if(!displayed) { showCustomToast(constraintText, Toast.LENGTH_SHORT); } mBeenSwiped = false; } private void showCustomToast(String message, int duration) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_view, null); // set the text in the view TextView tv = (TextView) view.findViewById(R.id.message); tv.setText(message); Toast t = new Toast(this); t.setView(view); t.setDuration(duration); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } /** * Creates and displays a dialog asking the user if they'd like to create a repeat of the * current group. */ private void createRepeatDialog() { ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme); View view = LayoutInflater.from(wrapper).inflate(R.layout.component_repeat_new_dialog, null); mRepeatDialog = new AlertDialog.Builder(wrapper).create(); final AlertDialog theDialog = mRepeatDialog; mRepeatDialog.setView(view); mRepeatDialog.setIcon(android.R.drawable.ic_dialog_info); boolean hasNavBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar(); //this is super gross... NavigationDetails details = null; if(hasNavBar) { details = calculateNavigationStatus(); } final boolean backExitsForm = hasNavBar && !details.relevantBeforeCurrentScreen; final boolean nextExitsForm = hasNavBar && details.relevantAfterCurrentScreen == 0; Button back = (Button)view.findViewById(R.id.component_repeat_back); back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(backExitsForm) { FormEntryActivity.this.triggerUserQuitInput(); } else { theDialog.dismiss(); FormEntryActivity.this.refreshCurrentView(false); } } }); Button newButton = (Button)view.findViewById(R.id.component_repeat_new); newButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { theDialog.dismiss(); try { mFormController.newRepeat(); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(FormEntryActivity.this, e.getMessage(), EXIT); return; } showNextView(); } }); Button skip = (Button)view.findViewById(R.id.component_repeat_skip); skip.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { theDialog.dismiss(); if(!nextExitsForm) { showNextView(); } else { triggerUserFormComplete(); } } }); back.setText(StringUtils.getStringSpannableRobust(this, R.string.repeat_go_back)); //Load up our icons Drawable exitIcon = getResources().getDrawable(R.drawable.icon_exit); exitIcon.setBounds(0, 0, exitIcon.getIntrinsicWidth(), exitIcon.getIntrinsicHeight()); Drawable doneIcon = getResources().getDrawable(R.drawable.icon_done); doneIcon.setBounds(0, 0, doneIcon.getIntrinsicWidth(), doneIcon.getIntrinsicHeight()); if (mFormController.getLastRepeatCount() > 0) { mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.leaving_repeat_ask)); mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_another_repeat, mFormController.getLastGroupText())); newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.add_another)); if(!nextExitsForm) { skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes)); } else { skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes_exits)); } } else { mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.entering_repeat_ask)); mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_repeat, mFormController.getLastGroupText())); newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.entering_repeat)); if(!nextExitsForm) { skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no)); } else { skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no_exits)); } } mRepeatDialog.setCancelable(false); mRepeatDialog.show(); if(nextExitsForm) { skip.setCompoundDrawables(null, doneIcon, null, null); } if(backExitsForm) { back.setCompoundDrawables(null, exitIcon, null, null); } mBeenSwiped = false; } /** * Saves form data to disk. * * @param exit If set, will exit program after save. * @param complete Has the user marked the instances as complete? * @param updatedSaveName Set name of the instance's content provider, if * non-null * @param headless Disables GUI warnings and lets answers that * violate constraints be saved. */ private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) { if (!formHasLoaded()) { return; } // save current answer; if headless, don't evaluate the constraints // before doing so. if (headless && (!saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS, complete, headless))) { return; } else if (!headless && !saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS, complete, headless)) { Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_SHORT).show(); return; } // If a save task is already running, just let it do its thing if ((mSaveToDiskTask != null) && (mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) { return; } mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName, this, instanceProviderContentURI, symetricKey, headless); mSaveToDiskTask.setFormSavedListener(this); mSaveToDiskTask.execute(); if (!headless) { showDialog(SAVING_DIALOG); } } /** * Create a dialog with options to save and exit, save, or quit without saving */ private void createQuitDialog() { final String[] items = mIncompleteEnabled ? new String[] {StringUtils.getStringRobust(this, R.string.keep_changes), StringUtils.getStringRobust(this, R.string.do_not_save)} : new String[] {StringUtils.getStringRobust(this, R.string.do_not_save)}; mAlertDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle(StringUtils.getStringRobust(this, R.string.quit_application, mFormController.getFormTitle())) .setNeutralButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_exit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // save and exit if(items.length == 1) { discardChangesAndExit(); } else { saveDataToDisk(EXIT, isInstanceComplete(false), null, false); } break; case 1: // discard changes and exit discardChangesAndExit(); break; case 2:// do nothing break; } } }).create(); mAlertDialog.getListView().setSelector(R.drawable.selector); mAlertDialog.show(); } private void discardChangesAndExit() { String selection = InstanceColumns.INSTANCE_FILE_PATH + " like '" + mInstancePath + "'"; Cursor c = null; int instanceCount = 0; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, null, null); instanceCount = c.getCount(); } finally { if (c != null) { c.close(); } } // if it's not already saved, erase everything if (instanceCount < 1) { int images = 0; int audio = 0; int video = 0; // delete media first String instanceFolder = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); Log.i(TAG, "attempting to delete: " + instanceFolder); String where = Images.Media.DATA + " like '" + instanceFolder + "%'"; String[] projection = { Images.ImageColumns._ID }; // images Cursor imageCursor = null; try { imageCursor = getContentResolver().query( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, where, null, null); if (imageCursor.getCount() > 0) { imageCursor.moveToFirst(); String id = imageCursor.getString(imageCursor .getColumnIndex(Images.ImageColumns._ID)); Log.i( TAG, "attempting to delete: " + Uri.withAppendedPath( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)); images = getContentResolver() .delete( Uri.withAppendedPath( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id), null, null); } } finally { if ( imageCursor != null ) { imageCursor.close(); } } // audio Cursor audioCursor = null; try { audioCursor = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, where, null, null); if (audioCursor.getCount() > 0) { audioCursor.moveToFirst(); String id = audioCursor.getString(imageCursor .getColumnIndex(Images.ImageColumns._ID)); Log.i( TAG, "attempting to delete: " + Uri.withAppendedPath( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id)); audio = getContentResolver() .delete( Uri.withAppendedPath( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id), null, null); } } finally { if ( audioCursor != null ) { audioCursor.close(); } } // video Cursor videoCursor = null; try { videoCursor = getContentResolver().query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, where, null, null); if (videoCursor.getCount() > 0) { videoCursor.moveToFirst(); String id = videoCursor.getString(imageCursor .getColumnIndex(Images.ImageColumns._ID)); Log.i( TAG, "attempting to delete: " + Uri.withAppendedPath( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)); video = getContentResolver() .delete( Uri.withAppendedPath( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id), null, null); } } finally { if ( videoCursor != null ) { videoCursor.close(); } } Log.i(TAG, "removed from content providers: " + images + " image files, " + audio + " audio files," + " and " + video + " video files."); File f = new File(instanceFolder); if (f.exists() && f.isDirectory()) { for (File del : f.listFiles()) { Log.i(TAG, "deleting file: " + del.getAbsolutePath()); del.delete(); } f.delete(); } } finishReturnInstance(false); } /** * Confirm clear answer dialog */ private void createClearDialog(final QuestionWidget qw) { mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(StringUtils.getStringRobust(this, R.string.clear_answer_ask)); String question = qw.getPrompt().getLongText(); if (question.length() > 50) { question = question.substring(0, 50) + "..."; } mAlertDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.clearanswer_confirm, question)); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: clearAnswer(qw); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE, StringUtils.getStringSpannableRobust(this, R.string.discard_answer), quitListener); mAlertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, StringUtils.getStringSpannableRobust(this, R.string.clear_answer_no), quitListener); mAlertDialog.show(); } /** * Creates and displays a dialog allowing the user to set the language for the form. */ private void createLanguageDialog() { final String[] languages = mFormController.getLanguages(); int selected = -1; if (languages != null) { String language = mFormController.getLanguage(); for (int i = 0; i < languages.length; i++) { if (language.equals(languages[i])) { selected = i; } } } mAlertDialog = new AlertDialog.Builder(this) .setSingleChoiceItems(languages, selected, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { // Update the language in the content provider when selecting a new // language ContentValues values = new ContentValues(); values.put(FormsColumns.LANGUAGE, languages[whichButton]); String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; int updated = getContentResolver().update(formProviderContentURI, values, selection, selectArgs); Log.i(TAG, "Updated language to: " + languages[whichButton] + " in " + updated + " rows"); mFormController.setLanguage(languages[whichButton]); dialog.dismiss(); if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } refreshCurrentView(); } }) .setTitle(StringUtils.getStringRobust(this, R.string.change_language)) .setNegativeButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_change), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { } }).create(); mAlertDialog.show(); } /** * We use Android's dialog management for loading/saving progress dialogs */ @Override protected Dialog onCreateDialog(int id) { ProgressDialog progressDialog; switch (id) { case PROGRESS_DIALOG: progressDialog = new ProgressDialog(this); DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mFormLoaderTask.setFormLoaderListener(null); mFormLoaderTask.cancel(true); finish(); } }; progressDialog.setIcon(android.R.drawable.ic_dialog_info); progressDialog.setTitle(StringUtils.getStringRobust(this, R.string.loading_form)); progressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait)); progressDialog.setIndeterminate(true); progressDialog.setCancelable(false); progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, StringUtils.getStringSpannableRobust(this, R.string.cancel_loading_form), loadingButtonListener); return progressDialog; case SAVING_DIALOG: progressDialog = new ProgressDialog(this); DialogInterface.OnClickListener savingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mSaveToDiskTask.setFormSavedListener(null); mSaveToDiskTask.cancel(true); } }; progressDialog.setIcon(android.R.drawable.ic_dialog_info); progressDialog.setTitle(StringUtils.getStringRobust(this, R.string.saving_form)); progressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait)); progressDialog.setIndeterminate(true); progressDialog.setCancelable(false); progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, StringUtils.getStringSpannableRobust(this, R.string.cancel), savingButtonListener); progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, StringUtils.getStringSpannableRobust(this, R.string.cancel_saving_form), savingButtonListener); return progressDialog; } return null; } /** * Dismiss any showing dialogs that we manually manage. */ private void dismissDialogs() { if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } if(mRepeatDialog != null && mRepeatDialog.isShowing()) { mRepeatDialog.dismiss(); } } @Override protected void onPause() { super.onPause(); SessionActivityRegistration.unregisterSessionExpirationReceiver(this); dismissDialogs(); if (mCurrentView != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } if (mLocationServiceIssueReceiver != null) { unregisterReceiver(mLocationServiceIssueReceiver); } } @Override protected void onResume() { super.onResume(); SessionActivityRegistration.handleOrListenForSessionExpiration(this); registerFormEntryReceiver(); if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(this); if (mFormController != null && mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { dismissDialog(PROGRESS_DIALOG); refreshCurrentView(); } } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(this); } //csims@dimagi.com - 22/08/2012 - For release only, fix immediately. //There is a _horribly obnoxious_ bug in TimePickers that messes up how they work //on screen rotation. We need to re-do any setAnswers that we perform on them after //onResume. try { if(mCurrentView instanceof ODKView) { ODKView ov = ((ODKView) mCurrentView); if(ov.getWidgets() != null) { for(QuestionWidget qw : ov.getWidgets()) { if(qw instanceof DateTimeWidget) { ((DateTimeWidget)qw).setAnswer(); } else if(qw instanceof TimeWidget) { ((TimeWidget)qw).setAnswer(); } } } } } catch(Exception e) { //if this fails, we _really_ don't want to mess anything up. this is a last minute //fix } if (mFormController != null) { mFormController.setPendingCalloutFormIndex(null); } } /** * Call when the user provides input that they want to quit the form */ private void triggerUserQuitInput() { //If we're just reviewing a read only form, don't worry about saving //or what not, just quit if(mFormController.isFormReadOnly()) { //It's possible we just want to "finish" here, but //I don't really wanna break any c compatibility finishReturnInstance(false); } else { createQuitDialog(); } } /** * Get the default title for ODK's "Form title" field */ private String getDefaultFormTitle() { String saveName = mFormController.getFormTitle(); if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance.getCount() == 1) { instance.moveToFirst(); saveName = instance.getString(instance .getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } return saveName; } /** * Call when the user is ready to save and return the current form as complete */ private void triggerUserFormComplete() { if (mFormController.isFormReadOnly()) { finishReturnInstance(false); } else { saveDataToDisk(EXIT, true, getDefaultFormTitle(), false); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: triggerUserQuitInput(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; showNextView(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; showPreviousView(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(null); // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. // but only if it's done, otherwise the thread never returns if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { mFormLoaderTask.cancel(true); mFormLoaderTask.destroy(); } } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(null); // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(false); } } super.onDestroy(); } @Override public void onAnimationEnd(Animation arg0) { mBeenSwiped = false; } @Override public void onAnimationRepeat(Animation animation) { // Added by AnimationListener interface. } @Override public void onAnimationStart(Animation animation) { // Added by AnimationListener interface. } /** * loadingComplete() is called by FormLoaderTask once it has finished loading a form. */ @SuppressLint("NewApi") @Override public void loadingComplete(FormController fc) { dismissDialog(PROGRESS_DIALOG); mFormController = fc; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ // Newer menus may have already built the menu, before all data was ready invalidateOptionsMenu(); } Localizer mLocalizer = Localization.getGlobalLocalizerAdvanced(); if(mLocalizer != null){ String mLocale = mLocalizer.getLocale(); if (mLocale != null && fc.getLanguages() != null && Arrays.asList(fc.getLanguages()).contains(mLocale)){ fc.setLanguage(mLocale); } else{ Logger.log("formloader", "The current locale is not set"); } } else{ Logger.log("formloader", "Could not get the localizer"); } registerSessionFormSaveCallback(); // Set saved answer path if (mInstancePath == null) { // Create new answer folder. String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss") .format(Calendar.getInstance().getTime()); String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')); String path = mInstanceDestination + file + "_" + time; if (FileUtils.createFolder(path)) { mInstancePath = path + "/" + file + "_" + time + ".xml"; } } else { // we've just loaded a saved form, so start in the hierarchy view Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY_FIRST_START); return; // so we don't show the intro screen before jumping to the hierarchy } refreshCurrentView(); updateNavigationCues(this.mCurrentView); } private void registerSessionFormSaveCallback() { if (mFormController != null && !mFormController.isFormReadOnly()) { try { // CommCareSessionService will call this.formSaveCallback when // the key session is closing down and we need to save any // intermediate results before they become un-saveable. CommCareApplication._().getSession().registerFormSaveCallback(this); } catch (SessionUnavailableException e) { Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Couldn't register form save callback because session doesn't exist"); } } } /** * called by the FormLoaderTask if something goes wrong. */ @Override public void loadingError(String errorMsg) { dismissDialog(PROGRESS_DIALOG); if (errorMsg != null) { CommCareActivity.createErrorDialog(this, errorMsg, EXIT); } else { CommCareActivity.createErrorDialog(this, StringUtils.getStringRobust(this, R.string.parse_error), EXIT); } } /** * {@inheritDoc} * * Display save status notification and exit or continue on in the form. * If form entry is being saved because key session is expiring then * continue closing the session/logging out. * * @see org.odk.collect.android.listeners.FormSavedListener#savingComplete(int, boolean) */ @Override public void savingComplete(int saveStatus, boolean headless) { if (!headless) { dismissDialog(SAVING_DIALOG); } // Did we just save a form because the key session // (CommCareSessionService) is ending? if (savingFormOnKeySessionExpiration) { savingFormOnKeySessionExpiration = false; // Notify the key session that the form state has been saved (or at // least attempted to be saved) so CommCareSessionService can // continue closing down key pool and user database. CommCareApplication._().expireUserSession(); } else { switch (saveStatus) { case SaveToDiskTask.SAVED: Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); hasSaved = true; break; case SaveToDiskTask.SAVED_AND_EXIT: Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); hasSaved = true; finishReturnInstance(); break; case SaveToDiskTask.SAVE_ERROR: Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_LONG).show(); break; case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: refreshCurrentView(); // an answer constraint was violated, so do a 'swipe' to the next // question to display the proper toast(s) next(); break; } } } /** * Attempts to save an answer to the specified index. * * @param evaluateConstraints Should form contraints be checked when saving answer? * @return status as determined in FormEntryController */ private int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) { try { if (evaluateConstraints) { return mFormController.answerQuestion(index, answer); } else { mFormController.saveAnswer(index, answer); return FormEntryController.ANSWER_OK; } } catch(XPathException e) { //this is where runtime exceptions get triggered after the form has loaded CommCareActivity.createErrorDialog(this, "There is a bug in one of your form's XPath Expressions \n" + e.getMessage(), EXIT); //We're exiting anyway return FormEntryController.ANSWER_OK; } } /** * Checks the database to determine if the current instance being edited has already been * 'marked completed'. A form can be 'unmarked' complete and then resaved. * * @return true if form has been marked completed, false otherwise. */ private boolean isInstanceComplete(boolean end) { // default to false if we're mid form boolean complete = false; // if we're at the end of the form, then check the preferences if (end) { // First get the value from the preferences SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); complete = sharedPreferences.getBoolean(PreferencesActivity.KEY_COMPLETED_DEFAULT, true); } // Then see if we've already marked this form as complete before String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS)); if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) { complete = true; } } } finally { if (c != null) { c.close(); } } return complete; } private void next() { if (!mBeenSwiped) { mBeenSwiped = true; showNextView(); } } private void finishReturnInstance() { finishReturnInstance(true); } /** * Returns the instance that was just filled out to the calling activity, * if requested. * * @param reportSaved was a form saved? Delegates the result code of the * activity */ private void finishReturnInstance(boolean reportSaved) { String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) { // caller is waiting on a picked form String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c.getCount() > 0) { // should only be one... c.moveToFirst(); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri instance = Uri.withAppendedPath(instanceProviderContentURI, id); Intent formReturnIntent = new Intent(); formReturnIntent.putExtra(IS_ARCHIVED_FORM, mFormController.isFormReadOnly()); if (reportSaved || hasSaved) { setResult(RESULT_OK, formReturnIntent.setData(instance)); } else { setResult(RESULT_CANCELED, formReturnIntent.setData(instance)); } } } finally { if (c != null) { c.close(); } } } try { CommCareApplication._().getSession().unregisterFormSaveCallback(); } catch (SessionUnavailableException sue) { // looks like the session expired } this.dismissDialogs(); finish(); } @Override public boolean onDown(MotionEvent e) { return false; } /** * Looks for user swipes. If the user has swiped, move to the appropriate screen. */ @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (CommCareActivity.isHorizontalSwipe(this, e1, e2)) { mBeenSwiped = true; if (velocityX > 0) { showPreviousView(); } else { int event = mFormController.getEvent(mFormController.getNextFormIndex(mFormController.getFormIndex(), true)); boolean navBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar(); if(!navBar || event != FormEntryController.EVENT_END_OF_FORM) { showNextView(); } } return true; } return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // The onFling() captures the 'up' event so our view thinks it gets long pressed. // We don't wnat that, so cancel it. mCurrentView.cancelLongPress(); return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void advance() { next(); } @Override public void widgetEntryChanged() { updateFormRelevencies(); updateNavigationCues(this.mCurrentView); } /** * Has form loading (via FormLoaderTask) completed? */ private boolean formHasLoaded() { return mFormController != null; } private void addBreadcrumbBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { final String fragmentClass = this.getIntent().getStringExtra("odk_title_fragment"); if (fragmentClass != null) { final FragmentManager fm = this.getSupportFragmentManager(); Fragment bar = fm.findFragmentByTag(TITLE_FRAGMENT_TAG); if (bar == null) { try { bar = ((Class<Fragment>)Class.forName(fragmentClass)).newInstance(); ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } fm.beginTransaction().add(bar, TITLE_FRAGMENT_TAG).commit(); } catch(Exception e) { Log.w(TAG, "couldn't instantiate fragment: " + fragmentClass); } } } } } private boolean loadStateFromBundle(Bundle savedInstanceState) { boolean isNewForm = true; if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { mFormPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(NEWFORM)) { isNewForm = savedInstanceState.getBoolean(NEWFORM, true); } if (savedInstanceState.containsKey(KEY_FORM_CONTENT_URI)) { formProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_FORM_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCE_CONTENT_URI)) { instanceProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_INSTANCE_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCEDESTINATION)) { mInstanceDestination = savedInstanceState.getString(KEY_INSTANCEDESTINATION); } if(savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) { mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED); } if(savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED); } if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) { String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(savedInstanceState.containsKey(KEY_HEADER_STRING)) { mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING); } if(savedInstanceState.containsKey(KEY_HAS_SAVED)) { hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED); } } return isNewForm; } private String getFormPath(Uri uri) throws FormQueryException { Cursor c = null; try { c = getContentResolver().query(uri, null, null, null, null); if (c.getCount() != 1) { throw new FormQueryException("Bad URI: " + uri); } else { c.moveToFirst(); return c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH)); } } finally { if (c != null) { c.close(); } } } private Pair<Uri, Boolean> getInstanceUri(Uri uri) throws FormQueryException { Cursor instanceCursor = null; Cursor formCursor = null; Boolean isInstanceReadOnly = false; Uri formUri = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor.getCount() != 1) { throw new FormQueryException("Bad URI: " + uri); } else { instanceCursor.moveToFirst(); mInstancePath = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String jrFormId = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.JR_FORM_ID)); //If this form is both already completed if (InstanceProviderAPI.STATUS_COMPLETE.equals(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS)))) { if (!Boolean.parseBoolean(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)))) { isInstanceReadOnly = true; } } final String[] selectionArgs = { jrFormId }; final String selection = FormsColumns.JR_FORM_ID + " like ?"; formCursor = getContentResolver().query(formProviderContentURI, null, selection, selectionArgs, null); if (formCursor.getCount() == 1) { formCursor.moveToFirst(); mFormPath = formCursor.getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); formUri = ContentUris.withAppendedId(formProviderContentURI, formCursor.getLong(formCursor.getColumnIndex(FormsColumns._ID))); } else if (formCursor.getCount() < 1) { throw new FormQueryException("Parent form does not exist"); } else if (formCursor.getCount() > 1) { throw new FormQueryException("More than one possible parent form"); } } } finally { if (instanceCursor != null) { instanceCursor.close(); } if (formCursor != null) { formCursor.close(); } } return new Pair<>(formUri, isInstanceReadOnly); } private void loadIntentFormData(Intent intent) { if(intent.hasExtra(KEY_FORM_CONTENT_URI)) { this.formProviderContentURI = Uri.parse(intent.getStringExtra(KEY_FORM_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCE_CONTENT_URI)) { this.instanceProviderContentURI = Uri.parse(intent.getStringExtra(KEY_INSTANCE_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCEDESTINATION)) { this.mInstanceDestination = intent.getStringExtra(KEY_INSTANCEDESTINATION); } else { mInstanceDestination = Collect.INSTANCES_PATH; } if(intent.hasExtra(KEY_AES_STORAGE_KEY)) { String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(intent.hasExtra(KEY_HEADER_STRING)) { FormEntryActivity.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING); } if(intent.hasExtra(KEY_INCOMPLETE_ENABLED)) { this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true); } if(intent.hasExtra(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED); } } private void setTitleToLoading() { if(mHeaderString != null) { setTitle(mHeaderString); } else { setTitle(StringUtils.getStringRobust(this, R.string.app_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form)); } } private class FormQueryException extends Exception { FormQueryException(String msg) { super(msg); } } }
package org.odk.collect.android.activities; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.location.LocationManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.SpannableStringBuilder; import android.util.Log; import android.util.Pair; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.ContextThemeWrapper; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.framework.CommCareActivity; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.logic.BarcodeScanListenerDefaultImpl; import org.commcare.android.util.FormUploadUtil; import org.commcare.android.util.SessionUnavailableException; import org.commcare.android.util.StringUtils; import org.commcare.dalvik.R; import org.commcare.dalvik.activities.CommCareHomeActivity; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.CustomProgressDialog; import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns; import org.commcare.dalvik.odk.provider.InstanceProviderAPI; import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns; import org.commcare.dalvik.utils.UriToFilePath; import org.javarosa.core.model.Constants; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.locale.Localizer; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.model.xform.XFormsModule; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathTypeMismatchException; import org.odk.collect.android.activities.components.FormNavigationController; import org.odk.collect.android.activities.components.FormNavigationUI; import org.odk.collect.android.activities.components.ImageCaptureProcessing; import org.odk.collect.android.application.Collect; import org.odk.collect.android.jr.extensions.IntentCallout; import org.odk.collect.android.jr.extensions.PollSensorAction; import org.odk.collect.android.listeners.AdvanceToNextListener; import org.odk.collect.android.listeners.FormSaveCallback; import org.odk.collect.android.listeners.FormSavedListener; import org.odk.collect.android.listeners.WidgetChangedListener; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.logic.PropertyManager; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.tasks.FormLoaderTask; import org.odk.collect.android.tasks.SaveToDiskTask; import org.odk.collect.android.utilities.Base64Wrapper; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.GeoUtils; import org.odk.collect.android.views.ODKView; import org.odk.collect.android.views.ResizingImageView; import org.odk.collect.android.widgets.DateTimeWidget; import org.odk.collect.android.widgets.ImageWidget; import org.odk.collect.android.widgets.IntentWidget; import org.odk.collect.android.widgets.QuestionWidget; import org.odk.collect.android.widgets.TimeWidget; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.crypto.spec.SecretKeySpec; /** * FormEntryActivity is responsible for displaying questions, animating transitions between * questions, and allowing the user to enter data. * * @author Carl Hartung (carlhartung@gmail.com) */ public class FormEntryActivity extends CommCareActivity<FormEntryActivity> implements AnimationListener, FormSavedListener, FormSaveCallback, AdvanceToNextListener, OnGestureListener, WidgetChangedListener { private static final String TAG = FormEntryActivity.class.getSimpleName(); // Defines for FormEntryActivity private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private static final boolean EVALUATE_CONSTRAINTS = true; private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false; // Request codes for returning data from specified intent. public static final int IMAGE_CAPTURE = 1; public static final int BARCODE_CAPTURE = 2; public static final int AUDIO_VIDEO_FETCH = 3; public static final int LOCATION_CAPTURE = 5; private static final int HIERARCHY_ACTIVITY = 6; public static final int IMAGE_CHOOSER = 7; public static final int INTENT_CALLOUT = 10; private static final int HIERARCHY_ACTIVITY_FIRST_START = 11; public static final int SIGNATURE_CAPTURE = 12; // Extra returned from gp activity public static final String LOCATION_RESULT = "LOCATION_RESULT"; // Identifies the gp of the form used to launch form entry private static final String KEY_FORMPATH = "formpath"; public static final String KEY_INSTANCEDESTINATION = "instancedestination"; public static final String TITLE_FRAGMENT_TAG = "odk_title_fragment"; public static final String KEY_FORM_CONTENT_URI = "form_content_uri"; public static final String KEY_INSTANCE_CONTENT_URI = "instance_content_uri"; public static final String KEY_AES_STORAGE_KEY = "key_aes_storage"; public static final String KEY_HEADER_STRING = "form_header"; public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management"; public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled"; private static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved"; /** * Intent extra flag to track if this form is an archive. Used to trigger * return logic when this activity exits to the home screen, such as * whether to redirect to archive view or sync the form. */ public static final String IS_ARCHIVED_FORM = "is-archive-form"; // Identifies whether this is a new form, or reloading a form after a screen // rotation (or similar) private static final String NEWFORM = "newform"; private static final int MENU_LANGUAGES = Menu.FIRST; private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1; private static final int MENU_SAVE = Menu.FIRST + 2; private static final int MENU_PREFERENCES = Menu.FIRST + 3; private static final int REPEAT_DIALOG = 3; private static final int EXIT_DIALOG = 4; private String mFormPath; // Path to a particular form instance public static String mInstancePath; private String mInstanceDestination; private GestureDetector mGestureDetector; private SecretKeySpec symetricKey = null; public static FormController mFormController; private Animation mInAnimation; private Animation mOutAnimation; private ViewGroup mViewPane; private View mCurrentView; private AlertDialog mAlertDialog; private boolean mIncompleteEnabled = true; // used to limit forward/backward swipes to one per question private boolean mBeenSwiped; private FormLoaderTask<FormEntryActivity> mFormLoaderTask; private SaveToDiskTask<FormEntryActivity> mSaveToDiskTask; private Uri formProviderContentURI = FormsColumns.CONTENT_URI; private Uri instanceProviderContentURI = InstanceColumns.CONTENT_URI; private static String mHeaderString; // Was the form saved? Used to set activity return code. private boolean hasSaved = false; private BroadcastReceiver mLocationServiceIssueReceiver; // marked true if we are in the process of saving a form because the user // database & key session are expiring. Being set causes savingComplete to // broadcast a form saving intent. private boolean savingFormOnKeySessionExpiration = false; enum AnimationType { LEFT, RIGHT, FADE } private boolean hasFormLoadBeenTriggered; @Override @SuppressLint("NewApi") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addBreadcrumbBar(); // must be at the beginning of any activity that can be called from an external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } setupUI(); // Load JavaRosa modules. needed to restore forms. new XFormsModule().registerModule(); // needed to override rms property manager org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager( getApplicationContext())); loadStateFromBundle(savedInstanceState); // Check to see if this is a screen flip or a new form load. Object data = this.getLastCustomNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask) data; mSaveToDiskTask.setFormSavedListener(this); } else if (hasFormLoadBeenTriggered) { // Screen orientation change refreshCurrentView(); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { /* * EventLog accepts only proper Strings as input, but prior to this version, * Android would try to send SpannedStrings to it, thus crashing the app. * This makes sure the title is actually a String. * This fixes bug 174626. */ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 && item.getTitleCondensed() != null) { item.setTitleCondensed(item.getTitleCondensed().toString()); } return super.onMenuItemSelected(featureId, item); } @Override public void formSaveCallback() { // note that we have started saving the form savingFormOnKeySessionExpiration = true; // start saving form, which will call the key session logout completion // function when it finishes. saveDataToDisk(EXIT, false, null, true); } private void registerFormEntryReceiver() { //BroadcastReceiver for: // a) An unresolvable xpath expression encountered in PollSensorAction.onLocationChanged // b) Checking if GPS services are not available mLocationServiceIssueReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { context.removeStickyBroadcast(intent); String action = intent.getAction(); if (GeoUtils.ACTION_CHECK_GPS_ENABLED.equals(action)) { handleNoGpsBroadcast(context); } else if (PollSensorAction.XPATH_ERROR_ACTION.equals(action)) { handleXpathErrorBroadcast(intent); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(PollSensorAction.XPATH_ERROR_ACTION); filter.addAction(GeoUtils.ACTION_CHECK_GPS_ENABLED); registerReceiver(mLocationServiceIssueReceiver, filter); } private void handleNoGpsBroadcast(Context context) { LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Set<String> providers = GeoUtils.evaluateProviders(manager); if (providers.isEmpty()) { DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { if (i == DialogInterface.BUTTON_POSITIVE) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } } }; GeoUtils.showNoGpsDialog(this, onChangeListener); } } private void handleXpathErrorBroadcast(Intent intent) { String problemXpath = intent.getStringExtra(PollSensorAction.KEY_UNRESOLVED_XPATH); CommCareActivity.createErrorDialog(FormEntryActivity.this, "There is a bug in one of your form's XPath Expressions \n" + problemXpath, EXIT); } private void setupUI() { setContentView(R.layout.screen_form_entry); ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!"done".equals(v.getTag())) { FormEntryActivity.this.showNextView(); } else { triggerUserFormComplete(); } } }); prevButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!"quit".equals(v.getTag())) { FormEntryActivity.this.showPreviousView(); } else { FormEntryActivity.this.triggerUserQuitInput(); } } }); mViewPane = (ViewGroup)findViewById(R.id.form_entry_pane); mBeenSwiped = false; mAlertDialog = null; mCurrentView = null; mInAnimation = null; mOutAnimation = null; mGestureDetector = new GestureDetector(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_FORMPATH, mFormPath); outState.putBoolean(NEWFORM, true); outState.putString(KEY_FORM_CONTENT_URI, formProviderContentURI.toString()); outState.putString(KEY_INSTANCE_CONTENT_URI, instanceProviderContentURI.toString()); outState.putString(KEY_INSTANCEDESTINATION, mInstanceDestination); outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled); outState.putBoolean(KEY_HAS_SAVED, hasSaved); outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod); if(symetricKey != null) { try { outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded())); } catch (ClassNotFoundException e) { // we can't really get here anyway, since we couldn't have decoded the string to begin with throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key"); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (resultCode == RESULT_CANCELED) { if (requestCode == HIERARCHY_ACTIVITY_FIRST_START) { // They pressed 'back' on the first hierarchy screen, so we should assume they want // to back out of form entry all together finishReturnInstance(false); } else if (requestCode == INTENT_CALLOUT){ processIntentResponse(intent, true); } // request was canceled, so do nothing return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra(BarcodeScanListenerDefaultImpl.SCAN_RESULT); ((ODKView) mCurrentView).setBinaryData(sb); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case INTENT_CALLOUT: processIntentResponse(intent); break; case IMAGE_CAPTURE: processCaptureResponse(true); break; case SIGNATURE_CAPTURE: processCaptureResponse(false); break; case IMAGE_CHOOSER: processImageChooserResponse(intent); break; case AUDIO_VIDEO_FETCH: processChooserResponse(intent); break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); ((ODKView) mCurrentView).setBinaryData(sl); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case HIERARCHY_ACTIVITY: // We may have jumped to a new index in hierarchy activity, so refresh refreshCurrentView(false); break; } } /** * Processes the return from an image capture intent, launched by either an ImageWidget or * SignatureWidget * * @param isImage true if this was from an ImageWidget, false if it was a SignatureWidget */ private void processCaptureResponse(boolean isImage) { /* We saved the image to the tempfile_path, but we really want it to be in: * /sdcard/odk/instances/[current instance]/something.[jpg/png/etc] so we move it there * before inserting it into the content provider. Once the android image capture bug gets * fixed, (read, we move on from Android 1.6) we want to handle images the audio and * video */ // The intent is empty, but we know we saved the image to the temp file File originalImage = ImageWidget.TEMP_FILE_FOR_IMAGE_CAPTURE; try { File unscaledFinalImage = ImageCaptureProcessing.moveAndScaleImage(originalImage, isImage, getInstanceFolder(), this); saveImageWidgetAnswer(unscaledFinalImage); } catch (IOException e) { e.printStackTrace(); showCustomToast(Localization.get("image.capture.not.saved"), Toast.LENGTH_LONG); } } private String getInstanceFolder() { return mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); } private void processImageChooserResponse(Intent intent) { /* We have a saved image somewhere, but we really want it to be in: * /sdcard/odk/instances/[current instance]/something.[jpg/png/etc] so we move it there * before inserting it into the content provider. Once the android image capture bug gets * fixed, (read, we move on from Android 1.6) we want to handle images the audio and * video */ // get gp of chosen file Uri selectedImage = intent.getData(); File originalImage = new File(FileUtils.getPath(this, selectedImage)); if (originalImage.exists()) { try { File unscaledFinalImage = ImageCaptureProcessing.moveAndScaleImage(originalImage, true, getInstanceFolder(), this); saveImageWidgetAnswer(unscaledFinalImage); } catch (IOException e) { e.printStackTrace(); showCustomToast(Localization.get("image.selection.not.saved"), Toast.LENGTH_LONG); } } else { // The user has managed to select a file from the image browser that doesn't actually // exist on the file system anymore showCustomToast(Localization.get("invalid.image.selection"), Toast.LENGTH_LONG); } } private void saveImageWidgetAnswer(File unscaledFinalImage) { // Add the new image to the Media content provider so that the viewing is fast in Android 2.0+ ContentValues values = new ContentValues(6); values.put(Images.Media.TITLE, unscaledFinalImage.getName()); values.put(Images.Media.DISPLAY_NAME, unscaledFinalImage.getName()); values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.DATA, unscaledFinalImage.getAbsolutePath()); Uri imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); Log.i(TAG, "Inserting image returned uri = " + imageURI.toString()); ((ODKView) mCurrentView).setBinaryData(imageURI); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } private void processChooserResponse(Intent intent) { // For audio/video capture/chooser, we get the URI from the content provider // then the widget copies the file and makes a new entry in the content provider. Uri media = intent.getData(); String binaryPath = UriToFilePath.getPathFromUri(CommCareApplication._(), media); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { // don't let the user select a file that won't be included in the // upload to the server ((ODKView) mCurrentView).clearAnswer(); Toast.makeText(FormEntryActivity.this, Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); } else { ((ODKView) mCurrentView).setBinaryData(media); } saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } // Search the the current view's widgets for one that has registered a pending callout with // the form controller public QuestionWidget getPendingWidget() { FormIndex pendingIndex = mFormController.getPendingCalloutFormIndex(); if (pendingIndex == null) { return null; } for (QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) { if (q.getFormId().equals(pendingIndex)) { return q; } } return null; } private void processIntentResponse(Intent response){ processIntentResponse(response, false); } private void processIntentResponse(Intent response, boolean cancelled) { // keep track of whether we should auto advance boolean advance = false; boolean quick = false; IntentWidget pendingIntentWidget = (IntentWidget)getPendingWidget(); TreeReference context; if (mFormController.getPendingCalloutFormIndex() != null) { context = mFormController.getPendingCalloutFormIndex().getReference(); } else { context = null; } if(pendingIntentWidget != null) { //Set our instance destination for binary data if needed String destination = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); //get the original intent callout IntentCallout ic = pendingIntentWidget.getIntentCallout(); quick = "quick".equals(ic.getAppearance()); //And process it advance = ic.processResponse(response, context, new File(destination)); ic.setCancelled(cancelled); } refreshCurrentView(); // auto advance if we got a good result and are in quick mode if(advance && quick){ showNextView(); } } private void updateFormRelevencies(){ saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); if(!(mCurrentView instanceof ODKView)){ throw new RuntimeException("Tried to update form relevency not on compound view"); } ODKView oldODKV = (ODKView)mCurrentView; FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts(); Set<FormEntryPrompt> used = new HashSet<>(); ArrayList<QuestionWidget> oldWidgets = oldODKV.getWidgets(); ArrayList<Integer> removeList = new ArrayList<>(); for(int i=0;i<oldWidgets.size();i++){ QuestionWidget oldWidget = oldWidgets.get(i); boolean stillRelevent = false; for(FormEntryPrompt prompt : newValidPrompts) { if(prompt.getIndex().equals(oldWidget.getPrompt().getIndex())) { stillRelevent = true; used.add(prompt); } } if(!stillRelevent){ removeList.add(i); } } // remove "atomically" to not mess up iterations oldODKV.removeQuestionsFromIndex(removeList); //Now go through add add any new prompts that we need for(int i = 0 ; i < newValidPrompts.length; ++i) { FormEntryPrompt prompt = newValidPrompts[i]; if(used.contains(prompt)) { continue; } oldODKV.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i); } } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView() { refreshCurrentView(true); } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView(boolean animateLastView) { if(mFormController == null) { throw new RuntimeException("Form state is lost! Cannot refresh current view. This shouldn't happen, please submit a bug report."); } int event = mFormController.getEvent(); // When we refresh, repeat dialog state isn't maintained, so step back to the previous // question. // Also, if we're within a group labeled 'field list', step back to the beginning of that // group. // That is, skip backwards over repeat prompts, groups that are not field-lists, // repeat events, and indexes in field-lists that is not the containing group. while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT || (event == FormEntryController.EVENT_GROUP && !mFormController.indexIsInFieldList()) || event == FormEntryController.EVENT_REPEAT || (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) { event = mFormController.stepToPreviousEvent(); } //If we're at the beginning of form event, but don't show the screen for that, we need //to get the next valid screen if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { this.showNextView(true); } else if(event == FormEntryController.EVENT_END_OF_FORM) { // TODO PLM: don't animate this view change (just like showNextView doesn't animate above) showPreviousView(); } else { View current = createView(); showView(current, AnimationType.FADE, animateLastView); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.removeItem(MENU_LANGUAGES); menu.removeItem(MENU_HIERARCHY_VIEW); menu.removeItem(MENU_SAVE); menu.removeItem(MENU_PREFERENCES); if(mIncompleteEnabled) { menu.add(0, MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)).setIcon( android.R.drawable.ic_menu_save); } menu.add(0, MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)).setIcon( R.drawable.ic_menu_goto); boolean hasMultipleLanguages = (!(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1)); menu.add(0, MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language)) .setIcon(R.drawable.ic_menu_start_conversation) .setEnabled(hasMultipleLanguages); menu.add(0, MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.general_preferences)).setIcon( android.R.drawable.ic_menu_preferences); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_LANGUAGES: createLanguageDialog(); return true; case MENU_SAVE: // don't exit saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null, false); return true; case MENU_HIERARCHY_VIEW: if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY); return true; case MENU_PREFERENCES: Intent pref = new Intent(this, PreferencesActivity.class); startActivity(pref); return true; case android.R.id.home: triggerUserQuitInput(); return true; } return super.onOptionsItemSelected(item); } /** * @return true If the current index of the form controller contains questions */ private boolean currentPromptIsQuestion() { return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController .getEvent() == FormEntryController.EVENT_GROUP); } private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) { return saveAnswersForCurrentScreen(evaluateConstraints, true, false); } /** * Attempt to save the answer(s) in the current screen to into the data model. * * @param failOnRequired Whether or not the constraint evaluation * should return false if the question is only * required. (this is helpful for incomplete * saves) * @param headless running in a process that can't display graphics * @return false if any error occurs while saving (constraint violated, * etc...), true otherwise. */ private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { // only try to save if the current event is a question or a field-list // group boolean success = true; if ((mFormController.getEvent() == FormEntryController.EVENT_QUESTION) || ((mFormController.getEvent() == FormEntryController.EVENT_GROUP) && mFormController.indexIsInFieldList())) { if (mCurrentView instanceof ODKView) { HashMap<FormIndex, IAnswerData> answers = ((ODKView)mCurrentView).getAnswers(); // Sort the answers so if there are multiple errors, we can // bring focus to the first one List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, new Comparator<FormIndex>() { @Override public int compare(FormIndex arg0, FormIndex arg1) { return arg0.compareTo(arg1); } }); for (FormIndex index : indexKeys) { // Within a group, you can only save for question events if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { createConstraintToast(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } else { String viewType; if (mCurrentView == null || mCurrentView.getClass() == null) { viewType = "null"; } else { viewType = mCurrentView.getClass().toString(); } Log.w(TAG, "Unknown view type rendered while current event was question or group! View type: " + viewType); } } return success; } /** * Clears the answer on the screen. */ private void clearAnswer(QuestionWidget qw) { qw.clearAnswer(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer)); menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt)); } @Override public boolean onContextItemSelected(MenuItem item) { // We don't have the right view here, so we store the View's ID as the // item ID and loop through the possible views to find the one the user // clicked on. for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) { if (item.getItemId() == qw.getId()) { createClearDialog(qw); } } return super.onContextItemSelected(item); } /** * If we're loading, then we pass the loading thread to our next instance. */ @Override public Object onRetainCustomNonConfigurationInstance() { // if a form is loading, pass the loader task if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) return mFormLoaderTask; // if a form is writing to disk, pass the save to disk task if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED) return mSaveToDiskTask; // mFormEntryController is static so we don't need to pass it. if (mFormController != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } return null; } private String getHeaderString() { if(mHeaderString != null) { //Localization? return mHeaderString; } else { return StringUtils.getStringRobust(this, R.string.app_name) + " > " + mFormController.getFormTitle(); } } /** * Creates a view given the View type and an event */ private View createView() { setTitle(getHeaderString()); ODKView odkv; // should only be a group here if the event_group is a field-list try { odkv = new ODKView(this, mFormController.getQuestionPrompts(), mFormController.getGroupsForCurrentIndex(), mFormController.getWidgetFactory(), this); Log.i(TAG, "created view for group"); } catch (RuntimeException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); // this is badness to avoid a crash. // really a next view should increment the formcontroller, create the view // if the view is null, then keep the current view and pop an error. return new View(this); } // Makes a "clear answer" menu pop up on long-click of // select-one/select-multiple questions for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly() && !mFormController.isFormReadOnly() && (qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_ONE || qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_MULTI)) { registerForContextMenu(qw); } } FormNavigationUI formNavUi = new FormNavigationUI(this, mCurrentView, mFormController); formNavUi.updateNavigationCues(odkv); return odkv; } @SuppressLint("NewApi") @Override public boolean dispatchTouchEvent(MotionEvent mv) { //We need to ignore this even if it's processed by the action //bar (if one exists) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar bar = getActionBar(); if (bar != null) { View customView = bar.getCustomView(); if (customView != null) { if (customView.dispatchTouchEvent(mv)) { return true; } } } } boolean handled = mGestureDetector.onTouchEvent(mv); return handled || super.dispatchTouchEvent(mv); } /** * Determines what should be displayed on the screen. Possible options are: a question, an ask * repeat dialog, or the submit screen. Also saves answers to the data model after checking * constraints. */ private void showNextView() { showNextView(false); } private void showNextView(boolean resuming) { if (currentPromptIsQuestion()) { if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) { // A constraint was violated so a dialog should be showing. return; } } if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) { int event; try{ group_skip: do { event = mFormController.stepToNextEvent(FormController.STEP_OVER_GROUP); switch (event) { case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_END_OF_FORM: View next = createView(); if(!resuming) { showView(next, AnimationType.RIGHT); } else { showView(next, AnimationType.FADE, false); } break group_skip; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); break group_skip; case FormEntryController.EVENT_GROUP: //We only hit this event if we're at the _opening_ of a field //list, so it seems totally fine to do it this way, technically //though this should test whether the index is the field list //host. if (mFormController.indexIsInFieldList() && mFormController.getQuestionPrompts().length != 0) { View nextGroupView = createView(); if(!resuming) { showView(nextGroupView, AnimationType.RIGHT); } else { showView(nextGroupView, AnimationType.FADE, false); } break group_skip; } // otherwise it's not a field-list group, so just skip it break; case FormEntryController.EVENT_REPEAT: Log.i(TAG, "repeat: " + mFormController.getFormIndex().getReference()); // skip repeats break; case FormEntryController.EVENT_REPEAT_JUNCTURE: Log.i(TAG, "repeat juncture: " + mFormController.getFormIndex().getReference()); // skip repeat junctures until we implement them break; default: Log.w(TAG, "JavaRosa added a new EVENT type and didn't tell us... shame on them."); break; } } while (event != FormEntryController.EVENT_END_OF_FORM); }catch(XPathTypeMismatchException e){ Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); } } else { mBeenSwiped = false; } } /** * Determines what should be displayed between a question, or the start screen and displays the * appropriate view. Also saves answers to the data model without checking constraints. */ private void showPreviousView() { // The answer is saved on a back swipe, but question constraints are ignored. if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } FormIndex startIndex = mFormController.getFormIndex(); FormIndex lastValidIndex = startIndex; if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) { int event = mFormController.stepToPreviousEvent(); //Step backwards until we either find a question, the beginning of the form, //or a field list with valid questions inside while (event != FormEntryController.EVENT_BEGINNING_OF_FORM && event != FormEntryController.EVENT_QUESTION && !(event == FormEntryController.EVENT_GROUP && mFormController.indexIsInFieldList() && mFormController .getQuestionPrompts().length != 0)) { event = mFormController.stepToPreviousEvent(); lastValidIndex = mFormController.getFormIndex(); } //check if we're at the beginning and not doing the whole "First screen" thing if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { //If so, we can't go all the way back here, so we've gotta hit the last index that was valid mFormController.jumpToIndex(lastValidIndex); //Did we jump at all? (not sure how we could have, but there might be a mismatch) if(lastValidIndex.equals(startIndex)) { //If not, don't even bother changing the view. //NOTE: This needs to be the same as the //exit condition below, in case either changes mBeenSwiped = false; FormEntryActivity.this.triggerUserQuitInput(); return; } //We might have walked all the way back still, which isn't great, //so keep moving forward again until we find it if(lastValidIndex.isBeginningOfFormIndex()) { //there must be a repeat between where we started and the beginning of hte form, walk back up to it this.showNextView(true); return; } } View next = createView(); showView(next, AnimationType.LEFT); } else { //NOTE: this needs to match the exist condition above //when there is no start screen mBeenSwiped = false; FormEntryActivity.this.triggerUserQuitInput(); } } /** * Displays the View specified by the parameter 'next', animating both the current view and next * appropriately given the AnimationType. Also updates the progress bar. */ private void showView(View next, AnimationType from) { showView(next, from, true); } private void showView(View next, AnimationType from, boolean animateLastView) { switch (from) { case RIGHT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out); break; case LEFT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out); break; case FADE: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out); break; } if (mCurrentView != null) { if(animateLastView) { mCurrentView.startAnimation(mOutAnimation); } mViewPane.removeView(mCurrentView); } mInAnimation.setAnimationListener(this); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); mCurrentView = next; mViewPane.addView(mCurrentView, lp); mCurrentView.startAnimation(mInAnimation); FrameLayout header = (FrameLayout)findViewById(R.id.form_entry_header); TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label)); header.setVisibility(View.GONE); groupLabel.setVisibility(View.GONE); if (mCurrentView instanceof ODKView) { ((ODKView) mCurrentView).setFocus(this); SpannableStringBuilder groupLabelText = ((ODKView) mCurrentView).getGroupLabel(); if(groupLabelText != null && !groupLabelText.toString().trim().equals("")) { groupLabel.setText(groupLabelText); header.setVisibility(View.VISIBLE); groupLabel.setVisibility(View.VISIBLE); } } else { InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0); } } /** * Creates and displays a dialog displaying the violated constraint. */ private void createConstraintToast(FormIndex index, String constraintText, int saveStatus, boolean requestFocus) { switch (saveStatus) { case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: if (constraintText == null) { constraintText = StringUtils.getStringRobust(this, R.string.invalid_answer_error); } break; case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: constraintText = StringUtils.getStringRobust(this, R.string.required_answer_error); break; } boolean displayed = false; //We need to see if question in violation is on the screen, so we can show this cleanly. for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) { if(index.equals(q.getFormId())) { q.notifyInvalid(constraintText, requestFocus); displayed = true; break; } } if(!displayed) { showCustomToast(constraintText, Toast.LENGTH_SHORT); } mBeenSwiped = false; } private void showCustomToast(String message, int duration) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_view, null); // set the text in the view TextView tv = (TextView) view.findViewById(R.id.message); tv.setText(message); Toast t = new Toast(this); t.setView(view); t.setDuration(duration); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } /** * Creates and displays a dialog asking the user if they'd like to create a repeat of the * current group. */ private void createRepeatDialog() { ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme); View view = LayoutInflater.from(wrapper).inflate(R.layout.component_repeat_new_dialog, null); AlertDialog repeatDialog = new AlertDialog.Builder(wrapper).create(); final AlertDialog theDialog = repeatDialog; repeatDialog.setView(view); repeatDialog.setIcon(android.R.drawable.ic_dialog_info); FormNavigationController.NavigationDetails details; try { details = FormNavigationController.calculateNavigationStatus(mFormController, mCurrentView); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } final boolean backExitsForm = !details.relevantBeforeCurrentScreen; final boolean nextExitsForm = details.relevantAfterCurrentScreen == 0; Button back = (Button)view.findViewById(R.id.component_repeat_back); back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(backExitsForm) { FormEntryActivity.this.triggerUserQuitInput(); } else { theDialog.dismiss(); FormEntryActivity.this.refreshCurrentView(false); } } }); Button newButton = (Button)view.findViewById(R.id.component_repeat_new); newButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { theDialog.dismiss(); try { mFormController.newRepeat(); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(FormEntryActivity.this, e.getMessage(), EXIT); return; } showNextView(); } }); Button skip = (Button)view.findViewById(R.id.component_repeat_skip); skip.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { theDialog.dismiss(); if(!nextExitsForm) { showNextView(); } else { triggerUserFormComplete(); } } }); back.setText(StringUtils.getStringSpannableRobust(this, R.string.repeat_go_back)); //Load up our icons Drawable exitIcon = getResources().getDrawable(R.drawable.icon_exit); exitIcon.setBounds(0, 0, exitIcon.getIntrinsicWidth(), exitIcon.getIntrinsicHeight()); Drawable doneIcon = getResources().getDrawable(R.drawable.icon_done); doneIcon.setBounds(0, 0, doneIcon.getIntrinsicWidth(), doneIcon.getIntrinsicHeight()); if (mFormController.getLastRepeatCount() > 0) { repeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.leaving_repeat_ask)); repeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_another_repeat, mFormController.getLastGroupText())); newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.add_another)); if(!nextExitsForm) { skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes)); } else { skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes_exits)); } } else { repeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.entering_repeat_ask)); repeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_repeat, mFormController.getLastGroupText())); newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.entering_repeat)); if(!nextExitsForm) { skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no)); } else { skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no_exits)); } } repeatDialog.setCancelable(false); repeatDialog.show(); if(nextExitsForm) { skip.setCompoundDrawables(null, doneIcon, null, null); } if(backExitsForm) { back.setCompoundDrawables(null, exitIcon, null, null); } mBeenSwiped = false; } /** * Saves form data to disk. * * @param exit If set, will exit program after save. * @param complete Has the user marked the instances as complete? * @param updatedSaveName Set name of the instance's content provider, if * non-null * @param headless Disables GUI warnings and lets answers that * violate constraints be saved. */ private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) { if (!formHasLoaded()) { return; } // save current answer; if headless, don't evaluate the constraints // before doing so. if (headless && (!saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS, complete, headless))) { return; } else if (!headless && !saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS, complete, headless)) { Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_SHORT).show(); return; } // If a save task is already running, just let it do its thing if ((mSaveToDiskTask != null) && (mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) { return; } mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName, this, instanceProviderContentURI, symetricKey, headless); if (!headless){ mSaveToDiskTask.connect(this); } mSaveToDiskTask.setFormSavedListener(this); mSaveToDiskTask.execute(); } /** * Create a dialog with options to save and exit, save, or quit without saving */ private void createQuitDialog() { final String[] items = mIncompleteEnabled ? new String[] {StringUtils.getStringRobust(this, R.string.keep_changes), StringUtils.getStringRobust(this, R.string.do_not_save)} : new String[] {StringUtils.getStringRobust(this, R.string.do_not_save)}; mAlertDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle(StringUtils.getStringRobust(this, R.string.quit_application, mFormController.getFormTitle())) .setNeutralButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_exit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // save and exit if(items.length == 1) { discardChangesAndExit(); } else { saveDataToDisk(EXIT, isInstanceComplete(false), null, false); } break; case 1: // discard changes and exit discardChangesAndExit(); break; case 2:// do nothing break; } } }).create(); mAlertDialog.getListView().setSelector(R.drawable.selector); mAlertDialog.show(); } private void discardChangesAndExit() { String selection = InstanceColumns.INSTANCE_FILE_PATH + " like '" + mInstancePath + "'"; Cursor c = null; int instanceCount = 0; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, null, null); instanceCount = c.getCount(); } finally { if (c != null) { c.close(); } } // if it's not already saved, erase everything if (instanceCount < 1) { int images = 0; int audio = 0; int video = 0; // delete media first String instanceFolder = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); Log.i(TAG, "attempting to delete: " + instanceFolder); String where = Images.Media.DATA + " like '" + instanceFolder + "%'"; String[] projection = { Images.ImageColumns._ID }; // images Cursor imageCursor = null; try { imageCursor = getContentResolver().query( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, where, null, null); if (imageCursor.getCount() > 0) { imageCursor.moveToFirst(); String id = imageCursor.getString(imageCursor .getColumnIndex(Images.ImageColumns._ID)); Log.i( TAG, "attempting to delete: " + Uri.withAppendedPath( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)); images = getContentResolver() .delete( Uri.withAppendedPath( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id), null, null); } } finally { if ( imageCursor != null ) { imageCursor.close(); } } // audio Cursor audioCursor = null; try { audioCursor = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, where, null, null); if (audioCursor.getCount() > 0) { audioCursor.moveToFirst(); String id = audioCursor.getString(imageCursor .getColumnIndex(Images.ImageColumns._ID)); Log.i( TAG, "attempting to delete: " + Uri.withAppendedPath( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id)); audio = getContentResolver() .delete( Uri.withAppendedPath( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id), null, null); } } finally { if ( audioCursor != null ) { audioCursor.close(); } } // video Cursor videoCursor = null; try { videoCursor = getContentResolver().query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, where, null, null); if (videoCursor.getCount() > 0) { videoCursor.moveToFirst(); String id = videoCursor.getString(imageCursor .getColumnIndex(Images.ImageColumns._ID)); Log.i( TAG, "attempting to delete: " + Uri.withAppendedPath( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)); video = getContentResolver() .delete( Uri.withAppendedPath( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id), null, null); } } finally { if ( videoCursor != null ) { videoCursor.close(); } } Log.i(TAG, "removed from content providers: " + images + " image files, " + audio + " audio files," + " and " + video + " video files."); File f = new File(instanceFolder); if (f.exists() && f.isDirectory()) { for (File del : f.listFiles()) { Log.i(TAG, "deleting file: " + del.getAbsolutePath()); del.delete(); } f.delete(); } } finishReturnInstance(false); } /** * Confirm clear answer dialog */ private void createClearDialog(final QuestionWidget qw) { mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(StringUtils.getStringRobust(this, R.string.clear_answer_ask)); String question = qw.getPrompt().getLongText(); if (question.length() > 50) { question = question.substring(0, 50) + "..."; } mAlertDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.clearanswer_confirm, question)); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: clearAnswer(qw); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE, StringUtils.getStringSpannableRobust(this, R.string.discard_answer), quitListener); mAlertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, StringUtils.getStringSpannableRobust(this, R.string.clear_answer_no), quitListener); mAlertDialog.show(); } /** * Creates and displays a dialog allowing the user to set the language for the form. */ private void createLanguageDialog() { final String[] languages = mFormController.getLanguages(); int selected = -1; if (languages != null) { String language = mFormController.getLanguage(); for (int i = 0; i < languages.length; i++) { if (language.equals(languages[i])) { selected = i; } } } mAlertDialog = new AlertDialog.Builder(this) .setSingleChoiceItems(languages, selected, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { // Update the language in the content provider when selecting a new // language ContentValues values = new ContentValues(); values.put(FormsColumns.LANGUAGE, languages[whichButton]); String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; int updated = getContentResolver().update(formProviderContentURI, values, selection, selectArgs); Log.i(TAG, "Updated language to: " + languages[whichButton] + " in " + updated + " rows"); mFormController.setLanguage(languages[whichButton]); dialog.dismiss(); if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } refreshCurrentView(); } }) .setTitle(StringUtils.getStringRobust(this, R.string.change_language)) .setNegativeButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_change), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { } }).create(); mAlertDialog.show(); } @Override public CustomProgressDialog generateProgressDialog(int id) { CustomProgressDialog dialog = null; switch (id) { case FormLoaderTask.FORM_LOADER_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.loading_form), StringUtils.getStringRobust(this, R.string.please_wait), id); dialog.addCancelButton(); dialog.addIndeterminantProgressBar(); break; case SaveToDiskTask.SAVING_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.saving_form), StringUtils.getStringRobust(this, R.string.please_wait), id); dialog.addIndeterminantProgressBar(); break; } return dialog; } @Override protected void onPause() { super.onPause(); if (mCurrentView != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } if (mLocationServiceIssueReceiver != null) { unregisterReceiver(mLocationServiceIssueReceiver); } } @Override protected void onResume() { super.onResume(); if (!hasFormLoadBeenTriggered) { loadForm(); } registerFormEntryReceiver(); //csims@dimagi.com - 22/08/2012 - For release only, fix immediately. //There is a _horribly obnoxious_ bug in TimePickers that messes up how they work //on screen rotation. We need to re-do any setAnswers that we perform on them after //onResume. try { if(mCurrentView instanceof ODKView) { ODKView ov = ((ODKView) mCurrentView); if(ov.getWidgets() != null) { for(QuestionWidget qw : ov.getWidgets()) { if(qw instanceof DateTimeWidget) { ((DateTimeWidget)qw).setAnswer(); } else if(qw instanceof TimeWidget) { ((TimeWidget)qw).setAnswer(); } } } } } catch(Exception e) { //if this fails, we _really_ don't want to mess anything up. this is a last minute //fix } if (mFormController != null) { mFormController.setPendingCalloutFormIndex(null); } } private void loadForm() { mFormController = null; mInstancePath = null; Intent intent = getIntent(); if (intent != null) { loadIntentFormData(intent); setTitleToLoading(); Uri uri = intent.getData(); final String contentType = getContentResolver().getType(uri); Uri formUri; boolean isInstanceReadOnly = false; try { switch (contentType) { case InstanceColumns.CONTENT_ITEM_TYPE: Pair<Uri, Boolean> instanceAndStatus = getInstanceUri(uri); formUri = instanceAndStatus.first; isInstanceReadOnly = instanceAndStatus.second; break; case FormsColumns.CONTENT_ITEM_TYPE: formUri = uri; mFormPath = getFormPath(uri); break; default: Log.e(TAG, "unrecognized URI"); CommCareHomeActivity.createErrorDialog(this, "unrecognized URI: " + uri, EXIT); return; } } catch (FormQueryException e) { CommCareHomeActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } if(formUri == null) { Log.e(TAG, "unrecognized URI"); CommCareActivity.createErrorDialog(this, "couldn't locate FormDB entry for the item at: " + uri, EXIT); return; } mFormLoaderTask = new FormLoaderTask<FormEntryActivity>(symetricKey, isInstanceReadOnly, this) { @Override protected void deliverResult(FormEntryActivity receiver, FECWrapper wrapperResult) { receiver.handleFormLoadCompletion(wrapperResult.getController()); } @Override protected void deliverUpdate(FormEntryActivity receiver, String... update) { } @Override protected void deliverCancellation(FormEntryActivity receiver, FECWrapper wrapperResult) { receiver.finish(); } @Override protected void deliverError(FormEntryActivity receiver, Exception e) { if (e != null) { CommCareActivity.createErrorDialog(receiver, e.getMessage(), EXIT); } else { CommCareActivity.createErrorDialog(receiver, StringUtils.getStringRobust(receiver, R.string.parse_error), EXIT); } } }; mFormLoaderTask.connect(this); mFormLoaderTask.execute(formUri); hasFormLoadBeenTriggered = true; } } public void handleFormLoadCompletion(FormController fc) { mFormController = fc; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ // Newer menus may have already built the menu, before all data was ready invalidateOptionsMenu(); } Localizer mLocalizer = Localization.getGlobalLocalizerAdvanced(); if(mLocalizer != null){ String mLocale = mLocalizer.getLocale(); if (mLocale != null && fc.getLanguages() != null && Arrays.asList(fc.getLanguages()).contains(mLocale)){ fc.setLanguage(mLocale); } else{ Logger.log("formloader", "The current locale is not set"); } } else{ Logger.log("formloader", "Could not get the localizer"); } registerSessionFormSaveCallback(); // Set saved answer path if (mInstancePath == null) { // Create new answer folder. String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss") .format(Calendar.getInstance().getTime()); String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')); String path = mInstanceDestination + file + "_" + time; if (FileUtils.createFolder(path)) { mInstancePath = path + "/" + file + "_" + time + ".xml"; } } else { // we've just loaded a saved form, so start in the hierarchy view Intent i = new Intent(FormEntryActivity.this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY_FIRST_START); return; // so we don't show the intro screen before jumping to the hierarchy } refreshCurrentView(); FormNavigationUI formNavUi = new FormNavigationUI(FormEntryActivity.this, mCurrentView, mFormController); formNavUi.updateNavigationCues(mCurrentView); } /** * Call when the user provides input that they want to quit the form */ private void triggerUserQuitInput() { //If we're just reviewing a read only form, don't worry about saving //or what not, just quit if(mFormController.isFormReadOnly()) { //It's possible we just want to "finish" here, but //I don't really wanna break any c compatibility finishReturnInstance(false); } else { createQuitDialog(); } } /** * Get the default title for ODK's "Form title" field */ private String getDefaultFormTitle() { String saveName = mFormController.getFormTitle(); if (getContentResolver().getType(getIntent().getData()).equals(InstanceColumns.CONTENT_ITEM_TYPE)) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance.getCount() == 1) { instance.moveToFirst(); saveName = instance.getString(instance .getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } return saveName; } /** * Call when the user is ready to save and return the current form as complete */ private void triggerUserFormComplete() { if (mFormController.isFormReadOnly()) { finishReturnInstance(false); } else { saveDataToDisk(EXIT, true, getDefaultFormTitle(), false); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: triggerUserQuitInput(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; showNextView(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; showPreviousView(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { if (mFormLoaderTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. // but only if it's done, otherwise the thread never returns if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { mFormLoaderTask.cancel(true); mFormLoaderTask.destroy(); } } if (mSaveToDiskTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(false); } } super.onDestroy(); } @Override public void onAnimationEnd(Animation arg0) { mBeenSwiped = false; } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } private void registerSessionFormSaveCallback() { if (mFormController != null && !mFormController.isFormReadOnly()) { try { // CommCareSessionService will call this.formSaveCallback when // the key session is closing down and we need to save any // intermediate results before they become un-saveable. CommCareApplication._().getSession().registerFormSaveCallback(this); } catch (SessionUnavailableException e) { Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Couldn't register form save callback because session doesn't exist"); } } } /** * {@inheritDoc} * * Display save status notification and exit or continue on in the form. * If form entry is being saved because key session is expiring then * continue closing the session/logging out. * * @see org.odk.collect.android.listeners.FormSavedListener#savingComplete(int, boolean) */ @Override public void savingComplete(int saveStatus, boolean headless) { // Did we just save a form because the key session // (CommCareSessionService) is ending? if (savingFormOnKeySessionExpiration) { savingFormOnKeySessionExpiration = false; // Notify the key session that the form state has been saved (or at // least attempted to be saved) so CommCareSessionService can // continue closing down key pool and user database. CommCareApplication._().expireUserSession(); } else { switch (saveStatus) { case SaveToDiskTask.SAVED: Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); hasSaved = true; break; case SaveToDiskTask.SAVED_AND_EXIT: Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); hasSaved = true; finishReturnInstance(); break; case SaveToDiskTask.SAVE_ERROR: Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_LONG).show(); break; case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: // an answer constraint was violated, so do a 'swipe' to the next // question to display the proper toast(s) next(); break; } refreshCurrentView(); } } /** * Attempts to save an answer to the specified index. * * @param evaluateConstraints Should form contraints be checked when saving answer? * @return status as determined in FormEntryController */ private int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) { try { if (evaluateConstraints) { return mFormController.answerQuestion(index, answer); } else { mFormController.saveAnswer(index, answer); return FormEntryController.ANSWER_OK; } } catch(XPathException e) { //this is where runtime exceptions get triggered after the form has loaded CommCareActivity.createErrorDialog(this, "There is a bug in one of your form's XPath Expressions \n" + e.getMessage(), EXIT); //We're exiting anyway return FormEntryController.ANSWER_OK; } } /** * Checks the database to determine if the current instance being edited has already been * 'marked completed'. A form can be 'unmarked' complete and then resaved. * * @return true if form has been marked completed, false otherwise. */ private boolean isInstanceComplete(boolean end) { // default to false if we're mid form boolean complete = false; // if we're at the end of the form, then check the preferences if (end) { // First get the value from the preferences SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); complete = sharedPreferences.getBoolean(PreferencesActivity.KEY_COMPLETED_DEFAULT, true); } // Then see if we've already marked this form as complete before String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS)); if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) { complete = true; } } } finally { if (c != null) { c.close(); } } return complete; } private void next() { if (!mBeenSwiped) { mBeenSwiped = true; showNextView(); } } private void finishReturnInstance() { finishReturnInstance(true); } /** * Returns the instance that was just filled out to the calling activity, * if requested. * * @param reportSaved was a form saved? Delegates the result code of the * activity */ private void finishReturnInstance(boolean reportSaved) { String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) { // caller is waiting on a picked form String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c.getCount() > 0) { // should only be one... c.moveToFirst(); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri instance = Uri.withAppendedPath(instanceProviderContentURI, id); Intent formReturnIntent = new Intent(); formReturnIntent.putExtra(IS_ARCHIVED_FORM, mFormController.isFormReadOnly()); if (reportSaved || hasSaved) { setResult(RESULT_OK, formReturnIntent.setData(instance)); } else { setResult(RESULT_CANCELED, formReturnIntent.setData(instance)); } } } finally { if (c != null) { c.close(); } } } try { CommCareApplication._().getSession().unregisterFormSaveCallback(); } catch (SessionUnavailableException sue) { // looks like the session expired } dismissProgressDialog(); finish(); } @Override public boolean onDown(MotionEvent e) { return false; } /** * Looks for user swipes. If the user has swiped, move to the appropriate screen. */ @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (CommCareActivity.isHorizontalSwipe(this, e1, e2)) { mBeenSwiped = true; if (velocityX > 0) { showPreviousView(); } else { int event = mFormController.getEvent(mFormController.getNextFormIndex(mFormController.getFormIndex(), true)); if(event != FormEntryController.EVENT_END_OF_FORM) { showNextView(); } } return true; } return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // The onFling() captures the 'up' event so our view thinks it gets long pressed. // We don't wnat that, so cancel it. mCurrentView.cancelLongPress(); return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void advance() { next(); } @Override public void widgetEntryChanged() { updateFormRelevencies(); FormNavigationUI formNavUi = new FormNavigationUI(this, mCurrentView, mFormController); formNavUi.updateNavigationCues(mCurrentView); } /** * Has form loading (via FormLoaderTask) completed? */ private boolean formHasLoaded() { return mFormController != null; } private void addBreadcrumbBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { final String fragmentClass = this.getIntent().getStringExtra("odk_title_fragment"); if (fragmentClass != null) { final FragmentManager fm = this.getSupportFragmentManager(); Fragment bar = fm.findFragmentByTag(TITLE_FRAGMENT_TAG); if (bar == null) { try { bar = ((Class<Fragment>)Class.forName(fragmentClass)).newInstance(); ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } fm.beginTransaction().add(bar, TITLE_FRAGMENT_TAG).commit(); } catch(Exception e) { Log.w(TAG, "couldn't instantiate fragment: " + fragmentClass); } } } } } private void loadStateFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { mFormPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(NEWFORM)) { hasFormLoadBeenTriggered = savedInstanceState.getBoolean(NEWFORM, false); } if (savedInstanceState.containsKey(KEY_FORM_CONTENT_URI)) { formProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_FORM_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCE_CONTENT_URI)) { instanceProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_INSTANCE_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCEDESTINATION)) { mInstanceDestination = savedInstanceState.getString(KEY_INSTANCEDESTINATION); } if(savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) { mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED); } if(savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED); } if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) { String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(savedInstanceState.containsKey(KEY_HEADER_STRING)) { mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING); } if(savedInstanceState.containsKey(KEY_HAS_SAVED)) { hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED); } } } private String getFormPath(Uri uri) throws FormQueryException { Cursor c = null; try { c = getContentResolver().query(uri, null, null, null, null); if (c.getCount() != 1) { throw new FormQueryException("Bad URI: " + uri); } else { c.moveToFirst(); return c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH)); } } finally { if (c != null) { c.close(); } } } private Pair<Uri, Boolean> getInstanceUri(Uri uri) throws FormQueryException { Cursor instanceCursor = null; Cursor formCursor = null; Boolean isInstanceReadOnly = false; Uri formUri = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor.getCount() != 1) { throw new FormQueryException("Bad URI: " + uri); } else { instanceCursor.moveToFirst(); mInstancePath = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String jrFormId = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.JR_FORM_ID)); //If this form is both already completed if (InstanceProviderAPI.STATUS_COMPLETE.equals(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS)))) { if (!Boolean.parseBoolean(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)))) { isInstanceReadOnly = true; } } final String[] selectionArgs = { jrFormId }; final String selection = FormsColumns.JR_FORM_ID + " like ?"; formCursor = getContentResolver().query(formProviderContentURI, null, selection, selectionArgs, null); if (formCursor.getCount() == 1) { formCursor.moveToFirst(); mFormPath = formCursor.getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); formUri = ContentUris.withAppendedId(formProviderContentURI, formCursor.getLong(formCursor.getColumnIndex(FormsColumns._ID))); } else if (formCursor.getCount() < 1) { throw new FormQueryException("Parent form does not exist"); } else if (formCursor.getCount() > 1) { throw new FormQueryException("More than one possible parent form"); } } } finally { if (instanceCursor != null) { instanceCursor.close(); } if (formCursor != null) { formCursor.close(); } } return new Pair<>(formUri, isInstanceReadOnly); } private void loadIntentFormData(Intent intent) { if(intent.hasExtra(KEY_FORM_CONTENT_URI)) { this.formProviderContentURI = Uri.parse(intent.getStringExtra(KEY_FORM_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCE_CONTENT_URI)) { this.instanceProviderContentURI = Uri.parse(intent.getStringExtra(KEY_INSTANCE_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCEDESTINATION)) { this.mInstanceDestination = intent.getStringExtra(KEY_INSTANCEDESTINATION); } else { mInstanceDestination = Collect.INSTANCES_PATH; } if(intent.hasExtra(KEY_AES_STORAGE_KEY)) { String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(intent.hasExtra(KEY_HEADER_STRING)) { FormEntryActivity.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING); } if(intent.hasExtra(KEY_INCOMPLETE_ENABLED)) { this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true); } if(intent.hasExtra(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED); } } private void setTitleToLoading() { if(mHeaderString != null) { setTitle(mHeaderString); } else { setTitle(StringUtils.getStringRobust(this, R.string.app_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form)); } } private class FormQueryException extends Exception { FormQueryException(String msg) { super(msg); } } }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; /** * Simple utility that shows you a sorted list of properties * that are missing in a i18n file * (as diff from the default en properties). * * @author Christoph Sauer * */ public class MissingTranslations { // Change this to your settings... static String base = "C:/workspace/JSPWiki HEAD"; static String suffix = "de_DE"; public static void main(String[] args) throws IOException { diff ("/etc/i18n/CoreResources.properties", "/etc/i18n/CoreResources_" + suffix + ".properties"); diff ("/etc/i18n/templates/default.properties", "/etc/i18n/templates/default_" + suffix + ".properties"); diff ("/src/com/ecyrd/jspwiki/plugin/PluginResources.properties", "/src/com/ecyrd/jspwiki/plugin/PluginResources_" + suffix + ".properties"); } public static void diff(String en, String other) throws FileNotFoundException, IOException { //Standard Properties Properties p = new Properties(); p.load( new FileInputStream(new File(base + en)) ); Properties p2 = new Properties(); p2.load( new FileInputStream(new File(base + other)) ); System.out.println("Missing Properties in " + other + ":"); System.out.println(" Iterator iter = sortedNames(p).iterator(); while(iter.hasNext()) { String name = (String)iter.next(); String value = p.getProperty(name); if (p2.get(name) == null) { System.out.println(name + " = " + value); } } System.out.println(""); } private static List sortedNames(Properties p) { List list = new ArrayList(); Enumeration iter = p.propertyNames(); while(iter.hasMoreElements()) { list.add(iter.nextElement()); } Collections.sort(list); return list; } }
package ru.job4j; //import java.util.Arrays; //import java.lang.* public class CheckSubString { public char[] stringToArrayOfChar(String inputString) { char[] arOfChar = new char[inputString.length()]; for (int i = 0; i < inputString.length(); i++) { arOfChar[i] = inputString.charAt(i); } return arOfChar; } public boolean contains(String origin, String sub) { char[] arOrigin = stringToArrayOfChar(origin); char[] arSub = stringToArrayOfChar(sub); boolean isArrayContains = true; boolean returnIsArrayContains = false; for (int i = 0; i < (arOrigin.length - arSub.length); i++) { if (arOrigin[i] == arSub[0]) { isArrayContains = true; for (int j = 0; j < (arSub.length - 1); j++) { isArrayContains &= (arSub[j] == arOrigin[i + j]); } returnIsArrayContains |= isArrayContains; } } return returnIsArrayContains; } }
package soot.jimple.infoflow; import java.util.List; import soot.Transform; import soot.jimple.infoflow.AbstractInfoflowProblem.PathTrackingMethod; import soot.jimple.infoflow.entryPointCreators.IEntryPointCreator; import soot.jimple.infoflow.source.ISourceSinkManager; import soot.jimple.infoflow.taintWrappers.ITaintPropagationWrapper; /** * interface for the main infoflow class * */ public interface IInfoflow { /** * Sets the taint wrapper for deciding on taint propagation through black-box * methods * @param wrapper The taint wrapper object that decides on how information is * propagated through black-box methods */ public void setTaintWrapper(ITaintPropagationWrapper wrapper); /** * Sets whether and how the paths between the sources and sinks shall be * tracked * @param method The method for tracking data flow paths through the * program. */ public void setPathTracking(PathTrackingMethod method); /** * Sets whether the information flow analysis shall stop after the first * flow has been found * @param stopAfterFirstFlow True if the analysis shall stop after the * first flow has been found, otherwise false. */ public void setStopAfterFirstFlow(boolean stopAfterFirstFlow); /** * Sets the interprocedural CFG to be used by the InfoFlowProblem * @param factory the interprocedural control flow factory */ public void setIcfgFactory(BiDirICFGFactory factory); /** * List of preprocessors that need to be executed in order before * the information flow. * @param preprocessors the pre-processors */ public void setPreProcessors(List<Transform> preprocessors); /** * Computes the information flow on a list of entry point methods. This list * is used to construct an artificial main method following the Android * life cycle for all methods that are detected to be part of Android's * application infrastructure (e.g. android.app.Activity.onCreate) * @param path the path to the main folder of the (unpacked) class files * @param entryPointCreator the entry point creator to use for generating the dummy * main method * @param entryPoints the entryPoints (string conforms to SootMethod representation) * @param sources list of source class+method (as string conforms to SootMethod representation) * @param sinks list of sink class+method (as string conforms to SootMethod representation) */ public void computeInfoflow(String path, IEntryPointCreator entryPointCreator, List<String> entryPoints, List<String> sources, List<String> sinks); /** * Computes the information flow on a list of entry point methods. This list * is used to construct an artificial main method following the Android * life cycle for all methods that are detected to be part of Android's * application infrastructure (e.g. android.app.Activity.onCreate) * @param path the path to the main folder of the (unpacked) class files * @param entryPoints the entryPoints (string conforms to SootMethod representation) * @param sources list of source class+method (as string conforms to SootMethod representation) * @param sinks list of sink class+method (as string conforms to SootMethod representation) */ public void computeInfoflow(String path, List<String> entryPoints, List<String> sources, List<String> sinks); /** * Computes the information flow on a single method. This method is * directly taken as the entry point into the program, even if it is an * instance method. * @param path the path to the main folder of the (unpacked) class files * @param entryPoint the main method to analyze * @param sources list of source class+method (as string conforms to SootMethod representation) * @param sinks list of sink class+method (as string conforms to SootMethod representation) */ public void computeInfoflow(String path, String entryPoint, List<String> sources, List<String> sinks); /** * Computes the information flow on a list of entry point methods. This list * is used to construct an artificial main method following the Android * life cycle for all methods that are detected to be part of Android's * application infrastructure (e.g. android.app.Activity.onCreate) * @param path the path to the main folder of the (unpacked) class files * @param entryPointCreator the entry point creator to use for generating the dummy * main method * @param entryPoints the entryPoints (string conforms to SootMethod representation) * @param sourcesSinks manager class for identifying sources and sinks in the source code */ public void computeInfoflow(String path, IEntryPointCreator entryPointCreator, List<String> entryPoints, ISourceSinkManager sourcesSinks); /** * Computes the information flow on a single method. This method is * directly taken as the entry point into the program, even if it is an * instance method. * @param path the path to the main folder of the (unpacked) class files * @param entryPoint the main method to analyze * @param sourcesSinks manager class for identifying sources and sinks in the source code */ public void computeInfoflow(String path, String entryPoint, ISourceSinkManager sourcesSinks); /** * getResults returns the results found by the analysis * @return the results */ public InfoflowResults getResults(); /** * A result is available if the analysis has finished - so if this method returns false the * analysis has not finished yet or was not started (e.g. no sources or sinks found) * @return boolean that states if a result is available */ public boolean isResultAvailable(); /** * default: inspectSinks is set to true, this means sinks are analyzed as well. * If inspectSinks is set to false, then the analysis does not propagate values into * the sink method. * @param inspect boolean that determines the inspectSink option */ public void setInspectSinks(boolean inspect); /** * sets the depth of the access path that are tracked * @param accessPathLength the maximum value of an access path. If it gets longer than * this value, it is truncated and all following fields are assumed as tainted * (which is imprecise but gains performance) * Default value is 5. */ public void setAccessPathLength(int accessPathLength); }
package spacesettlers.game; import java.util.Random; /** * 3D tic tac toe or naughts and crosses * * @author amy * */ public class TicTacToe3D extends AbstractGame { private static int player1 = 1; private static int player2 = 2; private static int empty = 0; private static int num_rows = 3; private static int num_cols = 3; private static int num_depth = 3; private int[][][] board; private boolean currentPlayer; private Random random; /** * Initialize an empty board and choose a random first player */ public TicTacToe3D() { board = new int[num_rows][num_cols][num_depth]; random = new Random(); currentPlayer = random.nextBoolean(); } @Override public boolean isGameOver() { // check in the 2D boards at each depth for (int dep = 0; dep < num_depth; dep++) { // check across the rows for (int row = 0; row < num_rows; row++) { int num_in_row = 1; int player = board[row][0][dep]; for (int col = 1; col < num_cols; col++) { if (board[row][col][dep] == player) { num_in_row++; } else { break; } if (num_in_row == num_rows) { return true; } } } // check down the columns for (int col = 0; col < num_cols; col++) { int num_in_row = 1; int player = board[0][col][dep]; for (int row = 1; row < num_rows; row++) { if (board[row][col][dep] == player) { num_in_row++; } else { break; } if (num_in_row == num_rows) { return true; } } } // check the diagonals int player = board[0][0][dep]; int num_in_row = 1; for (int row = 0; row < num_rows; row++) { if (board[row][row][dep] == player) { num_in_row++; } else { break; } } if (num_in_row == num_rows) { return true; } player = board[num_rows-1][num_cols-1][dep]; num_in_row = 1; for (int row = num_rows-1; row <= 0; row++) { if (board[row][row][dep] == player) { num_in_row++; } else { break; } } if (num_in_row == num_rows) { return true; } } // check rows across depth for (int row = 0; row < num_rows; row++) { // check across the rows for (int dep = 0; dep < num_depth; dep++) { int num_in_row = 1; int player = board[row][0][dep]; for (int col = 1; col < num_cols; col++) { if (board[row][col][dep] == player) { num_in_row++; } else { break; } if (num_in_row == num_rows) { return true; } } } // check down the columns for (int dep = 0; dep < num_depth; dep++) { int num_in_row = 1; int player = board[row][0][dep]; for (int col = 1; col < num_rows; col++) { if (board[row][col][dep] == player) { num_in_row++; } else { break; } if (num_in_row == num_rows) { return true; } } } // check the 3D diagonals int player = board[0][0][0]; int num_in_row = 1; for (int dep = 0; dep < num_depth; dep++) { if (board[dep][dep][dep] == player) { num_in_row++; } else { break; } } if (num_in_row == num_rows) { return true; } player = board[num_rows-1][num_cols-1][num_depth-1]; num_in_row = 1; for (int dep = num_depth-1; dep <= 0; dep++) { if (board[dep][dep][dep] == player) { num_in_row++; } else { break; } } if (num_in_row == num_rows) { return true; } } return false; } @Override public boolean getTurn() { // TODO Auto-generated method stub return false; } @Override public void playAction(AbstractGameAction action) { // TODO Auto-generated method stub } @Override public boolean getWinner() { // TODO Auto-generated method stub return false; } }
package net.i2p.router.web; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.Set; import net.i2p.data.DataHelper; import net.i2p.data.Destination; import net.i2p.data.LeaseSet; import net.i2p.stat.Rate; import net.i2p.stat.RateStat; import net.i2p.router.CommSystemFacade; import net.i2p.router.Router; import net.i2p.router.RouterContext; import net.i2p.router.RouterVersion; import net.i2p.router.TunnelPoolSettings; /** * Simple helper to query the appropriate router for data necessary to render * the summary sections on the router console. */ public class SummaryHelper { private RouterContext _context; /** * Configure this bean to query a particular router context * * @param contextId begging few characters of the routerHash, or null to pick * the first one we come across. */ public void setContextId(String contextId) { try { _context = ContextHelper.getContext(contextId); } catch (Throwable t) { t.printStackTrace(); } } /** * Retrieve the shortened 4 character ident for the router located within * the current JVM at the given context. * */ public String getIdent() { if (_context == null) return "[no router]"; if (_context.routerHash() != null) return _context.routerHash().toBase64().substring(0, 4); else return "[unknown]"; } /** * Retrieve the version number of the router. * */ public String getVersion() { return RouterVersion.VERSION + "-" + RouterVersion.BUILD; } /** * Retrieve a pretty printed uptime count (ala 4d or 7h or 39m) * */ public String getUptime() { if (_context == null) return "[no router]"; Router router = _context.router(); if (router == null) return "[not up]"; else return DataHelper.formatDuration(router.getUptime()); } private static final DateFormat _fmt = new java.text.SimpleDateFormat("HH:mm:ss", Locale.UK); public String getTime() { if (_context == null) return ""; String now = null; synchronized (_fmt) { now = _fmt.format(new Date(_context.clock().now())); } if (!_context.clock().getUpdatedSuccessfully()) return now + " (Unknown skew)"; long ms = _context.clock().getOffset(); long diff = ms; if (diff < 0) diff = 0 - diff; if (diff == 0) { return now + " (no skew)"; } else if (diff < 1000) { return now + " (" + ms + "ms skew)"; } else if (diff < 5 * 1000) { return now + " (" + (ms / 1000) + "s skew)"; } else if (diff < 60 * 1000) { return now + " <b>(" + (ms / 1000) + "s skew)</b>"; } else if (diff < 60 * 60 * 1000) { return now + " <b>(" + (ms / (60 * 1000)) + "m skew)</b>"; } else if (diff < 24 * 60 * 60 * 1000) { return now + " <b>(" + (ms / (60 * 60 * 1000)) + "h skew)</b>"; } else { return now + " <b>(" + (ms / (24 * 60 * 60 * 1000)) + "d skew)</b>"; } } public boolean allowReseed() { return (_context.netDb().getKnownRouters() < 30) || Boolean.valueOf(_context.getProperty("i2p.alwaysAllowReseed", "false")).booleanValue(); } public int getAllPeers() { return _context.netDb().getKnownRouters(); } public String getReachability() { if (!_context.clock().getUpdatedSuccessfully()) return "ERR-ClockSkew"; int status = _context.commSystem().getReachabilityStatus(); switch (status) { case CommSystemFacade.STATUS_OK: return "OK"; case CommSystemFacade.STATUS_DIFFERENT: return "ERR-SymmetricNAT"; case CommSystemFacade.STATUS_REJECT_UNSOLICITED: if (_context.router().getRouterInfo().getTargetAddress("NTCP") != null) return "WARN-Firewalled with Inbound TCP Enabled"; else if (_context.router().getRouterInfo().getCapabilities().indexOf('O') >= 0) return "WARN-Firewalled and Fast"; else return "Firewalled"; case CommSystemFacade.STATUS_UNKNOWN: // fallthrough default: return "Testing"; } } /** * Retrieve amount of used memory. * */ public String getMemory() { DecimalFormat integerFormatter = new DecimalFormat(" long used = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1024; long usedPc = 100 - ((Runtime.getRuntime().freeMemory() * 100) / Runtime.getRuntime().totalMemory()); return integerFormatter.format(used) + "KB (" + usedPc + "%)"; } /** * How many peers we are talking to now * */ public int getActivePeers() { if (_context == null) return 0; else return _context.commSystem().countActivePeers(); } /** * How many active identities have we spoken with recently * */ public int getActiveProfiles() { if (_context == null) return 0; else return _context.profileOrganizer().countActivePeers(); } /** * How many active peers the router ranks as fast. * */ public int getFastPeers() { if (_context == null) return 0; else return _context.profileOrganizer().countFastPeers(); } /** * How many active peers the router ranks as having a high capacity. * */ public int getHighCapacityPeers() { if (_context == null) return 0; else return _context.profileOrganizer().countHighCapacityPeers(); } /** * How many active peers the router ranks as well integrated. * */ public int getWellIntegratedPeers() { if (_context == null) return 0; else return _context.profileOrganizer().countWellIntegratedPeers(); } /** * How many peers the router ranks as failing. * */ public int getFailingPeers() { if (_context == null) return 0; else return _context.profileOrganizer().countFailingPeers(); } /** * How many peers totally suck. * */ public int getShitlistedPeers() { if (_context == null) return 0; else return _context.shitlist().getRouterCount(); } /** * How fast we have been receiving data over the last second (pretty printed * string with 2 decimal places representing the KBps) * */ public String getInboundSecondKBps() { if (_context == null) return "0.0"; double kbps = _context.bandwidthLimiter().getReceiveBps()/1024d; DecimalFormat fmt = new DecimalFormat("##0.00"); return fmt.format(kbps); } /** * How fast we have been sending data over the last second (pretty printed * string with 2 decimal places representing the KBps) * */ public String getOutboundSecondKBps() { if (_context == null) return "0.0"; double kbps = _context.bandwidthLimiter().getSendBps()/1024d; DecimalFormat fmt = new DecimalFormat("##0.00"); return fmt.format(kbps); } /** * How fast we have been receiving data over the last 5 minutes (pretty printed * string with 2 decimal places representing the KBps) * */ public String getInboundFiveMinuteKBps() { if (_context == null) return "0.0"; RateStat receiveRate = _context.statManager().getRate("bw.recvRate"); if (receiveRate == null) return "0.0"; Rate rate = receiveRate.getRate(5*60*1000); double kbps = rate.getAverageValue()/1024; DecimalFormat fmt = new DecimalFormat("##0.00"); return fmt.format(kbps); } /** * How fast we have been sending data over the last 5 minutes (pretty printed * string with 2 decimal places representing the KBps) * */ public String getOutboundFiveMinuteKBps() { if (_context == null) return "0.0"; RateStat receiveRate = _context.statManager().getRate("bw.sendRate"); if (receiveRate == null) return "0.0"; Rate rate = receiveRate.getRate(5*60*1000); double kbps = rate.getAverageValue()/1024; DecimalFormat fmt = new DecimalFormat("##0.00"); return fmt.format(kbps); } /** * How fast we have been receiving data since the router started (pretty printed * string with 2 decimal places representing the KBps) * */ public String getInboundLifetimeKBps() { if (_context == null) return "0.0"; RateStat receiveRate = _context.statManager().getRate("bw.recvRate"); if (receiveRate == null) return "0.0"; double kbps = receiveRate.getLifetimeAverageValue()/1024; DecimalFormat fmt = new DecimalFormat("##0.00"); return fmt.format(kbps); } /** * How fast we have been sending data since the router started (pretty printed * string with 2 decimal places representing the KBps) * */ public String getOutboundLifetimeKBps() { if (_context == null) return "0.0"; RateStat sendRate = _context.statManager().getRate("bw.sendRate"); if (sendRate == null) return "0.0"; double kbps = sendRate.getLifetimeAverageValue()/1024; DecimalFormat fmt = new DecimalFormat("##0.00"); return fmt.format(kbps); } /** * How much data have we received since the router started (pretty printed * string with 2 decimal places and the appropriate units - GB/MB/KB/bytes) * */ public String getInboundTransferred() { if (_context == null) return "0.0"; long received = _context.bandwidthLimiter().getTotalAllocatedInboundBytes(); return getTransferred(received); } /** * How much data have we sent since the router started (pretty printed * string with 2 decimal places and the appropriate units - GB/MB/KB/bytes) * */ public String getOutboundTransferred() { if (_context == null) return "0.0"; long sent = _context.bandwidthLimiter().getTotalAllocatedOutboundBytes(); return getTransferred(sent); } private static String getTransferred(long bytes) { double val = bytes; int scale = 0; if (bytes > 1024*1024*1024) { // gigs transferred scale = 3; val /= (double)(1024*1024*1024); } else if (bytes > 1024*1024) { // megs transferred scale = 2; val /= (double)(1024*1024); } else if (bytes > 1024) { // kbytes transferred scale = 1; val /= (double)1024; } else { scale = 0; } DecimalFormat fmt = new DecimalFormat("##0.00"); String str = fmt.format(val); switch (scale) { case 1: return str + "KB"; case 2: return str + "MB"; case 3: return str + "GB"; default: return bytes + "bytes"; } } /** * How many client destinations are connected locally. * * @return html section summary */ public String getDestinations() { Set clients = _context.clientManager().listClients(); StringBuffer buf = new StringBuffer(512); buf.append("<u><b>Local destinations</b></u><br />"); for (Iterator iter = clients.iterator(); iter.hasNext(); ) { Destination client = (Destination)iter.next(); TunnelPoolSettings in = _context.tunnelManager().getInboundSettings(client.calculateHash()); TunnelPoolSettings out = _context.tunnelManager().getOutboundSettings(client.calculateHash()); String name = (in != null ? in.getDestinationNickname() : null); if (name == null) name = (out != null ? out.getDestinationNickname() : null); if (name == null) name = client.calculateHash().toBase64().substring(0,6); buf.append("<b>*</b> ").append(name).append("<br />\n"); LeaseSet ls = _context.netDb().lookupLeaseSetLocally(client.calculateHash()); if (ls != null) { long timeToExpire = ls.getEarliestLeaseDate() - _context.clock().now(); if (timeToExpire < 0) { buf.append("<i>expired ").append(DataHelper.formatDuration(0-timeToExpire)); buf.append(" ago</i><br />\n"); } } else { buf.append("<i>No leases</i><br />\n"); } buf.append("<a href=\"tunnels.jsp#").append(client.calculateHash().toBase64().substring(0,4)); buf.append("\">Details</a> "); buf.append("<a href=\"configtunnels.jsp#").append(client.calculateHash().toBase64().substring(0,4)); buf.append("\">Config</a><br />\n"); } buf.append("<hr />\n"); return buf.toString(); } /** * How many free inbound tunnels we have. * */ public int getInboundTunnels() { if (_context == null) return 0; else return _context.tunnelManager().getFreeTunnelCount(); } /** * How many active outbound tunnels we have. * */ public int getOutboundTunnels() { if (_context == null) return 0; else return _context.tunnelManager().getOutboundTunnelCount(); } /** * How many inbound client tunnels we have. * */ public int getInboundClientTunnels() { if (_context == null) return 0; else return _context.tunnelManager().getInboundClientTunnelCount(); } /** * How many active outbound client tunnels we have. * */ public int getOutboundClientTunnels() { if (_context == null) return 0; else return _context.tunnelManager().getOutboundClientTunnelCount(); } /** * How many tunnels we are participating in. * */ public int getParticipatingTunnels() { if (_context == null) return 0; else return _context.tunnelManager().getParticipatingCount(); } /** * How lagged our job queue is over the last minute (pretty printed with * the units attached) * */ public String getJobLag() { if (_context == null) return "0ms"; Rate lagRate = _context.statManager().getRate("jobQueue.jobLag").getRate(60*1000); return ((int)lagRate.getAverageValue()) + "ms"; } /** * How long it takes us to pump out a message, averaged over the last minute * (pretty printed with the units attached) * */ public String getMessageDelay() { if (_context == null) return "0ms"; return _context.throttle().getMessageDelay() + "ms"; } /** * How long it takes us to test our tunnels, averaged over the last 10 minutes * (pretty printed with the units attached) * */ public String getTunnelLag() { if (_context == null) return "0ms"; return _context.throttle().getTunnelLag() + "ms"; } public String getTunnelStatus() { if (_context == null) return ""; return _context.throttle().getTunnelStatus(); } public String getInboundBacklog() { if (_context == null) return "0"; return String.valueOf(_context.tunnelManager().getInboundBuildQueueSize()); } public boolean updateAvailable() { return NewsFetcher.getInstance(_context).updateAvailable(); } }
package org.jimmutable.storage; import org.jimmutable.core.objects.Stringable; import org.jimmutable.core.utils.Validator; public class StorageKeyExtension extends Stringable { public StorageKeyExtension(String value) { super(value); } /** * @return the mime type of this extension. */ public String getSimpleMimeType() { switch(getSimpleValue()){ case "html": return "text/html"; case "htm": return "text/htm"; case "css": return "text/css"; case "js": return "application/js"; case "json": return "application/json"; case "xml": return "application/xml"; case "jpeg": return "image/jpeg"; case "jpg": return "image/jpg"; case "gif": return "image/gif"; case "png": return "image/png"; case "pdf": return "application/pdf"; case "xslx": return "application/xslx"; case "csv": return "text/csv"; case "txt": return "text/txt"; default: return "application/octet-stream"; } } @Override public void normalize() { Validator.notNull(getSimpleValue()); if(getSimpleValue().contains(".")) {//we want to strip out any leading ".". so that we do not confuse ourselves. setValue(getSimpleValue().substring(1)); } normalizeLowerCase(); } @Override public void validate() { Validator.min(getSimpleValue().length(), 1);//if we strip out the "." and nothing is left over, it will be caught here. Validator.containsOnlyValidCharacters(getSimpleValue(),Validator.LOWERCASE_LETTERS,Validator.NUMBERS); } }
package com.bagri.rest; import static com.bagri.xquery.api.XQUtils.getAtomicValue; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.ws.rs.WebApplicationException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import org.glassfish.jersey.process.Inflector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bagri.rest.service.RestService; import com.bagri.xdm.api.ResultCursor; import com.bagri.xdm.api.SchemaRepository; import com.bagri.xdm.api.XDMException; import com.bagri.xdm.system.Function; import com.bagri.xdm.system.Parameter; public class RestRequestProcessor implements Inflector<ContainerRequestContext, Response> { private static final transient Logger logger = LoggerFactory.getLogger(RestRequestProcessor.class); private Function fn; private String query; private RepositoryProvider rePro; public RestRequestProcessor(Function fn, String query, RepositoryProvider rePro) { this.fn = fn; this.query = query; this.rePro = rePro; } @Override public Response apply(ContainerRequestContext context) { String clientId = context.getCookies().get(RestService.bg_cookie).getValue(); SchemaRepository repo = rePro.getRepository(clientId); Map<String, Object> params = new HashMap<>(fn.getParameters().size()); logger.debug("apply.enter; path: {}; params: {}; query: {}", context.getUriInfo().getPath(), context.getUriInfo().getPathParameters(), context.getUriInfo().getQueryParameters()); for (Parameter pm: fn.getParameters()) { // TODO: resolve cardinality properly! if (isPathParameter(pm.getName())) { List<String> vals = context.getUriInfo().getPathParameters().get(pm.getName()); if (vals != null) { params.put(pm.getName(), getAtomicValue(pm.getType(), vals.get(0))); } } else { boolean found = false; List<String> atns = getParamAnnotations("rest:query-param", pm.getName()); if (atns != null) { List<String> vals = context.getUriInfo().getQueryParameters().get(pm.getName()); if (vals != null) { params.put(pm.getName(), getAtomicValue(pm.getType(), vals.get(0))); found = true; } } else { atns = getParamAnnotations("rest:form-param", pm.getName()); if (atns != null) { // content type must be application/x-www-form-urlencoded String body = getBody(context); if (body != null) { //logger.info("apply; form body: {}; ", body); String val = getParamValue(body, "&", pm.getName()); if (val != null) { params.put(pm.getName(), getAtomicValue(pm.getType(), val)); found = true; } } } else { atns = getParamAnnotations("rest:header-param", pm.getName()); if (atns != null) { String val = context.getHeaderString(atns.get(0)); if (val != null) { params.put(pm.getName(), getAtomicValue(pm.getType(), val)); found = true; } } else { atns = getParamAnnotations("rest:cookie-param", pm.getName()); if (atns != null) { Cookie val = context.getCookies().get(atns.get(0)); if (val != null) { params.put(pm.getName(), getAtomicValue(pm.getType(), val.getValue())); found = true; } } else { atns = getParamAnnotations("rest:matrix-param", pm.getName()); if (atns != null) { // does not work in Jersey: context.getUriInfo().getPathSegments(); String val = getParamValue(context.getUriInfo().getPath(), "&", pm.getName()); if (val != null) { params.put(pm.getName(), getAtomicValue(pm.getType(), val)); found = true; } } else { String body = getBody(context); if (context != null) { params.put(pm.getName(), getAtomicValue(pm.getType(), body)); found = true; } } } } } } if (!found) { setNotFoundParameter(params, atns, pm); } } List<String> vals = context.getUriInfo().getPathParameters().get(pm.getName()); if (vals != null) { // resolve cardinality.. params.put(pm.getName(), getAtomicValue(pm.getType(), vals.get(0))); } } logger.debug("apply; got params: {}", params); Properties props = new Properties(); try { final ResultCursor cursor = repo.getQueryManagement().executeQuery(query, params, props); logger.debug("apply.exit; got cursor: {}", cursor); StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream os) throws IOException, WebApplicationException { try (Writer writer = new BufferedWriter(new OutputStreamWriter(os))) { while (cursor.next()) { String chunk = cursor.getItemAsString(null); logger.trace("write; out: {}", chunk); writer.write(chunk + "\n"); writer.flush(); } } catch (XDMException ex) { logger.error("apply.error: error getting result from cursor ", ex); // how to handle it properly?? throw WebAppEx? } } }; return Response.ok(stream).build(); } catch (XDMException ex) { logger.error("apply.error: ", ex); return Response.serverError().entity(ex.getMessage()).build(); } } private boolean isPathParameter(String pName) { List<String> pa = fn.getAnnotations().get("rest:path"); return (pa != null && pa.size() == 1 && pa.get(0).indexOf("{" + pName + "}") > 0); } private List<String> getParamAnnotations(String aName, String pName) { List<String> pa = fn.getAnnotations().get(aName); if (pa != null && pa.size() > 0) { if (pName.equals(pa.get(0))) { return pa; } else if (pa.size() > 1 && ("{$" + pName + "}").equals(pa.get(1))) { return pa; } } return null; } private String getParamValue(String s, String d, String p) { String[] parts = s.split(d); for (String part: parts) { int pos = part.indexOf("="); if (pos > 0) { String name = part.substring(0, pos); if (name.equals(p)) { return part.substring(pos + 1); } } } return null; } private String getBody(ContainerRequestContext context) { if (context.hasEntity() && ("POST".equals(context.getMethod()) || "PUT".equals(context.getMethod()))) { java.util.Scanner s = new java.util.Scanner(context.getEntityStream()).useDelimiter("\\A"); return s.next(); } return null; } private void setNotFoundParameter(Map<String, Object> params, List<String> atns, Parameter pm) { // handle default values if (atns.size() > 2) { params.put(pm.getName(), getAtomicValue(pm.getType(), atns.get(2))); } else if (pm.getCardinality().isOptional()) { // pass empty value.. params.put(pm.getName(), null); } } }
package de.hbt.hackathon.rtb.base.type; public class Coordinate { private final double x; private final double y; private final long timeStamp; public Coordinate(double x, double y, long timeStamp) { this.x = x; this.y = y; this.timeStamp = timeStamp; } public double getX() { return x; } public double getY() { return y; } public long getTimeStamp() { return timeStamp; } @Override public String toString() { return "Coordinate[x=" + x + ",y=" + y + ",timeStamp=" + timeStamp; } }
package net.sf.bbarena.model.pitch; import net.sf.bbarena.model.Coordinate; import net.sf.bbarena.model.Direction; import net.sf.bbarena.model.RangeRuler; import net.sf.bbarena.model.exception.PitchException; import net.sf.bbarena.model.pitch.BallMove.BallMoveType; import net.sf.bbarena.model.pitch.Dugout.DugoutRoom; import net.sf.bbarena.model.pitch.Square.SquareType; import net.sf.bbarena.model.team.Player; import net.sf.bbarena.model.team.Team; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * The Pitch is the class to represent any BB Pitch. It is possible to * create a PitchFactory for classic BB Pitch, DungeonBowl, DeathBowl * and so on. This class is the only responsible of the consistency of the pitch * model, each change in players location, ball location and so on must be done * with this class and not modifing the single Square or Player objects. * * @author f.bellentani */ public class Pitch { private final String _name; private final Square[][] _squares; private final Set<Square> _squareSet; private final List<Dugout> _dugouts; private final List<Ball> _balls; private final Set<Player> _players; /** * Constructor for a general pitch The pitch MUST be rectangular or a * square, each row must have the same number of squares. Fill every square * out of bounds with a SquareType.OUT * * @param name Name of the pitch * @param width Width of the pitch * @param height Height of the pitch */ public Pitch(String name, int width, int height) { _name = name; _squareSet = new LinkedHashSet<>(); _squares = new Square[width][height]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { Square square = new Square(this, new Coordinate(x, y)); _squareSet.add(square); _squares[x][y] = square; } } _dugouts = new ArrayList<>(); _balls = new ArrayList<>(); _players = new LinkedHashSet<>(); } public boolean addDugout(Dugout dugout) { boolean res = false; if (dugout != null) { res = _dugouts.add(dugout); } return res; } public String getPitchName() { return _name; } public int getWidth() { return _squares.length; } public int getHeight() { return _squares[0].length; } /** * Return the Square in a Coordinate * * @param xy Square Coordinate from [0,0] * @return The Square in the Coordinate */ public Square getSquare(Coordinate xy) { Square res = null; int x = xy.getX(); int y = xy.getY(); if (x >= 0 && _squares.length > x && y >= 0 && _squares[x].length > y) { res = _squares[x][y]; } return res; } public Set<Square> getTeamSquares(Team team) { Set<Square> res = new LinkedHashSet<>(); _squareSet.stream().filter(square -> square.getTeamOwner() != null ? square.getTeamOwner().equals(team) : false).forEach(square -> res.add(square)); return res; } public List<Ball> getBalls() { return _balls; } /** * Returns the first (default one) ball. * * @return Default Ball, null if there are no balls. */ public Ball getBall() { return getBall(0); } public Ball getBall(int ballId) { Ball res = null; if (_balls.size() > ballId) { res = _balls.get(ballId); } return res; } public int addBall(Ball ball) { int res = _balls.size(); ball.setId(res); _balls.add(ball); return res; } /** * Counts the number of active Tackle Zones in a Square * * @param xy Square Coordinate * @param team Team of the player in the square * @return the number of Tackle Zones */ public int getOpponentTZCount(Coordinate xy, Team team) { int res = 0; for (Direction d : Direction.values()) { Square s = getNextSquare(xy, d); if (s != null && s.getType() != SquareType.OUT) { Player p = s.getPlayer(); if (p != null && !p.getTeam().equals(team) && p.hasTZ()) { res++; } } } return res; } /** * Search the next Square in a specified Direction * * @param xy Start Coordinate * @param direction Direction * @return The Square near the start Coordinate */ public Square getNextSquare(Coordinate xy, Direction direction) { return getSquare(xy.getNext(direction)); } /** * Move a player to a Direction. If the Player will move out of the pitch a * PitchException will be thrown (this doesn't apply for SquareType.OUT) * * @param player Player to move * @param direction Direction of the movement * @return The new Square occupied by the Player */ public Square movePlayer(Player player, Direction direction) { return movePlayer(player, direction, 1); } /** * Move a player to a Direction. If the Player will move out of the pitch a * PitchException will be thrown (this doesn't apply for SquareType.OUT) * * @param player Player to move * @param direction Direction of the movement * @param squares Number of squares * @return The new Square occupied by the Player */ public Square movePlayer(Player player, Direction direction, int squares) { if (squares < 0) { throw new PitchException( "Cannot move a negative number of squares!"); } Square res = null; Square origin = player.getSquare(); if (origin != null) { Coordinate pc = origin.getCoords(); Square next = origin; for (int i = 0; i < squares; i++) { next = getNextSquare(pc, direction); if (next != null && next.getType() != SquareType.OUT) { pc = next.getCoords(); } else { throw new PitchException("Player moved out of the pitch!"); } } origin.removePlayer(); next.setPlayer(player); player.setSquare(next); res = next; } else { throw new PitchException("Player is not on the pitch!"); } return res; } /** * Scatter the Ball in a Direction by one square * * @param ball Ball to scatter * @param direction Direction * @return The new Square occupied by the Ball */ public Square ballScatter(Ball ball, Direction direction) { return moveBall(ball, direction, 1, BallMoveType.SCATTER); } /** * Pass the Ball to a destination * * @param ball Ball to pass * @param destination Destination of the throw * @return The new Square occupied by the Ball */ public Square ballPass(Ball ball, Coordinate destination) { return putBall(ball, destination, BallMoveType.PASS); } /** * Kick Off the Ball to a destination * * @param ball Ball to kick * @param destination Destination of the kick * @return The new Square occupied by the Ball */ public Square ballKickOff(Ball ball, Coordinate destination) { return putBall(ball, destination, BallMoveType.KICK_OFF); } /** * Throw-In the Ball to a destination * * @param ball Ball to kick * @param direction Direction of the throw-in * @param range Number of squares * @return The new Square occupied by the Ball */ public Square ballThrowIn(Ball ball, Direction direction, int range) { return moveBall(ball, direction, range, BallMoveType.THROW_IN); } /** * Assign the Ball to a Player via Pick Up * * @param ball Ball to Pick Up * @param player Player that gets the Ball */ public void ballPickUp(Ball ball, Player player) { setBallOwner(ball, player, BallMoveType.PICK_UP); } /** * Deprive a Player the Ball. The Ball will be assigned to the Player * Square, waiting to be scattered * * @param ball Ball * @param player Player to deprive * @return The new Square of the Ball */ public Square ballLose(Ball ball, Player player) { return putBall(ball, player.getSquare().getCoords(), BallMoveType.LOSE); } /** * Assign the Ball to a Player via Catch * * @param ball Ball to Catch * @param player Player that gets the Ball */ public void ballCatch(Ball ball, Player player) { setBallOwner(ball, player, BallMoveType.CATCH); } /** * Move a Ball to a Direction. If the Ball will move out of the pitch a * PitchException will be thrown (this doesn't apply for SquareType.OUT) * * @param ball Ball to move * @param direction Direction of the movement * @param squares Number of squares * @param moveType Type of the Ball movement, default if range == 1 or == 0 is * SCATTER, if range > 1 is THROW_IN * @return The new Square occupied by the Ball */ public Square moveBall(Ball ball, Direction direction, int squares, BallMoveType moveType) { if (squares < 0) { throw new PitchException( "Cannot move a negative number of squares!"); } if (moveType == null) { if (squares <= 1) { moveType = BallMoveType.SCATTER; } else if (squares > 1) { moveType = BallMoveType.THROW_IN; } } Square res = null; Square origin = ball.getSquare(); if (origin != null) { Coordinate bc = origin.getCoords(); Square next = origin; for (int i = 0; i < squares; i++) { next = getNextSquare(bc, direction); if (next != null && next.getType() != SquareType.OUT) { bc = next.getCoords(); } else { throw new PitchException("Ball moved out of the pitch!"); } } removeBall(ball); next.setBall(ball); ball.setSquare(next, moveType); res = next; } else { throw new PitchException("Ball is not on the pitch!"); } return res; } public SquareDestination getDestination(Coordinate coordinate, Direction direction, int squares) { if (squares < 0) { throw new PitchException( "Cannot move a negative number of squares!"); } boolean out = false; Coordinate destination = coordinate; Integer i; for (i = 0; i < squares; i++) { Square nextSquare = getNextSquare(destination, direction); if (nextSquare != null && nextSquare.getType() != SquareType.OUT) { destination = nextSquare.getCoords(); } else { out = true; break; } } return new SquareDestination(destination, out, i); } /** * Assign the Ball owner * * @param ball Ball to assign * @param player Player that will have the Ball * @param moveType Type of the Ball movement, default is PICK_UP */ private void setBallOwner(Ball ball, Player player, BallMoveType moveType) { if (player.getSquare() == null || player.isInDugout()) { throw new PitchException("Player is not on the pitch!"); } else if (player.hasBall()) { throw new PitchException("Player has already a Ball!"); } if (moveType == null) { moveType = BallMoveType.PICK_UP; } removeBall(ball); ball.setOwner(player, moveType); player.setBall(ball); } /** * Put a Player in a specified Coordinate on the pitch. If the Player is in * the Dugout it will be removed. * * @param player Player to put in the pitch * @param xy Coordinate where to put the Player * @return The new Square for the Player */ public Square putPlayer(Player player, Coordinate xy) { Square res = getSquare(xy); if (res == null || res.getType() == SquareType.OUT) { throw new PitchException("Square " + xy.toString() + " is out of the pitch!"); } if (player.isInDugout()) { Dugout dugout = getDugout(player.getTeam()); dugout.removePlayer(player); _players.add(player); } Square origin = player.getSquare(); if (origin != null) { origin.removePlayer(); player.setSquare(null); } res.setPlayer(player); player.setSquare(res); return res; } /** * Put a Ball in a specified Coordinate on the pitch. * * @param ball Ball to put in the pitch * @param xy Coordinate where to put the Ball * @param moveType Type of the Ball movement, default is KICK_OFF * @return The new Square for the Ball */ private Square putBall(Ball ball, Coordinate xy, BallMoveType moveType) { Square res = getSquare(xy); if (res == null || res.getType() == SquareType.OUT) { throw new PitchException("Square " + xy.toString() + " is out of the pitch!"); } if (moveType == null) { moveType = BallMoveType.KICK_OFF; } removeBall(ball); ball.setSquare(res, moveType); res.setBall(ball); return res; } /** * Remove the Ball from the pitch * * @param ball Ball to remove */ private void removeBall(Ball ball) { Square origin = ball.getSquare(); if (origin != null) { origin.removeBall(); } Player player = ball.getOwner(); if (player != null) { player.removeBall(); } } public void ballRemove(Ball ball) { removeBall(ball); ball.remove(BallMoveType.OUT); } /** * Put a Player in a specified Room of his Team Dugout. If the player is in * a Square it will be removed. * * @param player Player to put in Dugout * @param room The DugoutRoom * @return true if the player is successfully added, false otherwise */ public boolean putPlayer(Player player, DugoutRoom room) { boolean res; Dugout dugout = getDugout(player.getTeam()); res = dugout.addPlayer(room, player); if (res) { Square square = player.getSquare(); if (square != null) { square.removePlayer(); player.setSquare(null); _players.remove(player); } } return res; } public List<Dugout> getDugouts() { return _dugouts; } public Dugout getDugout(Team team) { Dugout res = null; for (Dugout dugout : _dugouts) { if (dugout.getTeam().equals(team)) { res = dugout; break; } } return res; } /** * Given a coordinate and a range return every square that is in the range * from that coordinate. * * @param ref Coordinate from where will be calculated the range * @param squareRange Number of squares for the range * @return The list of Squares within range */ public List<Square> getSquaresInRange(Coordinate ref, int squareRange) { List<Square> res = new ArrayList<Square>(); int x1 = Math.max(0, ref.getX() - squareRange); int x2 = Math.min(_squares.length - 1, ref.getX() + squareRange); int y1 = Math.max(0, ref.getY() - squareRange); int y2 = Math.min(_squares[x2].length - 1, ref.getY() + squareRange); for (int x = x1; x <= x2; x++) { for (int y = y1; y <= y2; y++) { Square square = getSquare(new Coordinate(x, y)); if (square != null && square.getType() != SquareType.OUT) { res.add(square); } } } return res; } /** * Given a coordinate and a range return every player that is in the range * from that coordinate. This will be useful when testing which players are, * for example, 3 squares away from another player. Here there are no * controls over player skills or if the players have active tackle zones. * * @param ref Coordinate from where will be calculated the range * @param squareRange Number of squares for the range * @return The list of Players within range */ public List<Player> getPlayersInRange(Coordinate ref, int squareRange) { List<Player> res = new ArrayList<Player>(); List<Square> squares = getSquaresInRange(ref, squareRange); for (Square square : squares) { Player player = square.getPlayer(); if (player != null) { res.add(player); } } return res; } public RangeRuler getRangeRuler() { return new RangeRuler(this); } public Set<Player> getPlayers() { return _players; } void setSquare(Coordinate xy, SquareType type) { setSquare(xy, type, null); } void setSquare(Coordinate xy, SquareType type, Team teamOwner) { Square s = new Square(this, xy, type, teamOwner); Square oldSquare = _squares[xy.getX()][xy.getY()]; _squareSet.remove(oldSquare); _squareSet.add(s); _squares[xy.getX()][xy.getY()] = s; } }
package ucar.nc2.iosp.grib; import ucar.nc2.iosp.grid.GridServiceProvider; import ucar.nc2.iosp.grid.GridIndexToNC; import ucar.nc2.util.CancelTask; import ucar.nc2.util.DiskCache; import ucar.nc2.NetcdfFile; import ucar.grib.*; import ucar.grib.grib1.*; import ucar.grib.grib2.*; import ucar.grid.GridRecord; import ucar.grid.GridIndex; import ucar.grid.GridTableLookup; import ucar.unidata.io.RandomAccessFile; import java.io.*; import java.util.List; import java.util.Map; import java.net.URL; public class GribGridServiceProvider extends GridServiceProvider { private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GribGridServiceProvider.class); private int edition = 0; /** * returns Grib data */ private Grib1Data dataReaderGrib1; private Grib2Data dataReaderGrib2; public boolean isValidFile(RandomAccessFile raf) { try { raf.seek(0); raf.order(RandomAccessFile.BIG_ENDIAN); Grib2Input g2i = new Grib2Input(raf); int edition = g2i.getEdition(); return (edition == 1 || edition == 2); } catch (Exception e) { return false; } } public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask) throws IOException { this.raf = raf; this.ncfile = ncfile; //this.rafLength = raf.length(); long start = System.currentTimeMillis(); if (GridServiceProvider.debugOpen) System.out.println("GribGridServiceProvider open = " + ncfile.getLocation()); GridIndex index = getIndex(raf.getLocation()); Map<String, String> attr = index.getGlobalAttributes(); edition = attr.get("grid_edition").equals("2") ? 2 : 1; GridTableLookup lookup; if (edition == 2) { lookup = getLookup2(); } else { lookup = getLookup1(); } // make it into netcdf objects new GridIndexToNC().open(index, lookup, edition, ncfile, fmrcCoordSys, cancelTask); ncfile.finish(); if (debugTiming) { long took = System.currentTimeMillis() - start; System.out.println(" open " + ncfile.getLocation() + " took=" + took + " msec "); } log.debug("GridServiceProvider.open " + ncfile.getLocation() + " took " + (System.currentTimeMillis() - start)); } // not used public void open(GridIndex index, CancelTask cancelTask) { } protected GridTableLookup getLookup2() throws IOException { Grib2Record firstRecord = null; try { Grib2Input g2i = new Grib2Input(raf); long start2 = System.currentTimeMillis(); // params getProducts (implies unique GDSs too), oneRecord // open it up and get the first product raf.seek(0); g2i.scan(false, true); List records = g2i.getRecords(); firstRecord = (Grib2Record) records.get(0); if (debugTiming) { long took = System.currentTimeMillis() - start2; System.out.println(" read one record took=" + took + " msec "); } } catch (NotSupportedException noSupport) { System.err.println("NotSupportedException : " + noSupport); } Grib2GridTableLookup lookup = new Grib2GridTableLookup(firstRecord); dataReaderGrib2 = new Grib2Data(raf); return lookup; } protected GridTableLookup getLookup1() throws IOException { Grib1Record firstRecord = null; try { Grib1Input g1i = new Grib1Input(raf); long start2 = System.currentTimeMillis(); // params getProducts (implies unique GDSs too), oneRecord // open it up and get the first product raf.seek(0); g1i.scan(false, true); List records = g1i.getRecords(); firstRecord = (Grib1Record) records.get(0); if (debugTiming) { long took = System.currentTimeMillis() - start2; System.out.println(" read one record took=" + took + " msec "); } } catch (NotSupportedException noSupport) { System.err.println("NotSupportedException : " + noSupport); } catch (NoValidGribException noValid) { System.err.println("NoValidGribException : " + noValid); } Grib1GridTableLookup lookup = new Grib1GridTableLookup(firstRecord); dataReaderGrib1 = new Grib1Data(raf); return lookup; } /** * Open the index file. If not exists, else create it. * * @param gribLocation of the file. The index file has ".gbx" appended. * @return ucar.grid.GridIndex * @throws IOException on io error */ protected GridIndex getIndex(String gribLocation) throws IOException { // get an Index String indexLocation = gribLocation + ".gbx"; GridIndex index = null; File indexFile = null; boolean canWriteIndex = false; // just use the cache if ( alwaysInCache ) { indexFile = DiskCache.getCacheFile(indexLocation); canWriteIndex = true; // direct access through http } else if (indexLocation.startsWith("http:")) { InputStream ios = indexExistsAsURL(indexLocation); if (ios != null) { index = new GribReadIndex().open(indexLocation, ios); log.debug("opened HTTP index = " + indexLocation); return index; } else { // otherwise write it to / get it from the cache indexFile = DiskCache.getCacheFile(indexLocation); canWriteIndex = true; log.debug("HTTP index = " + indexFile.getPath()); } } else { // check first if the index file lives in the same dir as the regular file, and use it indexFile = new File(indexLocation); if (!indexFile.exists()) { // look in cache if need be indexFile = DiskCache.getCacheFile(indexLocation); if (!indexFile.exists()) { //cache doesn't exist indexFile = new File(indexLocation); if ( indexFile.createNewFile()) { indexFile.delete(); canWriteIndex = true; } else { indexFile = DiskCache.getCacheFile(indexLocation); canWriteIndex = true; } } } } log.debug("GribGridServiceProvider: using index " + indexFile.getPath()); // once index determined, if sync then write it. very expensive if( syncExtend ) return writeIndex( indexFile, gribLocation, indexLocation, raf); // if index exist already and extendMode, check/read it if ( ! extendMode && indexFile.exists() ) { try { File gribFile = new File( gribLocation ); if( gribFile.lastModified() < indexFile.lastModified() ) { index = new GribReadIndex().open(indexFile.getPath()); } else { index = extendIndex( gribFile, indexFile, gribLocation, indexLocation, raf ); } } catch (Exception e) { } if (index != null) { log.debug(" opened index = " + indexFile.getPath()); } else { // rewrite if fail to open log.debug(" index open failed, write index = " + indexFile.getPath()); index = writeIndex( indexFile, gribLocation, indexLocation, raf); } } else if (indexFile.exists()) { try { index = new GribReadIndex().open(indexFile.getPath()); } catch (Exception e) { } if (index != null) { log.debug(" opened index = " + indexFile.getPath()); } else { // rewrite if fail to open log.debug(" index open failed, write index = " + indexFile.getPath()); index = writeIndex( indexFile, gribLocation, indexLocation, raf); } } else { // doesnt exist log.debug(" creating index = " + indexFile.getPath()); index = writeIndex( indexFile, gribLocation, indexLocation, raf); } return index; } private GridIndex writeIndex( File indexFile, String gribName, String gbxName, RandomAccessFile raf) throws IOException { GridIndex index = null; try { if (indexFile.exists()) { indexFile.delete(); log.debug("Deleting old index " + indexFile.getPath()); } raf.seek(0); Grib2Input g2i = new Grib2Input(raf); edition = g2i.getEdition(); File gribFile = new File(raf.getLocation()); if (edition == 1) { index = new Grib1WriteIndex().writeGribIndex( gribFile, gribName, gbxName, raf, true); } else if (edition == 2) { index = new Grib2WriteIndex().writeGribIndex( gribFile, gribName, gbxName, raf, true); } return index; } catch (NotSupportedException noSupport) { System.err.println("NotSupportedException : " + noSupport); } return index; } private GridIndex extendIndex(File gribFile, File indexFile, String gribName, String gbxName, RandomAccessFile raf) throws IOException { GridIndex index = null; try { raf.seek(0); Grib2Input g2i = new Grib2Input(raf); edition = g2i.getEdition(); if (edition == 1) { index = new Grib1WriteIndex().extendGribIndex(gribFile, indexFile, gribName, gbxName, raf, true); } else if (edition == 2) { index = new Grib2WriteIndex().extendGribIndex(gribFile, indexFile, gribName, gbxName, raf, true); } return index; } catch (NotSupportedException noSupport) { System.err.println("NotSupportedException : " + noSupport); } return index; } // if exists, return input stream, otherwise null private InputStream indexExistsAsURL(String indexLocation) { try { URL url = new URL(indexLocation); return url.openStream(); } catch (IOException e) { return null; } } protected float[] _readData(GridRecord gr) throws IOException { GribGridRecord ggr = (GribGridRecord) gr; if (edition == 2) { return dataReaderGrib2.getData(ggr.offset1, ggr.offset2); } else { return dataReaderGrib1.getData(ggr.offset1, ggr.decimalScale, ggr.bmsExists); } } }
package ru.job4j.service; import java.util.Iterator; public class DynamicLinkedList<E> implements SimpleContainer<E> { public Node<E> first; public Node<E> last; public int size = last.index + 1; @Override public void add(E e) { Node<E> node = new Node<>(first, e, last); last.next = node; node.prev = last; last = node; } @Override public E get(int position) { Node<E> current = last; while (current.index != position) { current = current.next; } return current.item; } @Override public Iterator<E> iterator() { return new Iterator<E>() { @Override public boolean hasNext() { return false; } @Override public E next() { return null; } }; } private static class Node<E> { E item; Node<E> next; Node<E> prev; int index = 0; Node(Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; index++; } } }
package test.beast.util; import org.junit.Assert; import org.junit.Test; import beast.util.TreeParser; public class TreeParserTest { @Test public void testFullyLabelledWithIntegers() { String newick = "((0:1.0,1:1.0)4:1.0,(2:1.0,3:1.0)5:1.0)6:0.0;"; try { boolean isLabeled = false; TreeParser treeParser = new TreeParser(newick, false, false, isLabeled, 0); treeParser.offsetInput.setValue(0, treeParser); Assert.assertEquals(newick.split(";")[0], treeParser.getRoot().toShortNewick(true)); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. \ Assert.assertTrue("Exception!", false); } } @Test public void testOnlyLeafLabels() throws Exception { String newick = "((A:1.0,B:1.0):1.0,(C:1.0,D:1.0):1.0):0.0;"; boolean isLabeled = true; TreeParser treeParser = new TreeParser(newick, false, false, isLabeled, 1); System.out.println("adfgad"); Assert.assertEquals(newick.split(";")[0], treeParser.getRoot().toNewick()); } @Test public void testOnlyLeafLabels2() throws Exception { String newick = "((D:5.0,C:4.0):6.0,(A:1.0,B:2.0):3.0):0.0;"; TreeParser treeParser = new TreeParser(); treeParser.initByName("IsLabelledNewick", true, "newick", newick, "adjustTipHeights", false); String newick2 = treeParser.getRoot().toNewick(); Assert.assertEquals(newick.replaceAll(";", ""), newick2); } @Test public void testSomeInternalNodesLabelled() { String newick = "((A:1.0,B:1.0)E:1.0,(C:1.0,D:1.0):1.0):0.0;"; try { boolean isLabeled = true; TreeParser treeParser = new TreeParser(newick, false, false, isLabeled, 1); Assert.assertEquals(newick.split(";")[0], treeParser.getRoot().toNewick()); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. \ Assert.assertTrue("Exception!", false); } } @Test public void testDuplicates() throws Exception { String newick = "((A:1.0,B:1.0):1.0,(C:1.0,A:1.0):1.0):0.0;"; boolean exceptionRaised = false; try { boolean isLabeled = true; TreeParser treeParser = new TreeParser(newick, false, false, isLabeled, 1); System.out.println(treeParser.getRoot().toNewick()); } catch (RuntimeException e) { e.printStackTrace(); exceptionRaised = true; } Assert.assertTrue(exceptionRaised); } @Test public void testBinarization() throws Exception { String newick = "((A:1.0,B:1.0,C:1.0):1.0,(D:1.0,E:1.0,F:1.0,G:1.0):1.0):0.0;"; String binaryNewick = "((A:1.0,(B:1.0,C:1.0):0.0):1.0,(D:1.0,(E:1.0,(F:1.0,G:1.0):0.0):0.0):1.0):0.0;"; boolean isLabeled = true; TreeParser treeParser = new TreeParser(newick, false, false, isLabeled, 1); Assert.assertEquals(binaryNewick.split(";")[0], treeParser.getRoot().toNewick()); } @Test public void testMultifurcations() throws Exception { String newick = "((A:1.0,B:1.0,C:1.0):1.0,(D:1.0,E:1.0,F:1.0,G:1.0):1.0):0.0;"; boolean isLabeled = true; TreeParser treeParser = new TreeParser(newick, false, false, isLabeled, 1, false); Assert.assertEquals(newick.split(";")[0], treeParser.getRoot().toNewick()); } @Test public void testVectorMetadata() throws Exception { String newick = "((A:1.0,B[&key={1,2,3}]:1.0):1.0,(C:1.0,D:1.0):1.0):0.0;"; boolean isLabeled = true; TreeParser treeParser = new TreeParser(newick, false, false, isLabeled, 1); Assert.assertTrue((treeParser.getNode(1).getMetaData("key") instanceof Double[]) && ((Double[])(treeParser.getNode(1).getMetaData("key"))).length == 3); } @Test public void testNodeLengthMetadata() throws Exception { String newick = "((A:1.0,B[&key=42]:[&key=2.5]1.0):1.0,(C:1.0,D:1.0):1.0):0.0;"; boolean isLabeled = true; TreeParser treeParser = new TreeParser(newick, false, false, isLabeled, 1); Assert.assertTrue(treeParser.getNode(1).getLengthMetaData("key").equals(2.5)); Assert.assertTrue(treeParser.getNode(1).getMetaData("key").equals(42.0)); } @Test public void testInternalNodeLabels() throws Exception { String newick = "((xmr),((knw)ctm));"; boolean isLabeled = true; TreeParser treeParser = new TreeParser(newick,false, true, isLabeled, 0, false); Assert.assertTrue(treeParser.getNode(0).getID().equals("knw")); Assert.assertTrue(treeParser.getNode(1).getID().equals("xmr")); Assert.assertTrue(treeParser.getNode(0).getParent().getID().equals("ctm")); Assert.assertTrue(treeParser.getNode(1).getParent().getID() == null); } }
package eu.ess.jels; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import xal.model.ModelException; import xal.model.probe.Probe; import xal.sim.scenario.ElementMapping; import xal.smf.AcceleratorSeq; import xal.smf.impl.qualify.MagnetType; import xal.tools.beam.IConstants; import eu.ess.jels.smf.impl.Bend; @RunWith(Parameterized.class) public class BendTest extends TestCommon { public BendTest(Probe probe, ElementMapping elementMapping) { super(probe, elementMapping); } /* * Test used for madx comparison. * * */ // @Test public void doHorizontalBendTestMadX() throws InstantiationException, ModelException { probe.reset(); System.out.println("Horizontal madx"); AcceleratorSeq sequence = bend(-5.5, -11, -5.5, 9375.67, 0., 0, 0., 0, 0., 0, 0, 0); run(sequence); printResults(); // checkTWTransferMatrix(new double[][]{}); } @Test public void doVerticalBendTest() throws InstantiationException, ModelException { probe.reset(); System.out.println("Vertical"); /* EDGE -5.5 9375.67 50 0.45 2.8 50 1; this is a magnet length of 1.8 m BEND -11 9375.67 0 50 1 EDGE -5.5 9375.67 50 0.45 2.8 50 1 */ AcceleratorSeq sequence = bend(-5.5, -11, -5.5, 9375.67, 0., 50, 0.45, 2.80, 0.45, 2.80, 50, 1); run(sequence); //printResults(); if (initialEnergy == 3e6) { checkELSResults(1.799999E+00, new double[] {6.182466E-03, 5.210289E-03, 5.142904E-03}, new double [] { 1.458045E+01, 1.039017E+01, 7.424592E+00}); // when halfMag=true checkTWTransferMatrix(new double [][] { {+1.018958e+00, +1.799999e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+2.126416e-02, +1.018958e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +9.632544e-01, +1.788962e+00, +0.000000e+00, -1.722575e-01}, {+0.000000e+00, +0.000000e+00, -4.032563e-02, +9.632544e-01, +0.000000e+00, -1.890399e-01}, {+0.000000e+00, +0.000000e+00, +1.890399e-01, +1.722575e-01, +1.000000e+00, +1.777507e+00}, {+0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +1.000000e+00}, }); checkTWResults(1.003197291, new double[][] { {+3.822288e-11, +2.081295e-11, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+2.081295e-11, +1.151277e-11, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +2.730380e-11, +1.338170e-11, +9.152883e-13, -9.096619e-13}, {+0.000000e+00, +0.000000e+00, +1.338170e-11, +6.868014e-12, -7.836318e-13, -9.982870e-13}, {+0.000000e+00, +0.000000e+00, +9.152883e-13, -7.836318e-13, +2.675748e-11, +1.126873e-11}, {+0.000000e+00, +0.000000e+00, -9.096619e-13, -9.982870e-13, +1.126873e-11, +5.280827e-12} }); } if (initialEnergy == 2.5e9) { checkTWTransferMatrix(new double [][] { {+1.018958e+00, +1.799999e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+2.126416e-02, +1.018958e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +9.632544e-01, +1.788962e+00, +0.000000e+00, -1.722575e-01}, {+0.000000e+00, +0.000000e+00, -4.032563e-02, +9.632544e-01, +0.000000e+00, -1.890399e-01}, {+0.000000e+00, +0.000000e+00, +1.890399e-01, +1.722575e-01, +1.000000e+00, +1.230120e-01}, {+0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +1.000000e+00}, }); checkTWResults(3.664409209, new double[][] { {+8.677160e-13, +4.724847e-13, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+4.724847e-13, +2.613568e-13, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +6.637417e-13, +3.519667e-13, +2.359157e-14, -2.755303e-13}, {+0.000000e+00, +0.000000e+00, +3.519667e-13, +2.087907e-13, -1.470235e-14, -3.023743e-13}, {+0.000000e+00, +0.000000e+00, +2.359157e-14, -1.470235e-14, +4.693770e-14, +2.394856e-13}, {+0.000000e+00, +0.000000e+00, -2.755303e-13, -3.023743e-13, +2.394856e-13, +1.599526e-12}, }); } } @Test public void doHorizontalBendTest() throws InstantiationException, ModelException { probe.reset(); System.out.println("Horizontal"); /* EDGE -5.5 9375.67 50 0.45 2.8 50 0; this is a magnet length of 1.8 m BEND -11 9375.67 0 50 0 EDGE -5.5 9375.67 50 0.45 2.8 50 0 */ AcceleratorSeq sequence = bend(-5.5, -11, -5.5, 9375.67, 0., 50, 0.45, 2.80, 0.45, 2.80, 50, 0); run(sequence); //printResults(); if (initialEnergy == 3e6) { checkELSResults(1.799999E+00, new double[] {6.132800E-03, 5.266670E-03, 5.142904E-03}, new double [] { 1.434713E+01, 1.061625E+01, 7.424592E+00}); checkTWTransferMatrix(new double [][] { {+9.632544e-01, +1.788962e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, -1.722575e-01}, {-4.032563e-02, +9.632544e-01, +0.000000e+00, +0.000000e+00, +0.000000e+00, -1.890399e-01}, {+0.000000e+00, +0.000000e+00, +1.018958e+00, +1.799999e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +2.126416e-02, +1.018958e+00, +0.000000e+00, +0.000000e+00}, {+1.890399e-01, +1.722575e-01, +0.000000e+00, +0.000000e+00, +1.000000e+00, +1.777507e+00}, {+0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +1.000000e+00}, }); checkTWResults(1.003197291, new double[][] { {+3.776793e-11, +1.961660e-11, +0.000000e+00, +0.000000e+00, +1.819416e-12, -9.096619e-13}, {+1.961660e-11, +1.042412e-11, +0.000000e+00, +0.000000e+00, -2.175526e-13, -9.982870e-13}, {+0.000000e+00, +0.000000e+00, +2.773781e-11, +1.426590e-11, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +1.426590e-11, +7.583238e-12, +0.000000e+00, +0.000000e+00}, {+1.819416e-12, -2.175526e-13, +0.000000e+00, +0.000000e+00, +2.683088e-11, +1.126873e-11}, {-9.096619e-13, -9.982870e-13, +0.000000e+00, +0.000000e+00, +1.126873e-11, +5.280827e-12}, }); } if (initialEnergy == 2.5e9) { checkTWTransferMatrix(new double [][] { {+9.632544e-01, +1.788962e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, -1.722575e-01}, {-4.032563e-02, +9.632544e-01, +0.000000e+00, +0.000000e+00, +0.000000e+00, -1.890399e-01}, {+0.000000e+00, +0.000000e+00, +1.018958e+00, +1.799999e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +2.126416e-02, +1.018958e+00, +0.000000e+00, +0.000000e+00}, {+1.890399e-01, +1.722575e-01, +0.000000e+00, +0.000000e+00, +1.000000e+00, +1.230120e-01}, {+0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +1.000000e+00}, }); checkTWResults(3.664409209, new double[][] { {+9.012927e-13, +4.935083e-13, +0.000000e+00, +0.000000e+00, +4.411661e-14, -2.755303e-13}, {+4.935083e-13, +2.895197e-13, +0.000000e+00, +0.000000e+00, -1.851520e-15, -3.023743e-13}, {+0.000000e+00, +0.000000e+00, +6.296894e-13, +3.238570e-13, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +3.238570e-13, +1.721507e-13, +0.000000e+00, +0.000000e+00}, {+4.411661e-14, -1.851520e-15, +0.000000e+00, +0.000000e+00, +4.860410e-14, +2.394856e-13}, {-2.755303e-13, -3.023743e-13, +0.000000e+00, +0.000000e+00, +2.394856e-13, +1.599526e-12}, }); } } @Test public void doHorizontalBendTest2() throws InstantiationException, ModelException { probe.reset(); System.out.println("Horizontal N=0.2"); /* EDGE -5.5 9375.67 50 0.45 2.8 50 0; this is a magnet length of 1.8 m BEND -11 9375.67 0.2 50 0 EDGE -5.5 9375.67 50 0.45 2.8 50 0 */ AcceleratorSeq sequence = bend(-5.5, -11, -5.5, 9375.67, 0.2, 50, 0.45, 2.80, 0.45, 2.80, 50, 0); run(sequence); //printResults(); if (initialEnergy == 3e6) { checkELSResults(1.799999E+00, new double[] {6.132800E-03, 5.266670E-03, 5.142904E-03}, new double [] { 1.434713E+01, 1.061625E+01, 7.424592E+00}); checkTWTransferMatrix(new double [][] { {+9.668973e-01, +1.791166e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, -1.723634e-01}, {-3.635045e-02, +9.668973e-01, +0.000000e+00, +0.000000e+00, +0.000000e+00, -1.892739e-01}, {+0.000000e+00, +0.000000e+00, +1.015251e+00, +1.797789e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +1.709594e-02, +1.015251e+00, +0.000000e+00, +0.000000e+00}, {+1.892739e-01, +1.723634e-01, +0.000000e+00, +0.000000e+00, +1.000000e+00, +1.777503e+00}, {+0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +1.000000e+00}, }); checkTWResults(1.003197291, new double[][] { {+3.786796e-11, +1.972151e-11, +0.000000e+00, +0.000000e+00, +1.825838e-12, -9.102212e-13}, {+1.972151e-11, +1.050564e-11, +0.000000e+00, +0.000000e+00, -2.108931e-13, -9.995228e-13}, {+0.000000e+00, +0.000000e+00, +2.765705e-11, +1.418382e-11, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +1.418382e-11, +7.520955e-12, +0.000000e+00, +0.000000e+00}, {+1.825838e-12, -2.108931e-13, +0.000000e+00, +0.000000e+00, +2.683131e-11, +1.126871e-11}, {-9.102212e-13, -9.995228e-13, +0.000000e+00, +0.000000e+00, +1.126871e-11, +5.280827e-12}, }); } if (initialEnergy == 2.5e9) { checkTWTransferMatrix(new double [][] { {+9.668973e-01, +1.791166e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, -1.723634e-01}, {-3.635045e-02, +9.668973e-01, +0.000000e+00, +0.000000e+00, +0.000000e+00, -1.892739e-01}, {+0.000000e+00, +0.000000e+00, +1.015251e+00, +1.797789e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +1.709594e-02, +1.015251e+00, +0.000000e+00, +0.000000e+00}, {+1.892739e-01, +1.723634e-01, +0.000000e+00, +0.000000e+00, +1.000000e+00, +1.230079e-01}, {+0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +1.000000e+00}, }); checkTWResults( 3.664409209, new double[][] { {+9.036177e-13, +4.959792e-13, +0.000000e+00, +0.000000e+00, +4.426517e-14, -2.756997e-13}, {+4.959792e-13, +2.915013e-13, +0.000000e+00, +0.000000e+00, -1.695376e-15, -3.027486e-13}, {+0.000000e+00, +0.000000e+00, +6.278559e-13, +3.219938e-13, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +3.219938e-13, +1.707368e-13, +0.000000e+00, +0.000000e+00}, {+4.426517e-14, -1.695376e-15, +0.000000e+00, +0.000000e+00, +4.861388e-14, +2.394791e-13}, {-2.756997e-13, -3.027486e-13, +0.000000e+00, +0.000000e+00, +2.394791e-13, +1.599526e-12} }); } } @Test public void doVerticalBendTest2() throws InstantiationException, ModelException { probe.reset(); System.out.println("Vertical N=0.9"); /* EDGE -5.5 9375.67 50 0.45 2.8 50 1; this is a magnet length of 1.8 m BEND -11 9375.67 0.9 50 1 EDGE -5.5 9375.67 50 0.45 2.8 50 1 */ AcceleratorSeq sequence = bend(-5.5, -11, -5.5, 9375.67, 0.9, 50, 0.45, 2.80, 0.45, 2.80, 50, 1); run(sequence); //printResults(); if (initialEnergy == 3e6) { checkTWTransferMatrix(new double [][] { {+1.002313e+00, +1.790064e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+2.587002e-03, +1.002313e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +9.796828e-01, +1.798894e+00, +0.000000e+00, -1.727345e-01}, {+0.000000e+00, +0.000000e+00, -2.235906e-02, +9.796828e-01, +0.000000e+00, -1.900943e-01}, {+0.000000e+00, +0.000000e+00, +1.900943e-01, +1.727345e-01, +1.000000e+00, +1.777489e+00}, {+0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +1.000000e+00}, }); checkTWResults(1.003197291, new double[][] { {+3.776964e-11, +2.032777e-11, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+2.032777e-11, +1.112244e-11, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +2.766317e-11, +1.373920e-11, +9.388964e-13, -9.121809e-13}, {+0.000000e+00, +0.000000e+00, +1.373920e-11, +7.129682e-12, -7.619018e-13, -1.003855e-12}, {+0.000000e+00, +0.000000e+00, +9.388964e-13, -7.619018e-13, +2.675914e-11, +1.126863e-11}, {+0.000000e+00, +0.000000e+00, -9.121809e-13, -1.003855e-12, +1.126863e-11, +5.280827e-12}, }); } if (initialEnergy == 2.5e9) { checkTWTransferMatrix(new double [][] { {+1.002313e+00, +1.790064e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+2.587002e-03, +1.002313e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +9.796828e-01, +1.798894e+00, +0.000000e+00, -1.727345e-01}, {+0.000000e+00, +0.000000e+00, -2.235906e-02, +9.796828e-01, +0.000000e+00, -1.900943e-01}, {+0.000000e+00, +0.000000e+00, +1.900943e-01, +1.727345e-01, +1.000000e+00, +1.229937e-01}, {+0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00, +1.000000e+00}, }); checkTWResults( 3.664409209, new double[][] { {+8.574267e-13, +4.614705e-13, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+4.614705e-13, +2.524959e-13, +0.000000e+00, +0.000000e+00, +0.000000e+00, +0.000000e+00}, {+0.000000e+00, +0.000000e+00, +6.721433e-13, +3.604854e-13, +2.413998e-14, -2.762933e-13}, {+0.000000e+00, +0.000000e+00, +3.604854e-13, +2.153225e-13, -1.418668e-14, -3.040608e-13}, {+0.000000e+00, +0.000000e+00, +2.413998e-14, -1.418668e-14, +4.697599e-14, +2.394563e-13}, {+0.000000e+00, +0.000000e+00, -2.762933e-13, -3.040608e-13, +2.394563e-13, +1.599526e-12}, }); } } /** * * @param entry_angle_deg * @param alpha_deg angle in degrees * @param exit_angle_deg * @param rho absolute curvature radius * @param N field Index * @param G gap * @param entrK1 * @param entrK2 * @param exitK1 * @param exitK2 * @param R aperture * @param HV 0 - horizontal, 1 - vertical * @return sequence */ public AcceleratorSeq bend(double entry_angle_deg, double alpha_deg, double exit_angle_deg, double rho, double N, double G, double entrK1, double entrK2, double exitK1, double exitK2, double R, int HV) { AcceleratorSeq sequence = new AcceleratorSeq("BendTest"); // mm -> m rho *= 1e-3; G *= 1e-3; R *= 1e-3; // calculations double len = Math.abs(rho*alpha_deg * Math.PI/180.0); double quadComp = - N / (rho*rho); // following are used to calculate field double c = IConstants.LightSpeed; double e = probe.getSpeciesCharge(); double Er = probe.getSpeciesRestEnergy(); double gamma = probe.getGamma(); double b = probe.getBeta(); double k = b*gamma*Er/(e*c); // = -0.22862458629665997 double B0 = k/rho*Math.signum(alpha_deg); //double B0 = b*gamma*Er/(e*c*rho)*Math.signum(alpha); Bend bend = new Bend("b", HV == 0 ? MagnetType.HORIZONTAL : MagnetType.VERTICAL); bend.setPosition(len*0.5); //always position on center! bend.setLength(len); // both paths are used in calculation bend.getMagBucket().setPathLength(len); bend.getMagBucket().setDipoleEntrRotAngle(-entry_angle_deg); bend.getMagBucket().setBendAngle(alpha_deg); bend.getMagBucket().setDipoleExitRotAngle(-exit_angle_deg); bend.setDfltField(B0); bend.getMagBucket().setDipoleQuadComponent(quadComp); bend.setGap(G); bend.setEntrK1(entrK1); bend.setEntrK2(entrK2); bend.setExitK1(exitK1); bend.setExitK2(exitK2); sequence.addNode(bend); sequence.setLength(len); return sequence; } }
package jdrivesync; import com.google.api.client.auth.oauth2.Credential; import jdrivesync.cli.Options; import jdrivesync.gdrive.CredentialStore; import jdrivesync.gdrive.DriveFactory; import jdrivesync.gdrive.GoogleDriveAdapter; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class BaseClass { private static final Logger LOGGER = Logger.getLogger(ITBasicUpSync.class.getName()); protected Options options; protected GoogleDriveAdapter googleDriveAdapter; protected DriveFactory driveFactory = new DriveFactory(); protected static void beforeClass() { App.initLogging(); } protected void beforeEachTest(String testDirName, DriveFactory driveFactory) { options = createOptions(testDirName); googleDriveAdapter = createGoogleDriveAdapter(options, driveFactory); googleDriveAdapter.deleteAll(); assertThat(googleDriveAdapter.listAll().size(), is(0)); } protected Options createOptions(String testDirName) { Options options = new Options(); options.setAuthenticationFile(Optional.of(Paths.get(System.getProperty("user.dir"), "src", "test", "resources", ".jdrivesync").toString())); options.setLocalRootDir(Optional.of(Paths.get(basePathTestData(), testDirName).toFile())); options.setDeleteFiles(true); return options; } protected GoogleDriveAdapter createGoogleDriveAdapter(Options options, DriveFactory driveFactory) { CredentialStore credentialStore = new CredentialStore(options); Optional<Credential> credentialOptional = credentialStore.load(); assertThat(credentialOptional.isPresent(), is(true)); return new GoogleDriveAdapter(credentialOptional.get(), options, driveFactory); } protected void deleteDirectorySubtree(Path path) throws IOException { if(Files.exists(path)) { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } } protected String basePathTestData() { return Paths.get(System.getProperty("user.dir"), "target").toString(); } protected void sleep() { try { Thread.sleep(15000); } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Sleeping was interrupted: " + e.getMessage(), e); } } }
package org.jetel.component; import java.nio.charset.Charset; import org.apache.log4j.Logger; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.exception.AttributeNotFoundException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.Node; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.ExceptionUtils; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.property.RefResFlag; import org.w3c.dom.Element; public class GenericComponent extends Node { public final static String COMPONENT_TYPE = "GENERIC_COMPONENT"; private static final Logger logger = Logger.getLogger(GenericComponent.class); private static final String XML_GENERIC_TRANSFORM_CLASS_ATTRIBUTE = "genericTransformClass"; private static final String XML_GENERIC_TRANSFORM_ATTRIBUTE = "genericTransform"; private static final String XML_GENERIC_TRANSFORM_URL_ATTRIBUTE = "genericTransformURL"; private static final String XML_CHARSET_ATTRIBUTE = "charset"; private String genericTransformCode = null; private String genericTransformClass = null; private String genericTransformURL = null; private String charset = null; private GenericTransform genericTransform = null; /** * Just for blank reading records that the transformation left unread. */ private DataRecord[] inRecords; public GenericComponent(String id) { super(id); } private void initRecords() { DataRecordMetadata[] inMeta = getInMetadataArray(); inRecords = new DataRecord[inMeta.length]; for (int i = 0; i < inRecords.length; i++) { inRecords[i] = DataRecordFactory.newRecord(inMeta[i]); inRecords[i].init(); } } @Override public void init() throws ComponentNotReadyException { if (isInitialized()) { return; } super.init(); initRecords(); genericTransform = getTransformFactory().createTransform(); genericTransform.init(); } @Override public void preExecute() throws ComponentNotReadyException { super.preExecute(); genericTransform.preExecute(); } @Override public Result execute() throws Exception { try { genericTransform.execute(); } catch (Exception e) { if (ExceptionUtils.instanceOf(e, InterruptedException.class)) { // return as fast as possible when interrupted return Result.ABORTED; } genericTransform.executeOnError(e); } for (int i = 0; i < inRecords.length; i++) { boolean firstUnreadRecord = true; while (readRecord(i, inRecords[i]) != null) { if (firstUnreadRecord) { firstUnreadRecord = false; logger.warn(COMPONENT_TYPE + ": Component had unread records on input port " + i); } // blank read } } return runIt ? Result.FINISHED_OK : Result.ABORTED; } @Override public void postExecute() throws ComponentNotReadyException { super.postExecute(); genericTransform.postExecute(); } @Override public synchronized void free() { super.free(); if (genericTransform != null) { genericTransform.free(); } } /** * You can turn on CTL support in this method. Just change the commented lines accordingly. * @return */ private TransformFactory<GenericTransform> getTransformFactory() { /** This is Java only version */ TransformFactory<GenericTransform> transformFactory = TransformFactory.createTransformFactory(GenericTransform.class); /** This is Java and CTL version */ /* TransformFactory<GenericTransform> transformFactory = TransformFactory.createTransformFactory(GenericTransformDescriptor.newInstance()); transformFactory.setInMetadata(getInMetadata()); transformFactory.setOutMetadata(getOutMetadata()); */ transformFactory.setTransform(genericTransformCode); transformFactory.setTransformClass(genericTransformClass); transformFactory.setTransformUrl(genericTransformURL); transformFactory.setCharset(charset); transformFactory.setComponent(this); return transformFactory; } @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); if (charset != null && !Charset.isSupported(charset)) { status.add(new ConfigurationProblem("Charset " + charset + " not supported!", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL, XML_CHARSET_ATTRIBUTE)); } try { GenericTransform transform = getTransformFactory().createTransform(); transform.checkConfig(status); // delegating to implemented method } catch (org.jetel.exception.LoadClassException e) { status.add(e.getMessage() + " . Make sure to set classpath correctly.", Severity.WARNING, this, Priority.NORMAL); } return status; } /** * Creates new instance of this Component from XML definition. * @param graph * @param xmlElement * @return * @throws XMLConfigurationException * @throws AttributeNotFoundException */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException, AttributeNotFoundException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); GenericComponent genericComponent = new GenericComponent(xattribs.getString(XML_ID_ATTRIBUTE)); genericComponent.setCharset(xattribs.getString(XML_CHARSET_ATTRIBUTE, null)); genericComponent.setGenericTransformCode(xattribs.getStringEx(XML_GENERIC_TRANSFORM_ATTRIBUTE, null, RefResFlag.SPEC_CHARACTERS_OFF)); genericComponent.setGenericTransformURL(xattribs.getStringEx(XML_GENERIC_TRANSFORM_URL_ATTRIBUTE, null, RefResFlag.URL)); genericComponent.setGenericTransformClass(xattribs.getString(XML_GENERIC_TRANSFORM_CLASS_ATTRIBUTE, null)); return genericComponent; } public String getCharset() { return charset; } public void setCharset(String charset) { this.charset = charset; } public String getGenericTransformCode() { return genericTransformCode; } public void setGenericTransformCode(String genericTransformCode) { this.genericTransformCode = genericTransformCode; } public String getGenericTransformClass() { return genericTransformClass; } public void setGenericTransformClass(String genericTransformClass) { this.genericTransformClass = genericTransformClass; } public String getGenericTransformURL() { return genericTransformURL; } public void setGenericTransformURL(String genericTransformURL) { this.genericTransformURL = genericTransformURL; } }
package org.jetel.data.primitive; import java.math.BigDecimal; import org.jetel.data.Defaults; /** * Factory class produce implementations of Decimal interface. * *@author Martin Zatopek *@since November 30, 2005 *@see org.jetel.data.primitive.Decimal */ public class DecimalFactory { /** * How many decimal digits correspond to binary digits */ private static final int BOUNDS_FOR_DECIMAL_IMPLEMENTATION = 9; //FIXME in 1.5 java we can use next two line //private static final double MAGIC_CONST = Math.log(10)/Math.log(2); //private static final int BOUNDS_FOR_DECIMAL_IMPLEMENTATION = (int) Math.floor((Integer.SIZE - 1) / MAGIC_CONST); public static Decimal getDecimal(int value) { Decimal d = getDecimal(10, 0); d.setValue(value); return d; } public static Decimal getDecimal(int value, int precision, int scale) { Decimal d = getDecimal(precision, scale); d.setValue(value); return d; } public static Decimal getDecimal(double value) { BigDecimal bd = new BigDecimal(Double.toString(value)); //FIXME in java 1.5 call BigDecimal.valueof(a.getDouble()) Decimal d = getDecimal(HugeDecimal.precision(bd.unscaledValue()), bd.scale()); //FIXME it's maybe bug, if scale is negative, returned precision is invalid d.setValue(bd); return d; } public static Decimal getDecimal(double value, int precision, int scale) { BigDecimal bd = new BigDecimal(Double.toString(value)); //FIXME in java 1.5 call BigDecimal.valueof(a.getDouble()) Decimal d = getDecimal(precision, scale); d.setValue(bd); return d; } public static Decimal getDecimal(long value) { Decimal d = getDecimal(19, 0); d.setValue(value); return d; } public static Decimal getDecimal(long value, int precision, int scale) { Decimal d = getDecimal(precision, scale); d.setValue(value); return d; } public static Decimal getDecimal(Decimal value, int precision, int scale) { Decimal d = getDecimal(precision, scale); d.setValue(value); return d; } public static Decimal getDecimal() { return getDecimal(Defaults.DataFieldMetadata.DECIMAL_LENGTH, Defaults.DataFieldMetadata.DECIMAL_SCALE); } public static Decimal getDecimal(int precision, int scale) { if(precision <= BOUNDS_FOR_DECIMAL_IMPLEMENTATION && scale <= BOUNDS_FOR_DECIMAL_IMPLEMENTATION) { return new IntegerDecimal(precision, scale); } return new HugeDecimal(null, precision, scale, true); } }
package com.github.json.ui.editors; import java.io.IOException; import java.io.InputStream; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import com.github.json.core.model.INodeElement; import com.github.json.core.util.ModelUtils; import com.github.json.ui.control.JsonTreeViewer; import com.github.json.ui.providers.JsonContentProvider; import com.github.json.ui.providers.JsonLabelProvider; public class JsonEditor extends EditorPart { private JsonTreeViewer viewer; private INodeElement root; public JsonEditor() { } @Override public void doSave(IProgressMonitor monitor) { // TODO Auto-generated method stub } @Override public void doSaveAs() { // TODO Auto-generated method stub } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); if (input instanceof IFileEditorInput) { InputStream is = null; try { IFile file = ((IFileEditorInput) input).getFile(); setPartName(file.getName()); is = file.getContents(); root = ModelUtils.constructModel(is); } catch (Exception e) { MessageDialog.openError(site.getWorkbenchWindow().getShell(), "Parse Json", e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } @Override public boolean isDirty() { // TODO Auto-generated method stub return false; } @Override public boolean isSaveAsAllowed() { // TODO Auto-generated method stub return false; } @Override public void createPartControl(Composite parent) { viewer = new JsonTreeViewer(parent, SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LINE_DASH); viewer.setContentProvider(new JsonContentProvider()); viewer.setLabelProvider(new JsonLabelProvider()); viewer.getTree().setHeaderVisible(true); viewer.getTree().setLinesVisible(true); viewer.addColumns(); if (root != null) { viewer.setInput(root); } } @Override public void setFocus() { // TODO Auto-generated method stub } }
package com.sii.rental.ui.views; import java.util.Collection; import org.eclipse.emf.ecore.EObject; import org.eclipse.jface.viewers.IColorProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Display; import com.opcoach.training.rental.Customer; import com.opcoach.training.rental.Rental; import com.opcoach.training.rental.RentalAgency; import com.opcoach.training.rental.RentalObject; public class RentalProvider extends LabelProvider implements ITreeContentProvider, IColorProvider{ @Override public Object[] getElements(Object inputElement) { Object[] result = null; if (inputElement instanceof Collection<?>) { result=((Collection<?>) inputElement).toArray(); } return result; } @Override public Object[] getChildren(Object parentElement) { if(parentElement instanceof RentalAgency) { RentalAgency a = (RentalAgency) parentElement; return new Node[] { new Node(Node.CUSTOMERS, a), new Node(Node.LOCATIONS, a), new Node(Node.OBJETS__LOUER, a), }; } else if(parentElement instanceof Node) { return ((Node) parentElement).getChildren(); } return null; } @Override public Object getParent(Object element) { if(element instanceof EObject) return ((EObject) element).eContainer(); return null; } @Override public boolean hasChildren(Object element) { return element instanceof RentalAgency || element instanceof Node; } @Override public String getText(Object element) { if(element instanceof RentalAgency) return ((RentalAgency) element).getName(); else if (element instanceof Customer) return ((Customer) element).getDisplayName(); else if(element instanceof RentalObject) { return ((RentalObject) element).getName(); } return super.getText(element); } class Node{ public static final String OBJETS__LOUER = "Objets louer"; public static final String LOCATIONS = "Locations"; public static final String CUSTOMERS = "Customers"; private String title; private RentalAgency a; public Node(String title, RentalAgency a) { super(); this.title = title; this.a = a; } public Object[] getChildren() { if(title==CUSTOMERS) return a.getCustomers().toArray(); else if(title == LOCATIONS) return a.getRentals().toArray(); else if(title == OBJETS__LOUER) return a.getObjectsToRent().toArray(); return null; } @Override public String toString() { return title; } } @Override public Color getForeground(Object element) { if(element instanceof Customer) { return Display.getCurrent().getSystemColor(SWT.COLOR_BLUE); } else if(element instanceof Rental) { return Display.getCurrent().getSystemColor(SWT.COLOR_MAGENTA); } else if(element instanceof RentalObject) { return Display.getCurrent().getSystemColor(SWT.COLOR_GRAY); } return null; } @Override public Color getBackground(Object element) { // TODO Auto-generated method stub return null; } }
package com.versionone.common.sdk; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.ArrayList; import com.versionone.Oid; import com.versionone.apiclient.APIException; import com.versionone.apiclient.Asset; import com.versionone.apiclient.Attribute; import com.versionone.apiclient.IAttributeDefinition; import com.versionone.apiclient.V1Exception; import com.versionone.apiclient.IAttributeDefinition.AttributeType; import com.versionone.common.Activator; public class Workitem { public static final String TASK_PREFIX = "Task"; public static final String STORY_PREFIX = "Story"; public static final String DEFECT_PREFIX = "Defect"; public static final String TEST_PREFIX = "Test"; public static final String PROJECT_PREFIX = "Scope"; public static final String ID_PROPERTY = "Number"; public static final String DETAIL_ESTIMATE_PROPERTY = "DetailEstimate"; public static final String NAME_PROPERTY = "Name"; public static final String STATUS_PROPERTY = "Status"; public static final String EFFORT_PROPERTY = "Actuals"; public static final String DONE_PROPERTY = "Actuals.Value.@Sum"; public static final String SCHEDULE_NAME_PROPERTY = "Schedule.Name"; public static final String OWNERS_PROPERTY = "Owners"; public static final String TODO_PROPERTY = "ToDo"; public static final String DESCRIPTION_PROPERTY = "Description"; public static final String CHECK_QUICK_CLOSE_PROPERTY = "CheckQuickClose"; public static final String CHECK_QUICK_SIGNUP_PROPERTY = "CheckQuickSignup"; protected ApiDataLayer dataLayer = ApiDataLayer.getInstance(); protected Asset asset; public Workitem parent; /** * List of child Workitems. */ public final ArrayList<Workitem> children; public Workitem(Asset asset, Workitem parent) { this.parent = parent; this.asset = asset; children = new ArrayList<Workitem>(asset.getChildren().size()); for (Asset childAsset : asset.getChildren()) { if (dataLayer.isAssetSuspended(childAsset)) { continue; } if (getTypePrefix().equals(PROJECT_PREFIX) || dataLayer.showAllTasks || dataLayer.isCurrentUserOwnerAsset(childAsset)) { children.add(new Workitem(childAsset, this)); } } children.trimToSize(); } public String getTypePrefix() { return asset.getAssetType().getToken(); } public String getId() { if (asset == null) {// temporary return "NULL"; } return asset.getOid().getMomentless().getToken(); } public boolean hasChanges() { return asset.hasChanged(); } public boolean isPropertyReadOnly(String propertyName) { String fullName = getTypePrefix() + '.' + propertyName; try { if (dataLayer.isEffortTrackingRelated(propertyName)) { return isEffortTrackingPropertyReadOnly(propertyName); } return false; } catch (Exception e) { ApiDataLayer.warning("Cannot get property: " + fullName, e); return true; } } public boolean isPropertyDefinitionReadOnly(String propertyName) { String fullName = getTypePrefix() + '.' + propertyName; try { Attribute attribute = asset.getAttributes().get(fullName); return attribute.getDefinition().isReadOnly(); } catch (Exception e) { ApiDataLayer.warning("Cannot get property: " + fullName, e); return true; } } private boolean isEffortTrackingPropertyReadOnly(String propertyName) { if (!dataLayer.isEffortTrackingRelated(propertyName)) { throw new IllegalArgumentException("This property is not related to effort tracking."); } EffortTrackingLevel storyLevel = dataLayer.storyTrackingLevel; EffortTrackingLevel defectLevel = dataLayer.defectTrackingLevel; if (getTypePrefix().equals(STORY_PREFIX)) { return storyLevel != EffortTrackingLevel.PRIMARY_WORKITEM && storyLevel != EffortTrackingLevel.BOTH; } else if (getTypePrefix().equals(DEFECT_PREFIX)) { return defectLevel != EffortTrackingLevel.PRIMARY_WORKITEM && defectLevel != EffortTrackingLevel.BOTH; } else if (getTypePrefix().equals(TASK_PREFIX) || getTypePrefix().equals(TEST_PREFIX)) { EffortTrackingLevel parentLevel; if (parent.getTypePrefix().equals(STORY_PREFIX)) { parentLevel = storyLevel; } else if (parent.getTypePrefix().equals(DEFECT_PREFIX)) { parentLevel = defectLevel; } else { throw new IllegalStateException("Unexpected parent asset type."); } return parentLevel != EffortTrackingLevel.SECONDARY_WORKITEM && parentLevel != EffortTrackingLevel.BOTH; } else { throw new IllegalStateException("Unexpected asset type."); } } private PropertyValues getPropertyValues(String propertyName) { return dataLayer.getListPropertyValues(getTypePrefix(), propertyName); } /** * Checks if property value has changed. * * @param propertyName * Name of the property to get, e.g. "Status" * @return true if property has changed; false - otherwise. */ public boolean isPropertyChanged(String propertyName) throws IllegalArgumentException { if (propertyName.equals(EFFORT_PROPERTY)) { return dataLayer.getEffort(asset) != null; } final String fullName = getTypePrefix() + '.' + propertyName; Attribute attribute = asset.getAttributes().get(fullName); if (attribute == null) { throw new IllegalArgumentException("There is no property: " + fullName); } return attribute.hasChanged(); } /** * Resets property value if it was changed. * * @param propertyName * Name of the property to get, e.g. "Status" */ public void resetProperty(String propertyName) throws IllegalArgumentException { if (propertyName.equals(EFFORT_PROPERTY)) { dataLayer.setEffort(asset, null); } final String fullName = getTypePrefix() + '.' + propertyName; Attribute attribute = asset.getAttributes().get(fullName); if (attribute == null) { throw new IllegalArgumentException("There is no property: " + fullName); } attribute.rejectChanges(); } public Object getProperty(String propertyName) throws IllegalArgumentException { if (propertyName.equals(EFFORT_PROPERTY)) { return dataLayer.getEffort(asset); } final String fullName = getTypePrefix() + '.' + propertyName; Attribute attribute = asset.getAttributes().get(fullName); if (attribute == null) { throw new IllegalArgumentException("There is no property: " + fullName); } if (attribute.getDefinition().isMultiValue()) { return getPropertyValues(propertyName).subset(attribute.getValues()); } try { Object val = attribute.getValue(); if (val instanceof Oid) { return getPropertyValues(propertyName).find((Oid) val); } if (val instanceof Double) { return BigDecimal.valueOf((Double) val).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(); } return val; } catch (APIException e) { throw new IllegalArgumentException("Cannot get property: " + propertyName, e); } } public String getPropertyAsString(String propertyName) throws IllegalArgumentException { Object value = getProperty(propertyName); if (value == null) { return ""; } else if (value instanceof Double) { // return numberFormat.format(value); return BigDecimal.valueOf((Double) value).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(); } return value.toString(); } /** * Sets property value. * * @param propertyName * Short name of the property to set, e.g. "Name". * @param newValue * String, Double, null, ValueId, PropertyValues accepted. */ public void setProperty(String propertyName, Object newValue) { final boolean isEffort = propertyName.equals(EFFORT_PROPERTY); try { if ("".equals(newValue)) { newValue = null; } if ((isEffort || isNumeric(propertyName))) { setNumericProperty(propertyName, newValue); } else if (isMultiValue(propertyName)) { setMultiValueProperty(propertyName, (PropertyValues) newValue); } else {// List & String types if (newValue instanceof ValueId) { newValue = ((ValueId) newValue).oid; } setPropertyInternal(propertyName, newValue); } } catch (Exception ex) { ApiDataLayer.warning("Cannot set property " + propertyName + " of " + this, ex); } } private boolean isMultiValue(String propertyName) { final IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); return attrDef.isMultiValue(); } private boolean isNumeric(String propertyName) { final IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); return attrDef.getAttributeType() == AttributeType.Numeric; } private void setNumericProperty(String propertyName, Object newValue) throws APIException { Double doubleValue = null; if (newValue != null) { // newValue = numberFormat.parse((String) newValue); doubleValue = Double.parseDouble(BigDecimal.valueOf(Double.parseDouble((String) newValue)).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); } if (propertyName.equals(EFFORT_PROPERTY)) { dataLayer.setEffort(asset, doubleValue); } else { if (doubleValue < 0) { throw new IllegalArgumentException("The field cannot be negative"); } setPropertyInternal(propertyName, doubleValue); } } private void setPropertyInternal(String propertyName, Object newValue) throws APIException { final Attribute attribute = asset.getAttributes().get(getTypePrefix() + '.' + propertyName); final Object oldValue = attribute.getValue(); if ((oldValue == null && newValue != null) || !oldValue.equals(newValue)) { asset.setAttributeValue(asset.getAssetType().getAttributeDefinition(propertyName), newValue); } } private void setMultiValueProperty(String propertyName, PropertyValues newValues) throws APIException { final Attribute attribute = asset.getAttributes().get(getTypePrefix() + '.' + propertyName); final Object[] oldValues = attribute.getValues(); final IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); for (Object oldOid : oldValues) { if (!newValues.containsOid((Oid) oldOid)) { asset.removeAttributeValue(attrDef, oldOid); } } for (ValueId newValue : newValues) { if (!checkContains(oldValues, newValue.oid)) { asset.addAttributeValue(attrDef, newValue.oid); } } } private boolean checkContains(Object[] array, Object value) { for (Object item : array) { if (item.equals(value)) return true; } return false; } public boolean propertyChanged(String propertyName) { IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); return asset.getAttribute(attrDef).hasChanged(); } public void commitChanges() throws DataLayerException { try { dataLayer.commitAsset(asset); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to commit changes of workitem: " + this, e); } } public boolean isMine() { PropertyValues owners = (PropertyValues) getProperty(OWNERS_PROPERTY); return owners.containsOid(dataLayer.memberOid); } public boolean canQuickClose() { try { return (Boolean) getProperty("CheckQuickClose"); } catch (IllegalArgumentException e) { ApiDataLayer.warning("QuickClose not supported.", e); return false; } catch (NullPointerException e) { ApiDataLayer.warning("QuickClose not supported.", e); return false; } } /** * Performs 'QuickClose' operation. * * @throws DataLayerException */ public void quickClose() throws DataLayerException { commitChanges(); try { dataLayer.executeOperation(asset, asset.getAssetType().getOperation(ApiDataLayer.OP_QUICK_CLOSE)); dataLayer.addIgnoreRecursively(this); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to QuickClose workitem: " + this, e); } } public boolean canSignup() { try { return (Boolean) getProperty("CheckQuickSignup"); } catch (IllegalArgumentException e) { ApiDataLayer.warning("QuickSignup not supported.", e); return false; } catch (NullPointerException e) { ApiDataLayer.warning("QuickClose not supported.", e); return false; } } /** * Performs 'QuickSignup' operation. * * @throws DataLayerException */ public void signup() throws DataLayerException { try { dataLayer.executeOperation(asset, asset.getAssetType().getOperation(ApiDataLayer.OP_SIGNUP)); dataLayer.refreshAsset(this); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to QuickSignup workitem: " + this, e); } } /** * Perform 'Inactivate' operation. * * @throws DataLayerException */ public void close() throws DataLayerException { try { dataLayer.executeOperation(asset, asset.getAssetType().getOperation(ApiDataLayer.OP_CLOSE)); dataLayer.addIgnoreRecursively(this); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to Close workitem: " + this, e); } } public void revertChanges() { dataLayer.revertAsset(asset); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof Workitem)) { return false; } Workitem other = (Workitem) obj; if (!other.asset.getOid().equals(asset.getOid())) { return false; } return true; } @Override public int hashCode() { return asset.getOid().hashCode(); } @Override public String toString() { return getId() + (asset.hasChanged() ? " (Changed)" : ""); } }
package cgeo.geocaching; import cgeo.CGeoTestCase; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.gc.GCLogin; import cgeo.geocaching.connector.gc.GCParser; import cgeo.geocaching.connector.gc.MapTokens; import cgeo.geocaching.connector.gc.Tile; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.loaders.RecaptchaReceiver; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.settings.TestSettings; import cgeo.geocaching.test.RegExPerformanceTest; import cgeo.geocaching.test.mock.GC1ZXX2; import cgeo.geocaching.test.mock.GC2CJPF; import cgeo.geocaching.test.mock.GC2JVEH; import cgeo.geocaching.test.mock.MockedCache; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.Log; import cgeo.test.Compare; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import java.util.GregorianCalendar; import junit.framework.Assert; /** * The c:geo application test. It can be used for tests that require an * application and/or context. */ public class CgeoApplicationTest extends CGeoTestCase { private static final MapTokens INVALID_TOKEN = null; /** * The name 'test preconditions' is a convention to signal that if this test * doesn't pass, the test case was not set up properly and it might explain * any and all failures in other tests. This is not guaranteed to run before * other tests, as junit uses reflection to find the tests. */ @SuppressWarnings("static-method") @SmallTest public void testPreconditions() { assertEquals(StatusCode.NO_ERROR, GCLogin.getInstance().login()); } /** * Test {@link GCParser#searchTrackable(String, String, String)} */ @MediumTest public static void testSearchTrackableNotExisting() { final Trackable tb = GCParser.searchTrackable("123456", null, null); assertNull(tb); } /** * Test {@link GCParser#searchTrackable(String, String, String)} */ @MediumTest public static void testSearchTrackable() { final Trackable tb = GCParser.searchTrackable("TB2J1VZ", null, null); assertNotNull(tb); assert (tb != null); // eclipse bug // fix data assertEquals("aefffb86-099f-444f-b132-605436163aa8", tb.getGuid()); assertEquals("TB2J1VZ", tb.getGeocode()); assertEquals("http: assertEquals("blafoo's Children Music CD", tb.getName()); assertEquals("Travel Bug Dog Tag", tb.getType()); assertEquals(new GregorianCalendar(2009, 8 - 1, 24).getTime(), tb.getReleased()); assertEquals("Niedersachsen, Germany", tb.getOrigin()); assertEquals("blafoo", tb.getOwner()); assertEquals("0564a940-8311-40ee-8e76-7e91b2cf6284", tb.getOwnerGuid()); assertEquals("Kinder erfreuen.<br /><br />Make children happy.", tb.getGoal()); assertTrue(tb.getDetails().startsWith("Auf der CD sind")); assertEquals("http://imgcdn.geocaching.com/track/display/38382780-87a7-4393-8393-78841678ee8c.jpg", tb.getImage()); // Following data can change over time assertTrue(tb.getDistance() >= 10617.8f); assertTrue(tb.getLogs().size() >= 10); assertTrue(Trackable.SPOTTED_CACHE == tb.getSpottedType() || Trackable.SPOTTED_USER == tb.getSpottedType()); // no assumption possible: assertEquals("faa2d47d-19ea-422f-bec8-318fc82c8063", tb.getSpottedGuid()); // no assumption possible: assertEquals("Nice place for a break cache", tb.getSpottedName()); // we can't check specifics in the log entries since they change, but we can verify data was parsed for (LogEntry log : tb.getLogs()) { assertTrue(log.date > 0); assertTrue(StringUtils.isNotEmpty(log.author)); if (log.type == LogType.PLACED_IT || log.type == LogType.RETRIEVED_IT) { assertTrue(StringUtils.isNotEmpty(log.cacheName)); assertTrue(StringUtils.isNotEmpty(log.cacheGuid)); } else { assertTrue(log.type != LogType.UNKNOWN); } } } /** * Test {@link GCParser#searchByGeocode(String, String, int, boolean, CancellableHandler)} */ @MediumTest public static Geocache testSearchByGeocode(final String geocode) { final SearchResult search = Geocache.searchByGeocode(geocode, null, 0, true, null); assertNotNull(search); if (Settings.isGCPremiumMember() || search.getError() == null) { assertEquals(1, search.getGeocodes().size()); assertTrue(search.getGeocodes().contains(geocode)); return DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); } assertEquals(0, search.getGeocodes().size()); return null; } /** * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} */ @MediumTest public static void testSearchByGeocodeNotExisting() { final SearchResult search = Geocache.searchByGeocode("GC123456", null, 0, true, null); assertNotNull(search); assertEquals(StatusCode.COMMUNICATION_ERROR, search.getError()); } /** * Set the login data to the cgeo login, run the given Runnable, and restore the login. * * @param runnable */ private static void withMockedLoginDo(final Runnable runnable) { final ImmutablePair<String, String> login = Settings.getGcCredentials(); final String memberStatus = Settings.getGCMemberStatus(); try { runnable.run(); } finally { // restore user and password TestSettings.setLogin(login.left, login.right); Settings.setGCMemberStatus(memberStatus); GCLogin.getInstance().login(); } } /** * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} */ @MediumTest public static void testSearchByGeocodeNotLoggedIn() { withMockedLoginDo(new Runnable() { public void run() { // non premium cache MockedCache cache = new GC2CJPF(); deleteCacheFromDBAndLogout(cache.getGeocode()); SearchResult search = Geocache.searchByGeocode(cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null); assertNotNull(search); assertEquals(1, search.getGeocodes().size()); assertTrue(search.getGeocodes().contains(cache.getGeocode())); final Geocache searchedCache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); // coords must be null if the user is not logged in assertNotNull(searchedCache); assert (searchedCache != null); // eclipse bug assertNull(searchedCache.getCoords()); // premium cache. Not visible to guests cache = new GC2JVEH(); deleteCacheFromDBAndLogout(cache.getGeocode()); search = Geocache.searchByGeocode(cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null); assertNotNull(search); assertEquals(0, search.getGeocodes().size()); } }); } /** * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} */ @MediumTest public static void testSearchErrorOccured() { withMockedLoginDo(new Runnable() { public void run() { // non premium cache final MockedCache cache = new GC1ZXX2(); deleteCacheFromDBAndLogout(cache.getGeocode()); final SearchResult search = Geocache.searchByGeocode(cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null); assertNotNull(search); assertEquals(0, search.getGeocodes().size()); } }); } /** * mock the "exclude disabled caches" and "exclude my caches" options for the execution of the runnable * * @param runnable */ private static void withMockedFilters(Runnable runnable) { // backup user settings final boolean excludeMine = Settings.isExcludeMyCaches(); final boolean excludeDisabled = Settings.isExcludeDisabledCaches(); try { // set up settings required for test TestSettings.setExcludeMine(false); TestSettings.setExcludeDisabledCaches(false); runnable.run(); } finally { // restore user settings TestSettings.setExcludeMine(excludeMine); TestSettings.setExcludeDisabledCaches(excludeDisabled); } } /** * Test {@link GCParser#searchByCoords(Geopoint, CacheType, boolean, RecaptchaReceiver)} */ @MediumTest public static void testSearchByCoords() { withMockedFilters(new Runnable() { @Override public void run() { final SearchResult search = GCParser.searchByCoords(new Geopoint("N 52° 24.972 E 009° 35.647"), CacheType.MYSTERY, false, null); assertNotNull(search); assertTrue(20 <= search.getGeocodes().size()); assertTrue(search.getGeocodes().contains("GC1RMM2")); } }); } /** * Test {@link GCParser#searchByOwner(String, CacheType, boolean, RecaptchaReceiver)} */ @MediumTest public static void testSearchByOwner() { withMockedFilters(new Runnable() { @Override public void run() { final SearchResult search = GCParser.searchByOwner("blafoo", CacheType.MYSTERY, false, null); assertNotNull(search); assertEquals(3, search.getGeocodes().size()); assertTrue(search.getGeocodes().contains("GC36RT6")); } }); } /** * Test {@link GCParser#searchByUsername(String, CacheType, boolean, RecaptchaReceiver)} */ @MediumTest public static void testSearchByUsername() { withMockedFilters(new Runnable() { @Override public void run() { final SearchResult search = GCParser.searchByUsername("blafoo", CacheType.WEBCAM, false, null); assertNotNull(search); assertEquals(4, search.getTotalCountGC()); assertTrue(search.getGeocodes().contains("GCP0A9")); } }); } /** * Test {@link ConnectorFactory#searchByViewport(Viewport, String)} */ @MediumTest public static void testSearchByViewport() { withMockedFilters(new Runnable() { @Override public void run() { // backup user settings final Strategy strategy = Settings.getLiveMapStrategy(); final CacheType cacheType = Settings.getCacheType(); try { // set up settings required for test TestSettings.setExcludeMine(false); Settings.setCacheType(CacheType.ALL); final GC2CJPF mockedCache = new GC2CJPF(); deleteCacheFromDB(mockedCache.getGeocode()); final MapTokens tokens = GCLogin.getInstance().getMapTokens(); final Viewport viewport = new Viewport(mockedCache, 0.003, 0.003); // check coords for DETAILED Settings.setLiveMapStrategy(Strategy.DETAILED); SearchResult search = ConnectorFactory.searchByViewport(viewport, tokens).toBlockingObservable().single(); assertNotNull(search); assertTrue(search.getGeocodes().contains(mockedCache.getGeocode())); Geocache parsedCache = DataStore.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); assertEquals(Settings.isGCPremiumMember(), mockedCache.getCoords().equals(parsedCache.getCoords())); assertEquals(Settings.isGCPremiumMember(), parsedCache.isReliableLatLon()); // check update after switch strategy to FAST Settings.setLiveMapStrategy(Strategy.FAST); Tile.Cache.removeFromTileCache(mockedCache); search = ConnectorFactory.searchByViewport(viewport, tokens).toBlockingObservable().single(); assertNotNull(search); assertTrue(search.getGeocodes().contains(mockedCache.getGeocode())); parsedCache = DataStore.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); assertEquals(Settings.isGCPremiumMember(), mockedCache.getCoords().equals(parsedCache.getCoords())); assertEquals(Settings.isGCPremiumMember(), parsedCache.isReliableLatLon()); } finally { // restore user settings Settings.setLiveMapStrategy(strategy); Settings.setCacheType(cacheType); } } }); } /** * Test {@link ConnectorFactory#searchByViewport(Viewport, String)} */ @MediumTest public static void testSearchByViewportNotLoggedIn() { withMockedLoginDo(new Runnable() { public void run() { final Strategy strategy = Settings.getLiveMapStrategy(); final Strategy testStrategy = Strategy.FAST; // FASTEST, FAST or DETAILED for tests Settings.setLiveMapStrategy(testStrategy); final CacheType cacheType = Settings.getCacheType(); try { // non premium cache MockedCache cache = new GC2CJPF(); deleteCacheFromDBAndLogout(cache.getGeocode()); Tile.Cache.removeFromTileCache(cache); Settings.setCacheType(CacheType.ALL); Viewport viewport = new Viewport(cache, 0.003, 0.003); SearchResult search = ConnectorFactory.searchByViewport(viewport, INVALID_TOKEN).toBlockingObservable().single(); assertNotNull(search); assertTrue(search.getGeocodes().contains(cache.getGeocode())); // coords differ final Geocache cacheFromViewport = DataStore.loadCache(cache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); Log.d("cgeoApplicationTest.testSearchByViewportNotLoggedIn: Coords expected = " + cache.getCoords()); Log.d("cgeoApplicationTest.testSearchByViewportNotLoggedIn: Coords actual = " + cacheFromViewport.getCoords()); assertFalse(cache.getCoords().distanceTo(cacheFromViewport.getCoords()) <= 1e-3); // depending on the chosen strategy the coords can be reliable or not assertEquals(testStrategy == Strategy.DETAILED, cacheFromViewport.isReliableLatLon()); // premium cache cache = new GC2JVEH(); deleteCacheFromDBAndLogout(cache.getGeocode()); viewport = new Viewport(cache, 0.003, 0.003); search = ConnectorFactory.searchByViewport(viewport, INVALID_TOKEN).toBlockingObservable().single(); assertNotNull(search); // In the meantime, premium-member caches are also shown on map when not logged in assertTrue(search.getGeocodes().contains(cache.getGeocode())); } finally { Settings.setLiveMapStrategy(strategy); Settings.setCacheType(cacheType); } } }); } /** * Test cache parsing. Esp. useful after a GC.com update */ public static void testSearchByGeocodeBasis() { for (MockedCache mockedCache : RegExPerformanceTest.MOCKED_CACHES) { String oldUser = mockedCache.getMockedDataUser(); try { mockedCache.setMockedDataUser(Settings.getUsername()); Geocache parsedCache = CgeoApplicationTest.testSearchByGeocode(mockedCache.getGeocode()); if (null != parsedCache) { Compare.assertCompareCaches(mockedCache, parsedCache, true); } } finally { mockedCache.setMockedDataUser(oldUser); } } } /** * Caches that are good test cases */ public static void testSearchByGeocodeSpecialties() { final Geocache GCV2R9 = CgeoApplicationTest.testSearchByGeocode("GCV2R9"); Assert.assertEquals("California, United States", GCV2R9.getLocation()); final Geocache GC1ZXEZ = CgeoApplicationTest.testSearchByGeocode("GC1ZXEZ"); Assert.assertEquals("Ms.Marple/Mr.Stringer", GC1ZXEZ.getOwnerUserId()); } /** Remove cache from DB and cache to ensure that the cache is not loaded from the database */ private static void deleteCacheFromDBAndLogout(String geocode) { deleteCacheFromDB(geocode); GCLogin.getInstance().logout(); // Modify login data to avoid an automatic login again TestSettings.setLogin("c:geo", "c:geo"); Settings.setGCMemberStatus("Basic member"); } }
package org.jetel.component; import java.io.IOException; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.DynamicRecordBuffer; import org.jetel.data.RecordKey; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; /** * <h3>Dedup Component</h3> * * <!-- Removes duplicates (based on specified key) from data flow of sorted records--> * * <table border="1"> * <th>Component:</th> * <tr><td><h4><i>Name:</i></h4></td> * <td>Dedup</td></tr> * <tr><td><h4><i>Category:</i></h4></td> * <td></td></tr> * <tr><td><h4><i>Description:</i></h4></td> * <td>Dedup (remove duplicate records) from sorted incoming records based on specified key.<br> * The key is name (or combination of names) of field(s) from input record. * It keeps either First or Last record from the group based on the parameter <emp>{keep}</emp> specified. * All duplicated records are rejected to the second optional port.</td></tr> * <tr><td><h4><i>Inputs:</i></h4></td> * <td>[0]- input records</td></tr> * <tr><td><h4><i>Outputs:</i></h4></td> * <td>[0]- result of deduplication</td></tr> * <td>[0]- all rejected records</td></tr> * <tr><td><h4><i>Comment:</i></h4></td> * <td></td></tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"DEDUP"</td></tr> * <tr><td><b>id</b></td><td>component identification</td> * <tr><td><b>dedupKey</b></td><td>field names separated by :;| {colon, semicolon, pipe} or can be empty, then all records belong to one group</td> * <tr><td><b>keep</b></td><td>one of "First|Last|Unique" {the fist letter is sufficient, if not defined, then First}</td></tr> * <tr><td><b>equalNULL</b><br><i>optional</i></td><td>specifies whether two fields containing NULL values are considered equal. Default is TRUE.</td></tr> * <tr><td><b>noDupRecord</b><br><i>optional</i></td><td>number of duplicate record to be written to out port. Default is 1.</td></tr> * </table> * * <h4>Example:</h4> * <pre>&lt;Node id="DISTINCT" type="DEDUP" dedupKey="Name" keep="First"/&gt;</pre> * * @author dpavlis * @since April 4, 2002 * @revision $Revision$ */ public class Dedup extends Node { private static final String XML_KEEP_ATTRIBUTE = "keep"; private static final String XML_DEDUPKEY_ATTRIBUTE = "dedupKey"; private static final String XML_EQUAL_NULL_ATTRIBUTE = "equalNULL"; private static final String XML_NO_DUP_RECORD_ATTRIBUTE = "noDupRecord"; /** Description of the Field */ public final static String COMPONENT_TYPE = "DEDUP"; private final static int READ_FROM_PORT = 0; private final static int WRITE_TO_PORT = 0; private final static int REJECTED_PORT = 1; private final static int KEEP_FIRST = 1; private final static int KEEP_LAST = -1; private final static int KEEP_UNIQUE = 0; private final static int DEFAULT_NO_DUP_RECORD = 1; private int keep; private String[] dedupKeys; private RecordKey recordKey; private boolean equalNULLs = true; private boolean hasRejectedPort; // number of duplicate record to be written to out port private int noDupRecord = DEFAULT_NO_DUP_RECORD; //runtime variables int current; int previous; boolean isFirst; InputPort inPort; DataRecord[] records; /** *Constructor for the Dedup object * * @param id unique id of the component * @param dedupKeys definitio of key fields used to compare records * @param keep (1 - keep first; 0 - keep unique; -1 - keep last) */ public Dedup(String id, String[] dedupKeys, int keep) { super(id); this.keep = keep; this.dedupKeys = dedupKeys; } /** * Gets the change attribute of the Dedup object * * @param a Description of the Parameter * @param b Description of the Parameter * @return The change value */ private final boolean isChange(DataRecord a, DataRecord b) { if(recordKey != null) { return (recordKey.compare(a, b) != 0); } else { return false; } } @Override public Result execute() throws Exception { isFirst = true; // special treatment for 1st record inPort = getInputPort(READ_FROM_PORT); records = new DataRecord[2]; records[0] = new DataRecord(inPort.getMetadata()); records[0].init(); records[1] = new DataRecord(inPort.getMetadata()); records[1].init(); current = 1; previous = 0; if (dedupKeys == null) { writeAllRecordsToOutPort(); } else { switch(keep) { case KEEP_FIRST: executeFirst(); break; case KEEP_LAST: executeLast(); break; case KEEP_UNIQUE: executeUnique(); break; } } broadcastEOF(); return runIt ? Result.FINISHED_OK : Result.ABORTED; } /** * Execution a de-duplication with first function. * * @throws IOException * @throws InterruptedException */ private void executeFirst() throws IOException, InterruptedException { int groupItems = 0; while (runIt && (records[current] = inPort.readRecord(records[current])) != null) { if (isFirst) { writeOutRecord(records[current]); groupItems++; isFirst = false; } else { if (isChange(records[current], records[previous])) { writeOutRecord(records[current]); groupItems = 1; } else { if (groupItems < noDupRecord) { writeOutRecord(records[current]); groupItems++; } else { writeRejectedRecord(records[current]); } } } // swap indexes current = current ^ 1; previous = previous ^ 1; } } /** * Execution a de-duplication with last function. * * @throws IOException * @throws InterruptedException */ public void executeLast() throws IOException, InterruptedException { RingRecordBuffer ringBuffer = new RingRecordBuffer(noDupRecord, inPort.getMetadata()); ringBuffer.init(); while (runIt && (records[current] = inPort.readRecord(records[current])) != null) { if (isFirst) { isFirst = false; } else { if (isChange(records[current], records[previous])) { ringBuffer.flushRecords(); ringBuffer.clear(); } } ringBuffer.writeRecord(records[current]); // swap indexes current = current ^ 1; previous = previous ^ 1; } ringBuffer.flushRecords(); ringBuffer.free(); } /** * Execution a de-duplication with unique function. * * @throws IOException * @throws InterruptedException */ public void executeUnique() throws IOException, InterruptedException { int groupItems = 0; while (records[current] != null && runIt) { records[current] = inPort.readRecord(records[current]); if (records[current] != null) { if (isFirst) { isFirst = false; } else { if (isChange(records[current], records[previous])) { if (groupItems == 1) { writeOutRecord(records[previous]); } else { writeRejectedRecord(records[previous]); } groupItems = 0; } else { writeRejectedRecord(records[previous]); } } groupItems++; // swap indexes current = current ^ 1; previous = previous ^ 1; } else { if (!isFirst) { if(groupItems == 1) { writeOutRecord(records[previous]); } else { writeRejectedRecord(records[previous]); } } } } } /** * Write all records to output port. * Uses when all records belong to one group. * * @throws IOException * @throws InterruptedException */ private void writeAllRecordsToOutPort() throws IOException, InterruptedException { while (runIt && (records[0] = inPort.readRecord(records[0])) != null) { writeOutRecord(records[0]); } } /** * Tries to write given record to the rejected port, if is connected. * @param record * @throws InterruptedException * @throws IOException */ private void writeRejectedRecord(DataRecord record) throws IOException, InterruptedException { if(hasRejectedPort) { writeRecord(REJECTED_PORT, record); } } /** * Writes given record to the out port. * * @param record * @throws InterruptedException * @throws IOException */ private void writeOutRecord(DataRecord record) throws IOException, InterruptedException { writeRecord(WRITE_TO_PORT, record); } /** * Description of the Method * * @exception ComponentNotReadyException * Description of the Exception * @since April 4, 2002 */ public void init() throws ComponentNotReadyException { if(isInitialized()) return; super.init(); if(dedupKeys != null) { recordKey = new RecordKey(dedupKeys, getInputPort(READ_FROM_PORT).getMetadata()); recordKey.init(); // for DEDUP component, specify whether two fields with NULL // value indicator set are considered equal recordKey.setEqualNULLs(equalNULLs); } hasRejectedPort = (getOutPorts().size() == 2); if (noDupRecord < 1) { throw new ComponentNotReadyException(this, StringUtils.quote(XML_NO_DUP_RECORD_ATTRIBUTE) + " must be positive number."); } } /** * Description of the Method * * @return Description of the Returned Value * @since May 21, 2002 */ @Override public void toXML(Element xmlElement) { super.toXML(xmlElement); // dedupKeys attribute if (dedupKeys != null) { String keys = this.dedupKeys[0]; for (int i=1; i<this.dedupKeys.length; i++) { keys += Defaults.Component.KEY_FIELDS_DELIMITER + this.dedupKeys[i]; } xmlElement.setAttribute(XML_DEDUPKEY_ATTRIBUTE,keys); } // keep attribute switch(this.keep){ case KEEP_FIRST: xmlElement.setAttribute(XML_KEEP_ATTRIBUTE, "First"); break; case KEEP_LAST: xmlElement.setAttribute(XML_KEEP_ATTRIBUTE, "Last"); break; case KEEP_UNIQUE: xmlElement.setAttribute(XML_KEEP_ATTRIBUTE, "Unique"); break; } // equal NULL attribute xmlElement.setAttribute(XML_EQUAL_NULL_ATTRIBUTE, String.valueOf(equalNULLs)); if (noDupRecord != DEFAULT_NO_DUP_RECORD) { xmlElement.setAttribute(XML_NO_DUP_RECORD_ATTRIBUTE, String.valueOf(noDupRecord)); } } /** * Description of the Method * * @param nodeXML Description of Parameter * @return Description of the Returned Value * @since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); Dedup dedup; try { String dedupKey = xattribs.getString(XML_DEDUPKEY_ATTRIBUTE, null); dedup=new Dedup(xattribs.getString(XML_ID_ATTRIBUTE), dedupKey != null ? dedupKey.split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX) : null, xattribs.getString(XML_KEEP_ATTRIBUTE).matches("^[Ff].*") ? KEEP_FIRST : xattribs.getString(XML_KEEP_ATTRIBUTE).matches("^[Ll].*") ? KEEP_LAST : KEEP_UNIQUE); if (xattribs.exists(XML_EQUAL_NULL_ATTRIBUTE)){ dedup.setEqualNULLs(xattribs.getBoolean(XML_EQUAL_NULL_ATTRIBUTE)); } if (xattribs.exists(XML_NO_DUP_RECORD_ATTRIBUTE)){ dedup.setNumberRecord(xattribs.getInteger(XML_NO_DUP_RECORD_ATTRIBUTE)); } } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } return dedup; } /** Description of the Method */ @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); checkInputPorts(status, 1, 1); checkOutputPorts(status, 1, 2); checkMetadata(status, getInputPort(READ_FROM_PORT).getMetadata(), getOutMetadata()); try { init(); } catch (ComponentNotReadyException e) { ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); if(!StringUtils.isEmpty(e.getAttributeName())) { problem.setAttributeName(e.getAttributeName()); } status.add(problem); } finally { free(); } return status; } public String getType(){ return COMPONENT_TYPE; } public void setEqualNULLs(boolean equal){ this.equalNULLs=equal; } public void setNumberRecord(int numberRecord) { this.noDupRecord = numberRecord; } private class RingRecordBuffer { private DynamicRecordBufferExt recordBuffer; private DataRecordMetadata metadata; /** * Max number of records presented in buffer. * State (number of records) before or after call any of method. */ private long sizeOfBuffer; /** * @param sizeOfBuffer max number of records presented in buffer * @param metadata metadat of records that will be stored in buffer. */ public RingRecordBuffer(long sizeOfBuffer, DataRecordMetadata metadata) { this.sizeOfBuffer = sizeOfBuffer; this.metadata = metadata; } /** * Initializes the buffer. * Must be called before any write or read operation is performed. */ public void init() { recordBuffer = new DynamicRecordBufferExt(); recordBuffer.init(); } /** * Closes buffer, removes temporary file (is exists). */ public void free() { try { recordBuffer.close(); } catch (IOException e) { //do nothing } } /** * Adds record to the ring buffer - when buffer is full then the oldest * record in buffer is removed and pass to writeRejectedRecord() method. * @param record record that will be added to the ring buffer * @throws IOException * @throws InterruptedException */ public void writeRecord(DataRecord record) throws IOException, InterruptedException { recordBuffer.writeRecord(record); if (recordBuffer.getBufferedRecords() > sizeOfBuffer) { if (!recordBuffer.hasData()) { recordBuffer.swapBuffers(); } DataRecord rejectedRecord = new DataRecord(metadata); rejectedRecord.init(); rejectedRecord = recordBuffer.readRecord(rejectedRecord); writeRejectedRecord(rejectedRecord); } } /** * Flush all records from buffer to out port. * @throws IOException * @throws InterruptedException */ public void flushRecords() throws IOException, InterruptedException { DataRecord record = new DataRecord(metadata); record.init(); while (recordBuffer.getBufferedRecords() > 0) { if (!recordBuffer.hasData()) { recordBuffer.swapBuffers(); } record = recordBuffer.readRecord(record); writeOutRecord(record); } } /** * Clears the buffer. Temp file (if it was created) remains * unchanged size-wise */ public void clear() { recordBuffer.clear(); } } private class DynamicRecordBufferExt extends DynamicRecordBuffer { public DynamicRecordBufferExt() { super(Defaults.Graph.BUFFERED_EDGE_INTERNAL_BUFFER_SIZE); } /** * Remove data from writeDataBuffer and put it to readDataBuffer. */ public void swapBuffers() { swapWriteBufferToReadBuffer(); } } }
package info.tregmine.api; import info.tregmine.database.Mysql; import java.sql.ResultSet; import java.util.HashMap; //import java.util.Map; import org.bukkit.ChatColor; //import org.bukkit.GameMode; import org.bukkit.block.Block; import org.bukkit.entity.Player; public class TregminePlayer extends PlayerDelegate { private HashMap<String,String> settings = new HashMap<String,String>(); private HashMap<String,Block> block = new HashMap<String,Block>(); private HashMap<String,Integer> integer = new HashMap<String,Integer>(); // private HashMap<String,Location> location = new HashMap<String,Location>(); private int id = 0; private String name; private final Mysql mysql = new Mysql(); private Zone currentZone = null; public TregminePlayer(Player player, String _name) { super(player); this.name = _name; } public boolean exists() { this.mysql.connect(); if (this.mysql.connect != null) { try { String SQL = "SELECT COUNT(*) as count FROM user WHERE player = '"+ name +"';"; this.mysql.statement.executeQuery(SQL); ResultSet rs = this.mysql.statement.getResultSet(); rs.first(); if ( rs.getInt("count") != 1 ) { this.mysql.close(); return false; } else { this.mysql.close(); return true; } } catch (Exception e) { throw new RuntimeException(e); } } this.mysql.close(); return false; } public void load() { settings.clear(); // System.out.println("Loading settings for " + name); mysql.connect(); if (this.mysql.connect != null) { try { this.mysql.connect(); this.mysql.statement.executeQuery("SELECT * FROM user JOIN (user_settings) WHERE uid=id and player = '" + name + "';"); ResultSet rs = this.mysql.statement.getResultSet(); while (rs.next()) { //TODO: Make this much nicer, this is bad code this.id = rs.getInt("uid"); settings.put("uid", rs.getString("uid")); settings.put(rs.getString("key"), rs.getString("value")); } this.mysql.close(); } catch (Exception e) { throw new RuntimeException(e); } } mysql.close(); this.setTemporaryChatName(getNameColor() + name); } public void create() { this.mysql.connect(); if (this.mysql.connect != null) { try { String SQL = "INSERT INTO user (player) VALUE ('"+ name +"')"; this.mysql.statement.execute(SQL); } catch (Exception e) { e.printStackTrace(); } } this.mysql.close(); } private boolean getBoolean(String key) { String value = this.settings.get(key); try { if (value.contains("true")) { return true; } else { return false; } } catch (Exception e) { return false; } } public int getId() { return id; } public boolean isAdmin() { return getBoolean("admin"); } public boolean isDonator() { return getBoolean("donator"); } public boolean isBanned() { return getBoolean("banned"); } public boolean isTrusted() { return getBoolean("trusted"); } public boolean isChild() { return getBoolean("child"); } public boolean isImmortal() { return getBoolean("immortal"); } public boolean getMetaBoolean(String _key) { return getBoolean(_key); } public void setMetaString(String _key, String _value) { try { this.mysql.connect(); String SQLD = "DELETE FROM `minecraft`.`user_settings` WHERE `user_settings`.`id` = "+ settings.get("id") +" AND `user_settings`.`key` = '" + _key +"'"; this.mysql.statement.execute(SQLD); String SQLU = "INSERT INTO user_settings (id,`key`,`value`) VALUE ((SELECT uid FROM user WHERE player='" + this.name + "'),'"+ _key +"','"+ _value +"')"; this.settings.put(_key, _value); this.mysql.statement.execute(SQLU); this.mysql.close(); } catch (Exception e) { throw new RuntimeException(e); } } public void setTempMetaString(String _key, String _value) { try { this.settings.put(_key, _value); } catch (Exception e) { throw new RuntimeException(e); } } public String getMetaString(String _key) { return this.settings.get(_key); } public String getTimezone() { String value = this.settings.get("timezone"); if (value == null) { return "Europe/Stockholm"; } else { return value; } } public void setBlock(String _key, Block _block) { this.block.put(_key, _block); } public Block getBlock(String _key) { return this.block.get(_key); } public Integer getMetaInt(String _key) { return this.integer.get(_key); } public void setMetaInt(String _key, Integer _value) { this.integer.put(_key, _value); } public ChatColor getNameColor() { String color = this.settings.get("color"); if (this.settings.get("color") != null ) { if (color.toLowerCase().matches("admin")) { return ChatColor.RED; } if (color.toLowerCase().matches("broker")) { return ChatColor.DARK_RED; } if (color.toLowerCase().matches("helper")) { return ChatColor.YELLOW; } if (color.toLowerCase().matches("purle")) { return ChatColor.DARK_PURPLE; } if (color.toLowerCase().matches("donator")) { return ChatColor.GOLD; } if (color.toLowerCase().matches("trusted")) { return ChatColor.DARK_GREEN; } if (color.toLowerCase().matches("warned")) { return ChatColor.GRAY; } if (color.toLowerCase().matches("trial")) { return ChatColor.GREEN; } if (color.toLowerCase().matches("vampire")) { return ChatColor.DARK_RED; } if (color.toLowerCase().matches("hunter")) { return ChatColor.BLUE; } if (color.toLowerCase().matches("pink")) { return ChatColor.LIGHT_PURPLE; } if (color.toLowerCase().matches("child")) { return ChatColor.AQUA; } if (color.toLowerCase().matches("mentor")) { return ChatColor.DARK_AQUA; } if (color.toLowerCase().matches("police")) { return ChatColor.BLUE; } } return ChatColor.WHITE; } public String getChatName() { return name; } public void setTemporaryChatName(String _name) { name = _name; if (getChatName().length() > 16) { this.setPlayerListName(name.substring(0, 15)); } else { this.setPlayerListName(name); } } public void setCurrentZone(Zone zone) { this.currentZone = zone; } public Zone getCurrentZone() { return currentZone; } }
package alluxio.client.file; import alluxio.AlluxioURI; import alluxio.Constants; import alluxio.annotation.PublicApi; import alluxio.client.file.options.CreateDirectoryOptions; import alluxio.client.file.options.CreateFileOptions; import alluxio.client.file.options.DeleteOptions; import alluxio.client.file.options.ExistsOptions; import alluxio.client.file.options.FreeOptions; import alluxio.client.file.options.GetStatusOptions; import alluxio.client.file.options.ListStatusOptions; import alluxio.client.file.options.LoadMetadataOptions; import alluxio.client.file.options.MountOptions; import alluxio.client.file.options.OpenFileOptions; import alluxio.client.file.options.RenameOptions; import alluxio.client.file.options.SetAttributeOptions; import alluxio.client.file.options.UnmountOptions; import alluxio.exception.AlluxioException; import alluxio.exception.DirectoryNotEmptyException; import alluxio.exception.ExceptionMessage; import alluxio.exception.FileAlreadyExistsException; import alluxio.exception.FileDoesNotExistException; import alluxio.exception.InvalidPathException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import javax.annotation.concurrent.ThreadSafe; /** * Default implementation of the {@link FileSystem} interface. Developers can extend this class * instead of implementing the interface. This implementation reads and writes data through * {@link FileInStream} and {@link FileOutStream}. This class is thread safe. */ @PublicApi @ThreadSafe public class BaseFileSystem implements FileSystem { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); private final FileSystemContext mContext; /** * @return the {@link BaseFileSystem} */ public static BaseFileSystem get() { return new BaseFileSystem(); } protected BaseFileSystem() { mContext = FileSystemContext.INSTANCE; } @Override public void createDirectory(AlluxioURI path) throws FileAlreadyExistsException, InvalidPathException, IOException, AlluxioException { createDirectory(path, CreateDirectoryOptions.defaults()); } @Override public void createDirectory(AlluxioURI path, CreateDirectoryOptions options) throws FileAlreadyExistsException, InvalidPathException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { masterClient.createDirectory(path, options); LOG.info("Created directory " + path.getPath()); } finally { mContext.releaseMasterClient(masterClient); } } @Override public FileOutStream createFile(AlluxioURI path) throws FileAlreadyExistsException, InvalidPathException, IOException, AlluxioException { return createFile(path, CreateFileOptions.defaults()); } @Override public FileOutStream createFile(AlluxioURI path, CreateFileOptions options) throws FileAlreadyExistsException, InvalidPathException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { masterClient.createFile(path, options); LOG.info("Created file " + path.getPath()); } finally { mContext.releaseMasterClient(masterClient); } return new FileOutStream(path, options.toOutStreamOptions()); } @Override public void delete(AlluxioURI path) throws DirectoryNotEmptyException, FileDoesNotExistException, IOException, AlluxioException { delete(path, DeleteOptions.defaults()); } @Override public void delete(AlluxioURI path, DeleteOptions options) throws DirectoryNotEmptyException, FileDoesNotExistException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { masterClient.delete(path, options); LOG.info("Deleted file " + path.getName()); } finally { mContext.releaseMasterClient(masterClient); } } @Override public boolean exists(AlluxioURI path) throws InvalidPathException, IOException, AlluxioException { return exists(path, ExistsOptions.defaults()); } @Override public boolean exists(AlluxioURI path, ExistsOptions options) throws InvalidPathException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { // TODO(calvin): Make this more efficient masterClient.getStatus(path); return true; } catch (FileDoesNotExistException e) { return false; } catch (InvalidPathException e) { return false; } finally { mContext.releaseMasterClient(masterClient); } } @Override public void free(AlluxioURI path) throws FileDoesNotExistException, IOException, AlluxioException { free(path, FreeOptions.defaults()); } @Override public void free(AlluxioURI path, FreeOptions options) throws FileDoesNotExistException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { masterClient.free(path, options); } finally { mContext.releaseMasterClient(masterClient); } } @Override public URIStatus getStatus(AlluxioURI path) throws FileDoesNotExistException, IOException, AlluxioException { return getStatus(path, GetStatusOptions.defaults()); } @Override public URIStatus getStatus(AlluxioURI path, GetStatusOptions options) throws FileDoesNotExistException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { return masterClient.getStatus(path); } catch (FileDoesNotExistException e) { throw new FileDoesNotExistException(ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage(path)); } catch (InvalidPathException e) { throw new FileDoesNotExistException(ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage(path)); } finally { mContext.releaseMasterClient(masterClient); } } @Override public List<URIStatus> listStatus(AlluxioURI path) throws FileDoesNotExistException, IOException, AlluxioException { return listStatus(path, ListStatusOptions.defaults()); } @Override public List<URIStatus> listStatus(AlluxioURI path, ListStatusOptions options) throws FileDoesNotExistException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); // TODO(calvin): Fix the exception handling in the master try { return masterClient.listStatus(path); } catch (FileDoesNotExistException e) { throw new FileDoesNotExistException(ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage(path)); } finally { mContext.releaseMasterClient(masterClient); } } @Override public void loadMetadata(AlluxioURI path) throws FileDoesNotExistException, IOException, AlluxioException { loadMetadata(path, LoadMetadataOptions.defaults()); } @Override public void loadMetadata(AlluxioURI path, LoadMetadataOptions options) throws FileDoesNotExistException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { masterClient.loadMetadata(path, options); } finally { mContext.releaseMasterClient(masterClient); } } @Override public void mount(AlluxioURI src, AlluxioURI dst) throws IOException, AlluxioException { mount(src, dst, MountOptions.defaults()); } @Override public void mount(AlluxioURI src, AlluxioURI dst, MountOptions options) throws IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { // TODO(calvin): Make this fail on the master side masterClient.mount(src, dst, options); LOG.info("Mount " + src.getPath() + " to " + dst.getPath()); } finally { mContext.releaseMasterClient(masterClient); } } @Override public FileInStream openFile(AlluxioURI path) throws FileDoesNotExistException, IOException, AlluxioException { return openFile(path, OpenFileOptions.defaults()); } @Override public FileInStream openFile(AlluxioURI path, OpenFileOptions options) throws FileDoesNotExistException, IOException, AlluxioException { URIStatus status = getStatus(path); if (status.isFolder()) { throw new FileNotFoundException( ExceptionMessage.CANNOT_READ_DIRECTORY.getMessage(status.getName())); } return new FileInStream(status, options.toInStreamOptions()); } @Override public void rename(AlluxioURI src, AlluxioURI dst) throws FileDoesNotExistException, IOException, AlluxioException { rename(src, dst, RenameOptions.defaults()); } @Override public void rename(AlluxioURI src, AlluxioURI dst, RenameOptions options) throws FileDoesNotExistException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { // TODO(calvin): Update this code on the master side. masterClient.rename(src, dst); LOG.info("Renamed file " + src.getPath() + " to " + dst.getPath()); } finally { mContext.releaseMasterClient(masterClient); } } @Override public void setAttribute(AlluxioURI path) throws FileDoesNotExistException, IOException, AlluxioException { setAttribute(path, SetAttributeOptions.defaults()); } @Override public void setAttribute(AlluxioURI path, SetAttributeOptions options) throws FileDoesNotExistException, IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { masterClient.setAttribute(path, options); LOG.info("Set attributes for path {} with options {}", path.getPath(), options); } finally { mContext.releaseMasterClient(masterClient); } } @Override public void unmount(AlluxioURI path) throws IOException, AlluxioException { unmount(path, UnmountOptions.defaults()); } @Override public void unmount(AlluxioURI path, UnmountOptions options) throws IOException, AlluxioException { FileSystemMasterClient masterClient = mContext.acquireMasterClient(); try { masterClient.unmount(path); LOG.info("Unmount " + path); } finally { mContext.releaseMasterClient(masterClient); } } }
package ethanjones.modularworld.graphics.world; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.RenderableProvider; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Pool; import ethanjones.modularworld.block.Block; import ethanjones.modularworld.core.util.Direction; import ethanjones.modularworld.graphics.GraphicsHelper; import ethanjones.modularworld.world.storage.Area; import static ethanjones.modularworld.world.storage.Area.SIZE_BLOCKS; import static ethanjones.modularworld.world.storage.Area.SIZE_BLOCKS_CUBED; public class AreaRenderer implements RenderableProvider { public static final int topOffset = SIZE_BLOCKS * SIZE_BLOCKS; public static final int bottomOffset = -SIZE_BLOCKS * SIZE_BLOCKS; public static final int leftOffset = -1; public static final int rightOffset = 1; public static final int frontOffset = -SIZE_BLOCKS; public static final int backOffset = SIZE_BLOCKS; public static final int VERTEX_SIZE = 6; private static short[] indices; private static float vertices[]; static { int len = SIZE_BLOCKS_CUBED * 6 * 6 / 3; indices = new short[len]; short j = 0; for (int i = 0; i < len; i += 6, j += 4) { indices[i + 0] = (short) (j + 0); indices[i + 1] = (short) (j + 1); indices[i + 2] = (short) (j + 2); indices[i + 3] = (short) (j + 2); indices[i + 4] = (short) (j + 3); indices[i + 5] = (short) (j + 0); } vertices = new float[VERTEX_SIZE * 6 * SIZE_BLOCKS_CUBED]; } public Mesh mesh; public boolean dirty = true; Vector3 offset = new Vector3(); private int numVertices = 0; private Camera camera; private Area area; public AreaRenderer(Area area) { this.area = area; this.offset.set(area.minBlockX, area.minBlockY, area.minBlockZ); mesh = new Mesh(true, SIZE_BLOCKS_CUBED * 8 * 4, SIZE_BLOCKS_CUBED * 36 / 3, GraphicsHelper.vertexAttributes); mesh.setIndices(indices); } public static int createTop(Vector3 offset, TextureRegion region, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV2(); vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV2(); return vertexOffset; } public static int createBottom(Vector3 offset, TextureRegion region, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV2(); vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV2(); vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV(); return vertexOffset; } public static int createLeft(Vector3 offset, TextureRegion region, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV2(); vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV2(); return vertexOffset; } public static int createRight(Vector3 offset, TextureRegion region, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV2(); vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV2(); return vertexOffset; } public static int createFront(Vector3 offset, TextureRegion region, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV2(); vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = -1; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV2(); return vertexOffset; } public static int createBack(Vector3 offset, TextureRegion region, int x, int y, int z, float[] vertices, int vertexOffset) { vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV2(); vertices[vertexOffset++] = offset.x + x + 1; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = region.getU2(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y + 1; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV(); vertices[vertexOffset++] = offset.x + x; vertices[vertexOffset++] = offset.y + y; vertices[vertexOffset++] = offset.z + z + 1; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 0; vertices[vertexOffset++] = 1; vertices[vertexOffset++] = region.getU(); vertices[vertexOffset++] = region.getV2(); return vertexOffset; } public AreaRenderer set(Camera camera) { this.camera = camera; return this; } @Override public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) { if (dirty) { int numVerts = calculateVertices(vertices); numVertices = numVerts / 4 * 6; mesh.setVertices(vertices, 0, numVerts * VERTEX_SIZE); dirty = false; } if (numVertices == 0) return; Renderable renderable = pool.obtain(); renderable.material = GraphicsHelper.blockPackedTextures; renderable.mesh = mesh; renderable.meshPartOffset = 0; renderable.meshPartSize = numVertices; renderable.primitiveType = GL20.GL_TRIANGLES; renderables.add(renderable); } public int calculateVertices(float[] vertices) { int i = 0; int vertexOffset = 0; for (int y = 0; y < SIZE_BLOCKS; y++) { for (int z = 0; z < SIZE_BLOCKS; z++) { for (int x = 0; x < SIZE_BLOCKS; x++, i++) { Block block = area.blocks[i]; if (block == null) continue; BlockTextureHandler textureHandler = block.getTextureHandler(); if (y < SIZE_BLOCKS - 1) { if (area.blocks[i + topOffset] == null) vertexOffset = createTop(offset, textureHandler.getSide(Direction.posY).textureRegion, x, y, z, vertices, vertexOffset); } else { vertexOffset = createTop(offset, textureHandler.getSide(Direction.posY).textureRegion, x, y, z, vertices, vertexOffset); } if (y > 0) { if (area.blocks[i + bottomOffset] == null) vertexOffset = createBottom(offset, textureHandler.getSide(Direction.negY).textureRegion, x, y, z, vertices, vertexOffset); } else { vertexOffset = createBottom(offset, textureHandler.getSide(Direction.negY).textureRegion, x, y, z, vertices, vertexOffset); } if (x > 0) { if (area.blocks[i + leftOffset] == null) vertexOffset = createLeft(offset, textureHandler.getSide(Direction.negX).textureRegion, x, y, z, vertices, vertexOffset); } else { vertexOffset = createLeft(offset, textureHandler.getSide(Direction.negX).textureRegion, x, y, z, vertices, vertexOffset); } if (x < SIZE_BLOCKS - 1) { if (area.blocks[i + rightOffset] == null) vertexOffset = createRight(offset, textureHandler.getSide(Direction.posX).textureRegion, x, y, z, vertices, vertexOffset); } else { vertexOffset = createRight(offset, textureHandler.getSide(Direction.posX).textureRegion, x, y, z, vertices, vertexOffset); } if (z > 0) { if (area.blocks[i + frontOffset] == null) vertexOffset = createFront(offset, textureHandler.getSide(Direction.negZ).textureRegion, x, y, z, vertices, vertexOffset); } else { vertexOffset = createFront(offset, textureHandler.getSide(Direction.negZ).textureRegion, x, y, z, vertices, vertexOffset); } if (z < SIZE_BLOCKS - 1) { if (area.blocks[i + backOffset] == null) vertexOffset = createBack(offset, textureHandler.getSide(Direction.posZ).textureRegion, x, y, z, vertices, vertexOffset); } else { vertexOffset = createBack(offset, textureHandler.getSide(Direction.posZ).textureRegion, x, y, z, vertices, vertexOffset); } } } } return vertexOffset / VERTEX_SIZE; } }
package org.mskcc.cbio.portal.dao; import org.mskcc.cbio.portal.model.*; import org.mskcc.cbio.portal.util.InternalIdUtil; import java.sql.*; import java.util.*; /** * Data Access Object for `clinical` table * * @author Gideon Dresdner dresdnerg@cbio.mskcc.org */ public final class DaoClinicalData { public static final String SAMPLE_TABLE = "clinical_sample"; public static final String PATIENT_TABLE = "clinical_patient"; private static final String SAMPLE_INSERT = "INSERT INTO " + SAMPLE_TABLE + "(`INTERAL_ID`,`ATTR_ID`,`ATTR_VALUE` VALUES(?,?,?)"; private static final String PATIENT_INSERT = "INSERT INTO " + PATIENT_TABLE + "(`INTERNAL_ID`,`ATTR_ID`,`ATTR_VALUE` VALUES(?,?,?)"; private static final Map<String, String> sampleAttributes = new HashMap<String, String>(); private static final Map<String, String> patientAttributes = new HashMap<String, String>(); private DaoClinicalData() {} public static synchronized void reCache() { clearCache(); cacheAttributes(SAMPLE_TABLE, sampleAttributes); cacheAttributes(PATIENT_TABLE, patientAttributes); } private static void clearCache() { sampleAttributes.clear(); patientAttributes.clear(); } private static void cacheAttributes(String table, Map<String,String> cache) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoClinicalData.class); pstmt = con.prepareStatement("SELECT * FROM " + table); rs = pstmt.executeQuery(); while (rs.next()) { cache.put(rs.getString("ATTR_ID"), rs.getString("ATTR_ID")); } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtil.closeAll(DaoClinicalData.class, con, pstmt, rs); } } public static int addSampleDatum(int internalSampleId, String attrId, String attrVal) throws DaoException { sampleAttributes.put(attrId, attrId); return addDatum(SAMPLE_INSERT, SAMPLE_TABLE, internalSampleId, attrId, attrVal); } public static int addPatientDatum(int internalPatientId, String attrId, String attrVal) throws DaoException { patientAttributes.put(attrId, attrId); return addDatum(PATIENT_INSERT, PATIENT_TABLE, internalPatientId, attrId, attrVal); } public static int addDatum(String query, String tableName, int internalId, String attrId, String attrVal) throws DaoException { if (MySQLbulkLoader.isBulkLoad()) { MySQLbulkLoader.getMySQLbulkLoader(tableName).insertRecord(Integer.toString(internalId), attrId, attrVal); return 1; } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoClinicalData.class); pstmt = con.prepareStatement(query); pstmt.setInt(1, internalId); pstmt.setString(2, attrId); pstmt.setString(3, attrVal); int toReturn = pstmt.executeUpdate(); if (tableName.equals(PATIENT_TABLE)) { patientAttributes.put(attrId, attrId); } else { sampleAttributes.put(attrId, attrId); } return toReturn; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoClinicalData.class, con, pstmt, rs); } } public static ClinicalData getDatum(String cancerStudyId, String patientId, String attrId) throws DaoException { int internalCancerStudyId = getInternalCancerStudyId(cancerStudyId); String table = getAttributeTable(attrId); if (table==null) { return null; } return getDatum(internalCancerStudyId, table, DaoPatient.getPatientByCancerStudyAndPatientId(internalCancerStudyId, patientId).getInternalId(), attrId); } private static int getInternalCancerStudyId(String cancerStudyId) throws DaoException { return DaoCancerStudy.getCancerStudyByStableId(cancerStudyId).getInternalId(); } private static String getAttributeTable(String attrId) throws DaoException { if (sampleAttributes.containsKey(attrId)) { return SAMPLE_TABLE; } else if (patientAttributes.containsKey(attrId)) { return (PATIENT_TABLE); } else { return null; } } private static ClinicalData getDatum(int internalCancerStudyId, String table, int internalId, String attrId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoClinicalData.class); pstmt = con.prepareStatement("SELECT * FROM " + table + " WHERE INTERNAL_ID=? AND ATTR_ID=?"); pstmt.setInt(1, internalId); pstmt.setString(2, attrId); rs = pstmt.executeQuery(); if (rs.next()) { return extract(table, internalCancerStudyId, rs); } else { return null; } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoClinicalData.class, con, pstmt, rs); } } public static List<ClinicalData> getDataByPatientId(int cancerStudyId, String patientId) throws DaoException { List<Integer> internalIds = new ArrayList<Integer>(); internalIds.add(DaoPatient.getPatientByCancerStudyAndPatientId(cancerStudyId, patientId).getInternalId()); return getDataByInternalIds(cancerStudyId, PATIENT_TABLE, internalIds); } private static List<ClinicalData> getDataByInternalIds(int internalCancerStudyId, String table, List<Integer> internalIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<ClinicalData> clinicals = new ArrayList<ClinicalData>(); String sql = ("SELECT * FROM " + table + " WHERE `INTERNAL_ID` IN " + "(" + generateInClause(internalIds) + ")"); try { con = JdbcUtil.getDbConnection(DaoClinicalData.class); pstmt = con.prepareStatement(sql); for (int lc = 0; lc < internalIds.size(); lc++) { pstmt.setInt(lc+1, internalIds.get(lc)); } rs = pstmt.executeQuery(); while (rs.next()) { clinicals.add(extract(table, internalCancerStudyId, rs)); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoClinicalData.class, con, pstmt, rs); } return clinicals; } public static List<ClinicalData> getData(String cancerStudyId) throws DaoException { return getData(getInternalCancerStudyId(cancerStudyId)); } public static List<ClinicalData> getData(int cancerStudyId) throws DaoException { return getDataByInternalIds(cancerStudyId, PATIENT_TABLE, getPatientIdsByCancerStudy(cancerStudyId)); } private static List<Integer> getPatientIdsByCancerStudy(int cancerStudyId) { List<Integer> patientIds = new ArrayList<Integer>(); for (Patient patient : DaoPatient.getPatientsByCancerStudyId(cancerStudyId)) { patientIds.add(patient.getInternalId()); } return patientIds; } private static List<Integer> getSampleIdsByCancerStudy(int cancerStudyId) { List<Integer> sampleIds = new ArrayList<Integer>(); for (Patient patient : DaoPatient.getPatientsByCancerStudyId(cancerStudyId)) { for (Sample s : DaoSample.getSamplesByPatientId(patient.getInternalId())) { sampleIds.add(s.getInternalId()); } } return sampleIds; } public static List<ClinicalData> getData(String cancerStudyId, Collection<String> patientIds) throws DaoException { return getData(getInternalCancerStudyId(cancerStudyId), patientIds); } public static List<ClinicalData> getData(int cancerStudyId, Collection<String> patientIds) throws DaoException { List<Integer> patientIdsInt = new ArrayList<Integer>(); for (String patientId : patientIds) { patientIdsInt.add(DaoPatient.getPatientByCancerStudyAndPatientId(cancerStudyId, patientId).getInternalId()); } return getDataByInternalIds(cancerStudyId, PATIENT_TABLE, patientIdsInt); } public static List<ClinicalData> getSampleAndPatientData(int cancerStudyId, Collection<String> sampleIds) throws DaoException { List<Integer> sampleIdsInt = new ArrayList<Integer>(); List<Integer> patientIdsInt = new ArrayList<Integer>(); Map<String,Set<String>> mapPatientIdSampleIds = new HashMap<String,Set<String>>(); for (String sampleId : sampleIds) { Sample sample = DaoSample.getSampleByCancerStudyAndSampleId(cancerStudyId, sampleId); sampleIdsInt.add(sample.getInternalId()); int patientIdInt = sample.getInternalPatientId(); String patientIdStable = DaoPatient.getPatientById(patientIdInt).getStableId(); patientIdsInt.add(patientIdInt); Set<String> sampleIdsForPatient = mapPatientIdSampleIds.get(patientIdStable); if (sampleIdsForPatient==null) { sampleIdsForPatient = new HashSet<String>(); mapPatientIdSampleIds.put(patientIdStable, sampleIdsForPatient); } sampleIdsForPatient.add(sampleId); } List<ClinicalData> sampleClinicalData = getDataByInternalIds(cancerStudyId, SAMPLE_TABLE, sampleIdsInt); List<ClinicalData> patientClinicalData = getDataByInternalIds(cancerStudyId, PATIENT_TABLE, patientIdsInt); for (ClinicalData cd : patientClinicalData) { String stablePatientId = cd.getStableId(); Set<String> sampleIdsForPatient = mapPatientIdSampleIds.get(stablePatientId); for (String sampleId : sampleIdsForPatient) { ClinicalData cdSample = new ClinicalData(cd); cdSample.setStableId(sampleId); sampleClinicalData.add(cdSample); } } return sampleClinicalData; } public static List<ClinicalData> getSampleAndPatientData(int cancerStudyId, Collection<String> sampleIds, ClinicalAttribute attr) throws DaoException { List<Integer> sampleIdsInt = new ArrayList<Integer>(); List<Integer> patientIdsInt = new ArrayList<Integer>(); Map<String,Set<String>> mapPatientIdSampleIds = new HashMap<String,Set<String>>(); for (String sampleId : sampleIds) { Sample sample = DaoSample.getSampleByCancerStudyAndSampleId(cancerStudyId, sampleId); sampleIdsInt.add(sample.getInternalId()); int patientIdInt = sample.getInternalPatientId(); String patientIdStable = DaoPatient.getPatientById(patientIdInt).getStableId(); patientIdsInt.add(patientIdInt); Set<String> sampleIdsForPatient = mapPatientIdSampleIds.get(patientIdStable); if (sampleIdsForPatient==null) { sampleIdsForPatient = new HashSet<String>(); mapPatientIdSampleIds.put(patientIdStable, sampleIdsForPatient); } sampleIdsForPatient.add(sampleId); } List<ClinicalData> sampleClinicalData = getDataByInternalIds(cancerStudyId, SAMPLE_TABLE, sampleIdsInt, Collections.singletonList(attr.getAttrId())); List<ClinicalData> patientClinicalData = getDataByInternalIds(cancerStudyId, PATIENT_TABLE, patientIdsInt, Collections.singletonList(attr.getAttrId())); for (ClinicalData cd : patientClinicalData) { String stablePatientId = cd.getStableId(); Set<String> sampleIdsForPatient = mapPatientIdSampleIds.get(stablePatientId); for (String sampleId : sampleIdsForPatient) { ClinicalData cdSample = new ClinicalData(cd); cdSample.setStableId(sampleId); sampleClinicalData.add(cdSample); } } return sampleClinicalData; } public static List<ClinicalData> getSampleData(int cancerStudyId, Collection<String> sampleIds, ClinicalAttribute attr) throws DaoException { List<Integer> sampleIdsInt = new ArrayList<Integer>(); for (String sampleId : sampleIds) { Sample _sample = DaoSample.getSampleByCancerStudyAndSampleId(cancerStudyId, sampleId); if (_sample != null) { sampleIdsInt.add(_sample.getInternalId()); } } return getDataByInternalIds(cancerStudyId, SAMPLE_TABLE, sampleIdsInt, Collections.singletonList(attr.getAttrId())); } public static List<ClinicalData> getSampleData(int cancerStudyId, Collection<String> sampleIds) throws DaoException { List<Integer> sampleIdsInt = new ArrayList<Integer>(); for (String sampleId : sampleIds) { sampleIdsInt.add(DaoSample.getSampleByCancerStudyAndSampleId(cancerStudyId, sampleId).getInternalId()); } return getDataByInternalIds(cancerStudyId, SAMPLE_TABLE, sampleIdsInt); } public static List<ClinicalData> getData(String cancerStudyId, Collection<String> patientIds, ClinicalAttribute attr) throws DaoException { int internalCancerStudyId = getInternalCancerStudyId(cancerStudyId); List<Integer> patientIdsInt = new ArrayList<Integer>(); for (String patientId : patientIds) { patientIdsInt.add(DaoPatient.getPatientByCancerStudyAndPatientId(internalCancerStudyId, patientId).getInternalId()); } return getDataByInternalIds(internalCancerStudyId, PATIENT_TABLE, patientIdsInt, Collections.singletonList(attr.getAttrId())); } private static List<ClinicalData> getDataByInternalIds(int internalCancerStudyId, String table, List<Integer> internalIds, List<String> attributeIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<ClinicalData> clinicals = new ArrayList<ClinicalData>(); String sql = ("SELECT * FROM " + table + " WHERE `INTERNAL_ID` IN " + "(" + generateInClause(internalIds) + ") " + " AND ATTR_ID IN ('"+ generateInClause(attributeIds) + "')"); try { con = JdbcUtil.getDbConnection(DaoClinicalData.class); pstmt = con.prepareStatement(sql); for (int lc = 0; lc < internalIds.size(); lc++) { pstmt.setInt(lc+1, internalIds.get(lc)); } for (int lc = 0; lc < attributeIds.size(); lc++) { pstmt.setString(internalIds.size()+lc+1, attributeIds.get(lc)); } rs = pstmt.executeQuery(); while (rs.next()) { clinicals.add(extract(table, internalCancerStudyId, rs)); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoClinicalData.class, con, pstmt, rs); } return clinicals; } public static List<ClinicalData> getDataByAttributeIds(int internalCancerStudyId, Collection<String> attributeIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<ClinicalData> clinicals = new ArrayList<ClinicalData>(); List<String> attrIds = (attributeIds instanceof List) ? (List)attributeIds : new ArrayList<String>(attributeIds); try { con = JdbcUtil.getDbConnection(DaoClinicalData.class); pstmt = con.prepareStatement("SELECT * FROM clinical_patient WHERE" + " ATTR_ID IN (" + generateInClause(attrIds) +")"); for (int lc = 0; lc < attrIds.size(); lc++) { pstmt.setString(lc+1, attrIds.get(lc)); } rs = pstmt.executeQuery(); List<Integer> patients = getPatientIdsByCancerStudy(internalCancerStudyId); while(rs.next()) { Integer patientId = rs.getInt("INTERNAL_ID"); if (patients.contains(patientId)) { clinicals.add(extract(PATIENT_TABLE, internalCancerStudyId, rs)); } } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoClinicalData.class, con, pstmt, rs); } return clinicals; } private static ClinicalData extract(String table, int internalCancerStudyId, ResultSet rs) throws SQLException { // get String stableId = getStableIdFromInternalId(table, rs.getInt("INTERNAL_ID")); return new ClinicalData(internalCancerStudyId, stableId, rs.getString("ATTR_ID"), rs.getString("ATTR_VALUE")); } private static String getStableIdFromInternalId(String table, int internalId) { if (table.equals(SAMPLE_TABLE)) { return DaoSample.getSampleById(internalId).getStableId(); } else { return DaoPatient.getPatientById(internalId).getStableId(); } } private static String generateInClause(List<?> list) { StringBuilder toReturn = new StringBuilder(); for (int lc=0; lc < list.size(); lc++) { toReturn.append("?,"); } toReturn.deleteCharAt(toReturn.lastIndexOf(",")); return toReturn.toString(); } public static void deleteAllRecords() throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoClinicalData.class); pstmt = con.prepareStatement("TRUNCATE TABLE clinical_patient"); pstmt.executeUpdate(); pstmt = con.prepareStatement("TRUNCATE TABLE clinical_sample"); pstmt.executeUpdate(); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoClinicalData.class, con, pstmt, rs); } reCache(); } /** * Returns the survival data for the given patientSet, NOT necessarily in the * same order as the patientSet. * * @param cancerStudyId: the cancerstudy internal id * @param patientSet: set of patient ids * @return * @throws DaoException */ public static List<Patient> getSurvivalData(int cancerStudyId, Collection<String> patientSet) throws DaoException { CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByInternalId(cancerStudyId); List<ClinicalData> data = getData(cancerStudyId, patientSet); Map<String,Map<String,ClinicalData>> clinicalData = new LinkedHashMap<String,Map<String,ClinicalData>>(); for (ClinicalData cd : data) { String patientId = cd.getStableId(); Map<String,ClinicalData> msc = clinicalData.get(cd.getStableId()); if (msc==null) { msc = new HashMap<String,ClinicalData>(); clinicalData.put(patientId, msc); } msc.put(cd.getAttrId(), cd); } ArrayList<Patient> toReturn = new ArrayList<Patient>(); for (Map.Entry<String,Map<String,ClinicalData>> entry : clinicalData.entrySet()) { Patient patient = DaoPatient.getPatientByCancerStudyAndPatientId(cancerStudyId, entry.getKey()); toReturn.add(new Patient(cancerStudy, patient.getStableId(), patient.getInternalId(), entry.getValue())); } return toReturn; } public static List<ClinicalParameterMap> getDataSlice(int cancerStudyId, Collection<String> attributeIds) throws DaoException { Map<String,Map<String, String>> mapAttrStableIdValue = new HashMap<String,Map<String, String>>(); for (ClinicalData cd : getDataByAttributeIds(cancerStudyId, attributeIds)) { String attrId = cd.getAttrId(); String value = cd.getAttrVal(); String stableId = cd.getStableId(); if (value.isEmpty() || value.equals(ClinicalAttribute.NA)) { continue; } Map<String, String> mapStableIdValue = mapAttrStableIdValue.get(attrId); if (mapStableIdValue == null) { mapStableIdValue = new HashMap<String, String>(); mapAttrStableIdValue.put(attrId, mapStableIdValue); } mapStableIdValue.put(stableId, value); } List<ClinicalParameterMap> maps = new ArrayList<ClinicalParameterMap>(); for (Map.Entry<String,Map<String, String>> entry : mapAttrStableIdValue.entrySet()) { maps.add(new ClinicalParameterMap(entry.getKey(), entry.getValue())); } return maps; } public static HashSet<String> getDistinctParameters(int cancerStudyId) throws DaoException { HashSet<String> toReturn = new HashSet<String>(); for (ClinicalData clinicalData : DaoClinicalData.getData(cancerStudyId)) { toReturn.add(clinicalData.getAttrId()); } return toReturn; } public static HashSet<String> getAllPatients(int cancerStudyId) throws DaoException { HashSet<String> toReturn = new HashSet<String>(); for (ClinicalData clinicalData : getData(cancerStudyId)) { toReturn.add(clinicalData.getStableId()); } return toReturn; } public static List<ClinicalData> getDataByCancerStudy(int cancerStudyId) throws DaoException { return DaoClinicalData.getData(cancerStudyId); } public static List<ClinicalData> getDataByPatientIds(int cancerStudyId, List<String> patientIds) throws DaoException { return DaoClinicalData.getData(cancerStudyId, patientIds); } public static List<Patient> getPatientsByAttribute(int cancerStudy, String paramName, String paramValue) throws DaoException { List<Integer> ids = getIdsByAttribute(cancerStudy, paramName, paramValue, PATIENT_TABLE); return InternalIdUtil.getPatientsById(ids); } public static List<Sample> getSamplesByAttribute(int cancerStudy, String paramName, String paramValue) throws DaoException { List<Integer> ids = getIdsByAttribute(cancerStudy, paramName, paramValue, SAMPLE_TABLE); return InternalIdUtil.getSamplesById(ids); } private static List<Integer> getIdsByAttribute(int cancerStudyId, String paramName, String paramValue, String tableName) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try{ con = JdbcUtil.getDbConnection(DaoClinicalData.class); pstmt = con.prepareStatement ("SELECT INTERNAL_ID FROM `" + tableName + "`" + " WHERE ATTR_ID=? AND ATTR_VALUE=?"); pstmt.setString(1, paramName); pstmt.setString(2, paramValue); rs = pstmt.executeQuery(); List<Integer> ids = new ArrayList<Integer>(); while (rs.next()) { ids.add(rs.getInt("INTERNAL_ID")); } return ids; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoClinicalData.class, con, pstmt, rs); } } // get cancerType from the clinical_sample table to determine whether we have multiple cancer types // for given samples public static Map<String, Set<String>> getCancerTypeInfoBySamples(List<String> samplesList) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try{ con = JdbcUtil.getDbConnection(DaoClinicalData.class); pstmt = con.prepareStatement("select " + "distinct ATTR_VALUE as attributeValue, " + "ATTR_ID as attributeID from clinical_sample " + "where ATTR_ID in (?, ?) and INTERNAL_ID in (" + "select INTERNAL_ID from sample where STABLE_ID in (" + generateInClause(samplesList) +"))"); pstmt.setString(1, ClinicalAttribute.CANCER_TYPE); pstmt.setString(2, ClinicalAttribute.CANCER_TYPE_DETAILED); for (int lc = 0; lc < samplesList.size(); lc++) { pstmt.setString(2+lc+1, samplesList.get(lc)); } rs = pstmt.executeQuery(); // create a map for the results Map<String, Set<String>> result = new LinkedHashMap<String, Set<String>>(); result.put( ClinicalAttribute.CANCER_TYPE, new HashSet<String>()); result.put( ClinicalAttribute.CANCER_TYPE_DETAILED, new HashSet<String>()); while (rs.next()) { result.get(rs.getString("attributeID")).add(rs.getString("attributeValue")); } return result; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoClinicalData.class, con, pstmt, rs); } } }
package org.museautomation.core.step; import org.museautomation.core.*; import org.museautomation.core.context.*; import org.museautomation.core.events.*; import org.museautomation.core.execution.*; import org.museautomation.core.steptask.*; import org.museautomation.core.values.*; import org.slf4j.*; import java.util.*; public class StepExecutor { public StepExecutor(ContainsStep step, StepsExecutionContext context) { _context = context; _context.getExecutionStack().push(new SingleStepExecutionContext(_context, step.getStep(), false)); } public void executeAll() { boolean had_a_step_to_run = true; while (had_a_step_to_run && !isTerminateRequested()) had_a_step_to_run = executeNextStep(); } /** * @return false if there are no more steps to run. */ public boolean executeNextStep() { if (!_context.getExecutionStack().hasMoreSteps()) return false; if (Thread.currentThread().isInterrupted()) { _context.raiseEvent(new MuseEvent(InterruptedEventType.TYPE)); return false; } String error_message = null; StepExecutionResult step_result = null; MuseStep step = null; StepExecutionContext step_context = _context.getExecutionStack().peek(); StepConfiguration step_config = step_context.getCurrentStepConfiguration(); if (step_config == null) return false; if (!(_steps_in_progress.contains(step_config))) { _steps_in_progress.add(step_config); _context.raiseEvent(StartStepEventType.create(step_config, step_context)); } try { step = step_context.getCurrentStep(); step_result = step.execute(step_context); } catch (StepConfigurationError error) { error_message = "step error due to configuration problem: " + error.getMessage(); _context.raiseEvent(TaskErrorEventType.create("Step configuration problem: " + error.getMessage())); } catch (StepExecutionError error) { error_message = "step failed to execute: " + error.getMessage(); _context.raiseEvent(TaskErrorEventType.create("Step execution problem: " + error.getMessage())); } catch (ValueSourceResolutionError error) { error_message = "unable to evalute value source: " + error.getMessage(); _context.raiseEvent(TaskErrorEventType.create("Unable to resolve value source: " + error.getMessage())); } catch (Throwable t) { LOG.error("Unexpected error caught while executing step", t); error_message = "cannot execute the step due to an unexpected error: " + t.getMessage(); } if (error_message != null) // if the step did not complete normally, the EndStep event needs to be generated here, since it was not generated by the step itself. step_result = new BasicStepExecutionResult(StepExecutionStatus.ERROR, error_message); if (step != null && !step_result.getStatus().equals(StepExecutionStatus.INCOMPLETE)) step_context.stepComplete(step, step_result); _context.raiseEvent(EndStepEventType.create(step_config, step_context, step_result)); if (!step_result.getStatus().equals(StepExecutionStatus.INCOMPLETE)) _steps_in_progress.remove(step_config); return !_steps_in_progress.isEmpty(); } public StepConfiguration getNextStep() { if (_context.getExecutionStack().hasMoreSteps()) return _context.getExecutionStack().peek().getCurrentStepConfiguration(); return null; } @SuppressWarnings("WeakerAccess") // used in GUI public void requestTerminate() { _terminate = true; } public boolean isTerminateRequested() { return _terminate; } private StepsExecutionContext _context; private boolean _terminate = false; private Set<StepConfiguration> _steps_in_progress = new HashSet<>(); private final static Logger LOG = LoggerFactory.getLogger(StepExecutor.class); }
package org.verapdf.processor; import org.verapdf.features.FeatureExtractionResult; import org.verapdf.metadata.fixer.FixerFactory; import org.verapdf.pdfa.results.MetadataFixerResult; import org.verapdf.pdfa.results.ValidationResult; import org.verapdf.pdfa.results.ValidationResults; import org.verapdf.report.FeaturesReport; import org.verapdf.report.ItemDetails; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlAdapter; import java.util.Collection; import java.util.EnumMap; import java.util.EnumSet; /** * Instance of this class contains result of * {@link org.verapdf.processor.ProcessorImpl#validate(InputStream, ItemDetails, Config, OutputStream)} * work. * * @author Sergey Shemyakov */ @XmlRootElement(name="processorResult") class ProcessorResultImpl implements ProcessorResult { private final static ProcessorResult defaultInstance = new ProcessorResultImpl(); @XmlAttribute private final boolean isValidPdf; @XmlAttribute private final boolean isEncryptedPdf; @XmlElement private final ItemDetails itemDetails; private final EnumMap<TaskType, TaskResult> taskResults; @XmlElement private final ValidationResult validationResult; private final FeatureExtractionResult featuresResult; @XmlElement private final MetadataFixerResult fixerResult; private ProcessorResultImpl() { this(ItemDetails.defaultInstance()); } private ProcessorResultImpl(final ItemDetails details) { this(details, false, false); } private ProcessorResultImpl(final ItemDetails details, boolean isValidPdf, boolean isEncrypted) { this(details, isValidPdf, isEncrypted, new EnumMap<TaskType, TaskResult>(TaskType.class), ValidationResults.defaultResult(), new FeatureExtractionResult(), FixerFactory.defaultResult()); } private ProcessorResultImpl(final ItemDetails details, final EnumMap<TaskType, TaskResult> results, final ValidationResult validationResult, final FeatureExtractionResult featuresResult, final MetadataFixerResult fixerResult) { this(details, true, false, results, validationResult, featuresResult, fixerResult); } private ProcessorResultImpl(final ItemDetails details, final boolean isValidPdf, final boolean isEncrypted, final EnumMap<TaskType, TaskResult> results, final ValidationResult validationResult, final FeatureExtractionResult featuresResult, final MetadataFixerResult fixerResult) { super(); this.itemDetails = details; this.isValidPdf = isValidPdf; this.isEncryptedPdf = isEncrypted; this.taskResults = results; this.validationResult = validationResult; this.featuresResult = featuresResult; this.fixerResult = fixerResult; } /** * @return the results */ @Override public EnumMap<TaskType, TaskResult> getResults() { return this.taskResults; } @Override @XmlElementWrapper(name="taskResult") @XmlElement(name="taskResult") public Collection<TaskResult> getResultSet() { return this.taskResults.values(); } @Override public ItemDetails getProcessedItem() { return this.itemDetails; } @Override public EnumSet<TaskType> getTaskTypes() { return this.taskResults.isEmpty() ? EnumSet.noneOf(TaskType.class) : EnumSet.copyOf(this.taskResults.keySet()); } static ProcessorResult defaultInstance() { return defaultInstance; } static ProcessorResult fromValues(final ItemDetails details, final EnumMap<TaskType, TaskResult> results, final ValidationResult validationResult, final FeatureExtractionResult featuresResult, final MetadataFixerResult fixerResult) { return new ProcessorResultImpl(details, results, validationResult, featuresResult, fixerResult); } static ProcessorResult invalidPdfResult(final ItemDetails details) { return new ProcessorResultImpl(details); } static ProcessorResult encryptedResult(final ItemDetails details) { return new ProcessorResultImpl(details, true, true); } @Override public ValidationResult getValidationResult() { return this.validationResult; } @Override @XmlElement public FeaturesReport getFeaturesReport() { return FeaturesReport.fromValues(this.featuresResult); } @Override public MetadataFixerResult getFixerResult() { return this.fixerResult; } @Override public TaskResult getResultForTask(TaskType taskType) { return this.taskResults.get(taskType); } @Override public boolean isValidPdf() { return this.isValidPdf; } @Override public boolean isEncryptedPdf() { return this.isEncryptedPdf; } static class Adapter extends XmlAdapter<ProcessorResultImpl, ProcessorResult> { @Override public ProcessorResult unmarshal( ProcessorResultImpl procResultImpl) { return procResultImpl; } @Override public ProcessorResultImpl marshal(ProcessorResult procResult) { return (ProcessorResultImpl) procResult; } } }
package org.bouncycastle.pqc.crypto.test; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.bouncycastle.util.test.SimpleTestResult; public class AllTests extends TestCase { public static void main (String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite("Lightweight PQ Crypto Tests"); suite.addTestSuite(BitStringTest.class); suite.addTestSuite(EncryptionKeyTest.class); suite.addTestSuite(NTRUEncryptionParametersTest.class); suite.addTestSuite(NTRUEncryptTest.class); suite.addTestSuite(NTRUSignatureParametersTest.class); suite.addTestSuite(NTRUSignatureKeyTest.class); suite.addTestSuite(NTRUSignerTest.class); suite.addTestSuite(NTRUSigningParametersTest.class); suite.addTestSuite(QTESLATest.class); suite.addTestSuite(XMSSMTPrivateKeyTest.class); suite.addTestSuite(XMSSMTPublicKeyTest.class); suite.addTestSuite(XMSSMTSignatureTest.class); suite.addTestSuite(XMSSMTTest.class); suite.addTestSuite(XMSSOidTest.class); suite.addTestSuite(XMSSPrivateKeyTest.class); suite.addTestSuite(XMSSPublicKeyTest.class); suite.addTestSuite(XMSSReducedSignatureTest.class); suite.addTestSuite(XMSSSignatureTest.class); suite.addTestSuite(XMSSTest.class); suite.addTestSuite(XMSSUtilTest.class); suite.addTestSuite(AllTests.SimpleTestTest.class); return new BCTestSetup(suite); } public static class SimpleTestTest extends TestCase { public void testPQC() { org.bouncycastle.util.test.Test[] tests = RegressionTest.tests; for (int i = 0; i != tests.length; i++) { SimpleTestResult result = (SimpleTestResult)tests[i].perform(); if (!result.isSuccessful()) { if (result.getException() != null) { result.getException().printStackTrace(); } fail(result.toString()); } } } } static class BCTestSetup extends TestSetup { public BCTestSetup(Test test) { super(test); } protected void setUp() { } protected void tearDown() { } } }
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import gnu.io.*; public class AvrdudeUploader extends Uploader { public AvrdudeUploader() { } public boolean uploadUsingPreferences(String buildPath, String className) throws RunnerException { List commandDownloader = new ArrayList(); // avrdude doesn't want to read device signatures (it always gets // 0x000000); force it to continue uploading anyway commandDownloader.add("-F"); String protocol = Preferences.get("boards." + Preferences.get("board") + ".upload.protocol"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (protocol.equals("stk500")) protocol = "stk500v1"; commandDownloader.add("-c" + protocol); if (protocol.equals("dapa")) { // avrdude doesn't need to be told the address of the parallel port //commandDownloader.add("-dlpt=" + Preferences.get("parallel.port")); } else { commandDownloader.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port")); commandDownloader.add( "-b" + Preferences.getInteger("boards." + Preferences.get("board") + ".upload.speed")); } if (Preferences.getBoolean("upload.erase")) commandDownloader.add("-e"); else commandDownloader.add("-D"); if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); flushSerialBuffer(); return uisp(commandDownloader); } public boolean burnBootloaderAVRISP(String target) throws RunnerException { List commandDownloader = new ArrayList(); commandDownloader.add("-c" + Preferences.get("bootloader." + target + ".programmer")); if (Preferences.get("bootloader." + target + ".communication").equals("usb")) { commandDownloader.add("-Pusb"); } else { commandDownloader.add( "-P" + (Base.isWindows() ? "/dev/" + Preferences.get("serial.port").toLowerCase() : Preferences.get("serial.port"))); } commandDownloader.add("-b" + Preferences.get("serial.burn_rate")); return burnBootloader(target, commandDownloader); } public boolean burnBootloaderParallel(String target) throws RunnerException { List commandDownloader = new ArrayList(); commandDownloader.add("-dprog=dapa"); commandDownloader.add("-dlpt=" + Preferences.get("parallel.port")); return burnBootloader(target, commandDownloader); } protected boolean burnBootloader(String target, Collection params) throws RunnerException { return // unlock bootloader segment of flash memory and write fuses uisp(params, Arrays.asList(new String[] { "-e", "-Ulock:w:" + Preferences.get("bootloader." + target + ".unlock_bits") + ":m", "-Uefuse:w:" + Preferences.get("bootloader." + target + ".extended_fuses") + ":m", "-Uhfuse:w:" + Preferences.get("bootloader." + target + ".high_fuses") + ":m", "-Ulfuse:w:" + Preferences.get("bootloader." + target + ".low_fuses") + ":m", })) && // upload bootloader and lock bootloader segment uisp(params, Arrays.asList(new String[] { "-Uflash:w:" + Preferences.get("bootloader." + target + ".path") + File.separator + Preferences.get("bootloader." + target + ".file") + ":i", "-Ulock:w:" + Preferences.get("bootloader." + target + ".lock_bits") + ":m" })); } public boolean uisp(Collection p1, Collection p2) throws RunnerException { ArrayList p = new ArrayList(p1); p.addAll(p2); return uisp(p); } public boolean uisp(Collection params) throws RunnerException { List commandDownloader = new ArrayList(); commandDownloader.add("avrdude"); // On Windows and the Mac, we need to point avrdude at its config file // since it's getting installed in an unexpected location (i.e. a // sub-directory of wherever the user happens to stick Arduino). On Linux, // avrdude will have been properly installed by the distribution's package // manager and should be able to find its config file. if(Base.isMacOS()) { commandDownloader.add("-C" + "hardware/tools/avr/etc/avrdude.conf"); } else if(Base.isWindows()) { String userdir = System.getProperty("user.dir") + File.separator; commandDownloader.add("-C" + userdir + "hardware/tools/avr/etc/avrdude.conf"); } else { commandDownloader.add("-C" + "hardware/tools/avrdude.conf"); } if (Preferences.getBoolean("upload.verbose")) { commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); } else { commandDownloader.add("-q"); commandDownloader.add("-q"); } // XXX: quick hack to chop the "atmega" off of "atmega8" and "atmega168", // then shove an "m" at the beginning. won't work for attiny's, etc. commandDownloader.add("-pm" + Preferences.get("boards." + Preferences.get("board") + ".build.mcu").substring(6)); commandDownloader.addAll(params); return executeUploadCommand(commandDownloader); } }
package controllers; import play.*; import play.mvc.*; import play.data.binding.As; import play.db.jpa.JPA; import utils.GeoUtils; import java.io.IOException; import java.io.StringWriter; import java.math.BigInteger; import java.util.*; import javax.persistence.Entity; import static java.util.Collections.sort; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.geotools.geometry.jts.JTS; import org.opengis.referencing.operation.MathTransform; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.linearref.LengthLocationMap; import com.vividsolutions.jts.linearref.LinearLocation; import com.vividsolutions.jts.linearref.LocationIndexedLine; import models.*; import models.transit.Agency; import models.transit.Route; import models.transit.RouteType; import models.transit.ServiceCalendar; import models.transit.Stop; import models.transit.StopTime; import models.transit.Trip; import models.transit.TripPattern; import models.transit.TripPatternStop; import models.transit.TripShape; @With(Secure.class) public class Api extends Controller { @Before static void initSession() throws Throwable { if(!Security.isConnected()) Secure.login(); } private static ObjectMapper mapper = new ObjectMapper(); private static JsonFactory jf = new JsonFactory(); private static String toJson(Object pojo, boolean prettyPrint) throws JsonMappingException, JsonGenerationException, IOException { StringWriter sw = new StringWriter(); JsonGenerator jg = jf.createJsonGenerator(sw); if (prettyPrint) { jg.useDefaultPrettyPrinter(); } mapper.writeValue(jg, pojo); return sw.toString(); } public static void getAgency(Long id) { try { if(id != null) { Agency agency = Agency.findById(id); if(agency != null) renderJSON(Api.toJson(agency, false)); else notFound(); } else { renderJSON(Api.toJson(Agency.find("order by name").fetch(), false)); } } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void createAgency() { Agency agency; try { agency = mapper.readValue(params.get("body"), Agency.class); agency.save(); // check if gtfsAgencyId is specified, if not create from DB id if(agency.gtfsAgencyId == null) { agency.gtfsAgencyId = "AGENCY_" + agency.id.toString(); agency.save(); } renderJSON(Api.toJson(agency, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void updateAgency() { Agency agency; try { agency = mapper.readValue(params.get("body"), Agency.class); if(agency.id == null || Agency.findById(agency.id) == null) badRequest(); // check if gtfsAgencyId is specified, if not create from DB id if(agency.gtfsAgencyId == null) agency.gtfsAgencyId = "AGENCY_" + agency.id.toString(); Agency updatedAgency = Agency.em().merge(agency); updatedAgency.save(); renderJSON(Api.toJson(updatedAgency, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void deleteAgency(Long id) { if(id == null) badRequest(); Agency agency = Agency.findById(id); if(agency == null) badRequest(); agency.delete(); ok(); } public static void getRouteType(Long id) { try { if(id != null) { RouteType routeType = RouteType.findById(id); if(routeType != null) renderJSON(Api.toJson(routeType, false)); else notFound(); } else renderJSON(Api.toJson(RouteType.find("order by localizedvehicletype").fetch(), false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void createRouteType() { RouteType routeType; try { routeType = mapper.readValue(params.get("body"), RouteType.class); routeType.save(); renderJSON(Api.toJson(routeType, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void updateRouteType() { RouteType routeType; try { routeType = mapper.readValue(params.get("body"), RouteType.class); if(routeType.id == null ||RouteType.findById(routeType.id) == null) badRequest(); RouteType updatedRouteType = RouteType.em().merge(routeType); updatedRouteType.save(); renderJSON(Api.toJson(updatedRouteType, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void deleteRouteType(Long id) { if(id == null) badRequest(); RouteType routeType = RouteType.findById(id); if(routeType == null) badRequest(); routeType.delete(); ok(); } public static void getRoute(Long id, Long agencyId) { try { if(id != null) { Route route = Route.findById(id); if(route != null) renderJSON(Api.toJson(route, false)); else notFound(); } else { if(agencyId != null) { Agency agency = Agency.findById(agencyId); renderJSON(Api.toJson(Route.find("agency = ? order by routeShortName", agency).fetch(), false)); } else renderJSON(Api.toJson(Route.find("order by routeShortName").fetch(), false)); } } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void createRoute() { Route route; try { route = mapper.readValue(params.get("body"), Route.class); if(Agency.findById(route.agency.id) == null) badRequest(); route.save(); // check if gtfsRouteId is specified, if not create from DB id if(route.gtfsRouteId == null) { route.gtfsRouteId = "ROUTE_" + route.id.toString(); route.save(); } renderJSON(Api.toJson(route, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void updateRoute() { Route route; try { route = mapper.readValue(params.get("body"), Route.class); if(route.id == null || Route.findById(route.id) == null) badRequest(); // check if gtfsRouteId is specified, if not create from DB id if(route.gtfsRouteId == null) route.gtfsRouteId = "ROUTE_" + route.id.toString(); Route updatedRoute = Route.em().merge(route); updatedRoute.save(); renderJSON(Api.toJson(updatedRoute, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void deleteRoute(Long id) { if(id == null) badRequest(); Route route = Route.findById(id); if(route == null) badRequest(); route.delete(); ok(); } public static void getStop(Long id, Double lat, Double lon, Boolean majorStops, Long agencyId) { Agency agency = null; if(agencyId != null) agency = Agency.findById(agencyId); try { if(id != null) { Stop stop = Stop.findById(id); if(stop != null) renderJSON(Api.toJson(stop, false)); else notFound(); } else if (majorStops != null && majorStops) { if(agency != null) renderJSON(Api.toJson(Stop.find("agency = ? and majorStop = true", agency).fetch(), false)); else renderJSON(Api.toJson(Stop.find("majorStop = true").fetch(), false)); } else if (lat != null && lon != null) { //GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(),4326); //Geometry point = geometryFactory.createPoint(new Coordinate(lon,lat)); String point = "POINT(" + lon + " " + lat + ")"; if(agency != null) renderJSON(Api.toJson(Stop.find("agency = ? and distance(location, st_geomfromtext(?, 4326)) < 0.025", agency, point).fetch(), false)); else renderJSON(Api.toJson(Stop.find("distance(location, st_geomfromtext(?, 4326)) < 0.025", point).fetch(), false)); } else { if(agency != null) renderJSON(Api.toJson(Stop.find("agency = ?", agency).fetch(), false)); else renderJSON(Api.toJson(Stop.all().fetch(), false)); } } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void createStop() { Stop stop; try { stop = mapper.readValue(params.get("body"), Stop.class); if(Agency.findById(stop.agency.id) == null) badRequest(); stop.save(); // check if gtfsRouteId is specified, if not create from DB id if(stop.gtfsStopId == null) { stop.gtfsStopId = "STOP_" + stop.id.toString(); stop.save(); } renderJSON(Api.toJson(stop, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void updateStop() { Stop stop; try { stop = mapper.readValue(params.get("body"), Stop.class); if(stop.id == null || Stop.findById(stop.id) == null) badRequest(); // check if gtfsRouteId is specified, if not create from DB id if(stop.gtfsStopId == null) stop.gtfsStopId = "STOP_" + stop.id.toString(); Stop updatedStop = Stop.em().merge(stop); updatedStop.save(); renderJSON(Api.toJson(updatedStop, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void deleteStop(Long id) { if(id == null) badRequest(); Stop stop = Stop.findById(id); if(stop == null) badRequest(); stop.delete(); ok(); } public static void findDuplicateStops(Long agencyId) { try { List<List<Stop>> duplicateStopPairs = Stop.findDuplicateStops(BigInteger.valueOf(agencyId.longValue())); renderJSON(Api.toJson(duplicateStopPairs, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void mergeStops(Long stop1Id, @As(",") List<String> mergedStopIds) { if(stop1Id == null) badRequest(); Stop stop1 = Stop.findById(stop1Id); for(String stopIdStr : mergedStopIds) { Stop stop2 = Stop.findById(Long.parseLong(stopIdStr)); if(stop1 == null && stop2 == null) badRequest(); stop1.merge(stop2); ok(); } } public static void getTripPattern(Long id, Long routeId) { try { if(id != null) { TripPattern tripPattern = TripPattern.findById(id); sort(tripPattern.patternStops); if(tripPattern != null) renderJSON(Api.toJson(tripPattern, false)); else notFound(); } else if(routeId != null) { Route r = Route.findById(routeId); if(r == null) badRequest(); List<TripPattern> ret = TripPattern.find("route = ?", r).fetch(); for (TripPattern pat : ret) { sort(pat.patternStops); } renderJSON(Api.toJson(ret, false)); } else { List<TripPattern> ret = TripPattern.all().fetch(); for (TripPattern pat : ret) { sort(pat.patternStops); } renderJSON(Api.toJson(ret, false)); } } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void createTripPattern() { TripPattern tripPattern; try { tripPattern = mapper.readValue(params.get("body"), TripPattern.class); if(tripPattern.encodedShape != null) { TripShape ts = TripShape.createFromEncoded(tripPattern.encodedShape); tripPattern.shape = ts; } tripPattern.save(); renderJSON(Api.toJson(tripPattern, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void updateTripPattern() { TripPattern tripPattern; try { tripPattern = mapper.readValue(params.get("body"), TripPattern.class); if(tripPattern.id == null) badRequest(); TripPattern originalTripPattern = TripPattern.findById(tripPattern.id); if(originalTripPattern == null) badRequest(); if(tripPattern.encodedShape != null) { if(originalTripPattern.shape != null) { originalTripPattern.shape.updateShapeFromEncoded(tripPattern.encodedShape); tripPattern.shape = originalTripPattern.shape; } else { TripShape ts = TripShape.createFromEncoded(tripPattern.encodedShape); tripPattern.shape = ts; } } else { tripPattern.shape = null; // need to remove old shapes... } // update stop times originalTripPattern.reconcilePatternStops(tripPattern); TripPattern updatedTripPattern = TripPattern.em().merge(tripPattern); updatedTripPattern.save(); // save updated stop times for (Object trip : Trip.find("pattern = ?", updatedTripPattern).fetch()) { for (StopTime st : ((Trip) trip).getStopTimes()) { st.save(); } } Set<Long> patternStopIds = new HashSet<Long>(); for(TripPatternStop patternStop : updatedTripPattern.patternStops) { patternStopIds.add(patternStop.id); } List<TripPatternStop> patternStops = TripPatternStop.find("pattern = ?", tripPattern).fetch(); for(TripPatternStop patternStop : patternStops) { if(!patternStopIds.contains(patternStop.id)) patternStop.delete(); } if(tripPattern.shape != null) { MathTransform mt = GeoUtils.getTransform(new Coordinate(tripPattern.shape.shape.getCoordinateN(0).y, tripPattern.shape.shape.getCoordinateN(0).x)); GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 4326); Coordinate[] mCoords = tripPattern.shape.shape.getCoordinates(); ArrayList<Coordinate> coords = new ArrayList<Coordinate>(); for(Coordinate mCoord : mCoords) { coords.add(new Coordinate(mCoord.x, mCoord.y)); } Coordinate[] coordArray = coords.toArray(new Coordinate[coords.size()]); LineString ls = (LineString) JTS.transform(geometryFactory.createLineString(coordArray), mt); LocationIndexedLine indexLine = new LocationIndexedLine(ls); Logger.info("length: " + ls.getLength()); patternStops = TripPatternStop.find("pattern = ?", tripPattern).fetch(); for(TripPatternStop patternStop : patternStops) { Point p = (Point) JTS.transform(patternStop.stop.locationPoint(), mt); LinearLocation l = indexLine.project(p.getCoordinate()); patternStop.defaultDistance = LengthLocationMap.getLength(ls, l); patternStop.save(); } } // make sure that things are persisted; avoid DB race conditions // once upon a time, there was a bug in this code that only manifested itself once the entity manager // had been flushed, either here or by GC. JPA.em().flush(); renderJSON(Api.toJson(updatedTripPattern, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void deleteTripPattern(Long id) { if(id == null) badRequest(); TripPattern tripPattern = TripPattern.findById(id); if(tripPattern == null) badRequest(); tripPattern.delete(); ok(); } public static void calcTripPatternTimes(Long id, Double velocity, int defaultDwell) { TripPattern tripPattern = TripPattern.findById(id); List<TripPatternStop> patternStops = TripPatternStop.find("pattern = ? ORDER BY stopSequence", tripPattern).fetch(); Double distanceAlongLine = 0.0; for(TripPatternStop patternStop : patternStops) { patternStop.defaultTravelTime = (int) Math.round((patternStop.defaultDistance - distanceAlongLine) / velocity); patternStop.defaultDwellTime = defaultDwell; distanceAlongLine = patternStop.defaultDistance; patternStop.save(); } ok(); } public static void getCalendar(Long id, Long agencyId) { try { if(id != null) { ServiceCalendar cal = ServiceCalendar.findById(id); if(cal != null) renderJSON(Api.toJson(cal, false)); else notFound(); } else { if(agencyId != null) { Agency agency = Agency.findById(agencyId); renderJSON(Api.toJson(ServiceCalendar.find("agency = ?", agency).fetch(), false)); } else renderJSON(Api.toJson(ServiceCalendar.all().fetch(), false)); } } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void createCalendar() { ServiceCalendar cal; try { cal = mapper.readValue(params.get("body"), ServiceCalendar.class); if(Agency.findById(cal.agency.id) == null) badRequest(); cal.save(); // check if gtfsServiceId is specified, if not create from DB id if(cal.gtfsServiceId == null) { cal.gtfsServiceId = "CAL_" + cal.id.toString(); cal.save(); } renderJSON(Api.toJson(cal, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void updateCalendar() { ServiceCalendar cal; try { cal = mapper.readValue(params.get("body"), ServiceCalendar.class); if(cal.id == null || ServiceCalendar.findById(cal.id) == null) badRequest(); // check if gtfsAgencyId is specified, if not create from DB id if(cal.gtfsServiceId == null) cal.gtfsServiceId = "CAL_" + cal.id.toString(); ServiceCalendar updatedCal = ServiceCalendar.em().merge(cal); updatedCal.save(); renderJSON(Api.toJson(updatedCal, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void deleteCalendar(Long id) { if(id == null) badRequest(); ServiceCalendar cal = ServiceCalendar.findById(id); if(cal == null) badRequest(); cal.delete(); ok(); } // trip controllers public static void getTrip(Long id, Long patternId, Long calendarId, Long agencyId) { try { if(id != null) { Trip trip = Trip.findById(id); if(trip != null) renderJSON(Api.toJson(trip, false)); else notFound(); } else { if(agencyId != null) { Agency agency = Agency.findById(agencyId); renderJSON(Api.toJson(Trip.find("pattern.route.agency = ?", agency).fetch(), false)); } else if (patternId != null && calendarId != null) { TripPattern pattern = TripPattern.findById(patternId); ServiceCalendar calendar = ServiceCalendar.findById(calendarId); renderJSON(Api.toJson(Trip.find("byPatternAndServiceCalendar", pattern, calendar).fetch(), false)); } else if(patternId != null) { TripPattern pattern = TripPattern.findById(patternId); renderJSON(Api.toJson(Trip.find("pattern = ?", pattern).fetch(), false)); } else { renderJSON(Api.toJson(Trip.all().fetch(), false)); } } } catch (Exception e) { e.printStackTrace(); badRequest(); } } /** * When trips come back over the wire, they contain stop times directly due to hierarchical serialization. */ public static class TripWithStopTimes extends Trip { List<StopTimeWithDeletion> stopTimes; public Trip toTrip () { Trip ret = new Trip(); ret.blockId = this.blockId; ret.endTime = this.endTime; ret.gtfsTripId = this.gtfsTripId; ret.headway = this.headway; ret.id = this.id; ret.pattern = this.pattern; ret.route = this.route; ret.serviceCalendar = this.serviceCalendar; ret.serviceCalendarDate = this.serviceCalendarDate; ret.shape = this.shape; ret.startTime = this.startTime; ret.tripDescription = this.tripDescription; ret.tripDirection = this.tripDirection; ret.tripHeadsign = this.tripHeadsign; ret.tripShortName = this.tripShortName; ret.useFrequency = this.useFrequency; ret.wheelchairBoarding = this.wheelchairBoarding; return ret; } } /** * When StopTimes come back, they may also have the field deleted, which if true indicate that this stop time has * been deleted (i.e. trip no longer stops here). */ public static class StopTimeWithDeletion extends StopTime { public Boolean deleted; public StopTime toStopTime () { StopTime ret = new StopTime(); ret.id = this.id; ret.arrivalTime = this.arrivalTime; ret.departureTime = this.departureTime; ret.dropOffType = this.dropOffType; ret.patternStop = this.patternStop; ret.pickupType = this.pickupType; ret.shapeDistTraveled = this.shapeDistTraveled; ret.stop = this.stop; ret.stopHeadsign = this.stopHeadsign; ret.stopSequence = this.stopSequence; ret.trip = this.trip; return ret; } } public static void createTrip() { TripWithStopTimes tripWithStopTimes = null; Trip trip = null; try { try { tripWithStopTimes = mapper.readValue(params.get("body"), TripWithStopTimes.class); } catch (Exception e) { trip = mapper.readValue(params.get("body"), Trip.class); } if (tripWithStopTimes != null) { trip = tripWithStopTimes.toTrip(); } if(Route.findById(trip.pattern.route.id) == null) badRequest(); // if endtime is before start time add a day (e.g 07:00-00:30 becomes 07:00-24:30) if(trip != null && trip.useFrequency != null && trip.endTime != null && trip.useFrequency && trip.startTime != null && trip.endTime < trip.startTime) { trip.endTime += (24 * 60 * 60 ); } trip.save(); // check if gtfsRouteId is specified, if not create from DB id if(trip.gtfsTripId == null) { trip.gtfsTripId = "TRIP_" + trip.id.toString(); trip.save(); } if (tripWithStopTimes != null && tripWithStopTimes.stopTimes != null) { for (StopTimeWithDeletion stopTime: tripWithStopTimes.stopTimes) { stopTime.trip = trip; stopTime.toStopTime().save(); } } renderJSON(Api.toJson(trip, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void updateTrip() { TripWithStopTimes trip; try { trip = mapper.readValue(params.get("body"), TripWithStopTimes.class); if(trip.id == null || Trip.findById(trip.id) == null) badRequest(); // if endtime is before start time add a day (e.g 07:00-00:30 becomes 07:00-24:30) if(trip.useFrequency && trip.endTime < trip.startTime) { trip.endTime += (24 * 60 * 60 ); } // check if gtfsRouteId is specified, if not create from DB id if(trip.gtfsTripId == null) { trip.gtfsTripId = "TRIP_" + trip.id.toString(); } Trip updatedTrip = Trip.em().merge(trip.toTrip()); // update the stop times // TODO: how to detect deleted StopTimes (i.e. route no longer stops here)? for (StopTimeWithDeletion stopTime : trip.stopTimes) { if (Boolean.TRUE.equals(stopTime.deleted)) { StopTime.delete("id = ? AND trip = ?", stopTime.id, updatedTrip); } else { StopTime updatedStopTime = StopTime.em().merge(stopTime.toStopTime()); // this was getting lost somehow updatedStopTime.trip = updatedTrip; updatedStopTime.save(); } } updatedTrip.save(); renderJSON(Api.toJson(updatedTrip, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void deleteTrip(Long id) { if(id == null) badRequest(); Trip trip = Trip.findById(id); if(trip == null) badRequest(); StopTime.delete("trip = ?", trip); trip.delete(); ok(); } }
package org.jasig.portal.groups; import org.jasig.portal.EntityIdentifier; /** * Interface for finding and maintaining <code>IEntityGroups</code>. * @author Dan Ellentuck * @version 1.0, 11/29/01 */ public interface IEntityGroupStore extends IGroupConstants { /** * Delete this <code>IEntityGroup</code> from the data store. * @param group org.jasig.portal.groups.IEntityGroup */ public void delete(IEntityGroup group) throws GroupsException; /** * Returns an instance of the <code>IEntityGroup</code> from the data store. * @return org.jasig.portal.groups.IEntityGroup * @param key java.lang.String */ public IEntityGroup find(String key) throws GroupsException; /** * Returns an <code>Iterator</code> over the <code>Collection</code> of * <code>IEntityGroups</code> that the <code>IGroupMember</code> belongs to. * @return java.util.Iterator * @param gm org.jasig.portal.groups.IEntityGroup */ public java.util.Iterator findContainingGroups(IGroupMember gm) throws GroupsException; /** * Returns an <code>Iterator</code> over the <code>Collection</code> of * <code>IEntityGroups</code> that are members of this <code>IEntityGroup</code>. * @return java.util.Iterator * @param group org.jasig.portal.groups.IEntityGroup */ public java.util.Iterator findMemberGroups(IEntityGroup group) throws GroupsException; /** * @return org.jasig.portal.groups.IEntityGroup */ public IEntityGroup newInstance(Class entityType) throws GroupsException; /** * Adds or updates the <code>IEntityGroup</code> AND ITS MEMBERSHIPS to the * data store, as appropriate. * @param group org.jasig.portal.groups.IEntityGroup */ public void update(IEntityGroup group) throws GroupsException; /** * Commits the group memberships of the <code>IEntityGroup</code> to * the data store. * @param group org.jasig.portal.groups.IEntityGroup */ public void updateMembers(IEntityGroup group) throws GroupsException; /** * Returns an instance of the <code>ILockableEntityGroup</code> from the data store. * @return org.jasig.portal.groups.IEntityGroup * @param key java.lang.String */ public ILockableEntityGroup findLockable(String key) throws GroupsException; /** * Find EntityIdentifiers for groups whose name matches the query string * according to the specified method and matches the provided leaf type */ public EntityIdentifier[] searchForGroups(String query, int method, Class leaftype) throws GroupsException; }
package org.jasig.portal.utils; import java.util.Hashtable; import java.util.Iterator; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; /** * An implementation of IPortalDocument that decorates a generic * <code>Document</code> object. This is used to locally store and manage * the ID element mappings regardless of the DOM implementation. * * @see org.w3c.dom.Document for decorator method descriptions. * * @author Nick Bolton * @version $Revision$ */ public class PortalDocumentImpl implements IPortalDocument { private Hashtable identifiers = new Hashtable(1024); private final Hashtable keys = new Hashtable(1024); public Document document = null; PortalDocumentImpl() { document = DocumentFactory.__getNewDocument(); } PortalDocumentImpl(Document doc) { document = doc; } public final Hashtable getIdentifiers() { return identifiers; } public final void setIdentifiers( Hashtable identifiers ) { this.identifiers = identifiers; } /** * Registers an identifier name with a specified element. * * @param key a key used to store an <code>Element</code> object. * @param element an <code>Element</code> object to map. * @exception DOMException if the element does not belong to the * document. */ public void putIdentifier(String key, Element element) throws DOMException { if (element == null) { removeElement(key); return; } if (element.getOwnerDocument() != document) { StringBuffer msg = new StringBuffer(); msg.append("Trying to cache an element that doesn't belong to "); msg.append("this document."); throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, msg.toString()); } identifiers.put(key, element); } /** * Copies the element cache from the source document. This will * provide equivalent mappings from IDs to elements in this * document provided the elements exist in the source document. * If no element exists, it will be skipped. * * @param sourceDoc The source doc to copy from. */ public void copyCache(IPortalDocument sourceDoc) { for (Node n = this.getFirstChild(); n != null; n = n.getNextSibling()) { preserveCache(sourceDoc, n); } keys.clear(); } private void removeElement(String key) { Element elem = getElementById(key); if ( elem != null ) keys.remove(XML.serializeNode(elem)); identifiers.remove(key); } private void preserveCache(IPortalDocument sourceDoc, Node node) { if (node instanceof Element) { Element element = (Element) node; String serializedNode = XML.serializeNode(element); String key = ((PortalDocumentImpl)sourceDoc). getElementKey(serializedNode); if (key != null) { putIdentifier(key, element); } } node = node.getFirstChild(); while (node != null) { preserveCache(sourceDoc, node); node = node.getNextSibling(); } } private String getElementKey(String serializedNode) { String key = null; if ( keys.isEmpty() ) { Iterator itr = identifiers.keySet().iterator(); while (itr.hasNext()) { String id = (String) itr.next(); Element element = (Element) identifiers.get(key); String value = XML.serializeNode(element); keys.put(value,id); if ( serializedNode.equals(value) ) key = id; } } else key = (String) keys.get(serializedNode); return key; } // decorator methods /** * This method was overloaded to provide local element caching. */ public Element getElementById(String key) { return (Element)identifiers.get(key); } public DocumentType getDoctype() { return document.getDoctype(); } public DOMImplementation getImplementation() { return document.getImplementation(); } public Element getDocumentElement() { return document.getDocumentElement(); } public Element createElement(String tagName) throws DOMException { return document.createElement(tagName); } public DocumentFragment createDocumentFragment() { return document.createDocumentFragment(); } public Text createTextNode(String data) { return document.createTextNode(data); } public Comment createComment(String data) { return document.createComment(data); } public CDATASection createCDATASection(String data) throws DOMException { return document.createCDATASection(data); } public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException { return document.createProcessingInstruction(target, data); } public Attr createAttribute(String name) throws DOMException { return document.createAttribute(name); } public EntityReference createEntityReference(String name) throws DOMException { return document.createEntityReference(name); } public NodeList getElementsByTagName(String tagname) { return document.getElementsByTagName(tagname); } public Node importNode(Node importedNode, boolean deep) throws DOMException { return document.importNode(importedNode, deep); } public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException { return document.createElementNS(namespaceURI, qualifiedName); } public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException { return document.createAttributeNS(namespaceURI, qualifiedName); } public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { return document.getElementsByTagNameNS(namespaceURI, localName); } public String getNodeName() { return document.getNodeName(); } public String getNodeValue() throws DOMException { return document.getNodeValue(); } public void setNodeValue(String nodeValue) throws DOMException { document.setNodeValue(nodeValue); } public short getNodeType() { return document.getNodeType(); } public Node getParentNode() { return document.getParentNode(); } public NodeList getChildNodes() { return document.getChildNodes(); } public Node getFirstChild() { return document.getFirstChild(); } public Node getLastChild() { return document.getLastChild(); } public Node getPreviousSibling() { return document.getPreviousSibling(); } public Node getNextSibling() { return document.getNextSibling(); } public NamedNodeMap getAttributes() { return document.getAttributes(); } public Document getOwnerDocument() { return document.getOwnerDocument(); } public Node insertBefore(Node newChild, Node refChild) throws DOMException { return document.insertBefore(newChild, refChild); } public Node replaceChild(Node newChild, Node oldChild) throws DOMException { return document.replaceChild(newChild, oldChild); } public Node removeChild(Node oldChild) throws DOMException { return document.removeChild(oldChild); } public Node appendChild(Node newChild) throws DOMException { return document.appendChild(newChild); } public boolean hasChildNodes() { return document.hasChildNodes(); } public Node cloneNode(boolean deep) { Document newDoc = (Document)document.cloneNode(deep); PortalDocumentImpl newNode = new PortalDocumentImpl(newDoc); // only copy the identifiers if it's a deep cloning. Otherwise, // the children won't exist and you'd have an identifier mapping // that was invalid. if (deep) { //newNode.copyCache(this); newNode.setIdentifiers((Hashtable)identifiers.clone()); } return newNode; } public void normalize() { document.normalize(); } public boolean isSupported(String feature, String version) { return document.isSupported(feature, version); } public String getNamespaceURI() { return document.getNamespaceURI(); } public String getPrefix() { return document.getPrefix(); } public void setPrefix(String prefix) throws DOMException { document.setPrefix(prefix); } public String getLocalName() { return document.getLocalName(); } public boolean hasAttributes() { return document.hasAttributes(); } // used for debugging void checkCache() { String key; Element element; System.out.println("CHECKING CACHE for: " + this + " (" + this.hashCode() + ")"); Iterator itr = identifiers.keySet().iterator(); while (itr.hasNext()) { key = (String)itr.next(); element = (Element)identifiers.get(key); if (element.getOwnerDocument() != document) { System.out.println("ERROR: element does not belong to this document: " + key); } } System.out.println("DONE CHECKING CACHE for: " + this + " (" + this.hashCode() + ")\n"); } void checkCaches(PortalDocumentImpl doc2) { String key; Element element1; Element element2; String xml1; String xml2; System.out.println("CHECKING CACHES for: " + this + " (" + this.hashCode() + ") and " + doc2 + "( " + doc2.hashCode() + ")"); this.checkCache(); doc2.checkCache(); Iterator itr = this.identifiers.keySet().iterator(); while (itr.hasNext()) { key = (String)itr.next(); element1 = (Element)this.identifiers.get(key); element2 = (Element)doc2.identifiers.get(key); if (element2 == null) { System.out.println( "ERROR: Mapping does not exist in doc2 for key: " + key); continue; } xml1 = XML.serializeNode(element1); xml2 = XML.serializeNode(element2); if (!xml1.equals(xml2)) { System.out.println("ERROR: xml differs for key: " + key); System.out.println("xml1...\n" + xml1); System.out.println("xml2...\n" + xml2); } else { System.out.println("ok key: " + key); } } System.out.println("DONE CHECKING CACHES for: " + this + " (" + this.hashCode() + ") and " + doc2 + "( " + doc2.hashCode() + ")"); } void dumpCache() { String key; Node node; System.out.println("Element Map size: " + identifiers.size()); Iterator itr = identifiers.keySet().iterator(); while(itr.hasNext()) { key = (String)itr.next(); node = (Node)identifiers.get(key); System.out.println("key/node: " + key + "/" + node + " (" + node.hashCode() + ")"); } } }
package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.ParamChecks; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.util.PublicCloneable; import org.jfree.util.ShapeUtilities; /** * A renderer that draws a small dot at each data point for an {@link XYPlot}. * The example shown here is generated by the * <code>ScatterPlotDemo4.java</code> program included in the JFreeChart * demo collection: * <br><br> * <img src="../../../../../images/XYDotRendererSample.png" * alt="XYDotRendererSample.png" /> */ public class XYDotRenderer extends AbstractXYItemRenderer implements XYItemRenderer, PublicCloneable { /** For serialization. */ private static final long serialVersionUID = -2764344339073566425L; /** The dot width. */ private int dotWidth; /** The dot height. */ private int dotHeight; /** * The shape that is used to represent an item in the legend. * * @since 1.0.7 */ private transient Shape legendShape; /** * Constructs a new renderer. */ public XYDotRenderer() { super(); this.dotWidth = 1; this.dotHeight = 1; this.legendShape = new Rectangle2D.Double(-3.0, -3.0, 6.0, 6.0); } /** * Returns the dot width (the default value is 1). * * @return The dot width. * * @since 1.0.2 * @see #setDotWidth(int) */ public int getDotWidth() { return this.dotWidth; } public void setDotWidth(int w) { if (w < 1) { throw new IllegalArgumentException("Requires w > 0."); } this.dotWidth = w; fireChangeEvent(); } /** * Returns the dot height (the default value is 1). * * @return The dot height. * * @since 1.0.2 * @see #setDotHeight(int) */ public int getDotHeight() { return this.dotHeight; } public void setDotHeight(int h) { if (h < 1) { throw new IllegalArgumentException("Requires h > 0."); } this.dotHeight = h; fireChangeEvent(); } /** * Returns the shape used to represent an item in the legend. * * @return The legend shape (never <code>null</code>). * * @see #setLegendShape(Shape) * * @since 1.0.7 */ public Shape getLegendShape() { return this.legendShape; } /** * Sets the shape used as a line in each legend item and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param shape the shape (<code>null</code> not permitted). * * @see #getLegendShape() * * @since 1.0.7 */ public void setLegendShape(Shape shape) { ParamChecks.nullNotPermitted(shape, "shape"); this.legendShape = shape; fireChangeEvent(); } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain (horizontal) axis. * @param rangeAxis the range (vertical) axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // do nothing if item is not visible if (!getItemVisible(series, item)) { return; } // get the data point... double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); double adjx = (this.dotWidth - 1) / 2.0; double adjy = (this.dotHeight - 1) / 2.0; if (!Double.isNaN(y)) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX = domainAxis.valueToJava2D(x, dataArea, xAxisLocation) - adjx; double transY = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation) - adjy; g2.setPaint(getItemPaint(series, item)); PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { g2.fillRect((int) transY, (int) transX, this.dotHeight, this.dotWidth); } else if (orientation == PlotOrientation.VERTICAL) { g2.fillRect((int) transX, (int) transY, this.dotWidth, this.dotHeight); } int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x, y, domainAxisIndex, rangeAxisIndex, transX, transY, orientation); } } /** * Returns a legend item for the specified series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return A legend item for the series (possibly <code>null</code>). */ public LegendItem getLegendItem(int datasetIndex, int series) { // if the renderer isn't assigned to a plot, then we don't have a // dataset... XYPlot plot = getPlot(); if (plot == null) { return null; } XYDataset dataset = plot.getDataset(datasetIndex); if (dataset == null) { return null; } LegendItem result = null; if (getItemVisible(series, 0)) { String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Paint fillPaint = lookupSeriesPaint(series); result = new LegendItem(label, description, toolTipText, urlText, getLegendShape(), fillPaint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setSeriesKey(dataset.getSeriesKey(series)); result.setSeriesIndex(series); result.setDataset(dataset); result.setDatasetIndex(datasetIndex); } return result; } /** * Tests this renderer for equality with an arbitrary object. This method * returns <code>true</code> if and only if: * * <ul> * <li><code>obj</code> is not <code>null</code>;</li> * <li><code>obj</code> is an instance of <code>XYDotRenderer</code>;</li> * <li>both renderers have the same attribute values. * </ul> * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYDotRenderer)) { return false; } XYDotRenderer that = (XYDotRenderer) obj; if (this.dotWidth != that.dotWidth) { return false; } if (this.dotHeight != that.dotHeight) { return false; } if (!ShapeUtilities.equal(this.legendShape, that.legendShape)) { return false; } return super.equals(obj); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendShape = SerialUtilities.readShape(stream); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendShape, stream); } }
package org.jfree.data.gantt; import java.io.Serializable; import java.util.Iterator; import java.util.List; import org.jfree.data.general.AbstractSeriesDataset; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.time.TimePeriod; import org.jfree.util.ObjectUtilities; import org.jfree.util.PublicCloneable; /** * A collection of {@link TaskSeries} objects. This class provides one * implementation of the {@link GanttCategoryDataset} interface. */ public class TaskSeriesCollection extends AbstractSeriesDataset implements GanttCategoryDataset, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -2065799050738449903L; /** * Storage for aggregate task keys (the task description is used as the * key). */ private List keys; /** Storage for the series. */ private List data; /** * Default constructor. */ public TaskSeriesCollection() { this.keys = new java.util.ArrayList(); this.data = new java.util.ArrayList(); } /** * Returns a series from the collection. * * @param key the series key (<code>null</code> not permitted). * * @return The series. * * @since 1.0.1 */ public TaskSeries getSeries(Comparable key) { if (key == null) { throw new NullPointerException("Null 'key' argument."); } TaskSeries result = null; int index = getRowIndex(key); if (index >= 0) { result = getSeries(index); } return result; } /** * Returns a series from the collection. * * @param series the series index (zero-based). * * @return The series. * * @since 1.0.1 */ public TaskSeries getSeries(int series) { if ((series < 0) || (series >= getSeriesCount())) { throw new IllegalArgumentException("Series index out of bounds"); } return (TaskSeries) this.data.get(series); } /** * Returns the number of series in the collection. * * @return The series count. */ public int getSeriesCount() { return getRowCount(); } /** * Returns the name of a series. * * @param series the series index (zero-based). * * @return The name of a series. */ public Comparable getSeriesKey(int series) { TaskSeries ts = (TaskSeries) this.data.get(series); return ts.getKey(); } /** * Returns the number of rows (series) in the collection. * * @return The series count. */ public int getRowCount() { return this.data.size(); } /** * Returns the row keys. In this case, each series is a key. * * @return The row keys. */ public List getRowKeys() { return this.data; } /** * Returns the number of column in the dataset. * * @return The column count. */ public int getColumnCount() { return this.keys.size(); } /** * Returns a list of the column keys in the dataset. * * @return The category list. */ public List getColumnKeys() { return this.keys; } /** * Returns a column key. * * @param index the column index. * * @return The column key. */ public Comparable getColumnKey(int index) { return (Comparable) this.keys.get(index); } /** * Returns the column index for a column key. * * @param columnKey the column key (<code>null</code> not permitted). * * @return The column index. */ public int getColumnIndex(Comparable columnKey) { if (columnKey == null) { throw new IllegalArgumentException("Null 'columnKey' argument."); } return this.keys.indexOf(columnKey); } /** * Returns the row index for the given row key. * * @param rowKey the row key. * * @return The index. */ public int getRowIndex(Comparable rowKey) { int result = -1; int count = this.data.size(); for (int i = 0; i < count; i++) { TaskSeries s = (TaskSeries) this.data.get(i); if (s.getKey().equals(rowKey)) { result = i; break; } } return result; } /** * Returns the key for a row. * * @param index the row index (zero-based). * * @return The key. */ public Comparable getRowKey(int index) { TaskSeries series = (TaskSeries) this.data.get(index); return series.getKey(); } /** * Adds a series to the dataset and sends a * {@link org.jfree.data.general.DatasetChangeEvent} to all registered * listeners. * * @param series the series (<code>null</code> not permitted). */ public void add(TaskSeries series) { if (series == null) { throw new IllegalArgumentException("Null 'series' argument."); } this.data.add(series); series.addChangeListener(this); // look for any keys that we don't already know about... Iterator iterator = series.getTasks().iterator(); while (iterator.hasNext()) { Task task = (Task) iterator.next(); String key = task.getDescription(); int index = this.keys.indexOf(key); if (index < 0) { this.keys.add(key); } } fireDatasetChanged(); } /** * Removes a series from the collection and sends * a {@link org.jfree.data.general.DatasetChangeEvent} * to all registered listeners. * * @param series the series. */ public void remove(TaskSeries series) { if (series == null) { throw new IllegalArgumentException("Null 'series' argument."); } if (this.data.contains(series)) { series.removeChangeListener(this); this.data.remove(series); fireDatasetChanged(); } } /** * Removes a series from the collection and sends * a {@link org.jfree.data.general.DatasetChangeEvent} * to all registered listeners. * * @param series the series (zero based index). */ public void remove(int series) { if ((series < 0) || (series >= getSeriesCount())) { throw new IllegalArgumentException( "TaskSeriesCollection.remove(): index outside valid range."); } // fetch the series, remove the change listener, then remove the series. TaskSeries ts = (TaskSeries) this.data.get(series); ts.removeChangeListener(this); this.data.remove(series); fireDatasetChanged(); } /** * Removes all the series from the collection and sends * a {@link org.jfree.data.general.DatasetChangeEvent} * to all registered listeners. */ public void removeAll() { // deregister the collection as a change listener to each series in // the collection. Iterator iterator = this.data.iterator(); while (iterator.hasNext()) { TaskSeries series = (TaskSeries) iterator.next(); series.removeChangeListener(this); } // remove all the series from the collection and notify listeners. this.data.clear(); fireDatasetChanged(); } /** * Returns the value for an item. * * @param rowKey the row key. * @param columnKey the column key. * * @return The item value. */ public Number getValue(Comparable rowKey, Comparable columnKey) { return getStartValue(rowKey, columnKey); } /** * Returns the value for a task. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The start value. */ public Number getValue(int row, int column) { return getStartValue(row, column); } /** * Returns the start value for a task. This is a date/time value, measured * in milliseconds since 1-Jan-1970. * * @param rowKey the series. * @param columnKey the category. * * @return The start value (possibly <code>null</code>). */ public Number getStartValue(Comparable rowKey, Comparable columnKey) { Number result = null; int row = getRowIndex(rowKey); TaskSeries series = (TaskSeries) this.data.get(row); Task task = series.get(columnKey.toString()); if (task != null) { TimePeriod duration = task.getDuration(); if (duration != null) { result = new Long(duration.getStart().getTime()); } } return result; } /** * Returns the start value for a task. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The start value. */ public Number getStartValue(int row, int column) { Comparable rowKey = getRowKey(row); Comparable columnKey = getColumnKey(column); return getStartValue(rowKey, columnKey); } /** * Returns the end value for a task. This is a date/time value, measured * in milliseconds since 1-Jan-1970. * * @param rowKey the series. * @param columnKey the category. * * @return The end value (possibly <code>null</code>). */ public Number getEndValue(Comparable rowKey, Comparable columnKey) { Number result = null; int row = getRowIndex(rowKey); TaskSeries series = (TaskSeries) this.data.get(row); Task task = series.get(columnKey.toString()); if (task != null) { TimePeriod duration = task.getDuration(); if (duration != null) { result = new Long(duration.getEnd().getTime()); } } return result; } /** * Returns the end value for a task. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The end value. */ public Number getEndValue(int row, int column) { Comparable rowKey = getRowKey(row); Comparable columnKey = getColumnKey(column); return getEndValue(rowKey, columnKey); } /** * Returns the percent complete for a given item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The percent complete (possibly <code>null</code>). */ public Number getPercentComplete(int row, int column) { Comparable rowKey = getRowKey(row); Comparable columnKey = getColumnKey(column); return getPercentComplete(rowKey, columnKey); } /** * Returns the percent complete for a given item. * * @param rowKey the row key. * @param columnKey the column key. * * @return The percent complete. */ public Number getPercentComplete(Comparable rowKey, Comparable columnKey) { Number result = null; int row = getRowIndex(rowKey); TaskSeries series = (TaskSeries) this.data.get(row); Task task = series.get(columnKey.toString()); if (task != null) { result = task.getPercentComplete(); } return result; } /** * Returns the number of sub-intervals for a given item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The sub-interval count. */ public int getSubIntervalCount(int row, int column) { Comparable rowKey = getRowKey(row); Comparable columnKey = getColumnKey(column); return getSubIntervalCount(rowKey, columnKey); } /** * Returns the number of sub-intervals for a given item. * * @param rowKey the row key. * @param columnKey the column key. * * @return The sub-interval count. */ public int getSubIntervalCount(Comparable rowKey, Comparable columnKey) { int result = 0; int row = getRowIndex(rowKey); TaskSeries series = (TaskSeries) this.data.get(row); Task task = series.get(columnKey.toString()); if (task != null) { result = task.getSubtaskCount(); } return result; } /** * Returns the start value of a sub-interval for a given item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * @param subinterval the sub-interval index (zero-based). * * @return The start value (possibly <code>null</code>). */ public Number getStartValue(int row, int column, int subinterval) { Comparable rowKey = getRowKey(row); Comparable columnKey = getColumnKey(column); return getStartValue(rowKey, columnKey, subinterval); } /** * Returns the start value of a sub-interval for a given item. * * @param rowKey the row key. * @param columnKey the column key. * @param subinterval the subinterval. * * @return The start value (possibly <code>null</code>). */ public Number getStartValue(Comparable rowKey, Comparable columnKey, int subinterval) { Number result = null; int row = getRowIndex(rowKey); TaskSeries series = (TaskSeries) this.data.get(row); Task task = series.get(columnKey.toString()); if (task != null) { Task sub = task.getSubtask(subinterval); if (sub != null) { TimePeriod duration = sub.getDuration(); result = new Long(duration.getStart().getTime()); } } return result; } /** * Returns the end value of a sub-interval for a given item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * @param subinterval the subinterval. * * @return The end value (possibly <code>null</code>). */ public Number getEndValue(int row, int column, int subinterval) { Comparable rowKey = getRowKey(row); Comparable columnKey = getColumnKey(column); return getEndValue(rowKey, columnKey, subinterval); } /** * Returns the end value of a sub-interval for a given item. * * @param rowKey the row key. * @param columnKey the column key. * @param subinterval the subinterval. * * @return The end value (possibly <code>null</code>). */ public Number getEndValue(Comparable rowKey, Comparable columnKey, int subinterval) { Number result = null; int row = getRowIndex(rowKey); TaskSeries series = (TaskSeries) this.data.get(row); Task task = series.get(columnKey.toString()); if (task != null) { Task sub = task.getSubtask(subinterval); if (sub != null) { TimePeriod duration = sub.getDuration(); result = new Long(duration.getEnd().getTime()); } } return result; } /** * Returns the percentage complete value of a sub-interval for a given item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * @param subinterval the sub-interval. * * @return The percent complete value (possibly <code>null</code>). */ public Number getPercentComplete(int row, int column, int subinterval) { Comparable rowKey = getRowKey(row); Comparable columnKey = getColumnKey(column); return getPercentComplete(rowKey, columnKey, subinterval); } /** * Returns the percentage complete value of a sub-interval for a given item. * * @param rowKey the row key. * @param columnKey the column key. * @param subinterval the sub-interval. * * @return The precent complete value (possibly <code>null</code>). */ public Number getPercentComplete(Comparable rowKey, Comparable columnKey, int subinterval) { Number result = null; int row = getRowIndex(rowKey); TaskSeries series = (TaskSeries) this.data.get(row); Task task = series.get(columnKey.toString()); if (task != null) { Task sub = task.getSubtask(subinterval); if (sub != null) { result = sub.getPercentComplete(); } } return result; } /** * Called when a series belonging to the dataset changes. * * @param event information about the change. */ public void seriesChanged(SeriesChangeEvent event) { refreshKeys(); fireDatasetChanged(); } /** * Refreshes the keys. */ private void refreshKeys() { this.keys.clear(); for (int i = 0; i < getSeriesCount(); i++) { TaskSeries series = (TaskSeries) this.data.get(i); // look for any keys that we don't already know about... Iterator iterator = series.getTasks().iterator(); while (iterator.hasNext()) { Task task = (Task) iterator.next(); String key = task.getDescription(); int index = this.keys.indexOf(key); if (index < 0) { this.keys.add(key); } } } } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof TaskSeriesCollection)) { return false; } TaskSeriesCollection that = (TaskSeriesCollection) obj; if (!ObjectUtilities.equal(this.data, that.data)) { return false; } return true; } }
package java.util; public class ArrayList<E> { Object[] elementData; private int numElements; private int capacity; public ArrayList() { this.elementData = new Object[10]; this.capacity = 10; this.numElements = 0; } public ArrayList(int initialCapacity) { this.elementData = new Object[initialCapacity]; this.capacity = initialCapacity; this.numElements = 0; } // Expand capacity to size while keeping old elements of elementData private void copyNewElementData(int size) { Object[] newElementData = new Object[size]; int i = 0; for (i = 0; i < numElements; i++) { newElementData[i] = elementData[i]; } elementData = newElementData; capacity = size; } // if adding one would be out of bounds, expand elementData private void checkAdjustSize() { if (numElements + 1 >= capacity) { // Arbitrarily 10, should compare to source copyNewElementData(capacity + 10); } } private void createSpace(int index) { int j = 0; // Note - 1 because one after last element could be out of range for (j = numElements; j > index; j elementData[j] = elementData[j-1]; } } public <E> void add(int index, E e) { checkAdjustSize(); createSpace(index); elementData[index] = e; numElements ++; } public <E> boolean add(E e) { checkAdjustSize(); elementData[numElements++] = e; return true; } public void clear() { // clear for GC for (int i = 0; i < numElements; i++) { elementData[i] = null; } capacity = 10; numElements = 0; } public boolean contains(Object o) { return indexOf(o) >= 0; } public E get(int index) { if (index < 0 || index >= numElements) { return null; } return elementData[index]; } public int indexOf(Object o) { int i = 0; if (o == null) { for (i = 0; i < capacity; i++) { if (elementData[i]==null) { return i; } } } else { for (i = 0; i < numElements; i++) { if (o.equals(elementData[i])) { return i; } } } return -1; } private void removeElement(int index) { int j = 0; // Note - 1 because one after last element could be out of range for (j = index; j < numElements - 1; j++) { elementData[j] = elementData[j+1]; } elementData[numElements-1] = null; numElements } public E remove(int index) { E e; if (index < 0 || index >= numElements) { return null; } e = elementData[index]; removeElement(index); return e; } public boolean remove(Object o) { int i = 0; if (o == null) { for (i = 0; i < capacity; i++) { if (elementData[i]==null) { removeElement(i); return true; } } } else { for (i = 0; i < numElements; i++) { if (o.equals(elementData[i])) { removeElement(i); return true; } } } return false; } public <E> E set (int index, E element) { E oldElement; if (index < 0 || index >= numElements) { return null; } oldElement = elementData[index]; elementData[index] = element; return oldElement; } public int size() { return numElements; } public int length() { return size(); } public boolean isEmpty() { return numElements == 0; } public Object[] toArray() { Object[] arr = new Object[numElements]; int i = 0; for (i = 0; i < numElements; i++) { arr[i] = elementData[i]; } return arr; } public void ensureCapacity(int minCapacity) { // TODO: fill me in! } }
package com.rafkind.paintown.animator.events; import java.util.*; import com.rafkind.paintown.Lambda0; // Must populate when an event is added public class EventFactory{ private static HashMap events = new HashMap(); private static List ignoreEvents = new ArrayList(); private EventFactory(){ // Nothing } public static void init(){ events.put( "attack", new Lambda0(){public Object invoke(){return new com.rafkind.paintown.animator.events.scala.AttackEvent();}}); events.put( "bbox", new Lambda0(){public Object invoke(){return new BBoxEvent();}}); events.put( "coords", new Lambda0(){public Object invoke(){return new CoordsEvent();}}); events.put( "delay", new Lambda0(){public Object invoke(){return new DelayEvent();}}); events.put( "defense", new Lambda0(){public Object invoke(){return new com.rafkind.paintown.animator.events.scala.DefenseEvent();}}); events.put( "face", new Lambda0(){public Object invoke(){return new FaceEvent();}}); events.put( "frame", new Lambda0(){public Object invoke(){return new com.rafkind.paintown.animator.events.scala.FrameEvent();}}); events.put( "jump", new Lambda0(){public Object invoke(){return new JumpEvent();}}); events.put( "move", new Lambda0(){public Object invoke(){return new com.rafkind.paintown.animator.events.scala.MoveEvent();}}); events.put( "nop", new Lambda0(){public Object invoke(){return new NopEvent();}}); events.put( "next-ticket", new Lambda0(){public Object invoke(){return new TicketEvent();}}); events.put( "offset", new Lambda0(){public Object invoke(){return new OffsetEvent();}}); events.put( "projectile", new Lambda0(){public Object invoke(){return new ProjectileEvent();}}); events.put("trail", new Lambda0(){public Object invoke(){ return new TrailEvent();}}); events.put( "shadow", new Lambda0(){public Object invoke(){return new ShadowEvent();}}); events.put( "sound", new Lambda0(){public Object invoke(){return new SoundEvent();}}); events.put( "user", new Lambda0(){public Object invoke(){return new UserDefinedEvent();}}); events.put( "status", new Lambda0(){public Object invoke(){return new StatusEvent();}}); events.put( "z-distance", new Lambda0(){public Object invoke(){return new ZDistanceEvent();}}); ignoreEvents.add( "basedir" ); ignoreEvents.add( "range" ); ignoreEvents.add( "keys" ); ignoreEvents.add( "type" ); ignoreEvents.add( "name" ); ignoreEvents.add( "loop" ); ignoreEvents.add( "sequence" ); } static{ init(); } public static AnimationEvent getEvent(String name){ if ( ignoreEvents.contains( name ) ){ return null; } try{ return (AnimationEvent)(((Lambda0) events.get( name )).invoke()); } catch (Exception e) { System.out.println( "Could not get event '" + name + "'" ); return null; // e.printStackTrace(); } } public static Vector getNames(){ Object[] names = events.keySet().toArray(); Arrays.sort(names); return new Vector(Arrays.asList(names)); } }
package koopa.app; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.io.File; import java.net.URL; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractAction; import javax.swing.ButtonGroup; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; import javax.swing.JTabbedPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import koopa.app.actions.CloseFileAction; import koopa.app.actions.ExportASTToXMLAction; import koopa.app.actions.ExportBatchResultsToCSVAction; import koopa.app.actions.GoToLineAction; import koopa.app.actions.OpenFileAction; import koopa.app.actions.QueryUsingXPathAction; import koopa.app.actions.ReloadFileAction; import koopa.app.batchit.BatchResults; import koopa.app.batchit.ClearResultsAction; import koopa.app.components.detail.Detail; import koopa.app.components.misc.Tab; import koopa.app.components.overview.Overview; import koopa.parsers.Metrics; import koopa.parsers.ParseResults; import koopa.tokenizers.cobol.SourceFormat; import koopa.tokens.Token; import koopa.util.Getter; import koopa.util.Tuple; import org.antlr.runtime.tree.CommonTree; import org.apache.log4j.PropertyConfigurator; public class Koopa extends JFrame implements Application, Configurable { private static final long serialVersionUID = 1L; public static void main(String[] args) { final URL resource = Detail.class.getResource("/log4j.properties"); PropertyConfigurator.configure(resource); SwingUtilities.invokeLater(new Runnable() { public void run() { new Koopa().setVisible(true); } }); } private static DecimalFormat coverageFormatter = new DecimalFormat("0.0"); private List<ApplicationListener> listeners = new ArrayList<ApplicationListener>(); private JMenu file = null; private JMenuItem open = null; private JMenuItem reload = null; private JMenuItem close = null; private JMenuItem clearResults = null; private JMenuItem saveCSV = null; private JMenu parserSettings = null; private JRadioButtonMenuItem fixedFormat = null; private JRadioButtonMenuItem freeFormat = null; private JMenu navigation = null; private JMenuItem goToLine = null; private JMenu syntaxTree = null; private JMenuItem saveXML = null; private JMenuItem queryUsingXath = null; private JTabbedPane tabbedPane = null; private Overview overview = null; public Koopa() { super("Koopa"); ApplicationSupport.configureFromProperties("koopa.properties", this); setupComponents(); setupMenuBar(); updateMenus(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setSize(screenSize.width - 100, screenSize.height - 100); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } @Override public void setOption(String name, String value) { } private void setupMenuBar() { // Be nice to mac users (like me). System.setProperty("apple.laf.useScreenMenuBar", "true"); JMenuBar bar = new JMenuBar(); file = new JMenu("File"); open = new JMenuItem(new OpenFileAction("Parse ...", this, ApplicationSupport.getCobolFileFilter(false), this)); open.setAccelerator(KeyStroke.getKeyStroke("meta O")); file.add(open); reload = new JMenuItem(new ReloadFileAction(this)); reload.setAccelerator(KeyStroke.getKeyStroke("meta R")); file.add(reload); close = new JMenuItem(new CloseFileAction(this)); KeyStroke keystrokeForClosingATab = KeyStroke.getKeyStroke("meta W"); KeyStroke alternateKeystrokeForClosingATab = KeyStroke .getKeyStroke("ESCAPE"); close.setAccelerator(keystrokeForClosingATab); InputMap im = close.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(alternateKeystrokeForClosingATab, im.get(keystrokeForClosingATab)); file.add(close); file.addSeparator(); clearResults = new JMenuItem(new ClearResultsAction(overview)); file.add(clearResults); saveCSV = new JMenuItem(new ExportBatchResultsToCSVAction( new Getter<BatchResults>() { public BatchResults getIt() { return overview.getResults(); } }, this)); saveCSV.setAccelerator(KeyStroke.getKeyStroke("meta E")); file.add(saveCSV); bar.add(file); parserSettings = new JMenu("Parser settings"); final ButtonGroup group = new ButtonGroup(); fixedFormat = new JRadioButtonMenuItem(); AbstractAction selectFixedFormat = new AbstractAction("Fixed format") { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Component view = getView(); if (view == overview) { overview.setSourceFormat(SourceFormat.FIXED); } else { ((Detail) view).setSourceFormat(SourceFormat.FIXED); } } }; fixedFormat.setAction(selectFixedFormat); fixedFormat.setSelected(true); group.add(fixedFormat); parserSettings.add(fixedFormat); freeFormat = new JRadioButtonMenuItem(); AbstractAction selectFreeFormat = new AbstractAction("Free format") { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Component view = getView(); if (view == overview) { overview.setSourceFormat(SourceFormat.FREE); } else { ((Detail) view).setSourceFormat(SourceFormat.FREE); } } }; freeFormat.setAction(selectFreeFormat); group.add(freeFormat); parserSettings.add(freeFormat); bar.add(parserSettings); navigation = new JMenu("Navigation"); goToLine = new JMenuItem(new GoToLineAction(this, this)); goToLine.setAccelerator(KeyStroke.getKeyStroke("meta L")); navigation.add(goToLine); bar.add(navigation); syntaxTree = new JMenu("Syntax tree"); saveXML = new JMenuItem(new ExportASTToXMLAction(this, this)); saveXML.setAccelerator(KeyStroke.getKeyStroke("meta E")); syntaxTree.add(saveXML); syntaxTree.addSeparator(); queryUsingXath = new JMenuItem(new QueryUsingXPathAction(this, this)); queryUsingXath.setAccelerator(KeyStroke.getKeyStroke("meta P")); syntaxTree.add(queryUsingXath); bar.add(syntaxTree); setJMenuBar(bar); } private void setupComponents() { tabbedPane = new JTabbedPane(); overview = new Overview(this); tabbedPane.addTab("Overview", overview); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { updateMenus(); fireSwitchedView(getView()); } }); getContentPane().add(tabbedPane, BorderLayout.CENTER); } private void updateMenus() { Component view = getView(); if (view == overview) { boolean canDoExtraActions = !overview.isParsing(); boolean hasResults = canDoExtraActions && overview.getResults().getRowCount() > 0; // File menu ... open.setEnabled(canDoExtraActions); reload.setEnabled(false); close.setEnabled(false); clearResults.setEnabled(hasResults); saveCSV.setEnabled(hasResults); // Parse settings ... parserSettings.setEnabled(canDoExtraActions); switch (overview.getSourceFormat()) { case FIXED: fixedFormat.setSelected(true); break; case FREE: freeFormat.setSelected(true); break; } // Navigation ... navigation.setEnabled(false); goToLine.setEnabled(false); // Syntax tree ... syntaxTree.setEnabled(false); saveXML.setEnabled(false); queryUsingXath.setEnabled(false); } else { Detail detail = (Detail) view; boolean canDoExtraActions = !overview.isParsing() && !detail.isParsing(); // File menu ... open.setEnabled(canDoExtraActions); reload.setEnabled(canDoExtraActions); close.setEnabled(canDoExtraActions); clearResults.setEnabled(false); saveCSV.setEnabled(false); // Parse settings ... switch (detail.getSourceFormat()) { case FIXED: fixedFormat.setSelected(true); break; case FREE: freeFormat.setSelected(true); break; } // Navigation ... navigation.setEnabled(true); goToLine.setEnabled(true); // Syntax tree ... boolean hasSyntaxTree = detail.hasSyntaxTree(); syntaxTree.setEnabled(hasSyntaxTree); saveXML.setEnabled(hasSyntaxTree); queryUsingXath.setEnabled(hasSyntaxTree); } } @Override public void openFile(File file) { Component view = getView(); if (overview == view) { openFile(file, overview.getSourceFormat(), null); } else { Detail detail = (Detail) view; openFile(file, detail.getSourceFormat(), null); } } @Override public void openFile(File file, SourceFormat format) { openFile(file, format, null); } @Override public void openFile(File file, SourceFormat format, Tuple<Token, String> selectedToken) { if (file.isDirectory()) { overview.walkAndParse(file); return; } // TODO Check if there already exists a tab for the given file. In that // case do a reload instead. final Detail detail = new Detail(file, true, format); overview.addParseResults(detail.getParseResults()); String title = getTitleForDetail(detail); Tab tab = new Tab(title, this, detail); tabbedPane.addTab(title, detail); tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(detail), tab); if (selectedToken != null) detail.selectDetail(selectedToken); tabbedPane.setSelectedComponent(detail); } private String getTitleForDetail(Detail detail) { final ParseResults parseResults = detail.getParseResults(); float coverage = Metrics.getCoverage(parseResults); String title = detail.getFile().getName(); if (coverage < 100) title += " (" + coverageFormatter.format(coverage) + "%)"; return title; } @Override public void resultsWereCleared() { updateMenus(); } @Override public void walkingAndParsing() { updateMenus(); } @Override public void doneWalkingAndParsing() { updateMenus(); } @Override public void reloadFile() { Component view = getView(); if (view instanceof Detail) { Detail detail = (Detail) view; detail.reloadFile(); Tab tab = (Tab) tabbedPane.getTabComponentAt(tabbedPane .indexOfComponent(detail)); tab.setTitle(getTitleForDetail(detail)); updateMenus(); fireUpdatedView(view); } } @Override public void scrollTo(int position) { Component view = getView(); if (view instanceof Detail) { Detail detail = (Detail) view; detail.scrollTo(position); } } @Override public void addApplicationListener(ApplicationListener listener) { listeners.add(listener); } private void fireSwitchedView(Component view) { for (ApplicationListener listener : listeners) { listener.switchedView(view); } } private void fireUpdatedView(Component view) { for (ApplicationListener listener : listeners) { listener.updatedView(view); } } private void fireClosedDetail(Component view) { for (ApplicationListener listener : listeners) { listener.closedDetail(view); } } @Override public CommonTree getSyntaxTree() { final Component view = getView(); if (view == overview) return null; else return ((Detail) view).getParseResults().getTree(); } @Override public Component getView() { return tabbedPane.getSelectedComponent(); } @Override public void closeView(Component component) { if (component == overview) return; int index = tabbedPane.indexOfComponent(component); tabbedPane.removeTabAt(index); fireClosedDetail(component); updateMenus(); } @Override public void closeView() { closeView(getView()); } }
package com.netflix.eureka.util; import java.lang.management.ManagementFactory; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.provider.Serializer; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamOmitField; /** * An utility class for exposing status information of an instance. * * @author Greg Kim */ @Serializer("com.netflix.discovery.converters.EntityBodyConverter") @XStreamAlias("status") public class StatusInfo { private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss Z"; public static final class Builder { @XStreamOmitField private StatusInfo result; private Builder() { result = new StatusInfo(); } public static Builder newBuilder() { return new Builder(); } public Builder isHealthy(boolean b) { result.isHeathly = Boolean.valueOf(b); return this; } public Builder withInstanceInfo(InstanceInfo instanceInfo) { result.instanceInfo = instanceInfo; return this; } /** * Add any application specific status data. */ public Builder add(String key, String value) { if (result.applicationStats == null) { result.applicationStats = new HashMap<String, String>(); } result.applicationStats.put(key, value); return this; } /** * Build the {@link StatusInfo}. General information are automatically * built here too. */ public StatusInfo build() { if (result.instanceInfo == null) { throw new IllegalStateException("instanceInfo can not be null"); } result.generalStats.put("server-uptime", getUpTime()); result.generalStats.put("environment", ConfigurationManager .getDeploymentContext().getDeploymentEnvironment()); Runtime runtime = Runtime.getRuntime(); int totalMem = (int) (runtime.totalMemory() / 1048576); int freeMem = (int) (runtime.freeMemory() / 1048576); int usedPercent = (int) (((float) totalMem - freeMem) / (totalMem) * 100.0); result.generalStats.put("num-of-cpus", String.valueOf(runtime.availableProcessors())); result.generalStats.put("total-avail-memory", String.valueOf(totalMem) + "mb"); result.generalStats.put("current-memory-usage", String.valueOf(totalMem - freeMem) + "mb" + " (" + usedPercent + "%)"); return result; } } private Map<String, String> generalStats = new HashMap<String, String>(); private Map<String, String> applicationStats; private InstanceInfo instanceInfo; private Boolean isHeathly; private StatusInfo() { } public InstanceInfo getInstanceInfo() { return instanceInfo; } public boolean isHealthy() { return isHeathly.booleanValue(); } public Map<String, String> getGeneralStats() { return generalStats; } public Map<String, String> getApplicationStats() { return applicationStats; } /** * Output the amount of time that has elapsed since the given date in the * format x days, xx:xx. * * @return A string representing the formatted interval. */ public static String getUpTime() { long diff = ManagementFactory.getRuntimeMXBean().getUptime(); diff /= 1000 * 60; long minutes = diff % 60; diff /= 60; long hours = diff % 24; diff /= 24; long days = diff; StringBuilder buf = new StringBuilder(); if (days == 1) { buf.append("1 day "); } else if (days > 1) { buf.append(Long.valueOf(days).toString()).append(" days "); } DecimalFormat format = new DecimalFormat(); format.setMinimumIntegerDigits(2); buf.append(format.format(hours)).append(":") .append(format.format(minutes)); return buf.toString(); } public static String getCurrentTimeAsString() { SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); return format.format(new Date()); } }
package com.netflix.evcache; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.config.ChainedDynamicProperty; import com.netflix.config.DynamicBooleanProperty; import com.netflix.evcache.EVCacheLatch.Policy; import com.netflix.evcache.event.EVCacheEvent; import com.netflix.evcache.event.EVCacheEventListener; import com.netflix.evcache.metrics.EVCacheMetricsFactory; import com.netflix.evcache.metrics.Operation; import com.netflix.evcache.metrics.Stats; import com.netflix.evcache.operation.EVCacheFuture; import com.netflix.evcache.operation.EVCacheLatchImpl; import com.netflix.evcache.operation.EVCacheOperationFuture; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.EVCacheClientPool; import com.netflix.evcache.pool.EVCacheClientPoolManager; import com.netflix.evcache.util.EVCacheConfig; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.Counter; import com.netflix.spectator.api.DistributionSummary; import net.spy.memcached.CachedData; import net.spy.memcached.transcoders.Transcoder; import rx.Observable; import rx.Scheduler; import rx.Single; import static com.netflix.evcache.util.Sneaky.sneakyThrow; /** * An implementation of a ephemeral volatile cache. * * @author smadappa * @version 2.0 */ @SuppressWarnings("unchecked") @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS", "WMI_WRONG_MAP_ITERATOR", "DB_DUPLICATE_BRANCHES", "REC_CATCH_EXCEPTION", "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE" }) final public class EVCacheImpl implements EVCache { private static Logger log = LoggerFactory.getLogger(EVCacheImpl.class); private final String _appName; private final String _cacheName; private final String _metricPrefix; private final String _metricName; private final Transcoder<?> _transcoder; private final boolean _zoneFallback; private final boolean _throwException; private final int _timeToLive; // defaults to 15 minutes private final EVCacheClientPool _pool; private final ChainedDynamicProperty.BooleanProperty _throwExceptionFP, _zoneFallbackFP; private final DynamicBooleanProperty _bulkZoneFallbackFP; private final DynamicBooleanProperty _bulkPartialZoneFallbackFP; private final ChainedDynamicProperty.BooleanProperty _useInMemoryCache; private final Stats stats; private EVCacheInMemoryCache<?> cache; private final EVCacheClientPoolManager _poolManager; private DistributionSummary setTTLSummary, replaceTTLSummary, touchTTLSummary, setDataSizeSummary, replaceDataSizeSummary, appendDataSizeSummary; private Counter touchCounter; EVCacheImpl(String appName, String cacheName, int timeToLive, Transcoder<?> transcoder, boolean enableZoneFallback, boolean throwException, EVCacheClientPoolManager poolManager) { this._appName = appName; this._cacheName = cacheName; this._timeToLive = timeToLive; this._transcoder = transcoder; this._zoneFallback = enableZoneFallback; this._throwException = throwException; stats = EVCacheMetricsFactory.getStats(appName, cacheName); _metricName = (_cacheName == null) ? _appName : _appName + "." + _cacheName; _metricPrefix = (_cacheName == null) ? _appName : _appName + "-" + _cacheName + "-"; this._poolManager = poolManager; this._pool = poolManager.getEVCacheClientPool(_appName); _throwExceptionFP = EVCacheConfig.getInstance().getChainedBooleanProperty(_metricName + ".throw.exception", _appName + ".throw.exception", Boolean.FALSE); _zoneFallbackFP = EVCacheConfig.getInstance().getChainedBooleanProperty(_metricName + ".fallback.zone", _appName + ".fallback.zone", Boolean.TRUE); _bulkZoneFallbackFP = EVCacheConfig.getInstance().getDynamicBooleanProperty(_appName + ".bulk.fallback.zone", true); _bulkPartialZoneFallbackFP = EVCacheConfig.getInstance().getDynamicBooleanProperty(_appName + ".bulk.partial.fallback.zone", true); _useInMemoryCache = EVCacheConfig.getInstance().getChainedBooleanProperty(_appName + ".use.inmemory.cache", "evcache.use.inmemory.cache", Boolean.FALSE); _pool.pingServers(); } private String getCanonicalizedKey(String key) { if (this._cacheName == null) return key; return _cacheName + ':' + key; } private String getKey(String canonicalizedKey) { if (canonicalizedKey == null) return canonicalizedKey; if (_cacheName == null) return canonicalizedKey; final String _cacheNameDelimited = _cacheName + ':'; return canonicalizedKey.replaceFirst(_cacheNameDelimited, ""); } private boolean hasZoneFallbackForBulk() { if (!_pool.supportsFallback()) return false; if (!_bulkZoneFallbackFP.get()) return false; return _zoneFallback; } private boolean hasZoneFallback() { if (!_pool.supportsFallback()) return false; if (!_zoneFallbackFP.get().booleanValue()) return false; return _zoneFallback; } private boolean shouldLog() { return _poolManager.shouldLog(_appName); } private boolean doThrowException() { return (_throwException || _throwExceptionFP.get().booleanValue()); } private List<EVCacheEventListener> getEVCacheEventListeners() { return _poolManager.getEVCacheEventListeners(); } private EVCacheEvent createEVCacheEvent(Collection<EVCacheClient> clients, Collection<String> keys, Call call) { final List<EVCacheEventListener> evcacheEventListenerList = getEVCacheEventListeners(); if (evcacheEventListenerList == null || evcacheEventListenerList.size() == 0) return null; final EVCacheEvent event = new EVCacheEvent(call, _appName, _cacheName); event.setKeys(keys); event.setClients(clients); return event; } private boolean shouldThrottle(EVCacheEvent event) { for (EVCacheEventListener evcacheEventListener : getEVCacheEventListeners()) { if (evcacheEventListener.onThrottle(event)) { return true; } } return false; } private void startEvent(EVCacheEvent event) { final List<EVCacheEventListener> evcacheEventListenerList = getEVCacheEventListeners(); for (EVCacheEventListener evcacheEventListener : evcacheEventListenerList) { evcacheEventListener.onStart(event); } } private void endEvent(EVCacheEvent event) { final List<EVCacheEventListener> evcacheEventListenerList = getEVCacheEventListeners(); for (EVCacheEventListener evcacheEventListener : evcacheEventListenerList) { evcacheEventListener.onComplete(event); } } private void eventError(EVCacheEvent event, Throwable t) { final List<EVCacheEventListener> evcacheEventListenerList = getEVCacheEventListeners(); for (EVCacheEventListener evcacheEventListener : evcacheEventListenerList) { evcacheEventListener.onError(event, t); } } private <T> EVCacheInMemoryCache<T> getInMemoryCache() { if (cache == null) cache = new EVCacheInMemoryCache<T>(_appName); return (EVCacheInMemoryCache<T>) cache; } public <T> T get(String key) throws EVCacheException { return this.get(key, (Transcoder<T>) _transcoder); } private void increment(String metric) { increment(null, _metricPrefix + metric); } private void increment(String serverGroup, String metric) { EVCacheMetricsFactory.increment(_appName, _cacheName, serverGroup, _metricPrefix + metric); } public <T> T get(String key, Transcoder<T> tc) throws EVCacheException { if (null == key) throw new IllegalArgumentException("Key cannot be null"); final boolean throwExc = doThrowException(); EVCacheClient client = _pool.getEVCacheClientForRead(); if (client == null) { increment("NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to get the data APP " + _appName); return null; // Fast failure } final EVCacheEvent event = createEVCacheEvent(Collections.singletonList(client), Collections.singletonList(key), Call.GET); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return null; } startEvent(event); } final String canonicalKey = getCanonicalizedKey(key); if (_useInMemoryCache.get()) { T value = (T) getInMemoryCache().get(canonicalKey); if (log.isDebugEnabled() && shouldLog()) log.debug("Value retrieved from inmemory cache for APP " + _appName + ", key : " + canonicalKey + "; value : " + value); if (value != null) return value; } final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.GET, stats, Operation.TYPE.MILLI); try { final boolean hasZF = hasZoneFallback(); boolean throwEx = hasZF ? false : throwExc; T data = getData(client, canonicalKey, tc, throwEx, hasZF); if (data == null && hasZF) { final List<EVCacheClient> fbClients = _pool.getEVCacheClientsForReadExcluding(client.getServerGroup()); if (fbClients != null && !fbClients.isEmpty()) { for (int i = 0; i < fbClients.size(); i++) { final EVCacheClient fbClient = fbClients.get(i); if(i >= fbClients.size() - 1) throwEx = throwExc; data = getData(fbClient, canonicalKey, tc, throwEx, false); if (log.isDebugEnabled() && shouldLog()) log.debug("Retry for APP " + _appName + ", key [" + canonicalKey + "], Value [" + data + "]" + ", ServerGroup : " + fbClient.getServerGroup()); if (data != null) { client = fbClient; break; } } increment(client.getServerGroupName(), "RETRY_" + ((data == null) ? "MISS" : "HIT")); } } if (data != null) { stats.cacheHit(Call.GET); if (event != null) event.setAttribute("status", "GHIT"); if (_useInMemoryCache.get()) { getInMemoryCache().put(canonicalKey, data); if (log.isDebugEnabled() && shouldLog()) log.debug("Value added to inmemory cache for APP " + _appName + ", key : " + canonicalKey); } } else { if (event != null) event.setAttribute("status", "GMISS"); if (log.isInfoEnabled() && shouldLog()) log.info("GET : APP " + _appName + " ; cache miss for key : " + canonicalKey); } if (log.isDebugEnabled() && shouldLog()) log.debug("GET : APP " + _appName + ", key [" + canonicalKey + "], Value [" + data + "]" + ", ServerGroup : " + client .getServerGroup()); if (event != null) endEvent(event); return data; } catch (net.spy.memcached.internal.CheckedOperationTimeoutException ex) { if (event != null) eventError(event, ex); if (!throwExc) return null; throw new EVCacheException("CheckedOperationTimeoutException getting data for APP " + _appName + ", key = " + canonicalKey + ".\nYou can set the following property to increase the timeout " + _appName + ".EVCacheClientPool.readTimeout=<timeout in milli-seconds>", ex); } catch (Exception ex) { if (event != null) eventError(event, ex); if (!throwExc) return null; throw new EVCacheException("Exception getting data for APP " + _appName + ", key = " + canonicalKey, ex); } finally { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("GET : APP " + _appName + ", Took " + op.getDuration() + " milliSec."); } } public <T> Single<T> get(String key, Scheduler scheduler) { return this.get(key, (Transcoder<T>) _transcoder, scheduler); } public <T> Single<T> get(String key, Transcoder<T> tc, Scheduler scheduler) { if (null == key) return Single.error(new IllegalArgumentException("Key cannot be null")); final boolean throwExc = doThrowException(); final EVCacheClient client = _pool.getEVCacheClientForRead(); if (client == null) { increment("NULL_CLIENT"); return Single.error(new EVCacheException("Could not find a client to get the data APP " + _appName)); } final EVCacheEvent event = createEVCacheEvent(Collections.singletonList(client), Collections.singletonList(key), Call.GET); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); return Single.error(new EVCacheException("Request Throttled for app " + _appName + " & key " + key)); } startEvent(event); } final String canonicalKey = getCanonicalizedKey(key); if (_useInMemoryCache.get()) { T value = (T) getInMemoryCache().get(canonicalKey); if (log.isDebugEnabled() && shouldLog()) log.debug("Value retrieved from inmemory cache for APP " + _appName + ", key : " + canonicalKey + "; value : " + value); if (value != null) return Single.just(value); } final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.GET, stats, Operation.TYPE.MILLI); final boolean hasZF = hasZoneFallback(); boolean throwEx = hasZF ? false : throwExc; return getData(client, canonicalKey, tc, throwEx, hasZF, scheduler).flatMap(data -> { if (data == null && hasZF) { final List<EVCacheClient> fbClients = _pool.getEVCacheClientsForReadExcluding(client.getServerGroup()); if (fbClients != null && !fbClients.isEmpty()) { return Observable.concat(Observable.from(fbClients).map( fbClient -> getData(fbClient, canonicalKey, tc, throwEx, false, scheduler) //TODO : for the last one make sure to pass throwExc .doOnSuccess(fbData -> increment(fbClient.getServerGroupName(), "RETRY_" + ((fbData == null) ? "MISS" : "HIT"))) .toObservable())) .firstOrDefault(null, fbData -> (fbData != null)).toSingle(); } } return Single.just(data); }).map(data -> { if (data != null) { stats.cacheHit(Call.GET); if (event != null) event.setAttribute("status", "GHIT"); if (_useInMemoryCache.get()) { getInMemoryCache().put(canonicalKey, data); if (log.isDebugEnabled() && shouldLog()) log.debug("Value added to inmemory cache for APP " + _appName + ", key : " + canonicalKey); } } else { if (event != null) event.setAttribute("status", "GMISS"); if (log.isInfoEnabled() && shouldLog()) log.info("GET : APP " + _appName + " ; cache miss for key : " + canonicalKey); } if (log.isDebugEnabled() && shouldLog()) log.debug("GET : APP " + _appName + ", key [" + canonicalKey + "], Value [" + data + "]" + ", ServerGroup : " + client .getServerGroup()); if (event != null) endEvent(event); return data; }).onErrorReturn(ex -> { if (ex instanceof net.spy.memcached.internal.CheckedOperationTimeoutException) { if (event != null) eventError(event, ex); if (!throwExc) return null; throw sneakyThrow(new EVCacheException("CheckedOperationTimeoutException getting data for APP " + _appName + ", key = " + canonicalKey + ".\nYou can set the following property to increase the timeout " + _appName + ".EVCacheClientPool.readTimeout=<timeout in milli-seconds>", ex)); } else { if (event != null) eventError(event, ex); if (!throwExc) return null; throw sneakyThrow(new EVCacheException("Exception getting data for APP " + _appName + ", key = " + canonicalKey, ex)); } }).doAfterTerminate(() -> { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("GET : APP " + _appName + ", Took " + op.getDuration() + " milliSec."); }); } private <T> T getData(EVCacheClient client, String canonicalKey, Transcoder<T> tc, boolean throwException, boolean hasZF) throws Exception { if (client == null) return null; try { if(tc == null && _transcoder != null) tc = (Transcoder<T>)_transcoder; return client.get(canonicalKey, tc, throwException, hasZF); } catch (EVCacheReadQueueException ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("EVCacheReadQueueException while getting data for APP " + _appName + ", key : " + canonicalKey + "; hasZF : " + hasZF, ex); if (!throwException || hasZF) return null; throw ex; } catch (EVCacheException ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("EVCacheException while getting data for APP " + _appName + ", key : " + canonicalKey + "; hasZF : " + hasZF, ex); if (!throwException || hasZF) return null; throw ex; } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception while getting data for APP " + _appName + ", key : " + canonicalKey, ex); if (!throwException || hasZF) return null; throw ex; } } private <T> Single<T> getData(EVCacheClient client, String canonicalKey, Transcoder<T> tc, boolean throwException, boolean hasZF, Scheduler scheduler) { if (client == null) return Single.error(new IllegalArgumentException("Client cannot be null")); if(tc == null && _transcoder != null) tc = (Transcoder<T>)_transcoder; return client.get(canonicalKey, tc, throwException, hasZF, scheduler).onErrorReturn(ex -> { if (ex instanceof EVCacheReadQueueException) { if (log.isDebugEnabled() && shouldLog()) log.debug("EVCacheReadQueueException while getting data for APP " + _appName + ", key : " + canonicalKey + "; hasZF : " + hasZF, ex); if (!throwException || hasZF) return null; throw sneakyThrow(ex); } else if (ex instanceof EVCacheException) { if (log.isDebugEnabled() && shouldLog()) log.debug("EVCacheException while getting data for APP " + _appName + ", key : " + canonicalKey + "; hasZF : " + hasZF, ex); if (!throwException || hasZF) return null; throw sneakyThrow(ex); } else { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception while getting data for APP " + _appName + ", key : " + canonicalKey, ex); if (!throwException || hasZF) return null; throw sneakyThrow(ex); } }); } private <T> T getAndTouchData(EVCacheClient client, String canonicalKey, Transcoder<T> tc, boolean throwException, boolean hasZF, int timeToLive) throws Exception { try { if(tc == null && _transcoder != null) tc = (Transcoder<T>)_transcoder; return client.getAndTouch(canonicalKey, tc, timeToLive, throwException, hasZF); } catch (EVCacheReadQueueException ex) { if (log.isDebugEnabled() && shouldLog()) log.debug( "EVCacheReadQueueException while getAndTouch data for APP " + _appName + ", key : " + canonicalKey + "; hasZF : " + hasZF, ex); if (!throwException || hasZF) return null; throw ex; } catch (EVCacheException ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("EVCacheException while getAndTouch data for APP " + _appName + ", key : " + canonicalKey + "; hasZF : " + hasZF, ex); if (!throwException || hasZF) return null; throw ex; } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception while getAndTouch data for APP " + _appName + ", key : " + canonicalKey, ex); if (!throwException || hasZF) return null; throw ex; } } public <T> T getAndTouch(String key, int timeToLive) throws EVCacheException { return this.getAndTouch(key, timeToLive, (Transcoder<T>) _transcoder); } @Override public <T> T getAndTouch(String key, int timeToLive, Transcoder<T> tc) throws EVCacheException { if (null == key) throw new IllegalArgumentException("Key cannot be null"); final boolean throwExc = doThrowException(); EVCacheClient client = _pool.getEVCacheClientForRead(); if (client == null) { increment("NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to get and touch the data"); return null; // Fast failure } final EVCacheEvent event = createEVCacheEvent(Collections.singletonList(client), Collections.singletonList(key), Call.GET_AND_TOUCH); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return null; } startEvent(event); } final String canonicalKey = getCanonicalizedKey(key); if (_useInMemoryCache.get()) { T value = (T) getInMemoryCache().get(canonicalKey); if (value != null) { touch(key, timeToLive); return value; } } final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.GET_AND_TOUCH, stats, Operation.TYPE.MILLI); try { final boolean hasZF = hasZoneFallback(); boolean throwEx = hasZF ? false : throwExc; T data = getAndTouchData(client, canonicalKey, tc, throwEx, hasZF, timeToLive); if (data == null && hasZF) { final List<EVCacheClient> fbClients = _pool.getEVCacheClientsForReadExcluding(client.getServerGroup()); for (int i = 0; i < fbClients.size(); i++) { final EVCacheClient fbClient = fbClients.get(i); if(i >= fbClients.size() - 1) throwEx = throwExc; data = getData(fbClient, canonicalKey, tc, throwEx, false); if (log.isDebugEnabled() && shouldLog()) log.debug("GetAndTouch Retry for APP " + _appName + ", key [" + canonicalKey + "], Value [" + data + "]" + ", ServerGroup : " + fbClient.getServerGroup()); if (data != null) { client = fbClient; break; } } increment(client.getServerGroupName(), "RETRY_" + ((data == null) ? "MISS" : "HIT")); } if (data != null) { stats.cacheHit(Call.GET_AND_TOUCH); if (event != null) event.setAttribute("status", "THIT"); if (_useInMemoryCache.get()) { getInMemoryCache().put(canonicalKey, data); if (log.isDebugEnabled() && shouldLog()) log.debug("Value added to inmemory cache for APP " + _appName + ", key : " + canonicalKey); } // touch all zones touch(key, timeToLive); } else { if (log.isInfoEnabled() && shouldLog()) log.info("GET_AND_TOUCH : APP " + _appName + " ; cache miss for key : " + canonicalKey); if (event != null) event.setAttribute("status", "TMISS"); } if (log.isDebugEnabled() && shouldLog()) log.debug("GET_AND_TOUCH : APP " + _appName + ", key [" + canonicalKey + "], Value [" + data + "]" + ", ServerGroup : " + client.getServerGroup()); if (event != null) endEvent(event); return data; } catch (net.spy.memcached.internal.CheckedOperationTimeoutException ex) { if (log.isDebugEnabled() && shouldLog()) log.debug( "CheckedOperationTimeoutException executing getAndTouch APP " + _appName + ", key : " + canonicalKey, ex); if (event != null) eventError(event, ex); if (!throwExc) return null; throw new EVCacheException("CheckedOperationTimeoutException executing getAndTouch APP " + _appName + ", key = " + canonicalKey + ".\nYou can set the following property to increase the timeout " + _appName + ".EVCacheClientPool.readTimeout=<timeout in milli-seconds>", ex); } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception executing getAndTouch APP " + _appName + ", key = " + canonicalKey, ex); if (event != null) eventError(event, ex); if (!throwExc) return null; throw new EVCacheException("Exception executing getAndTouch APP " + _appName + ", key = " + canonicalKey, ex); } finally { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("Took " + op.getDuration() + " milliSec to get&Touch the value for APP " + _appName + ", key " + canonicalKey); } } public Future<Boolean>[] touch(String key, int timeToLive) throws EVCacheException { if (null == key) throw new IllegalArgumentException(); final boolean throwExc = doThrowException(); final EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); if (clients.length == 0) { increment("NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to set the data"); return new EVCacheFuture[0]; // Fast failure } final EVCacheEvent event = createEVCacheEvent(Arrays.asList(clients), Collections.singletonList(key), Call.TOUCH); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return new EVCacheFuture[0]; } startEvent(event); } final String canonicalKey = getCanonicalizedKey(key); try { final EVCacheFuture[] futures = new EVCacheFuture[clients.length]; int index = 0; for (EVCacheClient client : clients) { final Future<Boolean> future = client.touch(canonicalKey, timeToLive); futures[index++] = new EVCacheFuture(future, key, _appName, client.getServerGroup()); } if (touchTTLSummary == null) this.touchTTLSummary = EVCacheConfig.getInstance().getDistributionSummary(_appName + "-TouchData-TTL"); if (touchTTLSummary != null) touchTTLSummary.record(timeToLive); if (touchCounter == null) this.touchCounter = EVCacheMetricsFactory.getCounter(_appName, _cacheName, _metricPrefix + "-TouchCall", DataSourceType.COUNTER); if (touchCounter != null) touchCounter.increment(); if (event != null) { event.setCanonicalKeys(Arrays.asList(canonicalKey)); event.setTTL(timeToLive); endEvent(event); } return futures; } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception touching the data for APP " + _appName + ", key : " + canonicalKey, ex); if (event != null) eventError(event, ex); if (!throwExc) return new EVCacheFuture[0]; throw new EVCacheException("Exception setting data for APP " + _appName + ", key : " + canonicalKey, ex); } finally { if (log.isDebugEnabled() && shouldLog()) log.debug("TOUCH : APP " + _appName + " for key : " + canonicalKey + " with ttl : " + timeToLive); } } public <T> Future<T> getAsynchronous(String key) throws EVCacheException { return this.getAsynchronous(key, (Transcoder<T>) _transcoder); }; @Override public <T> Future<T> getAsynchronous(String key, Transcoder<T> tc) throws EVCacheException { if (null == key) throw new IllegalArgumentException(); final boolean throwExc = doThrowException(); final EVCacheClient client = _pool.getEVCacheClientForRead(); if (client == null) { increment("NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to asynchronously get the data"); return null; // Fast failure } final EVCacheEvent event = createEVCacheEvent(Collections.singletonList(client), Collections.singletonList(key), Call.ASYNC_GET); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return null; } startEvent(event); } final Future<T> r; final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.ASYNC_GET, stats, Operation.TYPE.MILLI); try { final String canonicalKey = getCanonicalizedKey(key); if(tc == null && _transcoder != null) tc = (Transcoder<T>)_transcoder; r = client.asyncGet(canonicalKey, tc, throwExc, false); if (event != null) endEvent(event); } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug( "Exception while getting data for keys Asynchronously APP " + _appName + ", key : " + key, ex); if (event != null) eventError(event, ex); if (!throwExc) return null; throw new EVCacheException("Exception getting data for APP " + _appName + ", key : " + key, ex); } finally { op.stop(); } return r; } private <T> Map<String, T> getBulkData(EVCacheClient client, Collection<String> canonicalKeys, Transcoder<T> tc, boolean throwException, boolean hasZF) throws Exception { try { if(tc == null && _transcoder != null) tc = (Transcoder<T>)_transcoder; return client.getBulk(canonicalKeys, tc, throwException, hasZF); } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception while getBulk data for APP " + _appName + ", key : " + canonicalKeys, ex); if (!throwException || hasZF) return null; throw ex; } } public <T> Map<String, T> getBulk(Collection<String> keys, Transcoder<T> tc) throws EVCacheException { return getBulk(keys, tc, false, 0); } public <T> Map<String, T> getBulkAndTouch(Collection<String> keys, Transcoder<T> tc, int timeToLive) throws EVCacheException { return getBulk(keys, tc, true, timeToLive); } private <T> Map<String, T> getBulk(Collection<String> keys, Transcoder<T> tc, boolean touch, int ttl) throws EVCacheException { if (null == keys) throw new IllegalArgumentException(); if (keys.isEmpty()) return Collections.<String, T> emptyMap(); final boolean throwExc = doThrowException(); EVCacheClient client = _pool.getEVCacheClientForRead(); if (client == null) { increment("NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to get the data in bulk"); return Collections.<String, T> emptyMap();// Fast failure } final EVCacheEvent event = createEVCacheEvent(Collections.singletonList(client), keys, Call.BULK); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & keys " + keys); return Collections.<String, T> emptyMap(); } startEvent(event); } final Collection<String> canonicalKeys = new ArrayList<String>(); /* Canonicalize keys and perform fast failure checking */ for (String k : keys) { final String canonicalK = getCanonicalizedKey(k); canonicalKeys.add(canonicalK); } final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.BULK, stats, Operation.TYPE.MILLI); try { final boolean hasZF = hasZoneFallbackForBulk(); boolean throwEx = hasZF ? false : throwExc; increment(client.getServerGroupName(), "BULK_GET"); Map<String, T> retMap = getBulkData(client, canonicalKeys, tc, throwEx, hasZF); List<EVCacheClient> fbClients = null; if (hasZF) { if (retMap == null || retMap.isEmpty()) { fbClients = _pool.getEVCacheClientsForReadExcluding(client.getServerGroup()); if (fbClients != null && !fbClients.isEmpty()) { for (int i = 0; i < fbClients.size(); i++) { final EVCacheClient fbClient = fbClients.get(i); if(i >= fbClients.size() - 1) throwEx = throwExc; retMap = getBulkData(fbClient, canonicalKeys, tc, throwEx, false); if (log.isDebugEnabled() && shouldLog()) log.debug("Fallback for APP " + _appName + ", key [" + canonicalKeys + "], Value [" + retMap + "]" + ", zone : " + fbClient.getZone()); if (retMap != null && !retMap.isEmpty()) break; } increment(client.getServerGroupName(), "BULK_GET-FULL_RETRY-" + ((retMap == null || retMap.isEmpty()) ? "MISS" : "HIT")); } } if (retMap != null && keys.size() > retMap.size() && _bulkPartialZoneFallbackFP.get()) { final int initRetMapSize = retMap.size(); final int initRetrySize = keys.size() - retMap.size(); List<String> retryKeys = new ArrayList<String>(initRetrySize); for (Iterator<String> keysItr = canonicalKeys.iterator(); keysItr.hasNext();) { final String key = keysItr.next(); if (!retMap.containsKey(key)) { retryKeys.add(key); } } fbClients = _pool.getEVCacheClientsForReadExcluding(client.getServerGroup()); if (fbClients != null && !fbClients.isEmpty()) { for (int ind = 0; ind < fbClients.size(); ind++) { final EVCacheClient fbClient = fbClients.get(ind); final Map<String, T> fbRetMap = getBulkData(fbClient, retryKeys, tc, false, hasZF); if (log.isDebugEnabled() && shouldLog()) log.debug("Fallback for APP " + _appName + ", key [" + retryKeys + "], Fallback Server Group : " + fbClient .getServerGroup().getName()); for (Map.Entry<String, T> i : fbRetMap.entrySet()) { retMap.put(i.getKey(), i.getValue()); if (log.isDebugEnabled() && shouldLog()) log.debug("Fallback for APP " + _appName + ", key [" + i.getKey() + "], Value [" + i.getValue() + "]"); } if (retryKeys.size() == fbRetMap.size()) break; if (ind < fbClients.size()) { retryKeys = new ArrayList<String>(keys.size() - retMap.size()); for (Iterator<String> keysItr = canonicalKeys.iterator(); keysItr.hasNext();) { final String key = keysItr.next(); if (!retMap.containsKey(key)) { retryKeys.add(key); } } } } if (retMap.size() > initRetMapSize) increment(client.getServerGroupName(), "BULK_GET-PARTIAL_RETRY-" + (retMap.isEmpty() ? "MISS" : "HIT")); } if (log.isDebugEnabled() && shouldLog() && retMap.size() == keys.size()) log.debug("Fallback SUCCESS for APP " + _appName + ", retMap [" + retMap + "]"); } } if (retMap == null || retMap.isEmpty()) { if (log.isInfoEnabled() && shouldLog()) log.info("BULK : APP " + _appName + " ; Full cache miss for keys : " + keys); if (event != null) event.setAttribute("status", "BMISS_ALL"); if (retMap != null && retMap.isEmpty()) { retMap = new HashMap<String, T>(); for (String k : keys) { retMap.put(k, null); } } /* If both Retry and first request fail Exit Immediately. */ increment(client.getServerGroupName(), "BULK_MISS"); if (event != null) endEvent(event); return retMap; } /* Decanonicalize the keys */ final Map<String, T> decanonicalR = new HashMap<String, T>((canonicalKeys.size() * 4) / 3 + 1); for (Iterator<String> itr = canonicalKeys.iterator(); itr.hasNext();) { final String key = itr.next(); final String deCanKey = getKey(key); final T value = retMap.get(key); if (value != null) { decanonicalR.put(deCanKey, value); if (touch) touch(deCanKey, ttl); } else if (fbClients != null && fbClients.size() > 0) { // this ensures the fallback was tried decanonicalR.put(deCanKey, null); } } if (!decanonicalR.isEmpty()) { if (decanonicalR.size() == keys.size()) { stats.cacheHit(Call.BULK); increment(client.getServerGroupName(), "BULK_HIT"); if (event != null) event.setAttribute("status", "BHIT"); } else { if (event != null) { event.setAttribute("status", "BHIT_PARTIAL"); event.setAttribute("BHIT_PARTIAL_KEYS", decanonicalR); } increment(client.getServerGroupName(), "BULK_HIT_PARTIAL"); if (log.isInfoEnabled() && shouldLog()) log.info("BULK_HIT_PARTIAL for APP " + _appName + ", keys in cache [" + decanonicalR + "], all keys [" + keys + "]"); } } if (log.isDebugEnabled() && shouldLog()) log.debug("APP " + _appName + ", BULK : Data [" + decanonicalR + "]"); if (event != null) endEvent(event); return decanonicalR; } catch (net.spy.memcached.internal.CheckedOperationTimeoutException ex) { if (log.isDebugEnabled() && shouldLog()) log.debug( "CheckedOperationTimeoutException getting bulk data for APP " + _appName + ", keys : " + canonicalKeys, ex); if (event != null) eventError(event, ex); if (!throwExc) return null; throw new EVCacheException("CheckedOperationTimeoutException getting bulk data for APP " + _appName + ", keys = " + canonicalKeys + ".\nYou can set the following property to increase the timeout " + _appName + ".EVCacheClientPool.bulkReadTimeout=<timeout in milli-seconds>", ex); } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception getting bulk data for APP " + _appName + ", keys = " + canonicalKeys, ex); if (event != null) eventError(event, ex); if (!throwExc) return null; throw new EVCacheException("Exception getting bulk data for APP " + _appName + ", keys = " + canonicalKeys, ex); } finally { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("BULK : APP " + _appName + " Took " + op.getDuration() + " milliSec to get the value for key " + canonicalKeys); } } public <T> Map<String, T> getBulk(Collection<String> keys) throws EVCacheException { return (this.getBulk(keys, (Transcoder<T>) _transcoder)); } public <T> Map<String, T> getBulk(String... keys) throws EVCacheException { return (this.getBulk(Arrays.asList(keys), (Transcoder<T>) _transcoder)); } public <T> Map<String, T> getBulk(Transcoder<T> tc, String... keys) throws EVCacheException { return (this.getBulk(Arrays.asList(keys), tc)); } @Override public <T> EVCacheFuture[] set(String key, T value, Transcoder<T> tc, int timeToLive) throws EVCacheException { final EVCacheLatch latch = this.set(key, value, tc, timeToLive, null); if (latch == null) return new EVCacheFuture[0]; final List<Future<Boolean>> futures = latch.getAllFutures(); if (futures == null || futures.isEmpty()) return new EVCacheFuture[0]; final EVCacheFuture[] eFutures = new EVCacheFuture[futures.size()]; for (int i = 0; i < futures.size(); i++) { final Future<Boolean> future = futures.get(i); if (future instanceof EVCacheFuture) { eFutures[i] = (EVCacheFuture) future; } else if (future instanceof EVCacheOperationFuture) { eFutures[i] = new EVCacheFuture(futures.get(i), key, _appName, ((EVCacheOperationFuture<T>) futures.get( i)).getServerGroup()); } else { eFutures[i] = new EVCacheFuture(futures.get(i), key, _appName, null); } } return eFutures; } public <T> EVCacheLatch set(String key, T value, Policy policy) throws EVCacheException { return set(key, value, (Transcoder<T>)_transcoder, _timeToLive, policy); } public <T> EVCacheLatch set(String key, T value, int timeToLive, Policy policy) throws EVCacheException { return set(key, value, (Transcoder<T>)_transcoder, timeToLive, policy); } public <T> EVCacheLatch set(String key, T value, Transcoder<T> tc, EVCacheLatch.Policy policy) throws EVCacheException { return set(key, value, tc, _timeToLive, policy); } public <T> EVCacheLatch set(String key, T value, Transcoder<T> tc, int timeToLive, Policy policy) throws EVCacheException { if ((null == key) || (null == value)) throw new IllegalArgumentException(); final boolean throwExc = doThrowException(); final EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); if (clients.length == 0) { increment("NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to set the data"); return new EVCacheLatchImpl(policy, 0, _appName); // Fast failure } final EVCacheEvent event = createEVCacheEvent(Arrays.asList(clients), Collections.singletonList(key), Call.SET); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return new EVCacheLatchImpl(policy, 0, _appName); } startEvent(event); } final String canonicalKey = getCanonicalizedKey(key); final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.SET, stats, Operation.TYPE.MILLI); final EVCacheLatchImpl latch = new EVCacheLatchImpl(policy == null ? Policy.ALL_MINUS_1 : policy, clients.length, _appName); try { CachedData cd = null; for (EVCacheClient client : clients) { if (cd == null) { if (tc != null) { cd = tc.encode(value); } else if ( _transcoder != null) { cd = ((Transcoder<Object>)_transcoder).encode(value); } else { cd = client.getTranscoder().encode(value); } if (setTTLSummary == null) this.setTTLSummary = EVCacheConfig.getInstance().getDistributionSummary( _appName + "-SetData-TTL"); if (setTTLSummary != null) setTTLSummary.record(timeToLive); if (cd != null) { if (setDataSizeSummary == null) this.setDataSizeSummary = EVCacheConfig.getInstance() .getDistributionSummary(_appName + "-SetData-Size"); if (setDataSizeSummary != null) this.setDataSizeSummary.record(cd.getData().length); } } final Future<Boolean> future = client.set(canonicalKey, cd, timeToLive, latch); if (log.isDebugEnabled() && shouldLog()) log.debug("SET : APP " + _appName + ", Future " + future + " for key : " + canonicalKey); if (_useInMemoryCache.get()) { getInMemoryCache().put(canonicalKey, value); } } if (event != null) { event.setCanonicalKeys(Arrays.asList(canonicalKey)); event.setTTL(timeToLive); event.setCachedData(cd); event.setLatch(latch); endEvent(event); } return latch; } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception setting the data for APP " + _appName + ", key : " + canonicalKey, ex); if (event != null) endEvent(event); if (!throwExc) return new EVCacheLatchImpl(policy, 0, _appName); throw new EVCacheException("Exception setting data for APP " + _appName + ", key : " + canonicalKey, ex); } finally { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("SET : APP " + _appName + ", Took " + op.getDuration() + " milliSec for key : " + canonicalKey); } } public <T> EVCacheFuture[] append(String key, T value) throws EVCacheException { return this.append(key, value, null); } public <T> EVCacheFuture[] append(String key, T value, Transcoder<T> tc) throws EVCacheException { if ((null == key) || (null == value)) throw new IllegalArgumentException(); final boolean throwExc = doThrowException(); final EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); if (clients.length == 0) { increment("NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to set the data"); return new EVCacheFuture[0]; // Fast failure } final EVCacheEvent event = createEVCacheEvent(Arrays.asList(clients), Collections.singletonList(key), Call.APPEND); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return new EVCacheFuture[0]; } startEvent(event); } final String canonicalKey = getCanonicalizedKey(key); final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.APPEND, stats, Operation.TYPE.MILLI); try { final EVCacheFuture[] futures = new EVCacheFuture[clients.length]; CachedData cd = null; int index = 0; for (EVCacheClient client : clients) { if (cd == null) { if (tc != null) { cd = tc.encode(value); } else if ( _transcoder != null) { cd = ((Transcoder<Object>)_transcoder).encode(value); } else { cd = client.getTranscoder().encode(value); } } final Future<Boolean> future = client.append(canonicalKey, cd); futures[index++] = new EVCacheFuture(future, key, _appName, client.getServerGroup()); if (cd != null) { if (appendDataSizeSummary == null) this.appendDataSizeSummary = EVCacheConfig.getInstance() .getDistributionSummary(_appName + "-AppendData-Size"); if (appendDataSizeSummary != null) this.appendDataSizeSummary.record(cd.getData().length); } } if (event != null) { event.setCanonicalKeys(Arrays.asList(canonicalKey)); event.setCachedData(cd); endEvent(event); } return futures; } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception setting the data for APP " + _appName + ", key : " + canonicalKey, ex); if (event != null) eventError(event, ex); if (!throwExc) return new EVCacheFuture[0]; throw new EVCacheException("Exception setting data for APP " + _appName + ", key : " + canonicalKey, ex); } finally { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("APPEND : APP " + _appName + ", Took " + op.getDuration() + " milliSec for key : " + canonicalKey); } } public <T> EVCacheFuture[] set(String key, T value, Transcoder<T> tc) throws EVCacheException { return this.set(key, value, tc, _timeToLive); } public <T> EVCacheFuture[] set(String key, T value, int timeToLive) throws EVCacheException { return this.set(key, value, (Transcoder<T>) _transcoder, timeToLive); } public <T> EVCacheFuture[] set(String key, T value) throws EVCacheException { return this.set(key, value, (Transcoder<T>) _transcoder, _timeToLive); } public EVCacheFuture[] delete(String key) throws EVCacheException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); final boolean throwExc = doThrowException(); final EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); if (clients.length == 0) { increment("NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to delete the keyAPP " + _appName + ", Key " + key); return new EVCacheFuture[0]; // Fast failure } final EVCacheEvent event = createEVCacheEvent(Arrays.asList(clients), Collections.singletonList(key), Call.DELETE); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return new EVCacheFuture[0]; } startEvent(event); } final String canonicalKey = getCanonicalizedKey(key); if (_useInMemoryCache.get()) { getInMemoryCache().delete(canonicalKey); } final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.DELETE, stats); try { final EVCacheFuture[] futures = new EVCacheFuture[clients.length]; for (int i = 0; i < clients.length; i++) { Future<Boolean> future = clients[i].delete(canonicalKey); futures[i] = new EVCacheFuture(future, key, _appName, clients[i].getServerGroup()); } if (event != null) { event.setCanonicalKeys(Arrays.asList(canonicalKey)); endEvent(event); } return futures; } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception while deleting the data for APP " + _appName + ", key : " + key, ex); if (event != null) eventError(event, ex); if (!throwExc) return new EVCacheFuture[0]; throw new EVCacheException("Exception while deleting the data for APP " + _appName + ", key : " + key, ex); } finally { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("DELETE : APP " + _appName + " Took " + op.getDuration() + " milliSec for key : " + key); } } public int getDefaultTTL() { return _timeToLive; } public String getAppName() { return _appName; } public String getCacheName() { return _cacheName; } public long incr(String key, long by, long defaultVal, int timeToLive) throws EVCacheException { if ((null == key) || by < 0 || defaultVal < 0 || timeToLive < 0) throw new IllegalArgumentException(); final boolean throwExc = doThrowException(); final EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); if (clients.length == 0) { increment("NULL_CLIENT"); if (log.isDebugEnabled() && shouldLog()) log.debug("INCR : " + _metricName + ":NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to incr the data"); return -1; } final EVCacheEvent event = createEVCacheEvent(Arrays.asList(clients), Collections.singletonList(key), Call.INCR); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return -1; } startEvent(event); } final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.INCR, stats, Operation.TYPE.MILLI); try { final long[] vals = new long[clients.length]; final String canonicalKey = getCanonicalizedKey(key); int index = 0; long currentValue = -1; for (EVCacheClient client : clients) { vals[index] = client.incr(canonicalKey, by, defaultVal, timeToLive); if (vals[index] != -1 && currentValue < vals[index]) currentValue = vals[index]; index++; } if (currentValue != -1) { if (log.isDebugEnabled()) log.debug("INCR : APP " + _appName + " current value = " + currentValue + " for key : " + key); for (int i = 0; i < vals.length; i++) { if (vals[i] == -1 && currentValue > -1) { if (log.isDebugEnabled()) log.debug("INCR : APP " + _appName + "; Zone " + clients[i].getZone() + " had a value = -1 so setting it to current value = " + currentValue + " for key : " + key); clients[i].incr(canonicalKey, 0, currentValue, timeToLive); } else if (vals[i] != currentValue) { if (log.isDebugEnabled()) log.debug("INCR : APP " + _appName + "; Zone " + clients[i].getZone() + " had a value of " + vals[i] + " so setting it to current value = " + currentValue + " for key : " + key); clients[i].set(canonicalKey, String.valueOf(currentValue), timeToLive); } } } if (event != null) endEvent(event); return currentValue; } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception incrementing the value for APP " + _appName + ", key : " + key, ex); if (event != null) eventError(event, ex); if (!throwExc) return -1; throw new EVCacheException("Exception incrementing value for APP " + _appName + ", key : " + key, ex); } finally { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("INCR : APP " + _appName + ", Took " + op.getDuration() + " milliSec for key : " + key); } } public long decr(String key, long by, long defaultVal, int timeToLive) throws EVCacheException { if ((null == key) || by < 0 || defaultVal < 0 || timeToLive < 0) throw new IllegalArgumentException(); final boolean throwExc = doThrowException(); final EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); if (clients.length == 0) { increment("NULL_CLIENT"); if (log.isDebugEnabled() && shouldLog()) log.debug("DECR : " + _metricName + ":NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to decr the data"); return -1; } final EVCacheEvent event = createEVCacheEvent(Arrays.asList(clients), Collections.singletonList(key), Call.DECR); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return -1; } startEvent(event); } final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.DECR, stats, Operation.TYPE.MILLI); try { final long[] vals = new long[clients.length]; final String canonicalKey = getCanonicalizedKey(key); int index = 0; long currentValue = -1; for (EVCacheClient client : clients) { vals[index] = client.decr(canonicalKey, by, defaultVal, timeToLive); if (vals[index] != -1 && currentValue < vals[index]) currentValue = vals[index]; index++; } if (currentValue != -1) { if (log.isDebugEnabled()) log.debug("DECR : APP " + _appName + " current value = " + currentValue + " for key : " + key); for (int i = 0; i < vals.length; i++) { if (vals[i] == -1 && currentValue > -1) { if (log.isDebugEnabled()) log.debug("DECR : APP " + _appName + "; Zone " + clients[i].getZone() + " had a value = -1 so setting it to current value = " + currentValue + " for key : " + key); clients[i].decr(canonicalKey, 0, currentValue, timeToLive); } else if (vals[i] != currentValue) { if (log.isDebugEnabled()) log.debug("DECR : APP " + _appName + "; Zone " + clients[i].getZone() + " had a value of " + vals[i] + " so setting it to current value = " + currentValue + " for key : " + key); clients[i].set(canonicalKey, String.valueOf(currentValue), timeToLive); } } } if (event != null) endEvent(event); return currentValue; } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception decrementing the value for APP " + _appName + ", key : " + key, ex); if (event != null) eventError(event, ex); if (!throwExc) return -1; throw new EVCacheException("Exception decrementing value for APP " + _appName + ", key : " + key, ex); } finally { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("DECR : APP " + _appName + ", Took " + op.getDuration() + " milliSec for key : " + key); } } @Override public <T> EVCacheLatch replace(String key, T value, Policy policy) throws EVCacheException { return replace(key, value, (Transcoder<T>) _transcoder, policy); } @Override public <T> EVCacheLatch replace(String key, T value, Transcoder<T> tc, Policy policy) throws EVCacheException { return replace(key, value, (Transcoder<T>) _transcoder, _timeToLive, policy); } public <T> EVCacheLatch replace(String key, T value, int timeToLive, Policy policy) throws EVCacheException { return replace(key, value, (Transcoder<T>)_transcoder, timeToLive, policy); } @Override public <T> EVCacheLatch replace(String key, T value, Transcoder<T> tc, int timeToLive, Policy policy) throws EVCacheException { if ((null == key) || (null == value)) throw new IllegalArgumentException(); final boolean throwExc = doThrowException(); final EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); if (clients.length == 0) { increment("NULL_CLIENT"); if (throwExc) throw new EVCacheException("Could not find a client to set the data"); return new EVCacheLatchImpl(policy, 0, _appName); // Fast failure } final EVCacheEvent event = createEVCacheEvent(Arrays.asList(clients), Collections.singletonList(key), Call.REPLACE); if (event != null) { if (shouldThrottle(event)) { increment("THROTTLED"); if (throwExc) throw new EVCacheException("Request Throttled for app " + _appName + " & key " + key); return new EVCacheLatchImpl(policy, 0, _appName); } startEvent(event); } final String canonicalKey = getCanonicalizedKey(key); final Operation op = EVCacheMetricsFactory.getOperation(_metricName, Call.REPLACE, stats, Operation.TYPE.MILLI); final EVCacheLatchImpl latch = new EVCacheLatchImpl(policy == null ? Policy.ALL_MINUS_1 : policy, clients.length, _appName); try { final EVCacheFuture[] futures = new EVCacheFuture[clients.length]; CachedData cd = null; int index = 0; for (EVCacheClient client : clients) { if (cd == null) { if (tc != null) { cd = tc.encode(value); } else if ( _transcoder != null) { cd = ((Transcoder<Object>)_transcoder).encode(value); } else { cd = client.getTranscoder().encode(value); } if (replaceTTLSummary == null) this.replaceTTLSummary = EVCacheConfig.getInstance().getDistributionSummary( _appName + "-ReplaceData-TTL"); if (replaceTTLSummary != null) replaceTTLSummary.record(timeToLive); if (cd != null) { if (replaceDataSizeSummary == null) this.replaceDataSizeSummary = EVCacheConfig.getInstance() .getDistributionSummary(_appName + "-ReplaceData-Size"); if (replaceDataSizeSummary != null) this.replaceDataSizeSummary.record(cd.getData().length); } } final Future<Boolean> future = client.replace(canonicalKey, cd, timeToLive, latch); futures[index++] = new EVCacheFuture(future, key, _appName, client.getServerGroup()); if (_useInMemoryCache.get()) { getInMemoryCache().put(canonicalKey, value); } } if (event != null) { event.setCanonicalKeys(Arrays.asList(canonicalKey)); event.setTTL(timeToLive); event.setCachedData(cd); event.setLatch(latch); endEvent(event); } return latch; } catch (Exception ex) { if (log.isDebugEnabled() && shouldLog()) log.debug("Exception setting the data for APP " + _appName + ", key : " + canonicalKey, ex); if (event != null) eventError(event, ex); if (!throwExc) return new EVCacheLatchImpl(policy, 0, _appName); throw new EVCacheException("Exception setting data for APP " + _appName + ", key : " + canonicalKey, ex); } finally { op.stop(); if (log.isDebugEnabled() && shouldLog()) log.debug("REPLACE : APP " + _appName + ", Took " + op .getDuration() + " milliSec for key : " + canonicalKey); } } }
package com.facebook.common.statfs; import android.annotation.SuppressLint; import android.os.Build; import android.os.Environment; import android.os.StatFs; import android.os.SystemClock; import com.facebook.common.internal.Throwables; import java.io.File; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; /** * Helper class that periodically checks the amount of free space available. * <p>To keep the overhead low, it caches the free space information, and * only updates that info after two minutes. * * <p>It is a singleton, and is thread-safe. * * <p>Initialization is delayed until first use, so the first call to any method may incur some * additional cost. */ @ThreadSafe public class StatFsHelper { public enum StorageType { INTERNAL, EXTERNAL }; public static final int DEFAULT_DISK_YELLOW_LEVEL_IN_MB = 400; public static final long DEFAULT_DISK_YELLOW_LEVEL_IN_BYTES = DEFAULT_DISK_YELLOW_LEVEL_IN_MB * 1024 * 1024; private static StatFsHelper sStatsFsHelper; // Time interval for updating disk information private static final long RESTAT_INTERVAL_MS = TimeUnit.MINUTES.toMillis(2); private volatile StatFs mInternalStatFs = null; private volatile File mInternalPath; private volatile StatFs mExternalStatFs = null; private volatile File mExternalPath; @GuardedBy("lock") private long mLastRestatTime; private final Lock lock; private volatile boolean mInitialized = false; public synchronized static StatFsHelper getInstance() { if (sStatsFsHelper == null) { sStatsFsHelper = new StatFsHelper(); } return sStatsFsHelper; } /** * Constructor. * * <p>Initialization is delayed until first use, so we must call {@link #ensureInitialized()} * when implementing member methods. */ protected StatFsHelper() { lock = new ReentrantLock(); } /** * Initialization code that can sometimes take a long time. */ private void ensureInitialized() { if (!mInitialized) { lock.lock(); try { if (!mInitialized) { mInternalPath = Environment.getDataDirectory(); mExternalPath = Environment.getExternalStorageDirectory(); updateStats(); mInitialized = true; } } finally { lock.unlock(); } } } /** * Check if available space in the filesystem is greater than the given threshold. * Note that the free space stats are cached and updated in intervals of RESTAT_INTERVAL_MS. * If the amount of free space has crossed over the threshold since the last update, it will * return incorrect results till the space stats are updated again. * * @param storageType StorageType (internal or external) to test * @param freeSpaceThreshold compare the available free space to this size * @return whether free space is lower than the input freeSpaceThreshold, * returns true if disk information is not available */ public boolean testLowDiskSpace(StorageType storageType, long freeSpaceThreshold) { ensureInitialized(); long availableStorageSpace = getAvailableStorageSpace(storageType); if (availableStorageSpace > 0) { return availableStorageSpace < freeSpaceThreshold; } return true; } /** * Gets the information about the free storage space, including reserved blocks, * either internal or external depends on the given input * @param storageType Internal or external storage type * @return available space in bytes, -1 if no information is available */ @SuppressLint("DeprecatedMethod") public long getFreeStorageSpace(StorageType storageType) { ensureInitialized(); maybeUpdateStats(); StatFs statFS = storageType == StorageType.INTERNAL ? mInternalStatFs : mExternalStatFs; if (statFS != null) { long blockSize, availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = statFS.getBlockSizeLong(); availableBlocks = statFS.getFreeBlocksLong(); } else { blockSize = statFS.getBlockSize(); availableBlocks = statFS.getFreeBlocks(); } return blockSize * availableBlocks; } return -1; } /** * Gets the information about the total storage space, * either internal or external depends on the given input * @param storageType Internal or external storage type * @return available space in bytes, -1 if no information is available */ @SuppressLint("DeprecatedMethod") public long getTotalStorageSpace(StorageType storageType) { ensureInitialized(); maybeUpdateStats(); StatFs statFS = storageType == StorageType.INTERNAL ? mInternalStatFs : mExternalStatFs; if (statFS != null) { long blockSize, totalBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = statFS.getBlockSizeLong(); totalBlocks = statFS.getBlockCountLong(); } else { blockSize = statFS.getBlockSize(); totalBlocks = statFS.getBlockCount(); } return blockSize * totalBlocks; } return -1; } /** * Gets the information about the available storage space * either internal or external depends on the give input * @param storageType Internal or external storage type * @return available space in bytes, 0 if no information is available */ @SuppressLint("DeprecatedMethod") public long getAvailableStorageSpace(StorageType storageType) { ensureInitialized(); maybeUpdateStats(); StatFs statFS = storageType == StorageType.INTERNAL ? mInternalStatFs : mExternalStatFs; if (statFS != null) { long blockSize, availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = statFS.getBlockSizeLong(); availableBlocks = statFS.getAvailableBlocksLong(); } else { blockSize = statFS.getBlockSize(); availableBlocks = statFS.getAvailableBlocks(); } return blockSize * availableBlocks; } return 0; } /** * Thread-safe call to update disk stats. Update occurs if the thread is able to acquire * the lock (i.e., no other thread is updating it at the same time), and it has been * at least RESTAT_INTERVAL_MS since the last update. * Assumes that initialization has been completed before this method is called. */ private void maybeUpdateStats() { // Update the free space if able to get the lock, // with a frequency of once in RESTAT_INTERVAL_MS if (lock.tryLock()) { try { if ((SystemClock.uptimeMillis() - mLastRestatTime) > RESTAT_INTERVAL_MS) { updateStats(); } } finally { lock.unlock(); } } } /** * Thread-safe call to reset the disk stats. * If we know that the free space has changed recently (for example, if we have * deleted files), use this method to reset the internal state and * start tracking disk stats afresh, resetting the internal timer for updating stats. */ public void resetStats() { // Update the free space if able to get the lock if (lock.tryLock()) { try { ensureInitialized(); updateStats(); } finally { lock.unlock(); } } } /** * (Re)calculate the stats. * It is the callers responsibility to ensure thread-safety. * Assumes that it is called after initialization (or at the end of it). */ @GuardedBy("lock") private void updateStats() { mInternalStatFs = updateStatsHelper(mInternalStatFs, mInternalPath); mExternalStatFs = updateStatsHelper(mExternalStatFs, mExternalPath); mLastRestatTime = SystemClock.uptimeMillis(); } /** * Update stats for a single directory and return the StatFs object for that directory. If the * directory does not exist or the StatFs restat() or constructor fails (throws), a null StatFs * object is returned. */ private StatFs updateStatsHelper(@Nullable StatFs statfs, @Nullable File dir) { if(dir == null || !dir.exists()) { // The path does not exist, do not track stats for it. return null; } try { if (statfs == null) { // Create a new StatFs object for this path. statfs = createStatFs(dir.getAbsolutePath()); } else { // Call restat and keep the existing StatFs object. statfs.restat(dir.getAbsolutePath()); } } catch (IllegalArgumentException ex) { // Invalidate the StatFs object for this directory. The native StatFs implementation throws // its internal data structures so subsequent calls against the StatFs object will fail or // throw (so we should make no more calls on the object). The most likely reason for this call // to fail is because the provided path no longer exists. The next call to updateStats() will // a new statfs object if the path exists. This will handle the case that a path is unmounted // and later remounted (but it has to have been mounted when this object was initialized). statfs = null; } catch (Throwable ex) { // Any other exception types are not expected and should be propagated as runtime errors. throw Throwables.propagate(ex); } return statfs; } protected static StatFs createStatFs(String path) { return new StatFs(path); } }
package org.immutables.generator; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.TreeSet; final class PostprocessingMachine { private static final Joiner JOINER = Joiner.on(""); private PostprocessingMachine() { } static CharSequence rewrite(CharSequence content) { String currentPackage = ""; ImportsBuilder importsBuilder = new ImportsBuilder(); ArrayList<String> parts = Lists.newArrayList(); // reserve position for package parts.add(""); // reserve position for imports parts.add(""); State state = State.UNDEFINED; int packageFrom = -1; int importFrom = -1; FiniteStateMachine machine = new FiniteStateMachine(); FullyQualifiedNameMachine fullyQualifiedNameMachine = new FullyQualifiedNameMachine(); for (int i = 0; i < content.length(); i++) { char c = content.charAt(i); switch (state) { case UNDEFINED: state = machine.nextChar(c).or(state); break; case PACKAGE: if (c == ' ') { packageFrom = i + 1; } if (c == ';') { currentPackage = content.subSequence(packageFrom, i).toString(); state = State.UNDEFINED; packageFrom = -1; } break; case IMPORTS: if (c == ' ') { importFrom = i + 1; } if (c == ';') { importsBuilder.addImport(content.subSequence(importFrom, i).toString()); state = State.UNDEFINED; importFrom = -1; } break; case CLASS: fullyQualifiedNameMachine.nextChar(c, i); break; } } parts.set(0, "package " + currentPackage + ";\n"); parts.set(1, importsBuilder.build(currentPackage)); return JOINER.join(parts); } enum State { UNDEFINED, PACKAGE, IMPORTS, CLASS } static final class FiniteStateMachine { private static final char[][] vocabulary = new char[][] { {'p', 'a', 'c', 'k', 'a', 'g', 'e'}, {'i', 'm', 'p', 'o', 'r', 't'}, {'c', 'l', 'a', 's', 's'} }; private static final State[] finalState = new State[] { State.PACKAGE, State.IMPORTS, State.CLASS }; int wordIndex = -1; int charIndex = -1; Optional<State> nextChar(char c) { Optional<State> state = Optional.absent(); if (wordIndex == -2) { if (!Character.isAlphabetic(c) && !Character.isDigit(c)) { wordIndex = -1; } } else if (wordIndex == -1) { for (int i = 0; i < vocabulary.length; i++) { if (c == vocabulary[i][0]) { wordIndex = i; charIndex = 0; break; } } if (wordIndex == -1 && (Character.isAlphabetic(c) || Character.isDigit(c))) { wordIndex = -2; } } else { if (vocabulary[wordIndex][charIndex + 1] == c) { charIndex++; if (vocabulary[wordIndex].length == charIndex + 1) { state = Optional.of(finalState[wordIndex]); wordIndex = -1; charIndex = -1; } } else { wordIndex = -1; charIndex = -1; } } return state; } } static final class ImportsBuilder { private static final String JAVA_LANG = "java.lang"; private TreeSet<String> imports = Sets.newTreeSet(); void addImport(String importedPackage) { imports.add(normalize(importedPackage)); } private String normalize(String s) { return s.replace(" ", "").replace("\n", "").replace("\t", "").replace("\r", ""); } String build(String currentPackage) { imports.remove(JAVA_LANG); imports.remove(currentPackage); return JOINER.join(Iterables.transform(imports, ToImportStatement.FUNCTION)); } } private enum ToImportStatement implements Function<String, String> { FUNCTION; @Override public String apply(String input) { return "import " + input + ";\n"; } } static final class FullyQualifiedNameMachine { FullyQualifiedNameState state = FullyQualifiedNameState.UNDEFINED; int importFrom = -1; int importTo = -1; int packageTo = -1; void nextChar(char c, int i) { switch (state) { case UNDEFINED: if (Character.isLetter(c) && Character.isAlphabetic(c)) { state = FullyQualifiedNameState.PACKAGE_PART_CANDIDATE; importFrom = i; } break; case PACKAGE_PART_CANDIDATE: if (c == '.') { state = FullyQualifiedNameState.DOT; } else if (!Character.isAlphabetic(c) && !Character.isDigit(c) && !isSpaceChar(c)) { state = FullyQualifiedNameState.UNDEFINED; } break; case DOT: if (Character.isAlphabetic(c) && Character.isLowerCase(c)) { state = FullyQualifiedNameState.PACKAGE_PART_CANDIDATE; } else if (Character.isAlphabetic(c) && Character.isUpperCase(c)) { state = FullyQualifiedNameState.CLASS; } else if (!isSpaceChar(c)) { state = FullyQualifiedNameState.UNDEFINED; } break; case CLASS: if (packageTo == -1) { packageTo = i - 1; } if (!Character.isAlphabetic(c) && !Character.isDigit(c) && !isSpaceChar(c)) { state = FullyQualifiedNameState.AFTER_CLASS; } break; case AFTER_CLASS: if (importTo == -1) { importTo = i - 1; } if (Character.isAlphabetic(c)) { state = FullyQualifiedNameState.METHOD_OR_FIELD; } else if (c == '(' || c == '<' || c == ')' || c == '>') { state = FullyQualifiedNameState.FINISH; } else if (!isSpaceChar(c)) { state = FullyQualifiedNameState.UNDEFINED; } break; case METHOD_OR_FIELD: if (!Character.isAlphabetic(c) && !Character.isDigit(c)) { state = FullyQualifiedNameState.FINISH; } break; case FINISH: reset(); break; } } void reset() { state = FullyQualifiedNameState.UNDEFINED; importFrom = -1; importTo = -1; packageTo = 1; } } enum FullyQualifiedNameState { UNDEFINED, PACKAGE_PART_CANDIDATE, DOT, CLASS, AFTER_CLASS, METHOD_OR_FIELD, FINISH } private static boolean isSpaceChar(char c) { return Character.isSpaceChar(c) || c == '\n' || c == '\t' || c == '\r'; } public static void main(String[] args) { String s1 = "com. google.\tcommon.base\n. Function . apply();"; String s2 = "com.google.common.base.Function.class;"; String s3 = "com.google.common.base.Function();"; String s4 = "com.google.common.collect.ImmutableList.Builder<>;"; String s5 = "com.google.common.base.Preconditions.checkState();"; test(s1); test(s2); test(s3); test(s4); test(s5); } private static void test(String s) { FullyQualifiedNameMachine fullyQualifiedNameMachine = new FullyQualifiedNameMachine(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); fullyQualifiedNameMachine.nextChar(c, i); if (FullyQualifiedNameState.FINISH.equals(fullyQualifiedNameMachine.state)) { System.out.println(s.substring(fullyQualifiedNameMachine.importFrom, fullyQualifiedNameMachine.importTo)); System.out.println(s.substring(fullyQualifiedNameMachine.importFrom, fullyQualifiedNameMachine.packageTo)); } } System.out.println(); System.out.println(); } }
// File: $Id$ import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; public class SuffixArray implements Configuration, Magic, java.io.Serializable { /** The lowest interesting commonality. */ private static final int MINCOMMONALITY = 3; /** The buffer containing the compressed text. */ private short text[]; /** The number of elements in `text' that are relevant. */ private int length; /** The next grammar rule number to hand out. */ private short nextcode = FIRSTCODE; private SuffixArray( short text[] ) throws VerificationException { this.text = text; length = text.length; } public SuffixArray( ShortBuffer b ) throws VerificationException { this( b.getText() ); } SuffixArray( byte t[] ) throws VerificationException { length = t.length; text = buildShortArray( t ); } SuffixArray( String text ) throws VerificationException { this( text.getBytes() ); } private SuffixArray( short t[], int l, short nextcode ) { text = t; length = l; this.nextcode = nextcode; } /** * Returns a clone of the SuffixArray. * @return The clone. */ public Object clone() { short nt[] = new short[length]; System.arraycopy( text, 0, nt, 0, length ); return new SuffixArray( nt, length, nextcode ); } private static short[] buildShortArray( byte text[] ) { short arr[] = new short[text.length+1]; for( int i=0; i<text.length; i++ ){ arr[i] = (short) text[i]; } arr[text.length] = STOP; return arr; } /** Returns the number of common characters in the two given spans. */ private int commonLength( int i0, int i1 ) { int n = 0; while( (text[i0+n] == text[i1+n]) && (text[i0+n] != STOP) ){ n++; } return n; } /** Given two text positions, calculates the non-overlapping * match of these two. */ private int disjunctMatch( int ix0, int ix1 ) { int n = 0; if( ix0 == ix1 ){ // TODO: complain, this should never happen. return 0; } if( ix0>ix1 ){ int h = ix0; ix0 = ix1; ix1 = h; } while( (ix0+n)<ix1 && (text[ix0+n] == text[ix1+n]) && (text[ix0+n] != STOP) ){ n++; } return n; } /** Returns true iff i0 refers to a smaller character than i1. */ private boolean isSmallerCharacter( int i0, int i1 ) { if( text[i0] == STOP ){ // The shortest string is first, this is as it should be. return true; } if( text[i1] == STOP ){ // The shortest string is last, this is not good. return false; } return (text[i0]<text[i1]); } /** Returns true iff i0 refers to a smaller text than i1. */ private boolean areCorrectlyOrdered( int i0, int i1 ) { int n = commonLength( i0, i1 ); return isSmallerCharacter( i0+n, i1+n ); } /** Returns true iff the indices are correctly ordered. */ private boolean rightIndexOrder( int i0, int i1 ) { if( i0>=length && i1>=length ){ return i0>i1; // Provide a stable sort. } if( i0>=length ){ return true; } if( i1>=length ){ return false; } if( text[i0]==text[i1] ){ return i0>i1; } return text[i0]>text[i1]; } private boolean rightIndexOrder1( int i0, int i1 ) { boolean res = rightIndexOrder1( i0, i1 ); System.out.println( "i0=" + i0 + " i1=" + i1 + " text[" + i0 + "]=" + text[i0] + " text[" + i1 + "]=" + text[i1] + " res=" + res ); return res; } private void sort( int indices[], int start, int end, int offset ) { // This implements Shell sort. // Unfortunately we cannot use the sorting functions from the library // (e.g. java.util.Arrays.sort), since the ones that work on int // arrays do not accept a comparison function, but only allow // sorting into natural order. int length = end - start; int jump = length; boolean done; while( jump>1 ){ jump /= 2; do { done = true; for( int j = 0; j<(length-jump); j++ ){ int i = j + jump; int ixi = indices[start+i]; int ixj = indices[start+j]; if( !rightIndexOrder( ixi+offset, ixj+offset ) ){ // Things are in the wrong order, swap them and step back. indices[start+i] = ixj; indices[start+j] = ixi; if( !rightIndexOrder( ixj+offset, ixi+offset ) ){ System.out.println( "There is no right order for " + ixj + " and " + ixi ); } done = false; } } } while( !done ); } if( false ){ for( int i=start; i<end; i++ ){ System.out.println( "i=" + i + " indices[" + i + "]=" + indices[i] + " offset=" + offset + " text[" + (indices[i]+offset) + "]=" + text[indices[i]+offset] ); } } } /** Fills the given index and commonality arrays with groups * of elements sorted according to the character at the given offset. */ private int sort1( int next[], int indices1[], boolean comm[], int p, int indices[], int start, int end, int offset ) { if( end-start<1 ){ // A span of 1 element is never interesting. return 0; } if( end-start == 2 ){ // A span of 2 elements can only survive if the two // are the same. int i0 = indices[start]+offset; int i1 = indices[start+1]+offset; if( i0>=length || i1>=length || text[i0] != text[i1] ){ return 0; } indices1[p] = indices[start]; indices1[p+1] = indices[start+1]; comm[p] = false; comm[p+1] = true; return p+2; } if( true ){ //System.out.println( "Elements: " + (end-start) ); int slot[] = new int[nextcode]; java.util.Arrays.fill( slot, -1 ); { // Fill the hash buckets // Walk from back to front to make sure the chains are in // the right order. int n = end; while( n>start ){ n int i = indices[n]; if( i+offset<length ){ short ix = text[i+offset]; next[i] = slot[ix]; slot[ix] = i; } } } slot[STOP] = -1; // Write out the indices and commonalities. for( int n=0; n<nextcode; n++ ){ int i = slot[n]; boolean c = false; if( i != -1 && next[i] != -1 ){ // There is a repeat, write out this chain. while( i != -1 ){ indices1[p] = i; i = next[i]; comm[p] = c; c = true; p++; } } } } else { // First, sort all indices in this range sort( indices, start, end, offset ); // And then copy out all interesting spans. int i = start; short prev = -1; int startp = p; while( i<end ){ int ix = indices[i++]; short c = text[ix]; if( c != prev ){ if( startp>p && !comm[p-1] ){ p } comm[p] = false; } else { comm[p] = true; } prev = c; indices1[p++] = ix; } } return p; } /** Determine whether the given list of indices is useful for the non-overlapping repeat we're searching. Too short or only overlapping repeats cause a reject. */ private boolean isAcceptable( int indices[], int start, int end, int offset ) { if( end-start<2 ){ return false; } for( int ix=start; ix<end; ix++ ){ for( int iy=ix+1; iy<end; iy++ ){ if( (indices[ix]+offset)<=indices[iy] ){ return true; } } } return false; } class Result { int offset; int l; int indices[]; boolean comm[]; Result( int offset, int l, int indices[], boolean comm[] ) { this.offset = offset; this.l = l; this.indices = indices; this.comm = comm; } void print() { for( int i=0; i<l; i++ ){ System.out.println( "" + indices[i] + " [" + buildString( indices[i], offset ) + "]" + (comm[i]?"":" <-") ); } } } /** Returns a selection of the suffix array that allows easy extraction * of the longest repeats. */ private Result selectRepeats( int top ) { int next[] = new int[length]; int indices[] = new int[length]; boolean comm[] = new boolean[length]; int offset = 0; for( int i=0; i<length; i++ ){ indices[i] = i; } int l = sort1( next, indices, comm, 0, indices, 0, length, offset ); for(;;){ int indices1[] = new int[l]; boolean comm1[] = new boolean[l]; int ix = 0; offset++; boolean acceptable = false; int p = 0; int spans = 0; if( false ){ Result r = new Result( offset, l, indices, comm ); r.print(); } while( ix<l ){ int start = ix; int oldp = p; ix++; while( ix<l && comm[ix] ){ ix++; } p = sort1( next, indices1, comm1, p, indices, start, ix, offset ); if( isAcceptable( indices1, oldp, p, offset ) ){ acceptable = true; comm1[oldp] = false; spans++; } else { p = oldp; } } if( spans<=top ){ // The next step would leave too few choices, stick to // the current one. break; } indices = indices1; comm = comm1; l = p; } return new Result( offset-1, l, indices, comm ); } /** Sorts the given range. */ private void sort( int indices[], int commonality[], int start, int end ) { // This implements Shell sort. // Unfortunately we cannot use the sorting functions from the library // (e.g. java.util.Arrays.sort), since the ones that work on int // arrays do not accept a comparison function, but only allow // sorting into natural order. int length = end - start; int jump = length; boolean done; final int kC = 1; // known commonality. while( jump>1 ){ jump /= 2; do { done = true; if( jump == 1 ){ for( int j = 0; j<(length-1); j++ ){ int i = j + 1; int ixi = indices[start+i]; int ixj = indices[start+j]; // We know the first character is equal... int n = kC+commonLength( ixi+kC, ixj+kC ); commonality[start+i] = n; if( !isSmallerCharacter( ixj+n, ixi+n ) ){ // Things are in the wrong order, swap them and step back. indices[start+i] = ixj; indices[start+j] = ixi; done = false; } } } else { for( int j = 0; j<(length-jump); j++ ){ int i = j + jump; int ixi = indices[start+i]; int ixj = indices[start+j]; int n = kC+commonLength( ixi+kC, ixj+kC ); if( !isSmallerCharacter( ixj+n, ixi+n ) ){ // Things are in the wrong order, swap them and step back. indices[start+i] = ixj; indices[start+j] = ixi; done = false; } } } } while( !done ); } commonality[start] = 0; } /** Sorts the administration arrays to implement ordering. */ private void buildAdministration( int indices[], int commonality[] ) { int slots[] = new int[nextcode]; int next[] = new int[length]; int filledSlots; { // First, construct the chains for the single character case. // We guarantee that the positions are in increasing order. Arrays.fill( slots, -1 ); // Fill each next array element with the next element with the // same character. We walk the string from back to front to // get the links in the correct order. int i = length; while( i>0 ){ i int ix = text[i]; next[i] = slots[ix]; slots[ix] = i; } filledSlots = slots.length; } // Now copy out the slots into the indices array. int ix = 0; // Next entry in the indices array. for( int i=0; i<filledSlots; i++ ){ int p = slots[i]; int start = ix; if( i == STOP ){ // The hash slot for the STOP symbol is not interesting. continue; } while( p != -1 ){ indices[ix++] = p; p = next[p]; } if( start+1<ix ){ sort( indices, commonality, start, ix ); } else { // A single entry is not interesting, skip it. ix = start; } } // Fill all unused slots with uninteresting information. while( ix<length ){ commonality[ix] = 0; ix++; } } String buildString( int start, int len ) { StringBuffer s = new StringBuffer( len+8 ); int i = start; while( len>0 && i<this.length ){ int c = (text[i] & 0xFFFF); if( c == '\n' ){ s.append( "<nl>" ); } else if( c == '\r' ){ s.append( "<cr>" ); } else if( c == '\t' ){ s.append( "<tab>" ); } else if( c<255 ){ s.append( (char) c ); } else if( c == STOP ){ s.append( "<stop>" ); } else { s.append( "<" + c + ">" ); } i++; len } return new String( s ); } String buildString( int start ) { return buildString( start, length ); } String buildString() { return buildString( 0 ); } String buildString( Step s ) { return buildString( s.occurences[0], s.len ); } public void printGrammar() { int start = 0; boolean busy; int rule = 0; // The rule we're printing, or 0 for the top level. for( int i=0; i<length+1; i++ ){ if( i>=length || text[i] == STOP ){ // We're at the end of a rule. Print it. String var; if( rule == 0 ){ var = "<start>"; rule = FIRSTCODE; } else { var = "<" + rule + ">"; rule++; } System.out.println( var + " -> [" + buildString( start, i-start ) + "]" ); start = i+1; } } } /** * Replaces the string at the given posititon, and with * the given length, with the given code. Also marks the replaced * text as deleted. */ private void replace( int ix, int len, short code, boolean deleted[] ) { text[ix] = code; Arrays.fill( deleted, ix+1, ix+len, true ); } /** Given an entry in the suffix array, creates a new grammar rule * to take advantage of the commonality indicated by that entry. * It also covers any further entries with the same commonality. */ public void applyCompression( Step s ) throws VerificationException { final int oldLength = length; // Remember the old length for verif. // System.out.println( "Applying compression step " + s ); // First, move the grammar text aside. int len = s.len; short t[] = new short[len]; System.arraycopy( text, s.occurences[0], t, 0, len ); boolean deleted[] = new boolean[length]; // Now assign a new variable and replace all occurences. short variable = nextcode++; int a[] = s.occurences; for( int i=0; i<a.length; i++ ){ replace( a[i], len, variable, deleted ); } int j = 0; for( int i=0; i<length; i++ ){ if( !deleted[i] ){ // Before the first deleted character this copies the // character onto itself. This is harmless. text[j++] = text[i]; } } length = j; // Separate the previous stuff from the grammar rule that follows. text[length++] = STOP; // Add the new grammar rule. System.arraycopy( t, 0, text, length, len ); length += len; text[length] = STOP; if( doVerification ){ int gain = s.getGain(); if( length+gain != oldLength ){ System.out.println( "Error: predicted gain was " + gain + ", but realized gain is " + (oldLength-length) ); } } } /** Returns true if the strings with the given positions and length * overlap. * @return True iff the strings overlap. */ private static boolean areOverlapping( int ix0, int ix1, int len ) { if( ix0<ix1 ){ return ix0+len>ix1; } else { return ix1+len>ix0; } } /** Returns true iff none of the `sz' strings in `a' overlaps with * `pos' over a length `len'. */ private static boolean areOverlapping( int a[], int sz, int pos, int len ) { for( int i=0; i<sz; i++ ){ if( areOverlapping( a[i], pos, len ) ){ return true; } } return false; } /** * Calculates the best folding step to take. * @return The best step, or null if there is nothing worthwile. */ public StepList selectBestSteps( int top ) { StepList res; if( true ){ int p = 0; int candidates[] = new int[length]; int mincom = MINCOMMONALITY; /** The indices in increasing alphabetical order of their suffix. */ int indices[] = new int[length]; /** For each position in `indices', the number of elements it * has in common with the previous entry, or -1 for element 0. * The commonality may be overlapping, and that should be taken * into account by compression algorithms. */ int commonality[] = new int[length]; buildAdministration( indices, commonality ); res = new StepList( top ); for( int i=1; i<length; i++ ){ if( commonality[i]>=mincom ){ // A new candidate match. Start a list, and see if we // get at least two non-overlapping strings. int pos0 = indices[i-1]; candidates[0] = pos0; p = 1; int len = commonality[i]; while( len>mincom ){ // Now search for non-overlapping substrings that // are equal for `len' characters. All possibilities // are the subsequent entries in the suffix array, up to // the first one with less than 'len' characters // commonality. // We must test each one for overlap with all // previously selected strings. // TODO: this fairly arbitrary way of gathering candidates // may not be optimal: a different subset of strings may // be larger. int j = i; while( j<length && commonality[j]>=len ){ int posj = indices[j]; if( !areOverlapping( candidates, p, posj, len ) ){ candidates[p++] = posj; } j++; } if( p>1 ){ // HEURISTIC: anything shorter than this is probably // not a reasonable candidate for best compression step. // (But we could be wrong.) // mincom = Math.max( mincom, len-1 ); res.add( new Step( candidates, p, len ) ); } len } } } } else { Result reps = selectRepeats( top ); // reps.print(); boolean commonality[] = reps.comm; int indices[] = reps.indices; int l = reps.l; int offset = reps.offset; int candidates[] = new int[l]; res = new StepList( top ); int ix = 0; while( ix<l ){ int start = ix; candidates[0] = indices[ix]; int p = 1; int minsz = length; ix++; while( ix<l && commonality[ix] ){ int posj = indices[ix]; int sz = disjunctMatch( candidates[p-1], posj ); if( sz>=offset ){ candidates[p++] = posj; if( sz<minsz ){ minsz = sz; } } ix++; } if( p>1 && minsz>=MINCOMMONALITY ){ Step s = new Step( candidates, p, minsz ); res.add( s ); } } } return res; } public int getLength() { return length; } public ByteBuffer getByteBuffer() { return new ByteBuffer( text, length ); } }
package org.intermine.web.logic.widget; import java.util.List; import org.intermine.pathquery.PathQuery; import org.intermine.web.logic.widget.config.WidgetConfig; /** * @author "Xavier Watkins" */ public abstract class Widget { protected WidgetConfig config; /** * The constructor * @param config the WidgetConfig */ public Widget(WidgetConfig config) { this.config = config; } /** * Process the data and create the widget * * @throws Exception if one of the classes in the widget isn't found */ public abstract void process() throws Exception; /** * @return the number of objects not analysed in this widget */ public abstract int getNotAnalysed(); /** * @param notAnalysed the number of objects not analysed in this widget */ public abstract void setNotAnalysed(int notAnalysed); /** * * @param selected the list of checked items from the form * @return the checked items in export format * @throws Exception something has gone wrong. oh no. */ public abstract List<List<String>> getExportResults(String[]selected) throws Exception; /** * @return the hasResults */ public abstract boolean getHasResults(); /** * checks if elem is in bag * @return true if elem is in bag */ public abstract List<String> getElementInList(); /** * Get the ID of the corresponding WidgetConfig * @return the WidgetConfig ID */ public String getConfigId() { return config.getId(); } /** * Get the widget title * @return the title */ public String getTitle() { return config.getTitle(); } /** * Return the result that represents the data from this widget. * Each row is represented as a list of Object * @return a list representing the rows conatining a list of objects * @throws Exception */ public abstract List<List<Object>> getResults() throws Exception; /** * Return the PathQuery generated dinamically by the attribute views in the config file * @return the pathquery */ public abstract PathQuery getPathQuery(); }
package org.xtreemfs.test.mrc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT; import static org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDONLY; import static org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import junit.extensions.PA; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.xtreemfs.common.ReplicaUpdatePolicies; import org.xtreemfs.common.libxtreemfs.AdminClient; import org.xtreemfs.common.libxtreemfs.AdminFileHandle; import org.xtreemfs.common.libxtreemfs.AdminVolume; import org.xtreemfs.common.libxtreemfs.ClientFactory; import org.xtreemfs.common.libxtreemfs.Helper; import org.xtreemfs.common.libxtreemfs.Options; import org.xtreemfs.common.libxtreemfs.Volume; import org.xtreemfs.common.libxtreemfs.exceptions.AddressToUUIDNotFoundException; import org.xtreemfs.common.libxtreemfs.exceptions.PosixErrorException; import org.xtreemfs.common.xloc.ReplicationFlags; import org.xtreemfs.foundation.buffer.ReusableBuffer; import org.xtreemfs.foundation.json.JSONException; import org.xtreemfs.foundation.json.JSONParser; import org.xtreemfs.foundation.json.JSONString; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.Auth; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials; import org.xtreemfs.foundation.pbrpc.server.RPCServerRequest; import org.xtreemfs.foundation.util.FSUtils; import org.xtreemfs.osd.OSD; import org.xtreemfs.osd.OSDConfig; import org.xtreemfs.osd.OSDRequestDispatcher; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.OSDSelectionPolicyType; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.Replica; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.StripingPolicy; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.StripingPolicyType; import org.xtreemfs.test.SetupUtils; import org.xtreemfs.test.TestEnvironment; public class VersionedXLocSetTest { private static TestEnvironment testEnv; private static UserCredentials userCredentials; private static Auth auth; private static AdminClient client; private static Options options; private static String mrcAddress; private static String dirAddress; private static StripingPolicy defaultStripingPolicy; private static OSD[] osds; private static OSDConfig[] configs; private final static int NUM_OSDS = 5; private static Long OFT_CLEAN_INTERVAL_MS; private static int LEASE_TIMEOUT_MS; @BeforeClass public static void initializeTest() throws Exception { System.out.println("TEST: " + VersionedXLocSetTest.class.getSimpleName()); // cleanup FSUtils.delTree(new java.io.File(SetupUtils.TEST_DIR)); Logging.start(Logging.LEVEL_WARN); // Logging.start(Logging.LEVEL_DEBUG); testEnv = new TestEnvironment( new TestEnvironment.Services[] { TestEnvironment.Services.TIME_SYNC, TestEnvironment.Services.UUID_RESOLVER, TestEnvironment.Services.RPC_CLIENT, TestEnvironment.Services.DIR_SERVICE, TestEnvironment.Services.DIR_CLIENT, TestEnvironment.Services.MRC, TestEnvironment.Services.MRC_CLIENT, TestEnvironment.Services.OSD_CLIENT }); testEnv.start(); // setup osds osds = new OSD[NUM_OSDS]; configs = SetupUtils.createMultipleOSDConfigs(NUM_OSDS); for (int i = 0; i < NUM_OSDS; i++) { osds[i] = new OSD(configs[i]); } dirAddress = testEnv.getDIRAddress().getHostName() + ":" + testEnv.getDIRAddress().getPort(); mrcAddress = testEnv.getMRCAddress().getHostName() + ":" + testEnv.getMRCAddress().getPort(); defaultStripingPolicy = StripingPolicy.newBuilder().setType(StripingPolicyType.STRIPING_POLICY_RAID0) .setStripeSize(128).setWidth(1).build(); userCredentials = UserCredentials.newBuilder().setUsername("test").addGroups("test").build(); auth = RPCAuthentication.authNone; options = new Options(); options.setMaxTries(2); client = ClientFactory.createAdminClient(dirAddress, userCredentials, null, options); client.start(); // get the current timeouts to save time spend waiting OFT_CLEAN_INTERVAL_MS = (Long) PA.getValue(osds[0].getDispatcher().getPreprocStage(), "OFT_CLEAN_INTERVAL"); LEASE_TIMEOUT_MS = configs[0].getFleaseLeaseToMS(); } @AfterClass public static void tearDown() throws Exception { for (int i = 0; i < osds.length; i++) { if (osds[i] != null) { osds[i].shutdown(); } } testEnv.shutdown(); client.shutdown(); } private void addReplicas(Volume volume, String fileName, int replicaNumber) throws IOException, InterruptedException { // due to a bug in the OSDSelectionPolicys the numOSDs parameter is not working properly and mostly // returns all suitable OSDs List<String> osdUUIDs = volume.getSuitableOSDs(userCredentials, fileName, replicaNumber); assert (osdUUIDs.size() >= replicaNumber); // save the current Replica Number int currentReplicaNumber = volume.listReplicas(userCredentials, fileName).getReplicasCount(); // get Replication Flags // copied from org.xtreemfs.common.libxtreemfs.VolumeImplementation.listACL(UserCredentials, String) // TODO(jdillmann): move to VolumeImplementation.getDefaultReplicationPolicy ? int repl_flags; try { String rpAsJSON = volume.getXAttr(userCredentials, "/", "xtreemfs.default_rp"); Map<String, Object> rp = (Map<String, Object>) JSONParser.parseJSON(new JSONString(rpAsJSON)); long temp = ((Long) rp.get("replication-flags")); repl_flags = (int) temp; } catch (JSONException e) { throw new IOException(e); } // 15s is the default lease timeout // we have to wait that long, because addReplica calls ping which requires do become primary // Thread.sleep(LEASE_TIMEOUT_MS + 500); // so we have to fall back to add the replicas individually for (int i = 0; i < replicaNumber; i++) { Replica replica = Replica.newBuilder().setStripingPolicy(defaultStripingPolicy) .setReplicationFlags(repl_flags).addOsdUuids(osdUUIDs.get(i)).build(); volume.addReplica(userCredentials, fileName, replica); // 15s is the default lease timeout // Thread.sleep(LEASE_TIMEOUT_MS + 500); System.out.println("Added replica on " + osdUUIDs.get(i)); } assertEquals(currentReplicaNumber + replicaNumber, volume.listReplicas(userCredentials, fileName) .getReplicasCount()); } private static void readInvalidView(AdminFileHandle file) throws AddressToUUIDNotFoundException, IOException { PosixErrorException catched = null; try { byte[] dataOut = new byte[1]; file.read(userCredentials, dataOut, 1, 0); } catch (PosixErrorException e) { catched = e; } // TODO(jdillmann): make this more dynamic assertTrue(catched != null); assertEquals(catched.getPosixError(), RPC.POSIXErrno.POSIX_ERROR_EAGAIN); assertTrue(catched.getMessage().contains("view is not valid")); } @Ignore @Test public void testRonlyRemoveReadOutdated() throws Exception { // TODO(jdillmann): This test will fail because the VersionState is deleted together with the data objects. // Subsequent calls, with any ViewID >= 0, are therefore valid. If a replica is marked as completed, this will // lead to the false assumption, that the missing object file resembles a sparse file and zeros will be returned // instead of raising an error. // For partial replicas this won't necessarily lead to an error, because internal fetch requests can be checked // for a valid view. String volumeName = "testRonlyRemoveReadOutdated"; String fileName = "/testfile"; client.createVolume(mrcAddress, auth, userCredentials, volumeName); AdminVolume volume = client.openVolume(volumeName, null, options); // setup a full read only replica with sequential access strategy int repl_flags = ReplicationFlags.setFullReplica(ReplicationFlags.setSequentialStrategy(0)); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY, 2, repl_flags); volume.close(); removeReadOutdated(volumeName, fileName); } @Test public void testWqRqRemoveReadOutdated() throws Exception { String volumeName = "testWqRqRemoveReadOutdated"; String fileName = "/testfile"; client.createVolume(mrcAddress, auth, userCredentials, volumeName); AdminVolume volume = client.openVolume(volumeName, null, options); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 3, 0); volume.setOSDSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_FILTER_DEFAULT, OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID })); volume.setReplicaSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID })); volume.close(); removeReadOutdated(volumeName, fileName); } private void removeReadOutdated(String volumeName, String fileName) throws Exception { AdminVolume volume = client.openVolume(volumeName, null, options); // open testfile and write some bytes not "0" AdminFileHandle fileHandle = volume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_CREAT, SYSTEM_V_FCNTL_H_O_RDWR), 0777); int count = 256 * 1024; ReusableBuffer data = SetupUtils.generateData(count, (byte) 1); System.out.println("writing"); fileHandle.write(userCredentials, data.createViewBuffer().getData(), count, 0); fileHandle.close(); // wait until the file is written and probably replicated Thread.sleep(20 * 1000); System.out.println("openagain"); // open the file again and wait until the primary replica is removed fileHandle = volume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDONLY)); // get the primary replica List<Replica> replicas = fileHandle.getReplicasList(); System.out.println(replicas); Replica replica = replicas.get(0); int prevReplicaCount = fileHandle.getReplicasList().size(); System.out.println("Remove replica: " + replica.getOsdUuids(0)); // since striping is disabled there should be only one OSD for this certain replica assertEquals(1, replica.getOsdUuidsCount()); // use another volume remove the replica from the OSD AdminVolume controlVolume = client.openVolume(volumeName, null, options); controlVolume.removeReplica(userCredentials, fileName, replica.getOsdUuids(0)); AdminFileHandle controlFile = controlVolume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDONLY)); assertEquals(controlFile.getReplicasList().size(), prevReplicaCount - 1); System.out.println(controlFile.getReplicasList()); controlFile.close(); controlVolume.close(); // wait until the file is actually deleted on the OSD System.out.println("wait until the file is closed and deleted on the OSD"); Thread.sleep(70 * 1000); // Reading the the file should result in a invalid view. System.out.println("Read with old version"); readInvalidView(fileHandle); fileHandle.close(); volume.close(); } @Test public void testRonlyInvalidViewOnAdd() throws Exception { String volumeName = "testRonlyInvalidViewOnAdd"; String fileName = "/testfile"; client.createVolume(mrcAddress, auth, userCredentials, volumeName); AdminVolume volume = client.openVolume(volumeName, null, options); volume.setReplicaSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID })); // setup a full read only replica with sequential access strategy int repl_flags = ReplicationFlags.setFullReplica(ReplicationFlags.setSequentialStrategy(0)); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY, 2, repl_flags); volume.close(); testInvalidViewOnAdd(volumeName, fileName); } @Test public void testWqRqInvalidViewOnAdd() throws Exception { String volumeName = "testWqRqInvalidViewOnAdd"; String fileName = "/testfile"; client.createVolume(mrcAddress, auth, userCredentials, volumeName); AdminVolume volume = client.openVolume(volumeName, null, options); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 2, 0); volume.close(); testInvalidViewOnAdd(volumeName, fileName); } private void testInvalidViewOnAdd(String volumeName, String fileName) throws Exception { // open outdated file handle and write some data AdminVolume outdatedVolume = client.openVolume(volumeName, null, options); AdminFileHandle outdatedFile = outdatedVolume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_CREAT, SYSTEM_V_FCNTL_H_O_RDWR), 0777); System.out.println("writing"); ReusableBuffer data = SetupUtils.generateData(256, (byte) 1); outdatedFile.write(userCredentials, data.createViewBuffer().getData(), 256, 0); outdatedFile.close(); System.out.println("reopen file"); outdatedFile = outdatedVolume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDONLY)); // open the volume again and add some more replicas AdminVolume volume = client.openVolume(volumeName, null, options); System.out.println("adding replicas"); addReplicas(volume, fileName, 1); volume.close(); // read data with outdated xLocSet System.out.println("read with old version"); readInvalidView(outdatedFile); outdatedFile.close(); outdatedVolume.close(); } /** * This test covers the case, that a number of replicas is added which will form a new majority. It has to be * ensured that the correct data is returned even if only new replicas are accessed. * * @throws Exception */ @Test public void testAddMajority() throws Exception { String volumeName = "testAddMajority"; String fileName = "/testfile"; SuspendableOSDRequestDispatcher[] suspOSDs = replaceWithSuspendableOSDs(0, 2); client.createVolume(mrcAddress, auth, userCredentials, volumeName); System.out.println("open"); AdminVolume volume = client.openVolume(volumeName, null, options); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 2, 0); volume.setOSDSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_FILTER_DEFAULT, OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID })); volume.setReplicaSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID })); System.out.println("write"); AdminFileHandle file = volume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDWR, SYSTEM_V_FCNTL_H_O_CREAT), 0777); ReusableBuffer dataIn = SetupUtils.generateData(256 * 1024, (byte) 1); file.write(userCredentials, dataIn.getData(), 256 * 1024, 0); dataIn.clear(); file.close(); System.out.println("add replicas"); addReplicas(volume, fileName, 3); System.out.println("ensure lease timed out"); Thread.sleep(LEASE_TIMEOUT_MS + 500); // reverse the selection policy volume.setReplicaSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID, OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_REVERSE })); // suspend the first two OSDs for (int i = 0; i < 2; i++) { suspOSDs[i].suspended.set(true); } System.out.println("read"); file = volume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDWR)); byte[] dataOut = new byte[1]; file.read(userCredentials, dataOut, 1, 0); file.close(); volume.close(); // resume the first two OSDs for (int i = 0; i < 2; i++) { suspOSDs[i].suspended.set(false); } resetSuspendableOSDs(suspOSDs, 0); assertEquals(dataOut[0], (byte) 1); } /** * This test covers the removal of replicas forming a majority. It has to be ensured that the remaining replicas are * up to date and the correct (last written) data is returned. * * @throws Exception */ @Test public void testRemoveMajority() throws Exception { String volumeName = "testRemoveMajority"; String fileName = "/testfile"; SuspendableOSDRequestDispatcher[] suspOSDs = replaceWithSuspendableOSDs(0, 2); client.createVolume(mrcAddress, auth, userCredentials, volumeName); System.out.println("open"); AdminVolume volume = client.openVolume(volumeName, null, options); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 5, 0); volume.setOSDSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_FILTER_DEFAULT, OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID })); volume.setReplicaSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID, OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_REVERSE })); // suspend the first two OSDs for (int i = 0; i < 2; i++) { suspOSDs[i].suspended.set(true); } System.out.println("write"); AdminFileHandle file = volume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDWR, SYSTEM_V_FCNTL_H_O_CREAT), 0777); ReusableBuffer dataIn = SetupUtils.generateData(256 * 1024, (byte) 1); file.write(userCredentials, dataIn.getData(), 256 * 1024, 0); dataIn.clear(); // start the OSDs again for (int i = 0; i < 2; i++) { suspOSDs[i].suspended.set(false); } System.out.println("remove replicas"); List<Replica> replicas = file.getReplicasList(); for (int i = 0; i < 3; i++) { Replica replica = replicas.get(i); // since striping is disabled there should be only one OSD for this certain replica assertEquals(1, replica.getOsdUuidsCount()); volume.removeReplica(userCredentials, fileName, replica.getOsdUuids(0)); } file.close(); // revert the selection policy volume.setReplicaSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID })); // reopen the file System.out.println("read"); file = volume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDONLY)); byte[] dataOut = new byte[1]; file.read(userCredentials, dataOut, 1, 0); file.close(); volume.close(); resetSuspendableOSDs(suspOSDs, 2); assertEquals(dataOut[0], (byte) 1); } private SuspendableOSDRequestDispatcher[] replaceWithSuspendableOSDs(int start, int count) throws Exception { SuspendableOSDRequestDispatcher[] suspOSDs = new SuspendableOSDRequestDispatcher[count]; for (int i = start; i < count; i++) { osds[i].shutdown(); osds[i] = null; suspOSDs[i] = new SuspendableOSDRequestDispatcher(configs[i]); suspOSDs[i].start(); } return suspOSDs; } private void resetSuspendableOSDs(SuspendableOSDRequestDispatcher[] suspOSDs, int start) { for (int i = start; i < suspOSDs.length; i++) { suspOSDs[i].shutdown(); suspOSDs[i] = null; osds[i] = new OSD(configs[i]); } } private class SuspendableOSDRequestDispatcher extends OSDRequestDispatcher { private AtomicBoolean suspended; public SuspendableOSDRequestDispatcher(OSDConfig config) throws Exception { super(config); suspended = new AtomicBoolean(false); } @Override public void receiveRecord(RPCServerRequest rq) { if (suspended.get()) { // Drop the request. rq.freeBuffers(); } else { super.receiveRecord(rq); } } } }
package org.xtreemfs.test.mrc; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.List; import java.util.Map; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.xtreemfs.common.ReplicaUpdatePolicies; import org.xtreemfs.common.libxtreemfs.AdminClient; import org.xtreemfs.common.libxtreemfs.AdminFileHandle; import org.xtreemfs.common.libxtreemfs.AdminVolume; import org.xtreemfs.common.libxtreemfs.ClientFactory; import org.xtreemfs.common.libxtreemfs.Options; import org.xtreemfs.common.libxtreemfs.Volume; import org.xtreemfs.common.libxtreemfs.exceptions.PosixErrorException; import org.xtreemfs.common.xloc.ReplicationFlags; import org.xtreemfs.foundation.buffer.ReusableBuffer; import org.xtreemfs.foundation.json.JSONException; import org.xtreemfs.foundation.json.JSONParser; import org.xtreemfs.foundation.json.JSONString; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.Auth; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials; import org.xtreemfs.foundation.util.FSUtils; import org.xtreemfs.osd.OSD; import org.xtreemfs.osd.OSDConfig; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.Replica; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.StripingPolicy; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.StripingPolicyType; import org.xtreemfs.test.SetupUtils; import org.xtreemfs.test.TestEnvironment; public class VersionedXLocSetTest { private static TestEnvironment testEnv; private static UserCredentials userCredentials; private static Auth auth; private static AdminClient client; private static Options options; private static String mrcAddress; private static String dirAddress; private static StripingPolicy defaultStripingPolicy; private static OSD[] osds; private static OSDConfig[] configs; private final static int NUM_OSDS = 5; @BeforeClass public static void initializeTest() throws Exception { System.out.println("TEST: " + VersionedXLocSetTest.class.getSimpleName()); // cleanup FSUtils.delTree(new java.io.File(SetupUtils.TEST_DIR)); Logging.start(Logging.LEVEL_WARN); testEnv = new TestEnvironment( new TestEnvironment.Services[] { TestEnvironment.Services.TIME_SYNC, TestEnvironment.Services.UUID_RESOLVER, TestEnvironment.Services.RPC_CLIENT, TestEnvironment.Services.DIR_SERVICE, TestEnvironment.Services.DIR_CLIENT, TestEnvironment.Services.MRC, TestEnvironment.Services.MRC_CLIENT, TestEnvironment.Services.OSD_CLIENT }); testEnv.start(); // setup osds osds = new OSD[NUM_OSDS]; configs = SetupUtils.createMultipleOSDConfigs(NUM_OSDS); for (int i = 0; i < NUM_OSDS; i++) { osds[i] = new OSD(configs[i]); } dirAddress = testEnv.getDIRAddress().getHostName() + ":" + testEnv.getDIRAddress().getPort(); mrcAddress = testEnv.getMRCAddress().getHostName() + ":" + testEnv.getMRCAddress().getPort(); defaultStripingPolicy = StripingPolicy.newBuilder().setType(StripingPolicyType.STRIPING_POLICY_RAID0) .setStripeSize(128).setWidth(1).build(); userCredentials = UserCredentials.newBuilder().setUsername("test").addGroups("test").build(); auth = RPCAuthentication.authNone; options = new Options(); client = ClientFactory.createAdminClient(dirAddress, userCredentials, null, options); client.start(); } @AfterClass public static void tearDown() throws Exception { for (int i = 0; i < osds.length; i++) { if (osds[i] != null) { osds[i].shutdown(); } } testEnv.shutdown(); client.shutdown(); } private void addReplicas(Volume volume, String fileName, int replicaNumber) throws IOException, InterruptedException { // due to a bug in the OSDSelectionPolicys the numOSDs parameter is not working properly and mostly // returns all suitable OSDs List<String> osdUUIDs = volume.getSuitableOSDs(userCredentials, fileName, replicaNumber); assert (osdUUIDs.size() >= replicaNumber); // save the current Rreplica Number int currentReplicaNumber = volume.listReplicas(userCredentials, fileName).getReplicasCount(); // get Replication Flags // copied from org.xtreemfs.common.libxtreemfs.VolumeImplementation.listACL(UserCredentials, String) // TODO (jdillmann): move to VolumeImplementation.getDefaultReplicationPolicy ? int repl_flags; try { String rpAsJSON = volume.getXAttr(userCredentials, "/", "xtreemfs.default_rp"); Map<String, Object> rp = (Map<String, Object>) JSONParser.parseJSON(new JSONString(rpAsJSON)); repl_flags = (int) ((long) rp.get("replication-flags")); } catch (JSONException e) { throw new IOException(e); } // 15s is the default lease timeout // we have to wait that long, because addReplica calls ping which requires do become primary Thread.sleep(16 * 1000); // for some reason addAllOsdUuids wont work and we have to add them individually // Replica replica = Replica.newBuilder().addAllOsdUuids(osdUUIDs.subList(0, newReplicaNumber)) // .setStripingPolicy(defaultStripingPolicy).setReplicationFlags(repl_flags).build(); // volume.addReplica(userCredentials, fileName, replica); // so we have to fall back to add the replicas individually for (int i = 0; i < replicaNumber; i++) { Replica replica = Replica.newBuilder().setStripingPolicy(defaultStripingPolicy) .setReplicationFlags(repl_flags).addOsdUuids(osdUUIDs.get(i)).build(); volume.addReplica(userCredentials, fileName, replica); // 15s is the default lease timeout Thread.sleep(16 * 1000); System.out.println("Added replica on " + osdUUIDs.get(i)); } assertEquals(currentReplicaNumber + replicaNumber, volume.listReplicas(userCredentials, fileName) .getReplicasCount()); } private void removeReadOutdated(AdminVolume volume, String fileName) throws Exception { // open testfile and write some bytes not "0" int flags = SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(); AdminFileHandle fileHandle = volume.openFile(userCredentials, fileName, flags, 0777); int stripeSize = fileHandle.getStripingPolicy().getStripeSize(); int count = stripeSize * 2; ReusableBuffer data = SetupUtils.generateData(count, (byte) 1); System.out.println("writing"); fileHandle.write(userCredentials, data.createViewBuffer().getData(), count, 0); fileHandle.close(); // wait until the file is written and probably replicated Thread.sleep(20 * 1000); System.out.println("openagain"); // open the file again and wait until the primary replica is removed flags = SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDONLY.getNumber(); fileHandle = volume.openFile(userCredentials, fileName, flags, 0777); // get the OSDs which are suitable for the file System.out.println(volume.getSuitableOSDs(userCredentials, fileName, NUM_OSDS)); // get the primary replica List<Replica> replicas = fileHandle.getReplicasList(); Replica replica = replicas.get(0); // since striping is disabled there should be only one OSD for this certain replica assertEquals(1, replica.getOsdUuidsCount()); // remove the replica from the OSD volume.removeReplica(userCredentials, fileName, replica.getOsdUuids(0)); // TODO (jdillmann): remove when the changeReplicaSet cooridnation is working // open the file again with another // wait until the file is actually deleted on the OSD Thread.sleep(70 * 1000); // reading a deleted file seems like reading a sparse file and should return "0" bytes // TODO (jdillmann): update assertions when versioned XLocSets are implemented byte[] data2 = new byte[1]; fileHandle.read(userCredentials, data2, 1, 0); fileHandle.close(); assert (data2[0] != (byte) 1); // get the OSDs which are suitable for the file System.out.println(volume.getSuitableOSDs(userCredentials, fileName, NUM_OSDS)); } private void removeReadOutdated(String volumeName, String fileName) throws Exception { AdminVolume volume = client.openVolume(volumeName, null, options); removeReadOutdated(volume, fileName); } @Ignore @Test public void testRonlyRemoveReadOutdated() throws Exception { String volumeName = "testRonlyRemoveReadOutdated"; String fileName = "/testfile"; client.createVolume(mrcAddress, auth, userCredentials, volumeName); AdminVolume volume = client.openVolume(volumeName, null, options); // setup a full read only replica with sequential access strategy int repl_flags = ReplicationFlags.setFullReplica(ReplicationFlags.setSequentialStrategy(0)); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY, 2, repl_flags); removeReadOutdated(volume, fileName); } @Ignore @Test public void testWqRqRemoveReadOutdated() throws Exception { String volumeName = "testWqRqRemoveReadOutdated"; String fileName = "/testfile"; client.createVolume(mrcAddress, auth, userCredentials, volumeName); AdminVolume volume = client.openVolume(volumeName, null, options); int repl_flags = ReplicationFlags.setSequentialStrategy(0); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 3, repl_flags); removeReadOutdated(volume, fileName); } @Test public void testRonlyAddReadOutdated() throws Exception { String volumeName = "testRonlyAddReadOutdated"; String fileName = "/testfile"; client.createVolume(mrcAddress, auth, userCredentials, volumeName); AdminVolume volume = client.openVolume(volumeName, null, options); // setup a full read only replica with sequential access strategy int repl_flags = ReplicationFlags.setFullReplica(ReplicationFlags.setSequentialStrategy(0)); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY, 2, repl_flags); // general part int flags = SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(); // open file handle AdminFileHandle fileHandle = volume.openFile(userCredentials, fileName, flags, 0777); int stripeSize = fileHandle.getStripingPolicy().getStripeSize(); int count = stripeSize * 2; ReusableBuffer data = SetupUtils.generateData(count, (byte) 1); System.out.println("writing"); fileHandle.write(userCredentials, data.createViewBuffer().getData(), count, 0); fileHandle.close(); flags = SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDONLY.getNumber(); fileHandle = volume.openFile(userCredentials, fileName, flags, 0777); // AdminVolume System.out.println("reopen file"); AdminVolume volume2 = client.openVolume(volumeName, null, options); // add replica System.out.println("adding replicas"); int newReplicaNumber = 1; addReplicas(volume2, fileName, newReplicaNumber); AdminFileHandle fileHandle2 = volume2.openFile(userCredentials, fileName, flags, 0777); // read data System.out.println("read with new version"); byte[] data2 = new byte[1]; fileHandle2.read(userCredentials, data2, 1, 0); fileHandle2.close(); fileHandle2.close(); volume2.close(); // read outdated System.out.println("read with old version"); PosixErrorException catched = null; try { fileHandle.read(userCredentials, data2, 1, 0); } catch (PosixErrorException e) { catched = e; } finally { fileHandle.close(); } // TODO (jdillmann): make this more dynamic assert (catched != null); assert (catched.getPosixError() == RPC.POSIXErrno.POSIX_ERROR_EAGAIN); assert (catched.getMessage().equals("view is not valid")); } // @Test // public void testWqRqOutdatedAdd() throws Exception { // String volumeName = "testWqRqOutdatedAdd"; // String fileName = "/testfile"; // // client.createVolume(mrcAddress, auth, userCredentials, volumeName, 0, // // userCredentials.getUsername(), // // userCredentials.getGroups(0), AccessControlPolicyType.ACCESS_CONTROL_POLICY_NULL, // // StripingPolicyType.STRIPING_POLICY_RAID0, defaultStripingPolicy.getStripeSize(), // // defaultStripingPolicy.getWidth(), new ArrayList<KeyValuePair>()); // client.createVolume(mrcAddress, auth, userCredentials, volumeName); // AdminVolume volume = client.openVolume(volumeName, null, options); // int replicaNumber = 3; // int repl_flags = ReplicationFlags.setSequentialStrategy(0); // // addReplica with WQRQ is not working for some reasons i don't understand // volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, // replicaNumber, repl_flags); // // volume.setDefaultReplicationPolicy(userCredentials, "/", // // ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE, // // replicaNumber, repl_flags); // // open testfile and write some bytes not "0" // int flags = SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() // | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(); // AdminFileHandle fileHandle = volume.openFile(userCredentials, fileName, flags, 0777); // int stripeSize = fileHandle.getStripingPolicy().getStripeSize(); // int count = stripeSize * 2; // ReusableBuffer data = SetupUtils.generateData(count, (byte) 1); // fileHandle.write(userCredentials, data.createViewBuffer().getData(), count, 0); // fileHandle.close(); // // wait some time to allow the file to replicate // // Thread.sleep(15 * 1000); // // add some more replicas // int newReplicaNumber = 1; // addReplicas(volume, fileName, newReplicaNumber); // // wait for flease // // Thread.sleep(20 * 1000); // assertEquals(replicaNumber + newReplicaNumber, volume.listReplicas(userCredentials, fileName) // .getReplicasCount()); // // fileHandle = volume.openFile(userCredentials, fileName, flags); // // byte[] data2 = new byte[1]; // // fileHandle.read(userCredentials, data2, 1, 0); // // fileHandle.close(); // // System.out.println(data2); // System.out.println("wait"); // @Test // public void testWqRqOutdatedRemove() throws Exception { // String volumeName = "testWqRqOutdatedRemove"; // String path = "/testfile"; // // client.createVolume(mrcAddress, auth, userCredentials, volumeName, 0, // // userCredentials.getUsername(), // // userCredentials.getGroups(0), AccessControlPolicyType.ACCESS_CONTROL_POLICY_NULL, // // StripingPolicyType.STRIPING_POLICY_RAID0, defaultStripingPolicy.getStripeSize(), // // defaultStripingPolicy.getWidth(), new ArrayList<KeyValuePair>()); // client.createVolume(mrcAddress, auth, userCredentials, volumeName); // AdminVolume volume = client.openVolume(volumeName, null, options); // int repl_flags = ReplicationFlags.setSequentialStrategy(0); // volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, // NUM_OSDS, // repl_flags); // AdminFileHandle fileHandle = volume.openFile(userCredentials, path, // SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber(), 0777); // assert (fileHandle.getReplicasList().size() == NUM_OSDS); // // write "1" bytes to the file // int stripeSize = fileHandle.getStripingPolicy().getStripeSize(); // int count = stripeSize * 2; // ReusableBuffer data = SetupUtils.generateData(count, (byte) 1); // byte[] dataout = new byte[count]; // fileHandle.write(userCredentials, data.createViewBuffer().getData(), count, 0); // fileHandle.close(); // assert (volume.getSuitableOSDs(userCredentials, path, NUM_OSDS).size() == 0); // // open a FileHandle which should be outdated // System.out.println("open outdated file handle"); // AdminClient outdatedClient = ClientFactory.createAdminClient(dirAddress, userCredentials, null, // options); // outdatedClient.start(); // AdminVolume outdatedVolume = outdatedClient.openVolume(volumeName, null, options); // AdminFileHandle outdatedFileHandle = outdatedVolume.openFile(userCredentials, path, // SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDONLY.getNumber()); // // remove replicas // System.out.println("removing replicas"); // fileHandle = volume.openFile(userCredentials, path, // SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDONLY.getNumber()); // List<Replica> replicas = fileHandle.getReplicasList(); // fileHandle.close(); // for (int i = 0; i<3; i++) { // volume.removeReplica(userCredentials, path, replicas.get(i).getOsdUuids(0)); // assert (volume.getSuitableOSDs(userCredentials, path, NUM_OSDS).size() == 3); // Thread.sleep(70 * 1000); // System.out.println("open the file with the new xlocset"); // // write something new => for example two // fileHandle = volume.openFile(userCredentials, path, // SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber()); // assert (fileHandle.getReplicasList().size() == 2); // System.out.println(fileHandle.getReplicasList()); // data = SetupUtils.generateData(count, (byte) 2); // fileHandle.write(userCredentials, data.createViewBuffer().getData(), count, 0); // fileHandle.read(userCredentials, dataout, count, 0); // fileHandle.close(); // assert (dataout[0] == (byte) 2); // outdatedFileHandle.read(userCredentials, dataout, count, 0); // outdatedFileHandle.close(); // assert (dataout[0] == (byte) 2); }
package javamm.typesystem; import javamm.javamm.JavammXAssignment; import org.eclipse.xtext.xbase.XExpression; import org.eclipse.xtext.xbase.typesystem.arguments.AssignmentFeatureCallArguments; import org.eclipse.xtext.xbase.typesystem.arguments.IFeatureCallArguments; import org.eclipse.xtext.xbase.typesystem.internal.AbstractLinkingCandidate; import org.eclipse.xtext.xbase.typesystem.internal.ExpressionArgumentFactory; import org.eclipse.xtext.xbase.typesystem.references.ArrayTypeReference; import org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference; /** * @author Lorenzo Bettini * */ public class JavammExpressionArgumentFactory extends ExpressionArgumentFactory { @Override public IFeatureCallArguments createExpressionArguments( XExpression expression, AbstractLinkingCandidate<?> candidate) { if (expression instanceof JavammXAssignment) { AssignmentFeatureCallArguments assignmentFeatureCallArguments = (AssignmentFeatureCallArguments) super.createExpressionArguments(expression, candidate); JavammXAssignment assignment = (JavammXAssignment) expression; LightweightTypeReference featureType = assignmentFeatureCallArguments.getDeclaredType(); if (featureType instanceof ArrayTypeReference) { return new AssignmentFeatureCallArguments(assignment.getValue(), ((ArrayTypeReference)featureType).getComponentType()); } else { return assignmentFeatureCallArguments; } } return super.createExpressionArguments(expression, candidate); } }
package uk.org.opentrv.ETV.driver; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import uk.org.opentrv.ETV.ETVHouseholdGroupSimpleSummaryStats; import uk.org.opentrv.ETV.ETVHouseholdGroupSimpleSummaryStats.SummaryStats; import uk.org.opentrv.ETV.ETVPerHouseholdComputation; import uk.org.opentrv.ETV.ETVPerHouseholdComputation.ETVPerHouseholdComputationInput; import uk.org.opentrv.ETV.ETVPerHouseholdComputation.ETVPerHouseholdComputationResult; import uk.org.opentrv.ETV.ETVPerHouseholdComputation.ETVPerHouseholdComputationSystemStatus; import uk.org.opentrv.ETV.ETVPerHouseholdComputationSimpleImpl; import uk.org.opentrv.ETV.filter.CommonSimpleResultFilters; import uk.org.opentrv.ETV.filter.StatusSegmentation; import uk.org.opentrv.ETV.output.ETVHouseholdGroupSimpleSummaryStatsToCSV; import uk.org.opentrv.ETV.output.ETVPerHouseholdComputationResultsToCSV; import uk.org.opentrv.ETV.output.ETVPerHouseholdComputationSystemStatusSummaryCSV; import uk.org.opentrv.ETV.parse.NBulkInputs; import uk.org.opentrv.ETV.parse.NBulkKWHParseByID; import uk.org.opentrv.ETV.parse.OTLogActivityParse; import uk.org.opentrv.hdd.HDDUtil; /**Simple driver from N bulk and HDD data to output files. * An input directory is supplied, * and the data files are read from specific named files within that input directory. * <p> * An output directory is supplied * and the output files will be written to specific named files within that output directory. */ public final class ETVSimpleDriverNBulkInputs { /**Name within input directory of simple daily HDD CSV ASCII7 file. */ public static final String INPUT_FILE_HDD = "HDD.csv"; /**Name within input directory of 'N' format kWh energy consumption CSV ASCII7 file. */ public static final String INPUT_FILE_NKWH = "NkWh.csv"; /**Name within input directory of per-household system state CSV ASCII7 file. */ public static final String INPUT_FILE_STATUS = "status.csv"; /**Name within output directory of basic per-household stats as ASCII7 CSV (no efficacy computation). */ public static final String OUTPUT_STATS_FILE_BASIC = "10_basicStatsOut.csv"; /**Name within output directory of filtered basic per-household stats as ASCII7 CSV (no efficacy computation). * The filtering removes those entries that are outliers * or have inadequate data points or no/poor correlation. */ public static final String OUTPUT_STATS_FILE_FILTERED_BASIC = "20_basicFilteredStatsOut.csv"; /**Name within output directory of pre-segmented per-household stats as ASCII7 CSV. * This consists of one line per house of houseID,controlDays,normalDays. */ public static final String OUTPUT_STATS_FILE_PRESEGMENTED = "30_presegmentedStatsOut.csv"; /**Name within output directory of segmented per-household stats as ASCII7 CSV including efficacy computation. * The HDD metrics are from the normal state, with energy-saving features enabled. */ public static final String OUTPUT_STATS_FILE_SEGMENTED = "31_segmentedStatsOut.csv"; /**Name within output directory of household group simple summary stats as ASCII7 CSV including efficacy computation. * The HDD metrics are from the normal state, with energy-saving features enabled. */ public static final String OUTPUT_STATS_FILE_MULITHOUSEHOLD_SUMMARY = "40_multihouseholdSummaryStatsOut.csv"; /**Gets a reader for the specified file; no checked exceptions. */ private static Reader getReader(final File f) { try { return(new FileReader(f)); } catch(final IOException e) { throw new RuntimeException(e); } } /**Trivial command-line front-end. */ public static void main(final String args[]) { if(args.length < 2) { throw new IllegalArgumentException(); } try { doComputation(new File(args[0]), new File(args[1])); } catch(final IOException e) { throw new RuntimeException(e); } } /**Process from specified input to output directories; sort result by house ID for consistency. * The input and output directories can be the same if required; * the file names for input and output are all distinct. * <p> * Efficacy computation will be attempted if log files are present. * <p> * Note: currently assumes N-format bulk energy data and timezone. * <p> * If this is unable to complete a run * eg because there is insufficient/unsuitable data * then it will terminating with an exception * having generated what outputs that it can. * * @param inDir directory containing input files, must exist and be readable; never null * @param outDir directory for output files, must exist and be writeable; never null * @throws IOException in case of difficulty */ public static void doComputation(final File inDir, final File outDir) throws IOException { if(null == inDir) { throw new IllegalArgumentException(); } if(null == outDir) { throw new IllegalArgumentException(); } if(!inDir.isDirectory()) { throw new IOException("Cannot open input directory " + inDir); } if(!outDir.isDirectory()) { throw new IOException("Cannot open output directory " + outDir); } // Gather raw kWh and HDD data; savings-measure status Map is null. final Map<String, ETVPerHouseholdComputationInput> mhi = NBulkInputs.gatherDataForAllHouseholds( () -> getReader(new File(inDir, INPUT_FILE_NKWH)), getReader(new File(inDir, INPUT_FILE_HDD))); // Compute and output basic results, no efficacy. final ETVPerHouseholdComputationSimpleImpl computationInstance = ETVPerHouseholdComputationSimpleImpl.getInstance(); final List<ETVPerHouseholdComputationResult> rlBasic = mhi.values().stream().map(computationInstance).collect(Collectors.toList()); Collections.sort(rlBasic, new ETVPerHouseholdComputation.ResultSortByHouseID()); final String rlBasicCSV = (new ETVPerHouseholdComputationResultsToCSV()).apply(rlBasic); final File basicResultFile = new File(outDir, ETVSimpleDriverNBulkInputs.OUTPUT_STATS_FILE_BASIC); //System.out.println(rlCSV); // Write output... try(final FileWriter w = new FileWriter(basicResultFile)) { w.write(rlBasicCSV); } // Compute and output basic *filtered* results. final List<ETVPerHouseholdComputationResult> rlBasicFiltered = rlBasic.stream().filter(CommonSimpleResultFilters.goodDailyDataResults).collect(Collectors.toList()); Collections.sort(rlBasicFiltered, new ETVPerHouseholdComputation.ResultSortByHouseID()); final String rlBasicFilteredCSV = (new ETVPerHouseholdComputationResultsToCSV()).apply(rlBasicFiltered); final File basicFilteredResultFile = new File(outDir, ETVSimpleDriverNBulkInputs.OUTPUT_STATS_FILE_FILTERED_BASIC); //System.out.println(rlCSV); // Write output... try(final FileWriter w = new FileWriter(basicFilteredResultFile)) { w.write(rlBasicFilteredCSV); } // Stop if no candidates left after filtering. // Probably an error. if(rlBasicFiltered.isEmpty()) { throw new UnsupportedOperationException("No candidate households left after filtering."); } // Test if log data is available for segmentation, else stop. // Not an error. if(!(new File(inDir, OTLogActivityParse.LOGDIR_PATH_TO_GROUPING_CSV)).exists()) { System.out.println("No grouping file in input dir, so no segmentation attempted: " + OTLogActivityParse.LOGDIR_PATH_TO_GROUPING_CSV); return; } // Segment, and look for changes in energy efficiency. final Set<String> stage1FilteredHouseIDs = rlBasicFiltered.stream().map(e -> e.getHouseID()).collect(Collectors.toSet()); final Map<String, ETVPerHouseholdComputationSystemStatus> byHouseholdSegmentation = OTLogActivityParse.loadAndParseAllOTLogs(HDDUtil.getDirSmartFileReader(inDir), NBulkKWHParseByID.DEFAULT_NB_TIMEZONE, stage1FilteredHouseIDs); // Output pre-segmented results per household // to give an indication of which (don't) have enough control and non-control days final List<ETVPerHouseholdComputationSystemStatus> rlPresegmented = new ArrayList<>(byHouseholdSegmentation.values()); // Collections.sort(rlPresegmented, new ETVPerHouseholdComputation.ResultSortByHouseID()); final String rlPresegmentedCSV = (new ETVPerHouseholdComputationSystemStatusSummaryCSV()).apply(rlPresegmented); final File presegmentedResultFile = new File(outDir, ETVSimpleDriverNBulkInputs.OUTPUT_STATS_FILE_PRESEGMENTED); try(final FileWriter w = new FileWriter(presegmentedResultFile)) { w.write(rlPresegmentedCSV); } // Filter out households with too little control and normal data left. final List<ETVPerHouseholdComputationSystemStatus> enoughControlAndNormal = byHouseholdSegmentation.values().stream().filter(CommonSimpleResultFilters.enoughControlAndNormal).collect(Collectors.toList()); // Stop if no candidates left after attempting to segment. // Probably an error. if(enoughControlAndNormal.isEmpty()) { throw new UnsupportedOperationException("No candidate households left after attempting to segment."); } //System.out.println(enoughControlAndNormal.iterator().next().getOptionalEnabledAndUsableFlagsByLocalDay()); // Analyse segmented data per household. // Inject the per-day savings-measures status into the input, // and use the split analysis. final List<ETVPerHouseholdComputationResult> rlSegmented = new ArrayList<>(); for(final ETVPerHouseholdComputationSystemStatus statusByID : enoughControlAndNormal) { final String houseID = statusByID.getHouseID(); final ETVPerHouseholdComputationInput input = mhi.get(houseID); if(null == input) { throw new Error("should not happen"); } final ETVPerHouseholdComputationInput inputWithStatus = StatusSegmentation.injectStatusInfo(input, statusByID); final ETVPerHouseholdComputationResult reanalysed = computationInstance.apply(inputWithStatus); //System.out.println(reanalysed.getRatiokWhPerHDDNotSmartOverSmart()); rlSegmented.add(reanalysed); } // Output segmented results per household. Collections.sort(rlSegmented, new ETVPerHouseholdComputation.ResultSortByHouseID()); final String rlSegmentedCSV = (new ETVPerHouseholdComputationResultsToCSV()).apply(rlSegmented); final File segmentedResultFile = new File(outDir, ETVSimpleDriverNBulkInputs.OUTPUT_STATS_FILE_SEGMENTED); try(final FileWriter w = new FileWriter(segmentedResultFile)) { w.write(rlSegmentedCSV); } // Analyse across groups of households, with confidence estimate. final SummaryStats summaryStats = ETVHouseholdGroupSimpleSummaryStats.computeSummaryStats(mhi.size(), rlSegmented); final String summaryCSV = (new ETVHouseholdGroupSimpleSummaryStatsToCSV()).apply(summaryStats); final File summaryResultFile = new File(outDir, ETVSimpleDriverNBulkInputs.OUTPUT_STATS_FILE_MULITHOUSEHOLD_SUMMARY); try(final FileWriter w = new FileWriter(summaryResultFile)) { w.write(summaryCSV); } // TODO // Generate and write report(s). } }
package com.jetbrains.jsonSchema.impl; import com.intellij.json.JsonLanguage; import com.intellij.json.psi.JsonFile; import com.intellij.json.psi.JsonObject; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.AtomicClearableLazyValue; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.ModificationTracker; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ArrayUtil; import com.intellij.util.ObjectUtils; import com.jetbrains.jsonSchema.JsonSchemaVfsListener; import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider; import com.jetbrains.jsonSchema.extension.JsonSchemaProviderFactory; import com.jetbrains.jsonSchema.extension.SchemaType; import com.jetbrains.jsonSchema.ide.JsonSchemaService; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.stream.Collectors; public class JsonSchemaServiceImpl implements JsonSchemaService { @NotNull private final Project myProject; private final MyState myState; private final AtomicLong myModificationCount = new AtomicLong(0); private final AtomicLong myAnyChangeCount = new AtomicLong(0); private final ModificationTracker myModificationTracker; private final ModificationTracker myAnySchemaChangeTracker; public JsonSchemaServiceImpl(@NotNull Project project) { myProject = project; myState = new MyState(() -> getProvidersFromFactories(factory -> factory.getProviders(myProject))); myModificationTracker = () -> myModificationCount.get(); myAnySchemaChangeTracker = () -> myAnyChangeCount.get(); project.getMessageBus().connect().subscribe(JsonSchemaVfsListener.JSON_SCHEMA_CHANGED, myAnyChangeCount::incrementAndGet); JsonSchemaVfsListener.startListening(project, this); } @Override public ModificationTracker getAnySchemaChangeTracker() { return myAnySchemaChangeTracker; } private List<JsonSchemaFileProvider> getProvidersFromFactories( @NotNull final Function<JsonSchemaProviderFactory, List<JsonSchemaFileProvider>> function) { return Arrays.stream(getProviderFactories()) .map(function) .flatMap(List::stream) .collect(Collectors.toList()); } @NotNull protected JsonSchemaProviderFactory[] getProviderFactories() { return JsonSchemaProviderFactory.EP_NAME.getExtensions(); } @Nullable @Override public JsonSchemaFileProvider getSchemaProvider(@NotNull VirtualFile schemaFile) { return myState.getProvider(schemaFile); } @Override public void reset() { myAnyChangeCount.incrementAndGet(); myState.reset(); ApplicationManager.getApplication().invokeLater(() -> WriteAction.run(() -> FileTypeManagerEx.getInstanceEx().fireFileTypesChanged()), ModalityState.NON_MODAL, myProject.getDisposed()); } @Override @Nullable public VirtualFile findSchemaFileByReference(@NotNull String reference, @Nullable VirtualFile referent) { final Optional<VirtualFile> optional = myState.getFiles().stream() .filter(file -> reference.equals(JsonSchemaReader.readSchemaId(myProject, file))) .findFirst(); return optional.orElseGet(() -> getSchemaFileByRefAsLocalFile(reference, referent)); } @Override @NotNull public Collection<VirtualFile> getSchemaFilesForFile(@NotNull final VirtualFile file) { return myState.getProviders().stream().filter(provider -> isProviderAvailable(file, provider)) .map(processor -> processor.getSchemaFile()).collect(Collectors.toList()); } @Nullable @Override public JsonSchemaObject getSchemaObject(@NotNull final VirtualFile file) { final List<JsonSchemaFileProvider> providers = myState.getProviders().stream().filter(provider -> isProviderAvailable(file, provider)).collect(Collectors.toList()); if (providers.isEmpty() || providers.size() > 2) return null; final JsonSchemaFileProvider selected; if (providers.size() > 1) { final Optional<JsonSchemaFileProvider> userSchema = providers.stream().filter(provider -> SchemaType.userSchema.equals(provider.getSchemaType())).findFirst(); if (!userSchema.isPresent()) return null; selected = userSchema.get(); } else selected = providers.get(0); if (selected.getSchemaFile() == null) return null; return readCachedObject(selected.getSchemaFile()); } @Nullable @Override public JsonSchemaObject getSchemaObjectForSchemaFile(@NotNull VirtualFile schemaFile) { return readCachedObject(schemaFile); } @Override public boolean isSchemaFile(@NotNull VirtualFile file) { return myState.getFiles().contains(file); } @Nullable private JsonSchemaObject readCachedObject(@NotNull VirtualFile schemaFile) { final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(schemaFile); if (psiFile == null || !(psiFile instanceof JsonFile)) return null; final CachedValueProvider<JsonSchemaObject> provider = () -> { final JsonObject topLevelValue = ObjectUtils.tryCast(((JsonFile)psiFile).getTopLevelValue(), JsonObject.class); final JsonSchemaObject object = topLevelValue == null ? null : new JsonSchemaReader().read(topLevelValue); return CachedValueProvider.Result.create(object, psiFile, myModificationTracker); }; return ReadAction.compute(() -> CachedValuesManager.getCachedValue(psiFile, provider)); } private boolean isProviderAvailable(@NotNull final VirtualFile file, @NotNull JsonSchemaFileProvider provider) { final FileType type = file.getFileType(); final boolean isJson = type instanceof LanguageFileType && ((LanguageFileType)type).getLanguage().isKindOf(JsonLanguage.INSTANCE); return (isJson || !SchemaType.userSchema.equals(provider.getSchemaType())) && provider.isAvailable(myProject, file); } @Nullable private static VirtualFile getSchemaFileByRefAsLocalFile(@NotNull String id, @Nullable VirtualFile referent) { final String normalizedId = JsonSchemaService.normalizeId(id); if (FileUtil.isAbsolute(normalizedId) || referent == null) return VfsUtil.findFileByIoFile(new File(normalizedId), false); VirtualFile dir = referent.isDirectory() ? referent : referent.getParent(); if (dir != null && dir.isValid()) { final List<String> parts = StringUtil.split(normalizedId.replace("\\", "/"), "/"); return VfsUtil.findRelativeFile(dir, ArrayUtil.toStringArray(parts)); } return null; } private static class MyState { @NotNull private final Factory<List<JsonSchemaFileProvider>> myFactory; @NotNull private final AtomicClearableLazyValue<Map<VirtualFile, JsonSchemaFileProvider>> myData; private MyState(@NotNull final Factory<List<JsonSchemaFileProvider>> factory) { myFactory = factory; myData = new AtomicClearableLazyValue<Map<VirtualFile, JsonSchemaFileProvider>>() { @NotNull @Override public Map<VirtualFile, JsonSchemaFileProvider> compute() { return Collections.unmodifiableMap(createFileProviderMap(myFactory.create())); } }; } public void reset() { myData.drop(); } @NotNull public Collection<JsonSchemaFileProvider> getProviders() { return myData.getValue().values(); } @NotNull public Set<VirtualFile> getFiles() { return myData.getValue().keySet(); } @Nullable public JsonSchemaFileProvider getProvider(@NotNull final VirtualFile file) { return myData.getValue().get(file); } private static Map<VirtualFile, JsonSchemaFileProvider> createFileProviderMap(@NotNull final List<JsonSchemaFileProvider> list) { return list.stream() .filter(provider -> provider.getSchemaFile() != null) .collect(Collectors.toMap(JsonSchemaFileProvider::getSchemaFile, Function.identity())); } } }
package com.jetbrains.jsonSchema.impl; import com.intellij.codeInsight.completion.CompletionContributor; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.idea.RareLogger; import com.intellij.json.JsonLanguage; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.lang.documentation.CompositeDocumentationProvider; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.util.Consumer; import com.intellij.util.NotNullFunction; import com.intellij.util.PairConsumer; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.jsonSchema.CodeInsightProviders; import com.jetbrains.jsonSchema.JsonSchemaFileTypeManager; import com.jetbrains.jsonSchema.JsonSchemaVfsListener; import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider; import com.jetbrains.jsonSchema.extension.JsonSchemaImportedProviderMarker; import com.jetbrains.jsonSchema.extension.JsonSchemaProviderFactory; import com.jetbrains.jsonSchema.extension.SchemaType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class JsonSchemaServiceImpl implements JsonSchemaServiceEx { private static final Logger LOGGER = Logger.getInstance(JsonSchemaServiceImpl.class); private static final Logger RARE_LOGGER = RareLogger.wrap(LOGGER, false); public static final Comparator<JsonSchemaFileProvider> FILE_PROVIDER_COMPARATOR = Comparator.comparingInt(JsonSchemaFileProvider::getOrder); @NotNull private final Project myProject; private final Object myLock; private final Map<VirtualFile, CodeInsightProviders> myWrappers = new HashMap<>(); private final Set<VirtualFile> mySchemaFiles = ContainerUtil.newConcurrentSet(); private volatile boolean initialized; private final JsonSchemaExportedDefinitions myDefinitions; public JsonSchemaServiceImpl(@NotNull Project project) { myLock = new Object(); myProject = project; myDefinitions = new JsonSchemaExportedDefinitions(); JsonSchemaVfsListener.startListening(project, this); ensureSchemaFiles(); } @NotNull protected JsonSchemaProviderFactory[] getProviderFactories() { return JsonSchemaProviderFactory.EP_NAME.getExtensions(); } private List<JsonSchemaFileProvider> getProviders() { final List<JsonSchemaFileProvider> providers = new ArrayList<>(); for (JsonSchemaProviderFactory factory : getProviderFactories()) { providers.addAll(factory.getProviders(myProject)); } Collections.sort(providers, FILE_PROVIDER_COMPARATOR); return providers; } @Nullable public Annotator getAnnotator(@Nullable VirtualFile file) { CodeInsightProviders wrapper = getWrapper(file); return wrapper != null ? wrapper.getAnnotator() : null; } @Nullable public CompletionContributor getCompletionContributor(@Nullable VirtualFile file) { CodeInsightProviders wrapper = getWrapper(file); return wrapper != null ? wrapper.getContributor() : null; } private void ensureSchemaFiles() { synchronized (myLock) { if (!initialized) { for (JsonSchemaFileProvider provider : getProviders()) { final VirtualFile schemaFile = provider.getSchemaFile(); if (schemaFile != null) { mySchemaFiles.add(schemaFile); // this will make it refresh myDefinitions.dropKey(schemaFile); myWrappers.remove(schemaFile); } } initialized = true; } } } @Override public boolean isSchemaFile(@NotNull VirtualFile file, @NotNull final Consumer<String> errorConsumer) { try { VfsUtilCore.loadText(file); } catch (IOException e) { errorConsumer.consume(e.getMessage()); return false; } try { return JsonSchemaReader.isJsonSchema(myProject, file, errorConsumer); } catch (Exception e) { reset(); errorConsumer.consume(e.getMessage()); return false; } } @Nullable @Override public DocumentationProvider getDocumentationProvider(@Nullable VirtualFile file) { CodeInsightProviders wrapper = getWrapper(file); return wrapper != null ? wrapper.getDocumentationProvider() : null; } @Override public void visitSchemaObject(@NotNull final VirtualFile schemaFile, @NotNull Processor<JsonSchemaObject> consumer) { final CodeInsightProviders wrapper = getWrapperBySchemaFile(schemaFile); if (wrapper == null) return; wrapper.iterateSchemaObjects(consumer); } @Nullable @Override public List<Pair<Boolean, String>> getMatchingSchemaDescriptors(@Nullable VirtualFile file) { final List<CodeInsightProviders> wrappers = getWrappers(file); if (wrappers == null || wrappers.isEmpty()) return null; return ContainerUtil.map(wrappers, (NotNullFunction<CodeInsightProviders, Pair<Boolean, String>>) wrapper -> Pair.create(wrapper.isUserSchema(), wrapper.getName())); } @Nullable private CodeInsightProviders createWrapper(@NotNull JsonSchemaFileProvider provider) { final JsonSchemaObject resultObject = readObject(provider); if (resultObject == null) return null; return provider.proxyCodeInsightProviders(new JsonSchemaObjectCodeInsightWrapper( myProject, provider.getName(), provider.getSchemaType(), provider.getSchemaFile(), resultObject)); } private JsonSchemaObject readObject(@NotNull JsonSchemaFileProvider provider) { final VirtualFile file = provider.getSchemaFile(); if (file == null) return null; return ReadAction.compute(() -> { try { final JsonSchemaReader reader = JsonSchemaReader.create(myProject, file); if (reader == null) return null; final JsonSchemaObject schemaObject = reader.read(); if (schemaObject.getId() != null) myDefinitions.register(file, schemaObject.getId()); return schemaObject; } catch (ProcessCanceledException e) { //ignored } catch (Exception e) { logException(provider, e); } return null; }); } private static void logException(@NotNull JsonSchemaFileProvider provider, Exception e) { final String message = "Error while processing json schema file: " + e.getMessage(); if (provider instanceof JsonSchemaImportedProviderMarker) { RARE_LOGGER.info(message, e); } else { LOGGER.error(message, e); } } @Override public void reset() { synchronized (myLock) { myWrappers.clear(); myDefinitions.reset(); initialized = false; mySchemaFiles.clear(); } JsonSchemaFileTypeManager.getInstance().reset(); } @Nullable private CodeInsightProviders getWrapper(@Nullable VirtualFile file) { if (file == null) return null; final List<CodeInsightProviders> wrappers = getWrappers(file); if (wrappers == null || wrappers.isEmpty()) { return null; } return (wrappers.size() == 1 ? wrappers.get(0) : new CompositeCodeInsightProviderWithWarning(wrappers)); } //! the only point for refreshing json schema caches @Override public void dropProviderFromCache(@NotNull final VirtualFile schemaFile) { synchronized (myLock) { myDefinitions.dropKey(schemaFile); myWrappers.remove(schemaFile); } } @Nullable private List<CodeInsightProviders> getWrappers(@Nullable VirtualFile file) { if (file == null) return null; final FileType type = file.getFileType(); final boolean isJson = type instanceof LanguageFileType && ((LanguageFileType)type).getLanguage().isKindOf(JsonLanguage.INSTANCE); synchronized (myLock) { if (mySchemaFiles.isEmpty()) { mySchemaFiles.addAll(getProviders().stream() .filter(provider -> provider.getSchemaFile() != null) .map(provider -> provider.getSchemaFile()).collect(Collectors.toSet())); } } final List<CodeInsightProviders> wrappers = new ArrayList<>(); getWrapperSkeletonMethod(provider -> provider.isAvailable(myProject, file) && (isJson || !SchemaType.userSchema.equals(provider.getSchemaType())), wrapper -> wrappers.add(wrapper), true); return wrappers; } @Nullable private CodeInsightProviders getWrapperBySchemaFile(@NotNull final VirtualFile schemaFile) { synchronized (myLock) { CodeInsightProviders wrapper = myWrappers.get(schemaFile); if (wrapper != null) return wrapper; } final Ref<CodeInsightProviders> ref = new Ref<>(); getWrapperSkeletonMethod(provider -> schemaFile.equals(provider.getSchemaFile()), wrapper -> ref.set(wrapper), false); return ref.get(); } private void getWrapperSkeletonMethod(@NotNull final Processor<JsonSchemaFileProvider> processor, @NotNull final Consumer<CodeInsightProviders> consumer, final boolean multiple) { final List<JsonSchemaFileProvider> matchingProviders = new ArrayList<>(); synchronized (myLock) { for (JsonSchemaFileProvider provider : getProviders()) { if (processor.process(provider)) { final CodeInsightProviders wrapper = myWrappers.get(provider.getSchemaFile()); if (wrapper != null) { consumer.consume(wrapper); if (!multiple) return; } else { matchingProviders.add(provider); if (!multiple) break; } } } } if (matchingProviders.isEmpty()) return; final Map<VirtualFile, Pair<CodeInsightProviders, JsonSchemaFileProvider>> created = new HashMap<>(); for (JsonSchemaFileProvider provider : matchingProviders) { // read action taken here => without wrapping lock final CodeInsightProviders wrapper = createWrapper(provider); if (wrapper != null) created.put(provider.getSchemaFile(), Pair.create(wrapper, provider)); } synchronized (myLock) { final List<JsonSchemaFileProvider> providers = getProviders(); created.forEach((file, pair) -> { final CodeInsightProviders wrapper = pair.getFirst(); final JsonSchemaFileProvider provider = pair.getSecond(); // check again, providers could have changed if (!providers.contains(provider)) return; // check again, rules could have changed if (processor.process(provider)) { myWrappers.putIfAbsent(file, wrapper); consumer.consume(wrapper); } }); } } private static class CompositeCodeInsightProviderWithWarning implements CodeInsightProviders { private final List<CodeInsightProviders> myWrappers; private final CompletionContributor myContributor; private final Annotator myAnnotator; private final DocumentationProvider myDocumentationProvider; public CompositeCodeInsightProviderWithWarning(List<CodeInsightProviders> wrappers) { final List<CodeInsightProviders> userSchemaWrappers = ContainerUtil.filter(wrappers, CodeInsightProviders::isUserSchema); // filter for the case when there are one system schema and one (several) user schemas // then do not use provided system schema: user schema will override it (maybe the user updated the version himself) // if there are 2 or more system schemas - just go the common way: it is unclear what happened and why if (!userSchemaWrappers.isEmpty() && ((userSchemaWrappers.size() + 1) == wrappers.size())) { myWrappers = userSchemaWrappers; } else { myWrappers = wrappers; } myContributor = new CompletionContributor() { @Override public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) { for (CodeInsightProviders wrapper : myWrappers) { wrapper.getContributor().fillCompletionVariants(parameters, result); } } }; myAnnotator = new Annotator() { @Override public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { for (CodeInsightProviders wrapper : myWrappers) { wrapper.getAnnotator().annotate(element, holder); } } }; final List<DocumentationProvider> list = new ArrayList<>(); for (CodeInsightProviders wrapper : myWrappers) { list.add(wrapper.getDocumentationProvider()); } myDocumentationProvider = CompositeDocumentationProvider.wrapProviders(list); } @NotNull @Override public CompletionContributor getContributor() { return myContributor; } @NotNull @Override public Annotator getAnnotator() { return myAnnotator; } @NotNull @Override public DocumentationProvider getDocumentationProvider() { return myDocumentationProvider; } @NotNull @Override public String getName() { return "Composite"; } @Override public boolean isUserSchema() { return false;// does not make sense to ask } @Override public boolean iterateSchemaObjects(@NotNull Processor<JsonSchemaObject> consumer) { for (CodeInsightProviders wrapper : myWrappers) { if (!wrapper.iterateSchemaObjects(consumer)) return false; } return true; } @Override public void iterateSchemaFiles(@NotNull PairConsumer<VirtualFile, String> consumer) { for (CodeInsightProviders wrapper : myWrappers) { wrapper.iterateSchemaFiles(consumer); } } } @Override @Nullable public VirtualFile getSchemaFileById(@NotNull String id, @Nullable VirtualFile referent) { final VirtualFile schemaFile = myDefinitions.getSchemaFileById(id, this); if (schemaFile != null) return schemaFile; return getSchemaFileByRefAsLocalFile(id, referent); } @Nullable public static VirtualFile getSchemaFileByRefAsLocalFile(@NotNull String id, @Nullable VirtualFile referent) { final String normalizedId = JsonSchemaExportedDefinitions.normalizeId(id); if (FileUtil.isAbsolute(normalizedId) || referent == null) return VfsUtil.findFileByIoFile(new File(normalizedId), false); VirtualFile dir = referent.isDirectory() ? referent : referent.getParent(); if (dir != null && dir.isValid()) { return VfsUtil.findRelativeFile(dir, normalizedId.replace("\\", "/").split("/")); } return null; } @Override @Nullable public Collection<Pair<VirtualFile, String>> getSchemaFilesByFile(@NotNull final VirtualFile file) { final CodeInsightProviders wrapper = getWrapper(file); if (wrapper != null) { final List<Pair<VirtualFile, String>> result = new ArrayList<>(); wrapper.iterateSchemaFiles((schemaFile, schemaId) -> result.add(Pair.create(schemaFile, schemaId))); return result; } return null; } @Override public Set<VirtualFile> getSchemaFiles() { if (!initialized) { ensureSchemaFiles(); } return Collections.unmodifiableSet(mySchemaFiles); } @Override public void refreshSchemaIds(Set<VirtualFile> toRefresh) { for (VirtualFile refresh : toRefresh) { getWrapperBySchemaFile(refresh); } } }
package org.vosao.dao.cache.impl; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.vosao.common.VosaoContext; import org.vosao.dao.DaoStat; import org.vosao.dao.cache.EntityCache; import org.vosao.dao.cache.QueryCache; import org.vosao.entity.BaseEntity; import org.vosao.global.CacheService; import org.vosao.global.SystemService; import org.vosao.utils.EntityUtil; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; public class QueryCacheImpl implements QueryCache, Serializable { protected static final Log logger = LogFactory.getLog( QueryCacheImpl.class); private static DaoStat getDaoStat() { return VosaoContext.getInstance().getBusiness().getDao().getDaoStat(); } private EntityCache entityCache; public QueryCacheImpl(EntityCache anEntityCache) { entityCache = anEntityCache; } public SystemService getSystemService() { return VosaoContext.getInstance().getBusiness().getSystemService(); } private CacheService getCache() { return getSystemService().getCache(); } private EntityCache getEntityCache() { return entityCache; } private String getQueryKey(Class clazz, String query, Object[] params) { StringBuffer result = new StringBuffer(clazz.getName()); result.append(query); if (params != null) { for (Object param : params) { result.append(param != null ? param.toString() : "null"); } } return result.toString(); } private String getClassResetdateKey(Class clazz) { return "classResetDate:" + clazz.getName(); } private Date getClassResetDate(Class clazz) { return (Date)getCache().get(getClassResetdateKey(clazz)); } @Override public List<BaseEntity> getQuery(Class clazz, String query, Object[] params) { try { CacheItem item = (CacheItem)getCache().get(getQueryKey(clazz, query, params)); if (item != null) { Date globalResetDate = getCache().getResetDate(); if (globalResetDate == null || item.getTimestamp().after(globalResetDate)) { Date classResetDate = getClassResetDate(clazz); if (classResetDate == null || item.getTimestamp().after(classResetDate)) { return getCachedQueryResult(clazz, item); } } } } catch (Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); } return null; } private List<BaseEntity> getCachedQueryResult(Class clazz, CacheItem item) { getDaoStat().incQueryCacheHits(); List<Long> ids = (List<Long>)item.getData(); Map<Long, BaseEntity> cached = getEntityCache().getEntities(clazz, ids); List<Key> toLoadKeys = new ArrayList<Key>(); for (Long id : cached.keySet()) { if (cached.get(id) == null) { toLoadKeys.add(KeyFactory.createKey(EntityUtil.getKind(clazz), id)); } else { getDaoStat().incEntityCacheHits(); } } cached.putAll(loadEntities(clazz, toLoadKeys)); List<BaseEntity> result = new ArrayList<BaseEntity>(); for (Long id : ids) { result.add(cached.get(id)); } return result; } private Map<Long, BaseEntity> loadEntities(Class clazz, List<Key> keys) { try { getDaoStat().incGetCalls(); Map<Key, Entity> loaded = getSystemService().getDatastore().get(keys); Map<Long, BaseEntity> result = new HashMap<Long, BaseEntity>(); for (Key key : loaded.keySet()) { BaseEntity model = (BaseEntity)clazz.newInstance(); model.load(loaded.get(key)); result.put(model.getId(), model); } return result; } catch (Exception e) { e.printStackTrace(); return null; } } @Override public void putQuery(Class clazz, String query, Object[] params, List<BaseEntity> list) { String key = getQueryKey(clazz, query, params); List<Long> ids = new ArrayList<Long>(); for (BaseEntity entity : list) { ids.add(entity.getId()); } getCache().put(key, new CacheItem(ids)); getEntityCache().putEntities(clazz, list); } @Override public void removeQueries(Class clazz) { getCache().put(getClassResetdateKey(clazz), new Date()); } }
/* * @author max */ package com.intellij.psi.stubs; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.io.DataInputOutputUtil; import com.intellij.util.io.PersistentStringEnumerator; import org.jetbrains.annotations.NotNull; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; public class SerializationManagerImpl extends SerializationManager implements ApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.stubs.SerializationManagerImpl"); private final PersistentStringEnumerator myNameStorage; private final Map<Class, StubSerializer> myStubClassToSerializer = new HashMap<Class, StubSerializer>(); private final Map<Integer, StubSerializer> myIdToSerializer = new HashMap<Integer, StubSerializer>(); private final Map<StubSerializer, Integer> mySerializerToId = new HashMap<StubSerializer, Integer>(); public SerializationManagerImpl() { try { myNameStorage = new PersistentStringEnumerator(new File(PathManager.getSystemPath() + "/rep.names")); } catch (IOException e) { throw new RuntimeException(e); } registerSerializer(PsiFileStub.class, new StubSerializer<PsiFileStub>() { public String getExternalId() { return "PsiFile.basic"; } public void serialize(final PsiFileStub stub, final DataOutputStream dataStream, final PersistentStringEnumerator nameStorage) throws IOException { } public PsiFileStub deserialize(final DataInputStream dataStream, final StubElement parentStub, final PersistentStringEnumerator nameStorage) throws IOException { return new PsiFileStubImpl(); } public void indexStub(final PsiFileStub stub, final IndexSink sink) { } }); } public <T extends StubElement> void registerSerializer(Class<T> stubClass, StubSerializer<T> serializer) { try { myStubClassToSerializer.put(stubClass, serializer); final int id = myNameStorage.enumerate(serializer.getExternalId()); myIdToSerializer.put(id, serializer); mySerializerToId.put(serializer, id); } catch (IOException e) { throw new RuntimeException(e); } } public StubSerializer getSerializer(Class<? extends StubElement> stubClass) { for (Map.Entry<Class, StubSerializer> entry : myStubClassToSerializer.entrySet()) { if (entry.getKey().isAssignableFrom(stubClass)) return entry.getValue(); } throw new IllegalStateException("Can't find stub serializer for " + stubClass.getName()); } public void serialize(StubElement rootStub, DataOutputStream stream) { try { final Class<? extends StubElement> stubClass = rootStub.getClass(); final StubSerializer serializer = getSerializer(stubClass); DataInputOutputUtil.writeINT(stream, getClassId(serializer)); serializer.serialize(rootStub, stream, myNameStorage); final List<StubElement> children = rootStub.getChildrenStubs(); DataInputOutputUtil.writeINT(stream, children.size()); for (StubElement child : children) { serialize(child, stream); } } catch (IOException e) { throw new RuntimeException(e); } } public StubElement deserialize(DataInputStream stream) { try { return deserialize(stream, null); } catch (IOException e) { throw new RuntimeException(e); } } private StubElement deserialize(DataInputStream stream, StubElement parentStub) throws IOException { final StubSerializer serializer = getClassById(DataInputOutputUtil.readINT(stream)); StubElement stub = serializer.deserialize(stream, parentStub, myNameStorage); int childCount = DataInputOutputUtil.readINT(stream); for (int i = 0; i < childCount; i++) { deserialize(stream, stub); } return stub; } private int getClassId(final StubSerializer serializer) { return mySerializerToId.get(serializer).intValue(); } private StubSerializer getClassById(int id) { return myIdToSerializer.get(id); } @NotNull public String getComponentName() { return "PSI.SerializationManager"; } public void initComponent() { } public void disposeComponent() { try { myNameStorage.close(); } catch (IOException e) { LOG.error(e); } } }
package com.google.sps.servlets; import com.google.gson.Gson; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.*; import java.io.PrintWriter; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.net.URLEncoder; import java.net.URLDecoder; import java.io.*; import java.util.*; @WebServlet("/topics") public class TopicServlet extends HttpServlet{ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String userId = user.getUserId(); Query query = new Query("UserInfo") .setFilter(new Query.FilterPredicate("id", Query.FilterOperator.EQUAL, userId)); PreparedQuery results = datastore.prepare(query); Entity entity = results.asSingleEntity(); String topics = (String) entity.getProperty("topics"); System.out.println(topics); if (topics.equals("")){ response.getWriter().println("{}"); return; } while (topics.length() > 0 && topics.substring(0,1).equals(",")){ try{ if (topics.length() > 1){ topics = topics.substring(1); } else{ topics = ""; entity.setProperty("topics", topics); datastore.put(entity); response.getWriter().println("{}"); return; } } catch (Exception e){ topics = ""; entity.setProperty("topics", topics); datastore.put(entity); response.getWriter().println("{}"); return; } } //topics += "," + (String) entity.getProperty("time"); String [] listedTopics = topics.split(","); System.out.println(Arrays.toString(listedTopics)); Gson gson = new Gson(); String returnTopics = gson.toJson(listedTopics); response.setContentType("application/json;"); response.getWriter().println(returnTopics); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String userId = user.getUserId(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query query = new Query("UserInfo") .setFilter(new Query.FilterPredicate("id", Query.FilterOperator.EQUAL, userId)); PreparedQuery results = datastore.prepare(query); Entity entity = results.asSingleEntity(); if (entity == null){ response.sendRedirect("/search.html"); } String currentUrl = (String) entity.getProperty("currentUrl"); String topic = request.getParameter("topic"); String topics = (String) entity.getProperty("topics"); ArrayList<String> urls = (ArrayList<String>) entity.getProperty("urls"); if(currentUrl == null) { currentUrl = "0"; } if (topics.equals("")){ entity.setProperty("topics", topic); } else { topics += ","; topics += topic; entity.setProperty("topics", topics); } if(urls == null) { urls = new ArrayList<>(); } String[] values = topics.split(","); urls = getSearch(topic, urls); System.out.println(urls); getInfo(urls, currentUrl); currentUrl = Integer.toString(Integer.parseInt(currentUrl)+1); entity.setProperty("currentUrl", currentUrl); entity.setProperty("urls", urls); datastore.put(entity); response.sendRedirect("/search.html"); } private ArrayList<String> getSearch(String topic, ArrayList<String> urls) throws IOException { String google = "https: int num = 5; String searchURL = google + "?q=" + topic + "&num=" + num; Document doc = Jsoup.connect(searchURL).userAgent("Chrome").get(); Elements results = doc.select("a[href]:has(span)").select("a[href]:not(:has(div))"); for (Element result : results) { String linkHref = result.attr("href"); String linkText = result.text(); if (linkHref.contains("https")) { urls.add(linkHref.substring(7, linkHref.indexOf("&"))); } } return urls; } private void getInfo(ArrayList<String> urls, String currentUrl) throws IOException { int currentUrlNum = Integer.parseInt(currentUrl); String url = urls.get(currentUrlNum); Document doc = Jsoup.connect(url).get(); Elements results = doc.select("p"); for(Element result : results) { System.out.println(result); } } }
package com.intellij.diagnostic; import com.intellij.CommonBundle; import com.intellij.errorreport.ErrorReportSender; import com.intellij.errorreport.bean.ErrorBean; import com.intellij.errorreport.bean.NotifierBean; import com.intellij.errorreport.error.InternalEAPException; import com.intellij.errorreport.error.NewBuildException; import com.intellij.errorreport.error.NoSuchEAPUserException; import com.intellij.errorreport.error.ThreadClosedException; import com.intellij.ide.BrowserUtil; import com.intellij.ide.DataManager; import com.intellij.idea.IdeaLogger; import com.intellij.openapi.diagnostic.ErrorReportSubmitter; import com.intellij.openapi.diagnostic.IdeaLoggingEvent; import com.intellij.openapi.diagnostic.SubmittedReportInfo; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.DataConstants; import com.intellij.openapi.project.Project; import com.intellij.util.net.IOExceptionDialog; import org.jetbrains.annotations.NonNls; import java.awt.Component; import java.io.IOException; public class ITNReporter extends ErrorReportSubmitter { private static int previousExceptionThreadId = 0; private static boolean wasException = false; @NonNls private static final String URL_HEADER = "http: public String getReportActionText() { return DiagnosticBundle.message("error.report.to.jetbrains.action"); } public SubmittedReportInfo submit(IdeaLoggingEvent[] events, Component parentComponent) { return sendError(events[0], parentComponent); } /** * @noinspection ThrowablePrintStackTrace */ private static SubmittedReportInfo sendError(IdeaLoggingEvent event, Component parentComponent) { NotifierBean notifierBean = new NotifierBean(); ErrorBean errorBean = new ErrorBean(); errorBean.autoInit(); errorBean.setLastAction(IdeaLogger.ourLastActionId); int threadId = 0; SubmittedReportInfo.SubmissionStatus submissionStatus = SubmittedReportInfo.SubmissionStatus.FAILED; final DataContext dataContext = DataManager.getInstance().getDataContext(parentComponent); Project project = (Project) dataContext.getData(DataConstants.PROJECT); String description = ""; do { // prepare try { ErrorReportSender sender = ErrorReportSender.getInstance(); sender.prepareError(project, event.getThrowable()); EAPSendErrorDialog dlg = new EAPSendErrorDialog(); dlg.setErrorDescription(description); dlg.show(); @NonNls String itnLogin = ErrorReportConfigurable.getInstance().ITN_LOGIN; @NonNls String itnPassword = ErrorReportConfigurable.getInstance().getPlainItnPassword(); if (itnLogin.trim().length() == 0 && itnPassword.trim().length() == 0) { itnLogin = "idea_anonymous"; itnPassword = "guest"; } notifierBean.setItnLogin(itnLogin); notifierBean.setItnPassword(itnPassword); description = dlg.getErrorDescription(); String message = event.getMessage(); @NonNls StringBuilder descBuilder = new StringBuilder(); if (description.length() > 0) { descBuilder.append("User description: ").append(description).append("\n"); } if (message != null) { descBuilder.append("Error message: ").append(message).append("\n"); } if (previousExceptionThreadId != 0) { descBuilder.append("Previous exception is: ").append(URL_HEADER).append(previousExceptionThreadId).append("\n"); } if (wasException) { descBuilder.append("There was at least one exception before this one.\n"); } errorBean.setDescription(descBuilder.toString()); if (dlg.isShouldSend()) { threadId = sender.sendError(notifierBean, errorBean); previousExceptionThreadId = threadId; wasException = true; submissionStatus = SubmittedReportInfo.SubmissionStatus.NEW_ISSUE; Messages.showInfoMessage(parentComponent, DiagnosticBundle.message("error.report.confirmation"), ReportMessages.ERROR_REPORT); break; } else { break; } } catch (NoSuchEAPUserException e) { if (Messages.showYesNoDialog(parentComponent, DiagnosticBundle.message("error.report.authentication.failed"), ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != 0) { break; } } catch (InternalEAPException e) { if (Messages.showYesNoDialog(parentComponent, DiagnosticBundle.message("error.report.posting.failed", e.getMessage()), ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != 0) { break; } } catch (IOException e) { if (!IOExceptionDialog.showErrorDialog(e, DiagnosticBundle.message("error.report.exception.title"), DiagnosticBundle.message("error.report.failure.message"))) { break; } } catch (NewBuildException e) { Messages.showMessageDialog(parentComponent, DiagnosticBundle.message("error.report.new.eap.build.message", e.getMessage()), CommonBundle.getWarningTitle(), Messages.getWarningIcon()); break; } catch (ThreadClosedException e) { submissionStatus = SubmittedReportInfo.SubmissionStatus.DUPLICATE; threadId = e.getThreadId(); if (Messages.showYesNoDialog(parentComponent, DiagnosticBundle.message("error.report.already.closed.message", e.getMessage()), ReportMessages.ERROR_REPORT, Messages.getQuestionIcon()) == 0) { try { BrowserUtil.launchBrowser(URL_HEADER + threadId); } catch (IllegalThreadStateException ex) { // it's OK // browser is not exited } } break; } catch (Exception e) { if (Messages.showYesNoDialog(parentComponent, DiagnosticBundle.message("error.report.sending.failure"), ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != 0) { break; } } } while (true); return new SubmittedReportInfo(submissionStatus != SubmittedReportInfo.SubmissionStatus.FAILED ? URL_HEADER + threadId : null, String.valueOf(threadId), submissionStatus); } }
package com.unnamed.b.atv.view; import android.content.Context; import android.text.TextUtils; import android.view.ContextThemeWrapper; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.Transformation; import android.widget.LinearLayout; import android.widget.ScrollView; import com.unnamed.b.atv.R; import com.unnamed.b.atv.holder.SimpleViewHolder; import com.unnamed.b.atv.model.TreeNode; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class AndroidTreeView { private static final String NODES_PATH_SEPARATOR = ";"; private TreeNode mRoot; private Context mContext; private boolean applyForRoot; private int containerStyle = 0; private Class<? extends TreeNode.BaseNodeViewHolder> defaultViewHolderClass = SimpleViewHolder.class; private TreeNode.TreeNodeClickListener nodeClickListener; private TreeNode.TreeNodeLongClickListener nodeLongClickListener; private boolean mSelectionModeEnabled; private boolean mUseDefaultAnimation = false; private boolean use2dScroll = false; public AndroidTreeView(Context context, TreeNode root) { mRoot = root; mContext = context; } public void setDefaultAnimation(boolean defaultAnimation) { this.mUseDefaultAnimation = defaultAnimation; } public void setDefaultContainerStyle(int style) { setDefaultContainerStyle(style, false); } public void setDefaultContainerStyle(int style, boolean applyForRoot) { containerStyle = style; this.applyForRoot = applyForRoot; } public void setUse2dScroll(boolean use2dScroll) { this.use2dScroll = use2dScroll; } public boolean is2dScrollEnabled() { return use2dScroll; } public void setDefaultViewHolder(Class<? extends TreeNode.BaseNodeViewHolder> viewHolder) { defaultViewHolderClass = viewHolder; } public void setDefaultNodeClickListener(TreeNode.TreeNodeClickListener listener) { nodeClickListener = listener; } public void setDefaultNodeLongClickListener(TreeNode.TreeNodeLongClickListener listener) { nodeLongClickListener = listener; } public void expandAll() { expandNode(mRoot, true); } public void collapseAll() { for (TreeNode n : mRoot.getChildren()) { collapseNode(n, true); } } public View getView(int style) { final ViewGroup view; if (style > 0) { ContextThemeWrapper newContext = new ContextThemeWrapper(mContext, style); view = use2dScroll ? new TwoDScrollView(newContext) : new ScrollView(newContext); } else { view = use2dScroll ? new TwoDScrollView(mContext) : new ScrollView(mContext); } Context containerContext = mContext; if (containerStyle != 0 && applyForRoot) { containerContext = new ContextThemeWrapper(mContext, containerStyle); } final LinearLayout viewTreeItems = new LinearLayout(containerContext, null, containerStyle); viewTreeItems.setId(R.id.tree_items); viewTreeItems.setOrientation(LinearLayout.VERTICAL); view.addView(viewTreeItems); mRoot.setViewHolder(new TreeNode.BaseNodeViewHolder(mContext) { @Override public View createNodeView(TreeNode node, Object value) { return null; } @Override public ViewGroup getNodeItemsView() { return viewTreeItems; } }); expandNode(mRoot, false); return view; } public View getView() { return getView(-1); } public void expandLevel(int level) { for (TreeNode n : mRoot.getChildren()) { expandLevel(n, level); } } private void expandLevel(TreeNode node, int level) { if (node.getLevel() <= level) { expandNode(node, false); } for (TreeNode n : node.getChildren()) { expandLevel(n, level); } } public void expandNode(TreeNode node) { expandNode(node, false); } public void collapseNode(TreeNode node) { collapseNode(node, false); } public String getSaveState() { final StringBuilder builder = new StringBuilder(); getSaveState(mRoot, builder); if (builder.length() > 0) { builder.setLength(builder.length() - 1); } return builder.toString(); } public void restoreState(String saveState) { if (!TextUtils.isEmpty(saveState)) { collapseAll(); final String[] openNodesArray = saveState.split(NODES_PATH_SEPARATOR); final Set<String> openNodes = new HashSet<>(Arrays.asList(openNodesArray)); restoreNodeState(mRoot, openNodes); } } private void restoreNodeState(TreeNode node, Set<String> openNodes) { for (TreeNode n : node.getChildren()) { if (openNodes.contains(n.getPath())) { expandNode(n); restoreNodeState(n, openNodes); } } } private void getSaveState(TreeNode root, StringBuilder sBuilder) { for (TreeNode node : root.getChildren()) { if (node.isExpanded()) { sBuilder.append(node.getPath()); sBuilder.append(NODES_PATH_SEPARATOR); getSaveState(node, sBuilder); } } } private void toggleNode(TreeNode node) { if (node.isExpanded()) { collapseNode(node, false); } else { expandNode(node, false); } } private void collapseNode(TreeNode node, final boolean includeSubnodes) { node.setExpanded(false); TreeNode.BaseNodeViewHolder nodeViewHolder = getViewHolderForNode(node); if (mUseDefaultAnimation) { collapse(nodeViewHolder.getNodeItemsView()); } else { nodeViewHolder.getNodeItemsView().setVisibility(View.GONE); } nodeViewHolder.toggle(false); if (includeSubnodes) { for (TreeNode n : node.getChildren()) { collapseNode(n, includeSubnodes); } } } private void expandNode(final TreeNode node, boolean includeSubnodes) { node.setExpanded(true); final TreeNode.BaseNodeViewHolder parentViewHolder = getViewHolderForNode(node); parentViewHolder.getNodeItemsView().removeAllViews(); parentViewHolder.toggle(true); for (final TreeNode n : node.getChildren()) { addNode(parentViewHolder.getNodeItemsView(), n); if (n.isExpanded() || includeSubnodes) { expandNode(n, includeSubnodes); } } if (mUseDefaultAnimation) { expand(parentViewHolder.getNodeItemsView()); } else { parentViewHolder.getNodeItemsView().setVisibility(View.VISIBLE); } } private void addNode(ViewGroup container, final TreeNode n) { final TreeNode.BaseNodeViewHolder viewHolder = getViewHolderForNode(n); final View nodeView = viewHolder.getView(); container.addView(nodeView); if (mSelectionModeEnabled) { viewHolder.toggleSelectionMode(mSelectionModeEnabled); } nodeView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (n.getClickListener() != null) { n.getClickListener().onClick(n, n.getValue()); } else if (nodeClickListener != null) { nodeClickListener.onClick(n, n.getValue()); } toggleNode(n); } }); nodeView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { if (n.getLongClickListener() != null) { return n.getLongClickListener().onLongClick(n, n.getValue()); } else if (nodeLongClickListener != null) { return nodeLongClickListener.onLongClick(n, n.getValue()); } return false; } }); } // Selection methods public void setSelectionModeEnabled(boolean selectionModeEnabled) { if (!selectionModeEnabled) { // TODO fix double iteration over tree deselectAll(); } mSelectionModeEnabled = selectionModeEnabled; for (TreeNode node : mRoot.getChildren()) { toggleSelectionMode(node, selectionModeEnabled); } } public <E> List<E> getSelectedValues(Class<E> clazz) { List<E> result = new ArrayList<>(); List<TreeNode> selected = getSelected(); for (TreeNode n : selected) { Object value = n.getValue(); if (value != null && value.getClass().equals(clazz)) { result.add((E) value); } } return result; } public boolean isSelectionModeEnabled() { return mSelectionModeEnabled; } private void toggleSelectionMode(TreeNode parent, boolean mSelectionModeEnabled) { toogleSelectionForNode(parent, mSelectionModeEnabled); if (parent.isExpanded()) { for (TreeNode node : parent.getChildren()) { toggleSelectionMode(node, mSelectionModeEnabled); } } } public List<TreeNode> getSelected() { if (mSelectionModeEnabled) { return getSelected(mRoot); } else { return new ArrayList<>(); } } // TODO Do we need to go through whole tree? Save references or consider collapsed nodes as not selected private List<TreeNode> getSelected(TreeNode parent) { List<TreeNode> result = new ArrayList<>(); for (TreeNode n : parent.getChildren()) { if (n.isSelected()) { result.add(n); } result.addAll(getSelected(n)); } return result; } public void selectAll(boolean skipCollapsed) { makeAllSelection(true, skipCollapsed); } public void deselectAll() { makeAllSelection(false, false); } private void makeAllSelection(boolean selected, boolean skipCollapsed) { if (mSelectionModeEnabled) { for (TreeNode node : mRoot.getChildren()) { selectNode(node, selected, skipCollapsed); } } } public void selectNode(TreeNode node, boolean selected) { if (mSelectionModeEnabled) { node.setSelected(selected); toogleSelectionForNode(node, true); } } private void selectNode(TreeNode parent, boolean selected, boolean skipCollapsed) { parent.setSelected(selected); toogleSelectionForNode(parent, true); boolean toContinue = skipCollapsed ? parent.isExpanded() : true; if (toContinue) { for (TreeNode node : parent.getChildren()) { selectNode(node, selected, skipCollapsed); } } } private void toogleSelectionForNode(TreeNode node, boolean makeSelectable) { TreeNode.BaseNodeViewHolder holder = getViewHolderForNode(node); if (holder.isInitialized()) { getViewHolderForNode(node).toggleSelectionMode(makeSelectable); } } private TreeNode.BaseNodeViewHolder getViewHolderForNode(TreeNode node) { TreeNode.BaseNodeViewHolder viewHolder = node.getViewHolder(); if (viewHolder == null) { try { final Object object = defaultViewHolderClass.getConstructor(Context.class).newInstance(new Object[]{mContext}); viewHolder = (TreeNode.BaseNodeViewHolder) object; node.setViewHolder(viewHolder); } catch (Exception e) { throw new RuntimeException("Could not instantiate class " + defaultViewHolderClass); } } if (viewHolder.getContainerStyle() <= 0) { viewHolder.setContainerStyle(containerStyle); } if (viewHolder.getTreeView() == null) { viewHolder.setTreeViev(this); } return viewHolder; } private static void expand(final View v) { v.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); final int targetHeight = v.getMeasuredHeight(); v.getLayoutParams().height = 0; v.setVisibility(View.VISIBLE); Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { v.getLayoutParams().height = interpolatedTime == 1 ? LinearLayout.LayoutParams.WRAP_CONTENT : (int) (targetHeight * interpolatedTime); v.requestLayout(); } @Override public boolean willChangeBounds() { return true; } }; // 1dp/ms a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density)); v.startAnimation(a); } private static void collapse(final View v) { final int initialHeight = v.getMeasuredHeight(); Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if (interpolatedTime == 1) { v.setVisibility(View.GONE); } else { v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime); v.requestLayout(); } } @Override public boolean willChangeBounds() { return true; } }; // 1dp/ms a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density)); v.startAnimation(a); } //Add / Remove public void addNode(TreeNode parent, final TreeNode nodeToAdd) { parent.addChild(nodeToAdd); if (parent.isExpanded()) { final TreeNode.BaseNodeViewHolder parentViewHolder = getViewHolderForNode(parent); addNode(parentViewHolder.getNodeItemsView(), nodeToAdd); } } public void removeNode(TreeNode node) { if (node.getParent() != null) { TreeNode parent = node.getParent(); int index = parent.deleteChild(node); if (parent.isExpanded() && index >= 0) { final TreeNode.BaseNodeViewHolder parentViewHolder = getViewHolderForNode(parent); parentViewHolder.getNodeItemsView().removeViewAt(index); } } } }
package io.jasonsparc.chemistry; import android.support.annotation.AnyRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.ViewGroup; import java.util.ArrayList; import io.jasonsparc.chemistry.util.IdSelectors; import io.jasonsparc.chemistry.util.ItemBinders; import io.jasonsparc.chemistry.util.VhFactories; import io.jasonsparc.chemistry.util.VhInitializers; import io.jasonsparc.chemistry.util.ViewTypes; public abstract class BasicChemistry<Item, VH extends ViewHolder> extends Chemistry<Item> implements VhFactory<VH>, ItemBinder<Item, VH> { @Override public final int getItemViewType(Item item) { return getViewType(); } @Override public final VhFactory<? extends VH> getVhFactory(Item item) { return this; } @Override public final ItemBinder<? super Item, ? super VH> getItemBinder(Item item) { return this; } @ViewType @AnyRes public abstract int getViewType(); @Override public abstract VH createViewHolder(ViewGroup parent); @Override public abstract void bindViewHolder(VH holder, Item item); // Utilities public <RI extends Item> Boiler<RI, VH> boiler() { return make(this); } public <RI extends Item> Boiler<RI, VH> boiler(@ViewType @AnyRes int viewType) { return this.<RI>boiler().useViewType(viewType); } // Boiler-delegating methods public interface Transformer<Item, VH extends ViewHolder> { void apply(Boiler<Item, VH> boiler); } public final Boiler<Item, VH> compose(@NonNull Transformer<? super Item, VH> transformer) { return boiler().compose(transformer); } public final Boiler<Item, VH> useItemIds(@NonNull IdSelector<? super Item> idSelector) { return boiler().useItemIds(idSelector); } public final Boiler<Item, VH> useViewType(@ViewType @AnyRes int viewType) { return boiler().useViewType(viewType); } public final Boiler<Item, VH> useUniqueViewType() { return boiler().useUniqueViewType(); } public final Boiler<Item, VH> useVhFactory(@NonNull VhFactory<? extends VH> vhFactory) { return boiler().useVhFactory(vhFactory); } public final Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return boiler().useVhFactory(viewFactory, itemVhFactory); } public final Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull Class<? extends VH> vhClass) { return boiler().useVhFactory(viewFactory, vhClass); } public final Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return boiler().useVhFactory(itemLayout, itemVhFactory); } public final Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull Class<? extends VH> vhClass) { return boiler().useVhFactory(itemLayout, vhClass); } public final Boiler<Item, VH> addInit(@NonNull VhInitializer<? super VH> vhInitializer) { return boiler().addInit(vhInitializer); } public final Boiler<Item, VH> addBinder(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { return boiler().addBinder(itemBinder); } public final Boiler<Item, VH> add(@NonNull VhInitializer<? super VH> vhInitializer) { return boiler().add(vhInitializer); } public final Boiler<Item, VH> add(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { return boiler().add(itemBinder); } // Boiler implementation public static class Boiler<Item, VH extends ViewHolder> { @Nullable IdSelector<? super Item> idSelector; @ViewType @AnyRes int viewType; @Nullable VhFactory<? extends VH> vhFactory; final ArrayList<VhInitializer<? super VH>> vhInitializers = new ArrayList<>(4); final ArrayList<ItemBinder<? super Item, ? super VH>> itemBinders = new ArrayList<>(4); protected Boiler() { } protected Boiler(Preperator<? super Item> preperator) { this.idSelector = preperator.idSelector; this.viewType = preperator.viewType; } protected Boiler(@NonNull BasicChemistry<? super Item, VH> base) { if (base instanceof CompositeImpl<?, ?>) { @SuppressWarnings("unchecked") CompositeImpl<? super Item, VH> composite = (CompositeImpl) base; viewType = composite.viewType; vhFactory = composite.vhFactory; itemBinders.add(composite.itemBinder); } else { viewType = base.getViewType(); vhFactory = base; itemBinders.add(base); } } public BasicChemistry<Item, VH> boil() { return new CompositeImpl<>(this); } @SuppressWarnings("unchecked") public Boiler<Item, VH> compose(@NonNull Transformer<? super Item, VH> transformer) { ((Transformer<Item, VH>) transformer).apply(this); return this; } public Boiler<Item, VH> useItemIds(@NonNull IdSelector<? super Item> idSelector) { this.idSelector = idSelector; return this; } public Boiler<Item, VH> useViewType(@ViewType @AnyRes int viewType) { ViewTypes.validateArgument(viewType); this.viewType = viewType; return this; } public Boiler<Item, VH> useUniqueViewType() { //noinspection Range this.viewType = 0; // Defer id generation. See CompositeImpl below... return this; } public Boiler<Item, VH> useVhFactory(@NonNull VhFactory<? extends VH> vhFactory) { this.vhFactory = vhFactory; return this; } public Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return useVhFactory(VhFactories.make(viewFactory, itemVhFactory)); } public Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull Class<? extends VH> vhClass) { return useVhFactory(VhFactories.make(viewFactory, vhClass)); } public Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return useVhFactory(VhFactories.make(itemLayout, itemVhFactory)); } public Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull Class<? extends VH> vhClass) { return useVhFactory(VhFactories.make(itemLayout, vhClass)); } public Boiler<Item, VH> addInit(@NonNull VhInitializer<? super VH> vhInitializer) { return add(vhInitializer); } public Boiler<Item, VH> addBinder(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { return add(itemBinder); } public Boiler<Item, VH> add(@NonNull VhInitializer<? super VH> vhInitializer) { vhInitializers.add(vhInitializer); return this; } public Boiler<Item, VH> add(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { itemBinders.add(itemBinder); return this; } public Boiler<Item, VH> removeInit(@NonNull VhInitializer<? super VH> vhInitializer) { return remove(vhInitializer); } public Boiler<Item, VH> removeBinder(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { return remove(itemBinder); } public Boiler<Item, VH> remove(@NonNull VhInitializer<? super VH> vhInitializer) { vhInitializers.remove(vhInitializer); return this; } public Boiler<Item, VH> remove(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { itemBinders.remove(itemBinder); return this; } } // Preperator implementation public static class Preperator<Item> { @Nullable IdSelector<? super Item> idSelector; @ViewType @AnyRes int viewType; protected Preperator() { } public Preperator<Item> useItemIds(@NonNull IdSelector<? super Item> idSelector) { this.idSelector = idSelector; return this; } public Preperator<Item> useViewType(@ViewType @AnyRes int viewType) { ViewTypes.validateArgument(viewType); this.viewType = viewType; return this; } public Preperator<Item> useUniqueViewType() { //noinspection Range this.viewType = 0; // Defer id generation. See CompositeImpl below... return this; } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@NonNull VhFactory<? extends VH> vhFactory) { return this.<VH>makeBoiler().useVhFactory(vhFactory); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return this.<VH>makeBoiler().useVhFactory(VhFactories.make(viewFactory, itemVhFactory)); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull Class<? extends VH> vhClass) { return this.<VH>makeBoiler().useVhFactory(VhFactories.make(viewFactory, vhClass)); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return this.<VH>makeBoiler().useVhFactory(VhFactories.make(itemLayout, itemVhFactory)); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull Class<? extends VH> vhClass) { return this.<VH>makeBoiler().useVhFactory(VhFactories.make(itemLayout, vhClass)); } public <VH extends ViewHolder> Boiler<Item, VH> compose(@NonNull Transformer<? super Item, VH> transformer) { return this.<VH>makeBoiler().compose(transformer); } public <VH extends ViewHolder> Boiler<Item, VH> makeBoiler() { return new Boiler<>(this); } } // Internals static final class CompositeImpl<Item, VH extends ViewHolder> extends BasicChemistry<Item, VH> { @NonNull final IdSelector<? super Item> idSelector; @ViewType @AnyRes final int viewType; @NonNull final VhFactory<? extends VH> vhFactory; @NonNull final ItemBinder<? super Item, ? super VH> itemBinder; CompositeImpl(@NonNull BasicChemistry.Boiler<Item, VH> boiler) { // Must perform a special null-check for vhFactory, in case the user forgot to set it. if (boiler.vhFactory == null) throw new NullPointerException("vhFactory == null; forgot to set it?"); this.vhFactory = VhFactories.make(boiler.vhFactory, VhInitializers.make(boiler.vhInitializers)); this.itemBinder = ItemBinders.make(boiler.itemBinders); this.idSelector = IdSelectors.ensureNoNull(boiler.idSelector); int viewType = boiler.viewType; if (viewType == 0) viewType = ViewTypes.generate(); this.viewType = viewType; } @Override public long getItemId(Item item) { return idSelector.getItemId(item); } @Override public int getViewType() { return viewType; } @Override public VH createViewHolder(ViewGroup parent) { return vhFactory.createViewHolder(parent); } @Override public void bindViewHolder(VH holder, Item item) { itemBinder.bindViewHolder(holder, item); } } }
package org.libreplan.web.common; import static org.libreplan.web.I18nHelper._; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.libreplan.business.common.Configuration; import org.libreplan.business.common.IOnTransaction; import org.libreplan.business.common.Registry; import org.zkoss.ganttz.util.ComponentsFinder; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.event.InputEvent; import org.zkoss.zkplus.databind.AnnotateDataBinder; import org.zkoss.zkplus.databind.DataBinder; import org.zkoss.zul.Bandbox; import org.zkoss.zul.Button; import org.zkoss.zul.Combobox; import org.zkoss.zul.Comboitem; import org.zkoss.zul.Datebox; import org.zkoss.zul.Decimalbox; import org.zkoss.zul.Intbox; import org.zkoss.zul.Radio; import org.zkoss.zul.Textbox; import org.zkoss.zul.Timebox; import org.zkoss.zul.api.Checkbox; import org.zkoss.zul.api.Column; public class Util { private static final Log LOG = LogFactory.getLog(Util.class); /** * Special chars from {@link DecimalFormat} class. */ private static final String[] DECIMAL_FORMAT_SPECIAL_CHARS = { "0", ",", ".", "\u2030", "%", " private Util() { } public static void reloadBindings(Component... toReload) { for (Component reload : toReload) { DataBinder binder = Util.getBinder(reload); if (binder != null) { binder.loadComponent(reload); } } } public static void saveBindings(Component... toReload) { for (Component reload : toReload) { DataBinder binder = Util.getBinder(reload); if (binder != null) { binder.saveComponent(reload); } } } public static DataBinder getBinder(Component component) { return (DataBinder) component.getVariable("binder", false); } @SuppressWarnings("unchecked") public static void createBindingsFor(org.zkoss.zk.ui.Component result) { List<org.zkoss.zk.ui.Component> children = new ArrayList<org.zkoss.zk.ui.Component>( result.getChildren()); for (org.zkoss.zk.ui.Component child : children) { createBindingsFor(child); } setBinderFor(result); } private static void setBinderFor(org.zkoss.zk.ui.Component result) { AnnotateDataBinder binder = new AnnotateDataBinder(result, true); result.setVariable("binder", binder, true); binder.loadAll(); } /** * Generic interface to represent a class with a typical get method. * @author Manuel Rego Casasnovas <mrego@igalia.com> * @param <T> * The type of the variable to be returned. */ public static interface Getter<T> { /** * Typical get method that returns a variable. * @return A variable of type <T>. */ public T get(); } /** * Generic interface to represent a class with a typical set method. * @author Manuel Rego Casasnovas <mrego@igalia.com> * @param <T> * The type of the variable to be set. */ public static interface Setter<T> { /** * Typical set method to store a variable. * @param value * A variable of type <T> to be set. */ public void set(T value); } /** * Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Textbox}. * @param textBox * The {@link Textbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @return The {@link Textbox} bound */ public static Textbox bind(Textbox textBox, Getter<String> getter) { textBox.setValue(getter.get()); textBox.setDisabled(true); return textBox; } /** * Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Textbox}. * The {@link Setter} will be used to store the value inserted by the user * in the {@link Textbox}. * @param textBox * The {@link Textbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. * @return The {@link Textbox} bound */ public static Textbox bind(final Textbox textBox, final Getter<String> getter, final Setter<String> setter) { textBox.setValue(getter.get()); textBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { InputEvent newInput = (InputEvent) event; String value = newInput.getValue(); setter.set(value); textBox.setValue(getter.get()); } }); return textBox; } /** * Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Textbox}. * @param textBox * The {@link Textbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @return The {@link Textbox} bound */ public static Combobox bind(Combobox comboBox, Getter<Comboitem> getter) { comboBox.setSelectedItem(getter.get()); comboBox.setDisabled(true); return comboBox; } /** * Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Textbox}. * The {@link Setter} will be used to store the value inserted by the user * in the {@link Textbox}. * @param textBox * The {@link Textbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. * @return The {@link Textbox} bound */ public static Combobox bind(final Combobox comboBox, final Getter<Comboitem> getter, final Setter<Comboitem> setter) { comboBox.setSelectedItem(getter.get()); comboBox.addEventListener("onSelect", new EventListener() { @Override public void onEvent(Event event) { setter.set(comboBox.getSelectedItem()); comboBox.setSelectedItem(getter.get()); } }); return comboBox; } /** * Binds a {@link Intbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Intbox}. * @param intBox * The {@link Intbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @return The {@link Intbox} bound */ public static Intbox bind(Intbox intBox, Getter<Integer> getter) { intBox.setValue(getter.get()); intBox.setDisabled(true); return intBox; } /** * Binds a {@link Intbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Intbox}. * The {@link Setter} will be used to store the value inserted by the user * in the {@link Intbox}. * @param intBox * The {@link Intbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. * @return The {@link Intbox} bound */ public static Intbox bind(final Intbox intBox, final Getter<Integer> getter, final Setter<Integer> setter) { intBox.setValue(getter.get()); intBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { InputEvent newInput = (InputEvent) event; String value = newInput.getValue().trim(); if (value.isEmpty()) { value = "0"; } setter.set(Integer.valueOf(value)); intBox.setValue(getter.get()); } }); return intBox; } /** * Binds a {@link Datebox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Datebox}. * @param dateBox * The {@link Datebox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @return The {@link Datebox} bound */ public static Datebox bind(final Datebox dateBox, final Getter<Date> getter) { dateBox.setValue(getter.get()); dateBox.setDisabled(true); return dateBox; } /** * Binds a {@link Datebox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Datebox}. * The {@link Setter} will be used to store the value inserted by the user * in the {@link Datebox}. * @param dateBox * The {@link Datebox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. * @return The {@link Datebox} bound */ public static Datebox bind(final Datebox dateBox, final Getter<Date> getter, final Setter<Date> setter) { dateBox.setValue(getter.get()); dateBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { setter.set(dateBox.getValue()); dateBox.setValue(getter.get()); } }); return dateBox; } /** * Binds a {@link Timebox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Timebox}. * @param dateBox * The {@link Timebox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @return The {@link Timebox} bound */ public static Timebox bind(final Timebox timeBox, final Getter<Date> getter) { timeBox.setValue(getter.get()); timeBox.setDisabled(true); return timeBox; } /** * Binds a {@link Timebox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Timebox}. * The {@link Setter} will be used to store the value inserted by the user * in the {@link Timebox}. * @param timeBox * The {@link Timebox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. * @return The {@link Timebox} bound */ public static Timebox bind(final Timebox timeBox, final Getter<Date> getter, final Setter<Date> setter) { timeBox.setValue(getter.get()); timeBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { setter.set(timeBox.getValue()); timeBox.setValue(getter.get()); } }); return timeBox; } /** * Binds a {@link Decimalbox} with a {@link Getter}. The {@link Getter} will * be used to get the value that is going to be showed in the * {@link Decimalbox}. * @param decimalBox * The {@link Decimalbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @return The {@link Decimalbox} bound */ public static Decimalbox bind(final Decimalbox decimalBox, final Getter<BigDecimal> getter) { decimalBox.setValue(getter.get()); decimalBox.setDisabled(true); return decimalBox; } /** * Binds a {@link Decimalbox} with a {@link Getter}. The {@link Getter} will * be used to get the value that is going to be showed in the * {@link Decimalbox}. The {@link Setter} will be used to store the value * inserted by the user in the {@link Decimalbox}. * @param decimalBox * The {@link Decimalbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. * @return The {@link Decimalbox} bound */ public static Decimalbox bind(final Decimalbox decimalBox, final Getter<BigDecimal> getter, final Setter<BigDecimal> setter) { decimalBox.setValue(getter.get()); decimalBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { setter.set(decimalBox.getValue()); decimalBox.setValue(getter.get()); } }); return decimalBox; } /** * Binds a {@link Checkbox} with a {@link Getter}. The {@link Getter} will * be used to get the value that is going to be showed in the * {@link Checkbox}. * @param decimalBox * The {@link Checkbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @return The {@link Checkbox} bound */ public static Checkbox bind(final Checkbox checkBox, final Getter<Boolean> getter) { checkBox.setChecked(getter.get()); checkBox.setDisabled(true); return checkBox; } /** * Binds a {@link Checkbox} with a {@link Getter}. The {@link Getter} will * be used to get the value that is going to be showed in the * {@link Checkbox}. The {@link Setter} will be used to store the value * inserted by the user in the {@link Checkbox}. * @param decimalBox * @param getter * The {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. * @return The {@link Checkbox} bound */ public static <C extends Checkbox> C bind(final C checkBox, final Getter<Boolean> getter, final Setter<Boolean> setter) { checkBox.setChecked(getter.get()); checkBox.addEventListener(Events.ON_CHECK, new EventListener() { @Override public void onEvent(Event event) { setter.set(checkBox.isChecked()); checkBox.setChecked(getter.get()); } }); return checkBox; } /** * Binds a {@link Checkbox} with a {@link Getter}. The {@link Getter} will * be used to get the value that is going to be showed in the * {@link Checkbox}. * @param Radio * The {@link Radio} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @return The {@link Radio} bound */ public static Radio bind(final Radio radio, final Getter<Boolean> getter) { radio.setSelected(getter.get()); radio.setDisabled(true); return radio; } /** * Binds a {@link Radio} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Radio}. * The {@link Setter} will be used to store the value inserted by the user * in the {@link Radio}. * @param decimalBox * The {@link Radio} to be bound * @param getter * he {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. * @return The {@link Radio} bound */ public static Radio bind(final Radio radio, final Getter<Boolean> getter, final Setter<Boolean> setter) { radio.setSelected(getter.get()); radio.addEventListener(Events.ON_CHECK, new EventListener() { @Override public void onEvent(Event event) { setter.set(radio.isSelected()); radio.setChecked(getter.get()); } }); return radio; } /** * Binds a {@link Bandbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Bandbox}. * * @param bandBox * The {@link Bandbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @return The {@link Bandbox} bound */ public static Bandbox bind(Bandbox bandBox, Getter<String> getter) { bandBox.setValue(getter.get()); bandBox.setDisabled(true); return bandBox; } /** * Binds a {@link Bandbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Bandbox}. * The {@link Setter} will be used to store the value inserted by the user * in the {@link Bandbox}. * * @param bandBox * The {@link Bandbox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. * @return The {@link Bandbox} bound */ public static Bandbox bind(final Bandbox bandBox, final Getter<String> getter, final Setter<String> setter) { bandBox.setValue(getter.get()); bandBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { InputEvent newInput = (InputEvent) event; String value = newInput.getValue(); setter.set(value); bandBox.setValue(getter.get()); } }); return bandBox; } /** * Creates an edit button with class and icon already set. * * @param eventListener * A event listener for {@link Events.ON_CLICK} * @return An edit {@link Button} */ public static Button createEditButton(EventListener eventListener) { Button result = new Button(); result.setTooltiptext(_("Edit")); result.setSclass("icono"); result.setImage("/common/img/ico_editar1.png"); result.setHoverImage("/common/img/ico_editar.png"); result.addEventListener(Events.ON_CLICK, eventListener); return result; } /** * Creates a remove button with class and icon already set. * * @param eventListener * A event listener for {@link Events.ON_CLICK} * @return A remove {@link Button} */ public static Button createRemoveButton(EventListener eventListener) { Button result = new Button(); result.setTooltiptext(_("Remove")); result.setSclass("icono"); result.setImage("/common/img/ico_borrar1.png"); result.setHoverImage("/common/img/ico_borrar.png"); result.addEventListener(Events.ON_CLICK, eventListener); return result; } @SuppressWarnings("unchecked") public static <T extends Component> T findComponentAt(Component container, String idOfComponentToBeFound) { return (T) container.getFellow(idOfComponentToBeFound); } public interface ICreation<T extends Component> { public T createAt(Component parent); } public static <T extends Component> T findOrCreate(Component container, Class<T> klassOfComponentToFind, ICreation<T> ifNotFound) { @SuppressWarnings("unchecked") List<T> existent = ComponentsFinder.findComponentsOfType( klassOfComponentToFind, container.getChildren()); if (!existent.isEmpty()) { return existent.get(0); } return ifNotFound.createAt(container); } /** * It removes all listeners registered for eventName and adds the new * listener. It's ensured that the only listener left in the component for * events of name eventName is uniqueListener * * @param component * @param eventName * @param uniqueListener */ public static void ensureUniqueListener(Component component, String eventName, EventListener uniqueListener) { ensureUniqueListeners(component, eventName, uniqueListener); } /** * It removes all listeners registered for eventName and adds the new * listeners. It's ensured that the only listeners left in the component for * events of name eventName is uniqueListeners * * @param component * @param eventName * @param uniqueListeners * new listeners to add */ public static void ensureUniqueListeners(Component component, String eventName, EventListener... uniqueListeners) { Iterator<?> listenerIterator = component.getListenerIterator(eventName); while (listenerIterator.hasNext()) { listenerIterator.next(); listenerIterator.remove(); } for (EventListener each : uniqueListeners) { component.addEventListener(eventName, each); } } public static void setSort(Column column, String sortSpec) { try { column.setSort(sortSpec); } catch (Exception e) { LOG.error("failed to set sort property for: " + column + " with: " + sortSpec, e); } } /** * Gets currency symbol from {@link Configuration} object. * * @return Currency symbol configured in the application */ public static String getCurrencySymbol() { return Registry.getTransactionService().runOnReadOnlyTransaction( new IOnTransaction<String>() { @Override public String execute() { return Registry.getConfigurationDAO() .getConfiguration().getCurrencySymbol(); } }); } public static String getMoneyFormat() { return "###.## " + escapeDecimalFormatSpecialChars(getCurrencySymbol()); } /** * Escapes special chars used in {@link DecimalFormat} to define the number * format that appear in the <code>currencySymbol</code>. */ private static String escapeDecimalFormatSpecialChars(String currencySymbol) { for (String specialChar : DECIMAL_FORMAT_SPECIAL_CHARS) { currencySymbol = currencySymbol.replace(specialChar, "'" + specialChar + "'"); } return currencySymbol; } }
package com.open.perf.core; import com.open.perf.domain.Group; import com.open.perf.domain.GroupFunction; import com.open.perf.domain.GroupTimer; import com.open.perf.util.Clock; import com.open.perf.util.Counter; import org.apache.log4j.Logger; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GroupController { private boolean started = false; private String groupName; private static Logger logger; static { logger = Logger.getLogger(GroupController.class); } private List<SequentialFunctionExecutor> sequentialFEs; private final Group group; private long startTimeMS = -1; private RequestQueue requestQueue; private Map<String, Counter> customCounters; private Map<String, FunctionCounter> functionCounters; private GroupStatsQueue groupStatsQueue; private StatsCollectorThread statsCollectorThread; private String basePath; private final List<String> ignoreDumpFunctions; private float throughput; public GroupController(String jobId, Group group) { this.basePath = System.getProperty("BASE_PATH", "/var/log/loader/"); basePath += jobId + File.separator + group.getName(); this.groupName = group.getName(); this.group = group; this.group.getParams().put("GROUP_NAME", this.groupName); this.ignoreDumpFunctions = findIgnoredDumpFunctions(); this.functionCounters = buildFunctionCounters(); this.customCounters = buildCustomCounter(); this.requestQueue = buildRequestQueue(); } private List<String> findIgnoredDumpFunctions() { List<String> functions = new ArrayList<String>(); for(GroupFunction gp : this.group.getFunctions()) if(!gp.isDumpData()) functions.add(gp.getFunctionalityName()); return functions; } /** * Building user defined counters * @return */ private Map<String, Counter> buildCustomCounter() { Map<String, Counter> functionCounters = new HashMap<String, Counter>(); for(String functionCounterName : group.getCustomCounters()) functionCounters.put(functionCounterName, new Counter(this.groupName, functionCounterName)); return functionCounters; } /** * Building counters for user defined functions * @return */ private Map<String, FunctionCounter> buildFunctionCounters() { Map<String, FunctionCounter> functionCounters = new HashMap<String, FunctionCounter>(); for(GroupFunction groupFunction : group.getFunctions()) { functionCounters.put(groupFunction.getFunctionalityName(), new FunctionCounter(this.groupName, groupFunction.getFunctionalityName())); if(!groupFunction.isDumpData()) functionCounters.get(groupFunction.getFunctionalityName()).ignore(); } return functionCounters; } /** * Building Request queue that would be shared across all Sequential Function Executors * @return */ private RequestQueue buildRequestQueue() { RequestQueue requestQueue = null; if(group.getRepeats() > 0) requestQueue = new RequestQueue(this.groupName, "requestQueue", this.group.getRepeats()); else requestQueue = new RequestQueue(this.groupName, "requestQueue"); return requestQueue; } /** * Starting the Group Execution * @throws InterruptedException * @throws FileNotFoundException */ public void start() throws InterruptedException, FileNotFoundException { logger.info("************Group Controller "+this.groupName+" Started**************"); groupStartDelay(); this.startTimeMS = Clock.milliTick(); this.groupStatsQueue = new GroupStatsQueue(); this.started = true; this.sequentialFEs = new ArrayList<SequentialFunctionExecutor>(); if(group.getTimers().size() > 0) { GroupTimer firstTimer = group.getTimers().get(0); this.group.setThreads(firstTimer.getThreads()).setThroughput(firstTimer.getThroughput()); GroupTimerManagerThread timerManager = new GroupTimerManagerThread(this, group.getTimers()); timerManager.start(); } for(int threadNo=0; threadNo<group.getThreads(); threadNo++) { SequentialFunctionExecutor sfe = buildSequentialFunctionExecutor(threadNo); this.sequentialFEs.add(sfe); threadStartDelay(); sfe.start(); if(group.getThreadResources().size() > threadNo) { sfe.setThreadResources(group.getThreadResources().get(threadNo)); } } // Starting stats collection thread. Eventually this might become part of this Group Controller only this.statsCollectorThread = new StatsCollectorThread( this.basePath, this.groupStatsQueue, this.functionCounters, this.group.getCustomTimers(), this.customCounters, this.startTimeMS); this.statsCollectorThread.start(); } /** * induce delay before starting the group * @throws InterruptedException */ private void groupStartDelay() throws InterruptedException { Thread.sleep(group.getGroupStartDelay()); } /** * induce delay before starting a thread */ private void threadStartDelay() { Clock.sleep(group.getThreadStartDelay()); } /** * Building a sequential Function executor thread. This thread is responsible for executing user functions in sequence in a thread * @param threadNo * @return */ private SequentialFunctionExecutor buildSequentialFunctionExecutor(int threadNo) { return new SequentialFunctionExecutor(group.getName()+"-"+threadNo, this.group.getFunctions(), this.group.getParams(), this.group.getDuration(), this.requestQueue, this.startTimeMS, this.functionCounters, this.customCounters, this.group.getCustomTimers(), this.groupStatsQueue, this.ignoreDumpFunctions, this.group.getThroughput() / group.getThreads()); } /** * Check all SequentialFunctionExecutor Threads and tell if this group is alive * @return */ public boolean isAlive() { synchronized (this.sequentialFEs){ for(SequentialFunctionExecutor sfe : this.sequentialFEs) if(sfe.isAlive()) return true; } return false; } /** * This function all user to change threads at runtime. * @param newThreads * @throws NoSuchMethodException * @throws ClassNotFoundException */ public void setThreads(int newThreads) throws NoSuchMethodException, ClassNotFoundException { synchronized (this.sequentialFEs) { int currentThreads = this.group.getThreads(); if(newThreads <= 0) { logger.warn("Group " + this.groupName + " :Can't set 0 <= number of threads. Retaining old '" + currentThreads + "' threads."); } else if(newThreads < currentThreads) { int reduceThreads = currentThreads - newThreads; logger.debug(reduceThreads+" threads have to be reduced"); for(int i=1; i<=reduceThreads; i++) { SequentialFunctionExecutor sfe = this.sequentialFEs.remove(this.sequentialFEs.size()-1); sfe.stopIt(); logger.debug("Group "+this.groupName+" : Thread :" + i +" stopped)"); } } else { int increasedThreads = newThreads - currentThreads; logger.debug("Group "+this.groupName + " :" + increasedThreads+" threads have to be increased"); for(int i=0; i<increasedThreads; i++) { int threadNo = this.sequentialFEs.size() + 1; SequentialFunctionExecutor sfe = buildSequentialFunctionExecutor(threadNo); this.sequentialFEs.add(sfe); threadStartDelay(); sfe.start(); if(group.getThreadResources().size() > threadNo) { sfe.setThreadResources(group.getThreadResources().get(threadNo)); } logger.debug("Group "+this.groupName+" :Thread '"+(threadNo+1)+"' started"); } } this.group.setThreads(newThreads); for(SequentialFunctionExecutor sfe : this.sequentialFEs) { sfe.setThroughput(this.group.getThroughput() / group.getThreads()); } } logger.info("Total Threads running "+this.sequentialFEs.size()+"(In List) "+this.group.getThreads()+"(ThreadCount)"); } public String getGroupName() { return this.groupName; } public boolean isDead() { return !this.isAlive(); } public boolean started() { return this.started; } public boolean paused() { synchronized (this.sequentialFEs) { for(SequentialFunctionExecutor sfe : this.sequentialFEs) { if(!sfe.isPaused()) return false; } } return true; } public boolean running() { synchronized (this.sequentialFEs) { for(SequentialFunctionExecutor sfe : this.sequentialFEs) { if(!sfe.isRunning()) return false; } } return true; } public void stopStatsCollection() { this.statsCollectorThread.stopIt(); try { this.statsCollectorThread.join(); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. throw new RuntimeException(e); } logger.info("************Group Controller "+this.groupName+" Ended**************"); } public long getRunTimeMS() { return Clock.milliTick() - this.startTimeMS; } public void pause() { synchronized (this.sequentialFEs) { for(SequentialFunctionExecutor sfe : this.sequentialFEs) { sfe.pauseIt(); } } } public void resume() { synchronized (this.sequentialFEs) { for(SequentialFunctionExecutor sfe : this.sequentialFEs) { sfe.resumeIt(); } } } public void setThroughput(float throughput) { this.group.setThroughput(throughput); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.uva.cs.lobcder; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.client.urlconnection.HTTPSProperties; import com.sun.jersey.core.util.MultivaluedMapImpl; import io.milton.common.Path; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.InetAddress; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPOutputStream; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import lombok.extern.java.Log; import static nl.uva.cs.lobcder.Util.ChacheEvictionAlgorithm.LRU; import static nl.uva.cs.lobcder.Util.ChacheEvictionAlgorithm.MRU; import nl.uva.cs.lobcder.auth.AuthTicket; import nl.uva.cs.lobcder.auth.MyPrincipal; import nl.uva.cs.lobcder.resources.PDRI; import nl.uva.cs.lobcder.resources.PDRIDescr; import nl.uva.cs.lobcder.resources.VPDRI; import nl.uva.cs.lobcder.rest.Endpoints; import nl.uva.cs.lobcder.rest.wrappers.LogicalDataWrapped; import nl.uva.cs.lobcder.rest.wrappers.Stats; import nl.uva.vlet.data.StringUtil; import nl.uva.vlet.exception.VlException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.output.TeeOutputStream; @Log public final class WorkerServlet extends HttpServlet { // private static final int DEFAULT_BUFFER_SIZE = 10240; // ..bytes = 10KB. private static final long DEFAULT_EXPIRE_TIME = 604800000L; // ..ms = 1 week. private static final String MULTIPART_BOUNDARY = "MULTIPART_BYTERANGES"; private Integer bufferSize; private Boolean setResponseBufferSize; // private Boolean useCircularBuffer; private String restURL; private String token; private ClientConfig clientConfig; private String fileUID; private final Map<String, LogicalDataWrapped> logicalDataCache = new HashMap<>(); private final Map<String, Long> fileAccessMap = new HashMap<>(); private Client restClient; // private long sleepTime = 2; private static final Map<String, Double> weightPDRIMap = new HashMap<>(); private static final HashMap<String, Integer> numOfGetsMap = new HashMap<>(); private InputStream in; private int responseBufferSize; // private double lim = 4; private boolean qosCopy; private int warnings; private double progressThresshold; private double coefficient; private String fileLogicalName; private File cacheDir; private File cacheFile; private boolean sendStats; private WebResource webResource; /** * Initialize the servlet. * * @see HttpServlet#init(). */ @Override public void init() throws ServletException { try { setResponseBufferSize = Util.isResponseBufferSize(); // useCircularBuffer = Util.isCircularBuffer(); qosCopy = Util.doQosCopy(); bufferSize = Util.getBufferSize(); restURL = Util.getRestURL(); token = Util.getRestPassword(); sendStats = Util.sendStats(); // lim = Util.getRateOfChangeLim(); // uname = prop.getProperty(("rest.uname")); clientConfig = configureClient(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); warnings = Util.getNumOfWarnings(); progressThresshold = Util.getProgressThresshold(); coefficient = Util.getProgressThressholdCoefficient(); cacheDir = new File(System.getProperty("java.io.tmpdir") + File.separator + Util.getBackendWorkingFolderName()); if (!cacheDir.exists()) { cacheDir.mkdirs(); } getPDRIs(); } catch (IOException ex) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); } } // /** // * Process HEAD request. This returns the same headers as GET request, but // * without content. // * // * @see HttpServlet#doHead(HttpServletRequest, HttpServletResponse). // */ // @Override // protected void doHead(HttpServletRequest request, HttpServletResponse response) // throws ServletException, IOException { // try { // // Process request without content. // processRequest(request, response, false); // } catch (InterruptedException ex) { // Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); // } catch (URISyntaxException ex) { // Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); /** * Process GET request. * * @see HttpServlet#doGet(HttpServletRequest, HttpServletResponse). */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, UnsupportedEncodingException { try { // Process request with content. // authenticate(request, response); processRequest(request, response, true); } catch (IOException | InterruptedException | URISyntaxException | VlException | JAXBException ex) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); handleError(ex, response); // } catch (NoSuchAlgorithmException ex) { // Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); // } catch (InvalidKeySpecException ex) { // Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); // } catch (InvalidKeyException ex) { // Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Process the actual request. * * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not * (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, InterruptedException, URISyntaxException, VlException, JAXBException { long startTime = System.currentTimeMillis(); // Get requested file by path info. String requestedFile = request.getPathInfo(); // Check if file is actually supplied to the request URL. PDRI pdri = null; if (requestedFile == null || requestedFile.split("/").length < 2) { // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Path pathAndToken = Path.path(requestedFile); // token = pathAndToken.getName(); fileUID = pathAndToken.getParent().toString(); Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "token: {0} fileUID: {1}", new Object[]{token, fileUID}); long startGetPDRI = System.currentTimeMillis(); Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "start getPDRI at:{0}", startGetPDRI); pdri = getPDRI(fileUID); // URL-decode the file name (might contain spaces and on) and prepare file object. // File file = new File("", URLDecoder.decode(requestedFile, "UTF-8")); // Check if file actually exists in filesystem. if (pdri == null) { // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. long length = pdri.getLength(); long lastModified = logicalDataCache.get(fileUID).getLogicalData().getModifiedDate(); String eTag = fileLogicalName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME; // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Get content type by file name and set default GZIP support and content disposition. String contentType = getServletContext().getMimeType(fileLogicalName); if (contentType == null) { contentType = this.logicalDataCache.get(fileUID).getLogicalData().getContentTypesAsString(); } boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); if (setResponseBufferSize) { response.setBufferSize(bufferSize); } responseBufferSize = response.getBufferSize(); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileLogicalName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); response.setContentLength(safeLongToInt(logicalDataCache.get(fileUID).getLogicalData().getLength())); // Prepare streams. // RandomAccessFile input = null; OutputStream output = null; try { // Open streams. // input = new RandomAccessFile(file, "r"); // input = pdri.getData() output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, bufferSize); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(pdri, output, r.start, r.length, request); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(pdri, output, r.start, r.length, request); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(pdri, output, r.start, r.length, request); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); if (in != null) { in.close(); } long elapsed = System.currentTimeMillis() - startTime; if (elapsed <= 0) { elapsed = 1; } double speed = ((this.logicalDataCache.get(fileUID).getLogicalData().getLength() * 8.0) * 1000.0) / (elapsed * 1000.0); Double oldSpeed = weightPDRIMap.get(pdri.getHost()); if (oldSpeed == null) { oldSpeed = speed; } Integer numOfGets = numOfGetsMap.get(pdri.getHost()); if (numOfGets == null) { numOfGets = 1; } double averagre = (speed + oldSpeed) / (double) numOfGets; numOfGetsMap.put(pdri.getHost(), numOfGets++); weightPDRIMap.put(pdri.getHost(), averagre); Stats stats = new Stats(); stats.setSource(request.getLocalAddr()); stats.setDestination(request.getRemoteAddr()); stats.setSpeed(speed); stats.setSize(this.logicalDataCache.get(fileUID).getLogicalData().getLength()); setSpeed(stats); String speedMsg = "Source: " + request.getLocalAddr() + " Destination: " + request.getRemoteAddr() + " Tx_Speed: " + speed + " Kbites/sec Tx_Size: " + this.logicalDataCache.get(fileUID).getLogicalData().getLength() + " bytes"; Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, speedMsg); String averageSpeedMsg = "Average speed: Source: " + pdri.getHost() + " Destination: " + request.getLocalAddr() + " Rx_Speed: " + averagre + " Kbites/sec Rx_Size: " + this.logicalDataCache.get(fileUID).getLogicalData().getLength() + " bytes"; if (Util.sendStats()) { stats.setSource(request.getLocalAddr()); stats.setDestination(request.getRemoteAddr()); stats.setSpeed(speed); stats.setSize(this.logicalDataCache.get(fileUID).getLogicalData().getLength()); setSpeed(stats); } Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, averageSpeedMsg); } } /** * Returns true if the given accept header accepts the given value. * * @param acceptHeader The accept header. * @param toAccept The value to be accepted. * @return True if the given accept header accepts the given value. */ private static boolean accepts(String acceptHeader, String toAccept) { String[] acceptValues = acceptHeader.split("\\s*(,|;)\\s*"); Arrays.sort(acceptValues); return Arrays.binarySearch(acceptValues, toAccept) > -1 || Arrays.binarySearch(acceptValues, "*/*") > -1; /** * Returns true if the given match header matches the given value. * * @param matchHeader The match header. * @param toMatch The value to be matched. * @return True if the given match header matches the given value. */ private static boolean matches(String matchHeader, String toMatch) { String[] matchValues = matchHeader.split("\\s*,\\s*"); Arrays.sort(matchValues); return Arrays.binarySearch(matchValues, toMatch) > -1 || Arrays.binarySearch(matchValues, "*") > -1; } /** * Returns a substring of the given string value from the given begin index * to the given end index as a long. If the substring is empty, then -1 will * be returned * * @param value The string value to return a substring as long for. * @param beginIndex The begin index of the substring to be returned as * long. * @param endIndex The end index of the substring to be returned as long. * @return A substring of the given string value as long or -1 if substring * is empty. */ private static long sublong(String value, int beginIndex, int endIndex) { String substring = value.substring(beginIndex, endIndex); return (substring.length() > 0) ? Long.parseLong(substring) : -1; } /** * Copy the given byte range of the given input to the given output. * * @param input The input to copy the given range to the given output for. * @param output The output to copy the given range from the given input * for. * @param start Start of the byte range. * @param length Length of the byte range. * @throws IOException If something fails at I/O level. */ private void copy(PDRI input, OutputStream output, long start, long length, HttpServletRequest request) throws IOException, VlException, JAXBException { OutputStream tos = null; try { if (input.getLength() == length) { // Write full range. in = input.getData(); byte[] buffer = new byte[bufferSize]; cacheFile = new File(cacheDir, input.getFileName()); if (!cacheFile.exists() || input.getLength() != cacheFile.length()) { cacheDir = new File(System.getProperty("java.io.tmpdir") + File.separator + Util.getBackendWorkingFolderName()); if (!cacheDir.exists()) { cacheDir.mkdirs(); } tos = new TeeOutputStream(new FileOutputStream(cacheFile), output); File file = new File(System.getProperty("user.home")); while (file.getUsableSpace() < Util.getCacheFreeSpaceLimit()) { evictCache(); } } else { tos = output; } if (!qosCopy) { int len; while ((len = in.read(buffer)) != -1) { tos.write(buffer, 0, len); } // CircularStreamBufferTransferer cBuff = new CircularStreamBufferTransferer((bufferSize), in, tos); // cBuff.setMaxReadChunkSize(bufferSize); // if (responseBufferSize > 0) { // cBuff.setMaxWriteChunkSize(responseBufferSize); // cBuff.startTransfer(new Long(-1)); } else { qoSCopy(buffer, tos, length, request); } } else { io.milton.http.Range range = new io.milton.http.Range(start, length - start); input.copyRange(range, output); // input.copyRange(output, start, length); } } finally { if (tos != null) { tos.flush(); } else { output.flush(); } } } private void qoSCopy(byte[] buffer, OutputStream output, long size, HttpServletRequest request) throws IOException, JAXBException { int read; long total = 0; double speed; long startTime = System.currentTimeMillis(); int count = 0; String d = ""; double maxSpeed = -1; double thresshold = 100.0 * Math.exp(coefficient * (size / (1024.0 * 1024.0))); double averageSpeed = -1; double averageSpeedPrev = -2; while ((read = in.read(buffer)) > 0) { output.write(buffer, 0, read); total += read; double progress = (100.0 * total) / size; if (progress >= thresshold && Math.round(progress) % progressThresshold == 0 && !Util.dropConnection() && !Util.getOptimizeFlow()) { long elapsed = System.currentTimeMillis() - startTime; double a = 0.5; if (elapsed < 1) { speed = Double.MAX_VALUE; } else { speed = (total / elapsed); } if (averageSpeed <= 0) { averageSpeed = speed; } averageSpeed = a * averageSpeed + (1 - a) * speed; if (averageSpeed >= maxSpeed) { maxSpeed = averageSpeed; } d += "progressThresshold: " + progressThresshold + " speed: " + speed + " averageSpeed: " + averageSpeed + " progress: " + progress + " maxSpeed: " + maxSpeed + " limit: " + (maxSpeed / Util.getRateOfChangeLim()) + "\n"; Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, d); if (averageSpeed < (maxSpeed / Util.getRateOfChangeLim()) && averageSpeed < averageSpeedPrev) { count++; Logger.getLogger(WorkerServlet.class.getName()).log(Level.WARNING, "We will not tolarate this !!!! Next time line is off"); if (Util.getOptimizeFlow()) { optimizeFlow(request); maxSpeed = averageSpeed; Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, "optimizeFlow: {0}", request); } if (count >= warnings && Util.dropConnection()) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.WARNING, "We will not tolarate this !!!! Find a new worker. rateOfChange: {0}", averageSpeed); break; } } averageSpeedPrev = averageSpeed; } } Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, d); } /** * Close the given resource. * * @param resource The resource to be closed. */ private static void close(Closeable resource) { if (resource != null) { try { resource.close(); } catch (IOException ignore) { // Ignore IOException. If you want to handle this anyway, it might be useful to know // that this will generally only be thrown when the client aborted the request. } } } private ClientConfig configureClient() { TrustManager[] certs = new TrustManager[]{ new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; SSLContext ctx = null; try { ctx = SSLContext.getInstance("TLS"); ctx.init(null, certs, new SecureRandom()); } catch (java.security.GeneralSecurityException ex) { } HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory()); ClientConfig config = new DefaultClientConfig(); try { config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }, ctx)); } catch (Exception e) { } return config; } private PDRI getPDRI(String fileUID) throws InterruptedException, IOException, URISyntaxException { PDRIDescr pdriDesc = null;//new PDRIDescr(); LogicalDataWrapped logicalData = null; logicalData = logicalDataCache.get(fileUID); if (logicalData == null) { if (restClient == null) { restClient = Client.create(clientConfig); restClient.removeAllFilters(); restClient.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter("worker-", token)); webResource = restClient.resource(restURL); } Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Asking master. Token: {0}", token); WebResource res = webResource.path("item").path("query").path(fileUID); logicalData = res.accept(MediaType.APPLICATION_XML). get(new GenericType<LogicalDataWrapped>() { }); logicalData = removeFilePDRIs(logicalData); } logicalData = addCacheToPDRIDescr(logicalData); pdriDesc = selectBestPDRI(logicalData.getPdriList()); Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Selected pdri: {0}", pdriDesc.getResourceUrl()); fileLogicalName = logicalData.getLogicalData().getName(); return new VPDRI(pdriDesc.getName(), pdriDesc.getId(), pdriDesc.getResourceUrl(), pdriDesc.getUsername(), pdriDesc.getPassword(), pdriDesc.getEncrypt(), pdriDesc.getKey(), false); } private PDRIDescr selectBestPDRI(List<PDRIDescr> pdris) throws URISyntaxException, UnknownHostException, SocketException { if (!pdris.isEmpty()) { PDRIDescr p = pdris.iterator().next(); URI uri = new URI(p.getResourceUrl()); String resourceIP = Util.getIP(uri.getHost()); List<String> ips = Util.getAllIPs(); for (String i : ips) { // Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "resourceIP: {0} localIP: {1}", new Object[]{resourceIP, i}); if (resourceIP != null && resourceIP.equals(i) || uri.getHost().equals("localhost") || uri.getHost().equals("127.0.0.1")) { String resURL = p.getResourceUrl().replaceFirst(uri.getScheme(), "file"); p.setResourceUrl(resURL); return p; } } } for (PDRIDescr p : pdris) { URI uri = new URI(p.getResourceUrl()); if (uri.getScheme().equals("file")) { return p; } String resourceIP = Util.getIP(uri.getHost()); List<String> ips = Util.getAllIPs(); for (String i : ips) { // Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, "Checking IP: {0}", i); if (resourceIP.equals(i)) { String resURL = p.getResourceUrl().replaceFirst(uri.getScheme(), "file"); p.setResourceUrl(resURL); return p; } } } if (weightPDRIMap.isEmpty() || weightPDRIMap.size() < pdris.size()) { //Just return one at random; int index = new Random().nextInt(pdris.size()); PDRIDescr[] array = pdris.toArray(new PDRIDescr[pdris.size()]); Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Selecting Random: {0}", array[index].getResourceUrl()); return array[index]; } long sumOfSpeed = 0; for (PDRIDescr p : pdris) { URI uri = new URI(p.getResourceUrl()); String host; if (uri.getScheme().equals("file") || StringUtil.isEmpty(uri.getHost()) || uri.getHost().equals("localhost") || uri.getHost().equals("127.0.0.1")) { host = InetAddress.getLocalHost().getHostName(); } else { host = uri.getHost(); } Double speed = weightPDRIMap.get(host); if (speed == null) { speed = Double.valueOf(0); } Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Speed: {0}", speed); sumOfSpeed += speed; } if (sumOfSpeed <= 0) { int index = new Random().nextInt(pdris.size()); PDRIDescr[] array = pdris.toArray(new PDRIDescr[pdris.size()]); return array[index]; } int itemIndex = new Random().nextInt((int) sumOfSpeed); for (PDRIDescr p : pdris) { Double speed = weightPDRIMap.get(new URI(p.getResourceUrl()).getHost()); if (speed == null) { speed = Double.valueOf(0); } if (itemIndex < speed) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Selecting:{0} with speed: {1}", new Object[]{p.getResourceUrl(), speed}); return p; } itemIndex -= speed; } int index = new Random().nextInt(pdris.size()); PDRIDescr[] array = pdris.toArray(new PDRIDescr[pdris.size()]); PDRIDescr res = array[index]; return res; } private void handleError(java.lang.Exception ex, HttpServletResponse response) throws IOException { if (ex instanceof IOException) { if (ex.getMessage().contains("PDRIS from master is either empty or contains unreachable files")) { response.sendError(HttpServletResponse.SC_MOVED_TEMPORARILY); return; } if (ex.getMessage().contains("Low B/W")) { // response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } } response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); } private void setSpeed(Stats stats) throws JAXBException { if (sendStats) { JAXBContext context = JAXBContext.newInstance(Stats.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); OutputStream out = new ByteArrayOutputStream(); m.marshal(stats, out); String stringStats = String.valueOf(out); if (restClient == null) { restClient = Client.create(clientConfig); restClient.removeAllFilters(); restClient.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter("worker-", token)); webResource = restClient.resource(restURL); } ClientResponse response = webResource.path("lob_statistics").path("set") .type(MediaType.APPLICATION_XML).put(ClientResponse.class, stringStats); } } private void optimizeFlow(HttpServletRequest request) throws JAXBException { Endpoints endpoints = new Endpoints(); endpoints.setDestination(request.getRemoteAddr()); endpoints.setSource(request.getLocalAddr()); JAXBContext context = JAXBContext.newInstance(Endpoints.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); OutputStream out = new ByteArrayOutputStream(); m.marshal(endpoints, out); WebResource webResource = restClient.resource(restURL); String stringStats = String.valueOf(out); ClientResponse response = webResource.path("sdn").path("optimizeFlow") .type(MediaType.APPLICATION_XML).put(ClientResponse.class, stringStats); Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, "response: {0}", response); } private static int safeLongToInt(long l) { if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { throw new IllegalArgumentException(l + " cannot be cast to int without changing its value."); } return (int) l; } private void evictCache() throws IOException { String key = null; switch (Util.getCacheEvictionPolicy()) { case LRU: case LFU: Set<Map.Entry<String, Long>> set = fileAccessMap.entrySet(); Long min = Long.MAX_VALUE; for (Map.Entry<String, Long> e : set) { if (e.getValue() < min) { min = e.getValue(); key = e.getKey(); } } break; case MRU: case MFU: set = fileAccessMap.entrySet(); Long max = Long.MIN_VALUE; for (Map.Entry<String, Long> e : set) { if (e.getValue() > max) { max = e.getValue(); key = e.getKey(); } } break; case RR: default: Random random = new Random(); List<String> keys = new ArrayList(fileAccessMap.keySet()); key = keys.get(random.nextInt(keys.size())); break; } new File(key).delete(); fileAccessMap.remove(key); } private LogicalDataWrapped addCacheToPDRIDescr(LogicalDataWrapped logicalData) throws IOException, URISyntaxException { List<PDRIDescr> pdris = logicalData.getPdriList(); cacheFile = new File(cacheDir, pdris.get(0).getName()); logicalData = removeFilePDRIs(logicalData); if (cacheFile.exists()) { String fileName = cacheFile.getName(); long ssID = -1; String resourceURI = "file:///" + cacheFile.getAbsoluteFile().getParentFile().getParent(); String uName = "fake"; String passwd = "fake"; boolean encrypt = false; long key = -1; long pdriId = -1; Long groupId = Long.valueOf(-1); pdris.add(new PDRIDescr(fileName, ssID, resourceURI, uName, passwd, encrypt, BigInteger.valueOf(key), groupId, pdriId)); switch (Util.getCacheEvictionPolicy()) { case LRU: case MRU: case RR: fileAccessMap.put(cacheFile.getAbsolutePath(), System.currentTimeMillis()); break; case LFU: case MFU: Long count = fileAccessMap.get(cacheFile.getAbsolutePath()); if (count == null) { count = Long.valueOf(0); } fileAccessMap.put(cacheFile.getAbsolutePath(), count++); break; } logicalData.setPdriList(pdris); } return logicalData; } private LogicalDataWrapped removeFilePDRIs(LogicalDataWrapped logicalData) throws IOException, URISyntaxException { List<PDRIDescr> pdris = logicalData.getPdriList(); if (logicalData != null && pdris != null) { List<PDRIDescr> removeIt = new ArrayList<>(); if (pdris != null && !pdris.isEmpty()) { //Remove masters's cache pdris for (PDRIDescr p : pdris) { URI uri = new URI(p.getResourceUrl()); boolean isCache = false; List<String> ips = Util.getAllIPs(); if (ips != null) { for (String h : ips) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, "uri: " + uri); Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, "uri.getHost(): " + uri.getHost()); String host = uri.getHost(); if (h != null) { if (host == null || host.equals(h)) { isCache = true; break; } } } } if (uri.getScheme().startsWith("file") && !isCache) { removeIt.add(p); } } if (!removeIt.isEmpty()) { pdris.removeAll(removeIt); if (pdris.isEmpty()) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, "PDRIS from master is either empty or contains unreachable files"); logicalDataCache.remove(fileUID); throw new IOException("PDRIS from master is either empty or contains unreachable files"); } } } logicalDataCache.put(fileUID, logicalData); } return logicalData; } private void authenticate(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; final String autheader = httpRequest.getHeader("Authorization"); if (autheader != null) { final int index = autheader.indexOf(' '); if (index > 0) { final String credentials = new String(Base64.decodeBase64(autheader.substring(index).getBytes()), "UTF8"); // final String credentials = new String(Base64.decodeBase64(autheader.substring(index)), "UTF8"); final String uname = credentials.substring(0, credentials.indexOf(":")); final String token = credentials.substring(credentials.indexOf(":") + 1); double start = System.currentTimeMillis(); AuthTicket a = new AuthTicket(); MyPrincipal principal = a.checkToken(uname, token); String method = ((HttpServletRequest) httpRequest).getMethod(); StringBuffer reqURL = ((HttpServletRequest) httpRequest).getRequestURL(); double elapsed = System.currentTimeMillis() - start; String userAgent = ((HttpServletRequest) httpRequest).getHeader("User-Agent"); String from = ((HttpServletRequest) httpRequest).getRemoteAddr(); // String user = ((HttpServletRequest) httpRequest).getRemoteUser(); int contentLen = ((HttpServletRequest) httpRequest).getContentLength(); String contentType = ((HttpServletRequest) httpRequest).getContentType(); String authorizationHeader = ((HttpServletRequest) httpRequest).getHeader("authorization"); String userNpasswd = ""; if (authorizationHeader != null) { userNpasswd = authorizationHeader.split("Basic ")[1]; } String queryString = ((HttpServletRequest) httpRequest).getQueryString(); if (principal != null) { httpRequest.setAttribute("myprincipal", principal); return; } } } String _realm = "SECRET"; httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"" + _realm + "\""); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); } private void getPDRIs() throws IOException, URISyntaxException { if (restClient == null) { restClient = Client.create(clientConfig); restClient.removeAllFilters(); restClient.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter("worker-", token)); webResource = restClient.resource(restURL); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("path", "/"); WebResource res = webResource.path("items").path("query").queryParams(params); List<LogicalDataWrapped> logicalDataList = res.accept(MediaType.APPLICATION_XML). get(new GenericType<List<LogicalDataWrapped>>() { }); for (LogicalDataWrapped ldw : logicalDataList) { if (!ldw.getLogicalData().isFolder()) { LogicalDataWrapped ld = removeFilePDRIs(ldw); this.logicalDataCache.put(String.valueOf(ld.getLogicalData().getUid()), ld); } } } } /** * This class represents a byte range. */ protected class Range { long start; long end; long length; long total; /** * Construct a byte range. * * @param start Start of the byte range. * @param end End of the byte range. * @param total Total length of the byte source. */ public Range(long start, long end, long total) { this.start = start; this.end = end; this.length = end - start + 1; this.total = total; } } }
package org.jboss.as.mail.extension; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.RestartParentResourceAddHandler; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceName; /** * @author Tomaz Cerar * @created 8.12.11 0:19 */ class MailServerAdd extends RestartParentResourceAddHandler { private final AttributeDefinition[] attributes; MailServerAdd(AttributeDefinition[] attributes) { super(MailSubsystemModel.MAIL_SESSION); this.attributes = attributes; } /** * Populate the given node in the persistent configuration model based on the values in the given operation. * * @param operation the operation * @param model persistent configuration model node that corresponds to the address of {@code operation} * @throws org.jboss.as.controller.OperationFailedException * if {@code operation} is invalid or populating the model otherwise fails */ @Override protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException { for (AttributeDefinition def : attributes) { def.validateAndSet(operation, model); } } @Override protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException { MailSessionAdd.installRuntimeServices(context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName(parentAddress.getLastElement().getValue()); } @Override protected void removeServices(OperationContext context, ServiceName parentService, ModelNode parentModel) throws OperationFailedException { super.removeServices(context,parentService,parentModel); String jndiName = MailSessionAdd.getJndiName(parentModel, context); final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(jndiName); context.removeService(bindInfo.getBinderServiceName()); } }
package com.macro.mall.dto; import io.swagger.annotations.ApiModelProperty; public class PmsProductResult extends PmsProductParam { @ApiModelProperty("id") private Long cateParentId; public Long getCateParentId() { return cateParentId; } public void setCateParentId(Long cateParentId) { this.cateParentId = cateParentId; } }
package com.zygon.htm.memory.core; import com.google.common.collect.Sets; import com.zygon.htm.core.Identifier; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Set; /** * * @author zygon */ public class IdentifierSet extends AbstractSet implements Comparable<IdentifierSet> { private final Set<Identifier> identifiers; private int hash = -1; public IdentifierSet(Set<Identifier> identifiers) { this.identifiers = Collections.unmodifiableSet(Sets.newTreeSet(identifiers)); } @Override public int compareTo(IdentifierSet t) { return this.hashCode() > t.hashCode() ? 1 : (this.hashCode() < t.hashCode() ? -1 : 0); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof IdentifierSet)) { return false; } return this.hashCode() == o.hashCode(); } public final Identifier[] getIdentifiers() { return this.identifiers.toArray(new Identifier[this.identifiers.size()]); } @Override public int hashCode() { if (hash == -1) { this.hash = Arrays.hashCode(getIdentifiers()); } return this.hash; } @Override public Iterator iterator() { return this.identifiers.iterator(); } @Override public int size() { return this.identifiers.size(); } }
package org.vrjuggler.tweek.iconviewer; import java.util.EventObject; public class PrefsEvent extends EventObject { public PrefsEvent(Object source, boolean smallGui) { super(source); this.smallGui = smallGui; } public boolean isSmallGui() { return smallGui; } private boolean smallGui; }
package org.fiteagle.adapters.motor; import info.openmultinet.ontology.vocabulary.Omn; import info.openmultinet.ontology.vocabulary.Omn_federation; import info.openmultinet.ontology.vocabulary.Omn_lifecycle; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.fiteagle.abstractAdapter.AbstractAdapter; import org.fiteagle.api.core.IMessageBus; import org.fiteagle.api.core.MessageBusOntologyModel; import org.fiteagle.api.core.OntologyModelUtil; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; public final class MotorAdapter extends AbstractAdapter { private Model adapterModel; private Resource adapterInstance; private static Resource adapter; private static List<Resource> resources = new ArrayList<>(); public static Map<String, AbstractAdapter> adapterInstances = new HashMap<String, AbstractAdapter>(); private static List<Property> motorControlProperties = new ArrayList<Property>(); protected HashMap<String, Motor> instanceList = new HashMap<String, Motor>(); static { Model adapterModel = OntologyModelUtil.loadModel("ontologies/motor.ttl", IMessageBus.SERIALIZATION_TURTLE); ResIterator adapterIterator = adapterModel.listSubjectsWithProperty(RDFS.subClassOf, MessageBusOntologyModel.classAdapter); if (adapterIterator.hasNext()) { adapter = adapterIterator.next(); } StmtIterator resourceIterator = adapter.listProperties(Omn_lifecycle.implements_); if (resourceIterator.hasNext()) { Resource resource = resourceIterator.next().getObject().asResource(); resources.add(resource); ResIterator propertiesIterator = adapterModel.listSubjectsWithProperty(RDFS.domain, resource); while (propertiesIterator.hasNext()) { Property p = adapterModel.getProperty(propertiesIterator.next().getURI()); motorControlProperties.add(p); } } createDefaultAdapterInstance(adapterModel); } private static void createDefaultAdapterInstance(Model model){ Resource adapterInstance = model.createResource(OntologyModelUtil.getLocalNamespace()+"MotorGarage-1"); adapterInstance.addProperty(RDF.type, adapter); adapterInstance.addProperty(Omn_lifecycle.parentTo,model.createResource("http://open-multinet.info/ontology/resource/motor#Motor")); adapterInstance.addProperty(RDFS.label, adapterInstance.getLocalName()); adapterInstance.addProperty(RDFS.comment, "A motor garage adapter that can simulate different dynamic motor resources."); adapterInstance.addLiteral(MessageBusOntologyModel.maxInstances, 10); Resource testbed = model.createResource("http://federation.av.tu-berlin.de/about#AV_Smart_Communication_Testbed"); adapterInstance.addProperty(Omn_federation.partOfFederation, testbed); Property longitude = model.createProperty("http://www.w3.org/2003/01/geo/wgs84_pos#long"); Property latitude = model.createProperty("http://www.w3.org/2003/01/geo/wgs84_pos#lat"); adapterInstance.addProperty(latitude, "52.516377"); adapterInstance.addProperty(longitude, "13.323732"); new MotorAdapter(adapterInstance, model); } private MotorAdapter(Resource adapterInstance, Model adapterModel) { super(adapterInstance.getLocalName()); this.adapterInstance = adapterInstance; this.adapterModel = adapterModel; adapterInstances.put(adapterInstance.getURI(), this); } @Override public Model createInstance(String instanceURI, Model modelCreate) { Motor motor = new Motor(this, instanceURI); instanceList.put(instanceURI, motor); updateInstance(instanceURI, modelCreate); return parseToModel(motor); } protected Model parseToModel(Motor motor) { Resource resource = ModelFactory.createDefaultModel().createResource(motor.getInstanceName()); resource.addProperty(RDF.type, MotorAdapter.resources.get(0)); resource.addProperty(RDF.type, Omn.Resource); resource.addProperty(RDFS.label, resource.getLocalName()); resource.addProperty(Omn_lifecycle.hasState, Omn_lifecycle.Ready); for (Property p : motorControlProperties) { switch (p.getLocalName()) { case "rpm": resource.addLiteral(p, motor.getRpm()); break; case "maxRpm": resource.addLiteral(p, motor.getMaxRpm()); break; case "manufacturer": resource.addLiteral(p, motor.getManufacturer()); break; case "throttle": resource.addLiteral(p, motor.getThrottle()); break; case "isDynamic": resource.addLiteral(p, motor.isDynamic()); break; } } return resource.getModel(); } @Override public Model updateInstance(String instanceURI, Model configureModel) { if (instanceList.containsKey(instanceURI)) { Motor currentMotor = (Motor) instanceList.get(instanceURI); StmtIterator iter = configureModel.listStatements(); while(iter.hasNext()){ currentMotor.updateProperty(iter.next()); } return parseToModel(currentMotor); } return ModelFactory.createDefaultModel(); } @Override public void deleteInstance(String instanceURI) { Motor motor = getInstanceByName(instanceURI); motor.terminate(); instanceList.remove(instanceURI); } public Motor getInstanceByName(String instanceURI) { return (Motor) instanceList.get(instanceURI); } @Override public List<Resource> getAdapterManagedResources() { return resources; } @Override public Resource getAdapterInstance() { return adapterInstance; } @Override public Resource getAdapterType() { return adapter; } @Override public Model getAdapterDescriptionModel() { return adapterModel; } @Override public void updateAdapterDescription() { } @Override public Model getInstance(String instanceURI) throws InstanceNotFoundException { Motor motor = instanceList.get(instanceURI); if(motor == null){ throw new InstanceNotFoundException("Instance "+instanceURI+" not found"); } return parseToModel(motor); } @Override public Model getAllInstances() throws InstanceNotFoundException { Model model = ModelFactory.createDefaultModel(); for(String uri : instanceList.keySet()){ model.add(getInstance(uri)); } return model; } }
package com.ibm.mqlight.api.impl.engine; import java.nio.ByteBuffer; import java.util.EnumSet; import org.apache.qpid.proton.Proton; import org.apache.qpid.proton.amqp.UnsignedInteger; import org.apache.qpid.proton.amqp.messaging.Modified; import org.apache.qpid.proton.amqp.messaging.Rejected; import org.apache.qpid.proton.amqp.messaging.Released; import org.apache.qpid.proton.amqp.messaging.Source; import org.apache.qpid.proton.amqp.messaging.Target; import org.apache.qpid.proton.amqp.messaging.TerminusExpiryPolicy; import org.apache.qpid.proton.amqp.transport.ReceiverSettleMode; import org.apache.qpid.proton.amqp.transport.SenderSettleMode; import org.apache.qpid.proton.engine.Collector; import org.apache.qpid.proton.engine.Connection; import org.apache.qpid.proton.engine.Delivery; import org.apache.qpid.proton.engine.EndpointState; import org.apache.qpid.proton.engine.Event; import org.apache.qpid.proton.engine.Link; import org.apache.qpid.proton.engine.Receiver; import org.apache.qpid.proton.engine.Sasl; import org.apache.qpid.proton.engine.Sender; import org.apache.qpid.proton.engine.Session; import org.apache.qpid.proton.engine.Transport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ibm.mqlight.api.ClientException; import com.ibm.mqlight.api.Promise; import com.ibm.mqlight.api.QOS; import com.ibm.mqlight.api.impl.Component; import com.ibm.mqlight.api.impl.Message; import com.ibm.mqlight.api.impl.network.ConnectResponse; import com.ibm.mqlight.api.impl.network.ConnectionError; import com.ibm.mqlight.api.impl.network.DataRead; import com.ibm.mqlight.api.impl.network.DisconnectResponse; import com.ibm.mqlight.api.impl.network.NetworkClosePromiseImpl; import com.ibm.mqlight.api.impl.network.NetworkConnectPromiseImpl; import com.ibm.mqlight.api.impl.network.NetworkListenerImpl; import com.ibm.mqlight.api.impl.network.NetworkWritePromiseImpl; import com.ibm.mqlight.api.impl.network.WriteResponse; import com.ibm.mqlight.api.impl.timer.PopResponse; import com.ibm.mqlight.api.impl.timer.TimerPromiseImpl; import com.ibm.mqlight.api.network.NetworkService; import com.ibm.mqlight.api.network.NetworkChannel; import com.ibm.mqlight.api.timer.TimerService; public class Engine extends Component { private final NetworkService network; private final TimerService timer; private final Logger logger = LoggerFactory.getLogger(getClass()); public Engine(NetworkService network, TimerService timer) { if (network == null) throw new IllegalArgumentException("NetworkService argument cannot be null"); if (timer == null) throw new IllegalArgumentException("TimerService argument cannot be null"); this.network = network; this.timer = timer; } @Override protected void onReceive(Message message) { if (message instanceof OpenRequest) { OpenRequest or = (OpenRequest)message; //ConnectRequest connectRequest = new ConnectRequest(or.endpoint.getHost(), or.endpoint.getPort()); //connectRequest.setContext(or); //nn.tell(connectRequest, this); NetworkListenerImpl listener = new NetworkListenerImpl(this); Promise<NetworkChannel> promise = new NetworkConnectPromiseImpl(this, or); network.connect(or.endpoint, listener, promise); } else if (message instanceof ConnectResponse) { // Message from network telling us that a connect request has completed... ConnectResponse cr = (ConnectResponse)message; OpenRequest or = (OpenRequest)cr.context; if (cr.exception != null) { or.getSender().tell(new OpenResponse(or, cr.exception), this); } else { Connection protonConnection = Proton.connection(); Transport transport = Proton.transport(); transport.bind(protonConnection); Collector collector = Proton.collector(); protonConnection.setContainer(or.clientId); protonConnection.setHostname(or.endpoint.getHost()); protonConnection.open(); Sasl sasl = transport.sasl(); sasl.client(); if (or.endpoint.getUser() == null) { sasl.setMechanisms(new String[]{"ANONYMOUS"}); } else { sasl.plain(or.endpoint.getUser(), new String(or.endpoint.getPassword())); } Session session = protonConnection.session(); session.open(); protonConnection.collect(collector); EngineConnection engineConnection = new EngineConnection(protonConnection, session, or.getSender(), transport, collector, cr.channel); engineConnection.openRequest = or; protonConnection.setContext(engineConnection); cr.channel.setContext(engineConnection); // Write any data from Proton to the network. writeToNetwork(engineConnection); } } else if (message instanceof CloseRequest) { CloseRequest cr = (CloseRequest)message; Connection protonConnection = cr.connection.connection; EngineConnection engineConnection = (EngineConnection)protonConnection.getContext(); engineConnection.heartbeatInterval = 0; if (engineConnection.timerPromise != null) { TimerPromiseImpl tmp = engineConnection.timerPromise; engineConnection.timerPromise = null; timer.cancel(tmp); } protonConnection.close(); //engineConnection.transport.close_head(); engineConnection.closeRequest = cr; writeToNetwork(engineConnection); } else if (message instanceof SendRequest) { SendRequest sr = (SendRequest)message; EngineConnection engineConnection = sr.connection; // Look to see if there is already a suitable sending link, and open one if there is not... Link link = sr.connection.connection.linkHead(EnumSet.of(EndpointState.ACTIVE), EnumSet.of(EndpointState.ACTIVE, EndpointState.UNINITIALIZED)); Sender linkSender; boolean linkOpened = false; while(true) { if (link == null) { linkSender = sr.connection.session.sender(sr.topic); // TODO: the Node.js client uses sender-xxx as a link name... Source source = new Source(); Target target = new Target(); source.setAddress(sr.topic); target.setAddress(sr.topic); linkSender.setSource(source); linkSender.setTarget(target); linkSender.open(); linkOpened = true; break; } if ((link instanceof Sender) && sr.topic.equals(link.getName())) { sr.topic.equals(link.getName()); linkSender = (Sender)link; break; } link = link.next(EnumSet.of(EndpointState.ACTIVE), EnumSet.of(EndpointState.ACTIVE, EndpointState.UNINITIALIZED)); } Delivery d = linkSender.delivery(String.valueOf(engineConnection.deliveryTag++).getBytes()); linkSender.send(sr.data, 0, sr.length); if (sr.qos == QOS.AT_MOST_ONCE) { d.settle(); } else { engineConnection.inProgressOutboundDeliveries.put(d, sr); } linkSender.advance(); engineConnection.drained = false; int delta = engineConnection.transport.head().remaining(); // If the link was also opened as part of processing this request then increase the // amount of data expected (as the linkSender.send() won't count against the amount of // data in transport.head() unless there is link credit - which there won't be until // the server responds to the link open). // TODO: track credit in this class so that we can detect this case and more accurately // calculate when the first message sent will have been flushed to the network. if (linkOpened) { delta += sr.length; } engineConnection.addInflightQos0(delta, new SendResponse(sr, null), sr.getSender(), this); writeToNetwork(engineConnection); } else if (message instanceof SubscribeRequest) { SubscribeRequest sr = (SubscribeRequest) message; EngineConnection engineConnection = sr.connection; if (engineConnection.subscriptionData.containsKey(sr.topic)) { // The client is already subscribed... // TODO: should this be an error condition? sr.getSender().tell(new SubscribeResponse(engineConnection, sr.topic), this); } else { Receiver linkReceiver = sr.connection.session.receiver(sr.topic); engineConnection.subscriptionData.put(sr.topic, new EngineConnection.SubscriptionData(sr.getSender(), sr.initialCredit, linkReceiver)); Source source = new Source(); source.setAddress(sr.topic); Target target = new Target(); target.setAddress(sr.topic); if (sr.ttl > 0) { source.setExpiryPolicy(TerminusExpiryPolicy.LINK_DETACH); source.setTimeout(new UnsignedInteger(sr.ttl)); target.setExpiryPolicy(TerminusExpiryPolicy.LINK_DETACH); target.setTimeout(new UnsignedInteger(sr.ttl)); } linkReceiver.setSource(source); linkReceiver.setTarget(target); if (sr.qos == QOS.AT_LEAST_ONCE) { linkReceiver.setSenderSettleMode(SenderSettleMode.UNSETTLED); linkReceiver.setReceiverSettleMode(ReceiverSettleMode.FIRST); } else { linkReceiver.setSenderSettleMode(SenderSettleMode.SETTLED); linkReceiver.setReceiverSettleMode(ReceiverSettleMode.FIRST); } linkReceiver.open(); linkReceiver.flow(sr.initialCredit); writeToNetwork(engineConnection); } } else if (message instanceof UnsubscribeRequest) { UnsubscribeRequest ur = (UnsubscribeRequest) message; EngineConnection engineConnection = ur.connection; EngineConnection.SubscriptionData sd = engineConnection.subscriptionData.get(ur.topic); if (ur.zeroTtl) { Target t = (Target)sd.receiver.getTarget(); t.setExpiryPolicy(TerminusExpiryPolicy.LINK_DETACH); t.setTimeout(new UnsignedInteger(0)); Source s = (Source)sd.receiver.getSource(); s.setTimeout(new UnsignedInteger(0)); s.setExpiryPolicy(TerminusExpiryPolicy.LINK_DETACH); } sd.receiver.close(); writeToNetwork(engineConnection); } else if (message instanceof DeliveryResponse) { DeliveryResponse dr = (DeliveryResponse)message; Delivery delivery = dr.request.delivery; delivery.settle(); EngineConnection engineConnection = (EngineConnection)dr.request.protonConnection.getContext(); EngineConnection.SubscriptionData subData = engineConnection.subscriptionData.get(dr.request.topicPattern); subData.settled++; subData.unsettled double available = subData.maxLinkCredit - subData.unsettled; if ((available / subData.settled) <= 1.25 || (subData.unsettled == 0 && subData.settled > 0)) { subData.receiver.flow(subData.settled); subData.settled = 0; } writeToNetwork(engineConnection); } else if (message instanceof WriteResponse) { // Message from network telling us that a write operation has completed... // Try to flush any pending data to the network... WriteResponse wr = (WriteResponse)message; EngineConnection engineConnection = (EngineConnection)wr.context; if (engineConnection != null) { engineConnection.bytesWritten += wr.amount; engineConnection.notifyInflightQos0(false); if (engineConnection.transport.pending() > 0) { writeToNetwork(engineConnection); } else if (!engineConnection.drained){ engineConnection.drained = true; engineConnection.requestor.tell(new DrainNotification(), this); } } } else if (message instanceof DataRead) { // Message from the network telling us that data has been read... DataRead dr = (DataRead)message; EngineConnection engineConnection = (EngineConnection)dr.channel.getContext(); while (dr.buffer.remaining() > 0) { int origLimit = dr.buffer.limit(); ByteBuffer tail = engineConnection.transport.tail(); int amount = Math.min(tail.remaining(), dr.buffer.remaining()); dr.buffer.limit(dr.buffer.position() + amount); tail.put(dr.buffer); dr.buffer.limit(origLimit); engineConnection.transport.process(); process(engineConnection.collector); } // Write any data from Proton to the network. writeToNetwork(engineConnection); } else if (message instanceof DisconnectResponse) { // Message from network telling us that it has completed our disconnect request. DisconnectResponse dr = (DisconnectResponse)message; CloseRequest cr = (CloseRequest)dr.context; cr.connection.dead = true; cr.connection.notifyInflightQos0(true); if (cr != null) { cr.getSender().tell(new CloseResponse(cr), this); } } else if (message instanceof ConnectionError) { // Message from network telling us that a error has occurred at the TCP/IP level. ConnectionError ce = (ConnectionError)message; EngineConnection engineConnection = (EngineConnection)ce.channel.getContext(); if (!engineConnection.dead) { engineConnection.heartbeatInterval = 0; if (engineConnection.timerPromise != null) { TimerPromiseImpl tmp = engineConnection.timerPromise; engineConnection.timerPromise = null; timer.cancel(tmp); } engineConnection.notifyInflightQos0(true); engineConnection.dead = true; engineConnection.transport.close_tail(); engineConnection.requestor.tell(new DisconnectNotification(engineConnection, ce.cause.getClass().toString(), ce.cause.getMessage()), this); } } else if (message instanceof PopResponse) { PopResponse pr = (PopResponse)message; EngineConnection engineConnection = (EngineConnection)pr.promise.getContext(); if (engineConnection.heartbeatInterval > 0) { TimerPromiseImpl promise = new TimerPromiseImpl(this, engineConnection); engineConnection.timerPromise = promise; timer.schedule(engineConnection.heartbeatInterval, promise); engineConnection.transport.writeEmptyFrame(); writeToNetwork(engineConnection); } } } // Drains any pending data from a Proton transport object onto the network private void writeToNetwork(EngineConnection engineConnection) { if (engineConnection.transport.pending() > 0) { ByteBuffer head = engineConnection.transport.head(); int amount = head.remaining(); ByteBuffer tmp = ByteBuffer.allocate(amount); // TODO: we could avoid allocating this if we were a bit smarter tmp.put(head); // about when we popped the transport... tmp.flip(); //ByteBuf buf = Unpooled.wrappedBuffer(head); engineConnection.transport.pop(amount); engineConnection.channel.write(tmp, new NetworkWritePromiseImpl(this, amount, engineConnection)); //nn.tell(new WriteRequest(connection, buf), this); } } // TODO: Proton 0.8 provides an Event.dispatch() method that could be used to replace this code... private void process(Collector collector) { while (collector.peek() != null) { Event event = collector.peek(); logger.debug("Processing event: {}", event.getType()); switch(event.getType()) { // TODO: could some of these be common'ed up? E.g. have one processEventConnection - which deals with both local and remote state changes case CONNECTION_BOUND: case CONNECTION_FINAL: case CONNECTION_INIT: case CONNECTION_UNBOUND: break; case CONNECTION_LOCAL_CLOSE: case CONNECTION_LOCAL_OPEN: processEventConnectionLocalState(event); break; case CONNECTION_REMOTE_CLOSE: case CONNECTION_REMOTE_OPEN: processEventConnectionRemoteState(event); break; case DELIVERY: processEventDelivery(event); break; case LINK_FINAL: case LINK_INIT: break; case LINK_FLOW: processEventLinkFlow(event); break; case LINK_LOCAL_CLOSE: case LINK_LOCAL_DETACH: case LINK_LOCAL_OPEN: processEventLinkLocalState(event); break; case LINK_REMOTE_CLOSE: case LINK_REMOTE_DETACH: case LINK_REMOTE_OPEN: processEventLinkRemoteState(event); break; case SESSION_FINAL: case SESSION_INIT: break; case SESSION_LOCAL_CLOSE: case SESSION_LOCAL_OPEN: processEventSessionLocalState(event); break; case SESSION_REMOTE_CLOSE: case SESSION_REMOTE_OPEN: processEventSessionRemoteState(event); break; case TRANSPORT: case TRANSPORT_CLOSED: case TRANSPORT_ERROR: case TRANSPORT_HEAD_CLOSED: case TRANSPORT_TAIL_CLOSED: processEventTransport(event); break; default: throw new IllegalStateException("Unknown event type: " + event.getType()); } collector.pop(); } } private void processEventConnectionLocalState(Event event) { logger.debug("CONNECTION_LOCAL_STATE: {}", event.getConnection()); // TODO: do we care about this event? } private void processEventConnectionRemoteState(Event event) { logger.debug("CONNECTION_REMOTE_STATE: {}", event.getConnection()); if (event.getConnection().getRemoteState() == EndpointState.CLOSED) { if (event.getConnection().getLocalState() != EndpointState.CLOSED) { EngineConnection engineConnection = (EngineConnection)event.getConnection().getContext(); engineConnection.heartbeatInterval = 0; if (engineConnection.timerPromise != null) { TimerPromiseImpl tmp = engineConnection.timerPromise; engineConnection.timerPromise = null; timer.cancel(tmp); } if (engineConnection.openRequest != null) { OpenRequest req = engineConnection.openRequest; engineConnection.openRequest = null; if (!engineConnection.dead) { engineConnection.notifyInflightQos0(true); engineConnection.dead = true; engineConnection.channel.close(null); String errorDescription = event.getConnection().getRemoteCondition().getDescription(); ClientException clientException = new ClientException(errorDescription == null ? "The server closed the connection without providing any error information." : errorDescription); req.getSender().tell(new OpenResponse(req, clientException), this); } } else { // TODO: should we also special case closeRequest in progress?? if (!engineConnection.dead) { engineConnection.notifyInflightQos0(true); engineConnection.dead = true; engineConnection.channel.close(null); String condition = event.getConnection().getRemoteCondition().getCondition().toString(); if (condition == null) condition = ""; String description = event.getConnection().getRemoteCondition().getDescription(); if (description == null) description = ""; engineConnection.requestor.tell(new DisconnectNotification(engineConnection, condition, description), this); } } } else { EngineConnection engineConnection = (EngineConnection)event.getConnection().getContext(); if (!engineConnection.dead) { engineConnection.notifyInflightQos0(true); engineConnection.dead = true; CloseRequest cr = engineConnection.closeRequest; NetworkClosePromiseImpl future = new NetworkClosePromiseImpl(this, cr); engineConnection.channel.close(future); // DisconnectRequest req = new DisconnectRequest(engineConnection.networkConnection); // req.setContext(cr); // NettyNetwork.getInstance().tell(req, this); } } } else if (event.getConnection().getRemoteState() == EndpointState.ACTIVE) { UnsignedInteger ui = event.getConnection().getRemoteIdleTimeOut(); if (ui != null) { EngineConnection engineConnection = (EngineConnection)event.getConnection().getContext(); engineConnection.heartbeatInterval = ui.longValue() / 2; engineConnection.timerPromise = new TimerPromiseImpl(this, engineConnection); timer.schedule(engineConnection.heartbeatInterval, engineConnection.timerPromise); } } } private void processEventDelivery(Event event) { EngineConnection engineConnection = (EngineConnection)event.getConnection().getContext(); Delivery delivery = event.getDelivery(); if (event.getLink() instanceof Sender) { SendRequest sr = engineConnection.inProgressOutboundDeliveries.remove(delivery); Exception exception = null; if (delivery.getRemoteState() instanceof Rejected) { Rejected rejected = (Rejected)delivery.getRemoteState(); // If we ever need to check the symbolic error code returned by the server - // this is accessible via the getCondition() method - e.g. // rejected.getError().getCondition() => 'MAX_TTL_EXCEEDED' String description = rejected.getError().getDescription(); if (description == null) { exception = new Exception("Message was rejected"); } else { exception = new Exception(description); } } else if (delivery.getRemoteState() instanceof Released) {; exception = new Exception("Message was released"); } else if (delivery.getRemoteState() instanceof Modified) { exception = new Exception("Message was modified"); } sr.getSender().tell(new SendResponse(sr, exception), this); } else if (delivery.isReadable() && !delivery.isPartial()) { // Assuming link instanceof Receiver... Receiver receiver = (Receiver)event.getLink(); int amount = delivery.pending(); byte[] data = new byte[amount]; receiver.recv(data, 0, amount); receiver.advance(); EngineConnection.SubscriptionData subData = engineConnection.subscriptionData.get(event.getLink().getName()); subData.unsettled++; QOS qos = delivery.remotelySettled() ? QOS.AT_MOST_ONCE : QOS.AT_LEAST_ONCE; subData.subscriber.tell(new DeliveryRequest(data, qos, event.getLink().getName(), delivery, event.getConnection()), this); } } private void processEventLinkFlow(Event event) { } private void processEventLinkLocalState(Event event) { Link link = event.getLink(); logger.debug("LINK_LOCAL {} {} {}", link, link.getLocalState(), link.getRemoteState()); } private void processEventLinkRemoteState(Event event) { Link link = event.getLink(); logger.debug("LINK_REMOTE {} {} {}", link, link.getLocalState(), link.getRemoteState()); if (link instanceof Receiver) { if (link.getLocalState() == EndpointState.ACTIVE && link.getRemoteState() == EndpointState.ACTIVE) { // Receiver link open has been ack'ed by server. EngineConnection engineConnection = (EngineConnection)event.getConnection().getContext(); EngineConnection.SubscriptionData sd = engineConnection.subscriptionData.get(link.getName()); sd.subscriber.tell(new SubscribeResponse(engineConnection, link.getName()), this); } else if (link.getRemoteState() == EndpointState.CLOSED) { if (link.getLocalState() != EndpointState.CLOSED) { link.close(); } link.free(); EngineConnection engineConnection = (EngineConnection)event.getConnection().getContext(); EngineConnection.SubscriptionData sd = engineConnection.subscriptionData.remove(link.getName()); // TODO: can we assume that getRemoteConnection will be null if there is no error? sd.subscriber.tell(new UnsubscribeResponse(engineConnection, link.getName(), link.getRemoteCondition() != null), this); } } else if (link instanceof Sender) { if (link.getRemoteState() == EndpointState.CLOSED) { if (link.getLocalState() != EndpointState.CLOSED) { // TODO: trace an error - as the server has closed our sending link unexpectedly... link.close(); } link.free(); } } } private void processEventSessionLocalState(Event event) { logger.debug("processEventSessionLocalState ", event.getSession()); // TODO: do we care about this event? } private void processEventSessionRemoteState(Event event) { logger.debug("processEventSessionRemoteState", event.getSession()); if (event.getSession().getLocalState() == EndpointState.ACTIVE && event.getSession().getRemoteState() == EndpointState.ACTIVE) { // First session has opened on the connection EngineConnection engineConnection = (EngineConnection)event.getConnection().getContext(); OpenRequest req = engineConnection.openRequest; engineConnection.openRequest = null; engineConnection.requestor.tell(new OpenResponse(req, engineConnection), this); } // TODO: should reject remote party trying to establish sessions with us } private void processEventTransport(Event event) { logger.debug("processEventTransport", event.getTransport()); } }
package com.sun.star.comp.Calc.NLPSolver; import com.sun.star.awt.XReschedule; import com.sun.star.beans.Property; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertyChangeListener; import com.sun.star.beans.XPropertySetInfo; import com.sun.star.beans.XVetoableChangeListener; import com.sun.star.chart.XChartDataArray; import com.sun.star.container.XIndexAccess; import com.sun.star.document.XEmbeddedObjectSupplier; import com.sun.star.frame.XModel; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.IndexOutOfBoundsException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lib.uno.helper.WeakBase; import com.sun.star.sheet.SolverConstraint; import com.sun.star.sheet.SolverConstraintOperator; import com.sun.star.sheet.XSpreadsheet; import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.sheet.XSpreadsheets; import com.sun.star.table.CellAddress; import com.sun.star.table.CellContentType; import com.sun.star.table.CellRangeAddress; import com.sun.star.table.XCell; import com.sun.star.table.XTableChartsSupplier; import com.sun.star.uno.Exception; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import java.util.ArrayList; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; public abstract class BaseNLPSolver extends WeakBase implements com.sun.star.lang.XLocalizable, com.sun.star.sheet.XSolver, com.sun.star.sheet.XSolverDescription, com.sun.star.beans.XPropertySet, com.sun.star.beans.XPropertySetInfo { protected final XComponentContext m_xContext; private final String m_name; private final ArrayList<PropertyInfo> m_properties = new ArrayList<PropertyInfo>(); private final HashMap<String, PropertyInfo> m_propertyMap = new HashMap<String, PropertyInfo>(); private com.sun.star.lang.Locale m_locale = new com.sun.star.lang.Locale(); private final ResourceManager resourceManager; public BaseNLPSolver(XComponentContext xContext, String name) { m_xContext = xContext; m_name = name; XMultiComponentFactory componentFactory = xContext.getServiceManager(); try { Object toolkit = componentFactory.createInstanceWithContext("com.sun.star.awt.Toolkit", xContext); m_xReschedule = UnoRuntime.queryInterface(XReschedule.class, toolkit); } catch (Exception ex) { Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); } resourceManager = new ResourceManager(xContext, "com.sun.star.comp.Calc.NLPSolver", "/locale", "NLPSolverCommon"); registerProperty(m_assumeNonNegative); } protected void registerProperty(PropertyInfo property) { m_properties.add(property); m_propertyMap.put(property.getProperty().Name, property); property.localize(resourceManager); } // com.sun.star.lang.XLocalizable: public void setLocale(com.sun.star.lang.Locale eLocale) { m_locale = eLocale; } public com.sun.star.lang.Locale getLocale() { return m_locale; } // com.sun.star.sheet.XSolver: private XSpreadsheetDocument m_document; private XModel m_xModel; protected XReschedule m_xReschedule; private CellAddress m_objective; protected CellAddress[] m_variables; protected SolverConstraint[] m_constraints; protected ExtSolverConstraint[] m_extConstraints; protected boolean m_maximize; protected int m_variableCount; protected int m_constraintCount; protected int m_cellRangeCount; protected XCell m_objectiveCell; protected XCell[] m_variableCells; protected XChartDataArray[] m_cellRangeData; protected CellMap[] m_variableMap; protected double[][][] m_variableData; protected double m_functionValue; protected double[] m_currentParameters; protected boolean m_success = false; public XSpreadsheetDocument getDocument() { return m_document; } public void setDocument(XSpreadsheetDocument document) { m_document = document; m_xModel = UnoRuntime.queryInterface(XModel.class, m_document); } public CellAddress getObjective() { return m_objective; } public void setObjective(CellAddress objective) { m_objective = objective; m_objectiveCell = getCell(objective); } public CellAddress[] getVariables() { if (m_variables == null) return new CellAddress[0]; //Workaround for basic scripts; otherwise //setting the Variables property fails. return m_variables; } private class RowInfo { private short Sheet; private int Row; private int StartCol; private int EndCol; private RowInfo(short sheet, int row) { Sheet = sheet; Row = row; } private CellRangeAddress getCellRangeAddress(int lastRow) { CellRangeAddress result = new CellRangeAddress(); result.Sheet = Sheet; result.StartColumn = StartCol; result.StartRow = Row; result.EndColumn = EndCol; result.EndRow = lastRow; return result; } } protected class CellMap { protected int Range; protected int Col; protected int Row; } protected class ExtSolverConstraint { public XCell Left; public SolverConstraintOperator Operator; public XCell Right; public double Data; private ExtSolverConstraint(XCell left, SolverConstraintOperator operator, Object right) { this.Left = left; this.Operator = operator; this.Right = null; if (right instanceof Number) { this.Data = ((Number)right).doubleValue(); } else if (right instanceof CellAddress) { XCell cell = getCell((CellAddress)right); if (cell.getType() == CellContentType.VALUE) { this.Data = cell.getValue(); } else { this.Right = cell; this.Data = 0.0; } } } public double getLeftValue() { if (this.Right == null) { return this.Left.getValue(); } else { return this.Left.getValue() - this.Right.getValue(); } } } public void setVariables(CellAddress[] variables) { m_variables = variables; m_variableCount = variables.length; //update cell references m_variableCells = new XCell[m_variableCount]; m_currentParameters = new double[m_variableCount]; for (int i = 0; i < m_variableCount; i++) { m_variableCells[i] = getCell(variables[i]); m_currentParameters[i] = m_variableCells[i].getValue(); } //parse for cell ranges (under the assumption, that the cells are ordered //left to right, top to bottom for each cell range m_variableMap = new CellMap[m_variableCount]; m_variableData = new double[m_variableCount][][]; ArrayList<RowInfo> rows = new ArrayList<RowInfo>(); RowInfo currentRow = null; int lastSheet = -1, lastRow = -1; for (int i = 0; i < m_variableCount; i++) { if (lastSheet == m_variables[i].Sheet && lastRow == m_variables[i].Row && currentRow.EndCol == m_variables[i].Column - 1) currentRow.EndCol++; else { currentRow = new RowInfo(m_variables[i].Sheet, m_variables[i].Row); currentRow.StartCol = m_variables[i].Column; currentRow.EndCol = m_variables[i].Column; rows.add(currentRow); lastSheet = currentRow.Sheet; lastRow = currentRow.Row; } } ArrayList<CellRangeAddress> cellRangeAddresses = new ArrayList<CellRangeAddress>(); if (rows.size() > 0) { RowInfo firstRow = rows.get(0); int offset = 0; for (int i = 1; i < rows.size(); i++) { currentRow = rows.get(i); if (currentRow.Sheet != firstRow.Sheet || currentRow.Row != firstRow.Row + offset + 1 || currentRow.StartCol != firstRow.StartCol || currentRow.EndCol != firstRow.EndCol) { cellRangeAddresses.add(firstRow.getCellRangeAddress(firstRow.Row + offset)); firstRow = currentRow; offset = 0; } else { offset++; } } cellRangeAddresses.add(firstRow.getCellRangeAddress(firstRow.Row + offset)); } m_cellRangeCount = cellRangeAddresses.size(); m_cellRangeData = new XChartDataArray[m_cellRangeCount]; int varID = 0; //get cell range data and map the variables to their new location for (int i = 0; i < m_cellRangeCount; i++) { for (int y = 0; y <= cellRangeAddresses.get(i).EndRow - cellRangeAddresses.get(i).StartRow; y++) for (int x = 0; x <= cellRangeAddresses.get(i).EndColumn - cellRangeAddresses.get(i).StartColumn; x++) { CellMap map = new CellMap(); m_variableMap[varID++] = map; map.Range = i; map.Col = x; map.Row = y; } m_cellRangeData[i] = getChartDataArray(cellRangeAddresses.get(i)); m_variableData[i] = m_cellRangeData[i].getData(); } } public SolverConstraint[] getConstraints() { if (m_constraints == null) return new SolverConstraint[0]; //Workaround for basic scripts; otherwise //setting the Constraints property fails. return m_constraints; } public void setConstraints(SolverConstraint[] constraints) { m_constraints = constraints; m_constraintCount = constraints.length; //update cell references m_extConstraints = new ExtSolverConstraint[m_constraintCount]; for (int i = 0; i < m_constraintCount; i++) { m_extConstraints[i] = new ExtSolverConstraint( getCell(constraints[i].Left), constraints[i].Operator, constraints[i].Right); } } public boolean getMaximize() { return m_maximize; } public void setMaximize(boolean maximize) { m_maximize = maximize; } public boolean getSuccess() { return m_success; } public double getResultValue() { return m_functionValue; } public double[] getSolution() { return m_currentParameters; } private XCell getCell(CellAddress cellAddress) { return getCell(cellAddress.Column, cellAddress.Row, cellAddress.Sheet); } private XCell getCell(int col, int row, int sheet) { try { XSpreadsheets xSpreadsheets = m_document.getSheets(); XIndexAccess xSheetIndex = UnoRuntime.queryInterface(XIndexAccess.class, xSpreadsheets); XSpreadsheet xSpreadsheet = UnoRuntime.queryInterface(XSpreadsheet.class, xSheetIndex.getByIndex(sheet)); return xSpreadsheet.getCellByPosition(col, row); } catch (IndexOutOfBoundsException ex) { Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); } catch (WrappedTargetException ex) { Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); } return null; } private XChartDataArray getChartDataArray(CellRangeAddress cellRangeAddress) { return getChartDataArray(cellRangeAddress.Sheet, cellRangeAddress.StartColumn, cellRangeAddress.StartRow, cellRangeAddress.EndColumn, cellRangeAddress.EndRow); } private XChartDataArray getChartDataArray(int sheet, int startCol, int startRow, int endCol, int endRow) { try { XSpreadsheets xSpreadsheets = m_document.getSheets(); XIndexAccess xSheetIndex = UnoRuntime.queryInterface(XIndexAccess.class, xSpreadsheets); XSpreadsheet xSpreadsheet = UnoRuntime.queryInterface(XSpreadsheet.class, xSheetIndex.getByIndex(sheet)); return UnoRuntime.queryInterface(XChartDataArray.class, xSpreadsheet.getCellRangeByPosition(startCol, startRow, endCol, endRow)); } catch (IndexOutOfBoundsException ex) { Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); } catch (WrappedTargetException ex) { Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); } return null; } protected PropertyInfo<Boolean> m_assumeNonNegative = new PropertyInfo<Boolean>("AssumeNonNegative", false, "Assume Non-Negative Variables"); protected void initializeSolve() { lockDocument(); } protected void finalizeSolve() { unlockDocument(); } public String getComponentDescription() { return m_name; } public String getStatusDescription() { return ""; } public String getPropertyDescription(String property) { PropertyInfo propertyInfo = m_propertyMap.get(property); if (propertyInfo != null) return propertyInfo.getDescription(); else return ""; } // com.sun.star.beans.XPropertySet: public XPropertySetInfo getPropertySetInfo() { return this; } public void setPropertyValue(String property, Object value) throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException { PropertyInfo propertyInfo = m_propertyMap.get(property); if (propertyInfo != null) propertyInfo.setValue(value); else throw new UnknownPropertyException(); } public Object getPropertyValue(String property) throws UnknownPropertyException, WrappedTargetException { PropertyInfo propertyInfo = m_propertyMap.get(property); if (propertyInfo != null) return propertyInfo.getValue(); else throw new UnknownPropertyException(); } public void addPropertyChangeListener(String property, XPropertyChangeListener listener) throws UnknownPropertyException, WrappedTargetException { throw new UnsupportedOperationException("Not supported yet."); } public void removePropertyChangeListener(String property, XPropertyChangeListener listener) throws UnknownPropertyException, WrappedTargetException { throw new UnsupportedOperationException("Not supported yet."); } public void addVetoableChangeListener(String property, XVetoableChangeListener listener) throws UnknownPropertyException, WrappedTargetException { throw new UnsupportedOperationException("Not supported yet."); } public void removeVetoableChangeListener(String property, XVetoableChangeListener listener) throws UnknownPropertyException, WrappedTargetException { throw new UnsupportedOperationException("Not supported yet."); } // com.sun.star.beans.XPropertySetInfo: public Property[] getProperties() { int propertyCount = m_properties.size(); Property[] properties = new Property[propertyCount]; for (int i = 0; i < propertyCount; i++) properties[i] = m_properties.get(i).getProperty(); return properties; } public Property getPropertyByName(String property) throws UnknownPropertyException { PropertyInfo propertyInfo = m_propertyMap.get(property); if (propertyInfo != null) return propertyInfo.getProperty(); else throw new UnknownPropertyException(); } public boolean hasPropertyByName(String property) { return m_propertyMap.containsKey(property); } // <editor-fold defaultstate="collapsed" desc="Helper functions"> private void lockDocument(boolean lock) { if (lock) m_xModel.lockControllers(); else m_xModel.unlockControllers(); try { XIndexAccess xSpreadsheets = UnoRuntime.queryInterface(XIndexAccess.class, m_document.getSheets()); int sheets = xSpreadsheets.getCount(); for (int i = 0; i < sheets; i++) { Object sheet = xSpreadsheets.getByIndex(i); XTableChartsSupplier xTableChartsSupplier = UnoRuntime.queryInterface(XTableChartsSupplier.class, sheet); XIndexAccess xCharts = UnoRuntime.queryInterface(XIndexAccess.class, xTableChartsSupplier.getCharts()); int charts = xCharts.getCount(); for (int j = 0; j < charts; j++) { Object chart = xCharts.getByIndex(j); XEmbeddedObjectSupplier xChartObjects = UnoRuntime.queryInterface(XEmbeddedObjectSupplier.class, chart); XModel xChartModel = UnoRuntime.queryInterface(XModel.class, xChartObjects.getEmbeddedObject()); if (lock) xChartModel.lockControllers(); else xChartModel.unlockControllers(); } } } catch (Exception ex) { Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); } } protected void lockDocument() { lockDocument(true); } protected void unlockDocument() { lockDocument(false); } public static String nanoTimeToString(ResourceManager resourceManager, long nanoseconds) { if (nanoseconds < 0) return null; //shouldn't happen .... but if it does, throw an error! if (nanoseconds == 0) return "0"; if (nanoseconds < 1000) return nanoseconds + " " + resourceManager.getLocalizedString("Time.Nanoseconds", "Nanoseconds"); double microseconds = (double) nanoseconds / 1000; if (microseconds < 1000) return String.format("%.2f %s", microseconds, resourceManager.getLocalizedString("Time.Microseconds", "Microseconds")); double milliseconds = microseconds / 1000; if (milliseconds < 1000) return String.format("%.2f %s", milliseconds, resourceManager.getLocalizedString("Time.Milliseconds", "Milliseconds")); double seconds = milliseconds / 1000; if (seconds < 90) return String.format("%.2f %s", seconds, resourceManager.getLocalizedString("Time.Seconds", "Seconds")); long minutes = (long) seconds / 60; seconds -= minutes * 60; long hours = minutes / 60; minutes -= hours * 60; long days = hours / 24; hours -= days * 24; if (days > 0) return String.format("%d %s, %d %s", days, resourceManager.getLocalizedString(String.format("Time.Day%s", days == 1 ? "" : "s"), "Days"), hours, resourceManager.getLocalizedString(String.format("Time.Hour%s", hours == 1 ? "" : "s"), "Hours")); if (hours > 0) return String.format("%d %s, %d %s", hours, resourceManager.getLocalizedString(String.format("Time.Hour%s", hours == 1 ? "" : "s"), "Hours"), minutes, resourceManager.getLocalizedString(String.format("Time.Minute%s", minutes == 1 ? "" : "s"), "Minutes")); if (minutes > 0) return String.format("%d %s, %.0f %s", minutes, resourceManager.getLocalizedString(String.format("Time.Minute%s", minutes == 1 ? "" : "s"), "Minutes"), Math.floor(seconds), resourceManager.getLocalizedString(String.format("Time.Second%s", Math.floor(seconds) == 1 ? "" : "s"), "Seconds")); return String.format("%.2f %s", seconds, resourceManager.getLocalizedString("Time.Seconds", "Seconds")); } // </editor-fold> }
package eu.chargetime.ocpp; import eu.chargetime.ocpp.model.SessionInformation; import eu.chargetime.ocpp.wss.WssFactoryBuilder; import org.java_websocket.WebSocket; import org.java_websocket.drafts.Draft; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class WebSocketListener implements Listener { private static final Logger logger = LoggerFactory.getLogger(WebSocketListener.class); private static final int TIMEOUT_IN_MILLIS = 10000; private final IServerSessionFactory sessionFactory; private final List<Draft> drafts; private final JSONConfiguration configuration; private volatile WebSocketServer server; private WssFactoryBuilder wssFactoryBuilder; private final Map<WebSocket, WebSocketReceiver> sockets; private volatile boolean closed = true; private boolean handleRequestAsync; public WebSocketListener(IServerSessionFactory sessionFactory, JSONConfiguration configuration, Draft... drafts) { this.sessionFactory = sessionFactory; this.configuration = configuration; this.drafts = Arrays.asList(drafts); this.sockets = new ConcurrentHashMap<>(); } public WebSocketListener(IServerSessionFactory sessionFactory, Draft... drafts) { this(sessionFactory, JSONConfiguration.get(), drafts); } @Override public void open(String hostname, int port, ListenerEvents handler) { server = new WebSocketServer(new InetSocketAddress(hostname, port), drafts) { @Override public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) { logger.debug("On connection open (resource descriptor: {})", clientHandshake.getResourceDescriptor()); WebSocketReceiver receiver = new WebSocketReceiver( new WebSocketReceiverEvents() { @Override public boolean isClosed() { return closed; } @Override public void relay(String message) { webSocket.send(message); } } ); sockets.put(webSocket, receiver); SessionInformation information = new SessionInformation.Builder() .Identifier(clientHandshake.getResourceDescriptor()) .InternetAddress(webSocket.getRemoteSocketAddress()).build(); handler.newSession(sessionFactory.createSession(new JSONCommunicator(receiver)), information); } @Override public void onClose(WebSocket webSocket, int code, String reason, boolean remote) { logger.debug("On connection close (resource descriptor: {}, code: {}, reason: {}, remote: {})", webSocket.getResourceDescriptor(), code, reason, remote); sockets.get(webSocket).disconnect(); sockets.remove(webSocket); } @Override public void onMessage(WebSocket webSocket, String message) { sockets.get(webSocket).relay(message); } @Override public void onError(WebSocket webSocket, Exception ex) { String resourceDescriptor = (webSocket != null) ? webSocket.getResourceDescriptor() : "not defined (webSocket is null)"; if(ex instanceof ConnectException) { logger.error("On error (resource descriptor: " + resourceDescriptor + ") triggered caused by:", ex); } else { logger.error("On error (resource descriptor: " + resourceDescriptor + ") triggered:", ex); } } @Override public void onStart() { logger.debug("Server socket bound"); } }; if(wssFactoryBuilder != null) { server.setWebSocketFactory(wssFactoryBuilder.build()); } configure(); server.start(); closed = false; } void configure() { server.setReuseAddr( configuration.getParameter(JSONConfiguration.REUSE_ADDR_PARAMETER, true)); server.setTcpNoDelay( configuration.getParameter(JSONConfiguration.TCP_NO_DELAY_PARAMETER, false)); server.setConnectionLostTimeout( configuration.getParameter(JSONConfiguration.PING_INTERVAL_PARAMETER, 60)); } void enableWSS(WssFactoryBuilder wssFactoryBuilder) { if(server != null) { throw new IllegalStateException("Cannot enable WSS on already running server"); } this.wssFactoryBuilder = wssFactoryBuilder; } @Override public void close() { if(server == null) { return; } try { sockets.clear(); server.stop(TIMEOUT_IN_MILLIS); } catch (InterruptedException e) { // Do second try try { server.stop(); } catch (IOException | InterruptedException ex) { logger.error("Failed to close listener", ex); } } finally { closed = true; server = null; } } @Override public boolean isClosed() { return closed; } @Override public void setAsyncRequestHandler(boolean async) { this.handleRequestAsync = async; } }
package com.olmatix.ui.fragment; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AlertDialog; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.olmatix.adapter.OlmatixAdapter; import com.olmatix.database.dbHelper; import com.olmatix.database.dbNode; import com.olmatix.database.dbNodeRepo; import com.olmatix.helper.OnStartDragListener; import com.olmatix.helper.SimpleItemTouchHelperCallback; import com.olmatix.lesjaw.olmatix.R; import com.olmatix.model.NodeModel; import com.olmatix.service.OlmatixService; import com.olmatix.utils.Connection; import org.eclipse.paho.client.mqttv3.IMqttActionListener; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.util.Strings; import org.w3c.dom.Node; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.olmatix.database.dbNode.KEY_ADDING; import static com.olmatix.database.dbNode.KEY_FWNAME; import static com.olmatix.database.dbNode.KEY_FWVERSION; import static com.olmatix.database.dbNode.KEY_ICON; import static com.olmatix.database.dbNode.KEY_LOCALIP; import static com.olmatix.database.dbNode.KEY_NAME; import static com.olmatix.database.dbNode.KEY_NODES; import static com.olmatix.database.dbNode.KEY_ONLINE; import static com.olmatix.database.dbNode.KEY_OTA; import static com.olmatix.database.dbNode.KEY_RESET; import static com.olmatix.database.dbNode.KEY_SIGNAL; import static com.olmatix.database.dbNode.KEY_UPTIME; import static com.olmatix.database.dbNode.TABLE; public class Installed_Node extends Fragment implements OnStartDragListener { private View mView; private List<NodeModel> nodeList = new ArrayList<>(); private RecyclerView mRecycleView; private FloatingActionButton mFab; private AlertDialog.Builder alertDialog; private View view; private static OlmatixAdapter adapter; private TextView etTopic,version; ImageView icon_node; private RecyclerView.LayoutManager layoutManager; private static ArrayList<NodeModel> data; private Paint p = new Paint(); private ItemTouchHelper mItemTouchHelper; HashMap<String,String> messageReceive = new HashMap<>(); public static dbNodeRepo dbNodeRepo; private NodeModel nodeModel; private String inputResult; private String NodeID; private String mMessage; private String NodeSplit; int flag =0; int flagNodeAdd =0; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mView = inflater.inflate(R.layout.frag_installed_node, container, false); return mView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); data = new ArrayList<>(); dbNodeRepo = new dbNodeRepo(getActivity()); nodeModel = new NodeModel(); initDialog(); setupView(); onClickListener(); } private void onClickListener() { mFab.setOnClickListener(mFabClickListener()); } private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String device = intent.getStringExtra("MQTT devices"); String message = intent.getStringExtra("MQTT message"); Log.d("receiver", "Got message : " + device + " : "+ message); NodeSplit = device; String[] outputDevices = NodeSplit.split("/"); NodeID = outputDevices[1]; mMessage = message; device = device.substring(device.indexOf("$")+1,device.length()); messageReceive.put(device,message); if (flagNodeAdd==1) { addCheckValidation(); } saveandpersist(); } }; private void addCheckValidation(){ if(messageReceive.containsKey("online")){ Log.d("addCheckValid 1", "Passed"); if (inputResult.equals(NodeID)){ Log.d("addCheckValid 2", "Passed"); if (mMessage.equals("true")){ Log.d("addCheckValid 3", "Passed"); Log.d("Running = ", "saveIfOnline"); saveIfOnline(); } } } } private void saveIfOnline() { if(messageReceive.containsKey("online")) { for(int i=0; i<dbNodeRepo.getNodeList().size(); i++) { if (data.get(i).getNid().equals(NodeID)) { Toast.makeText(getActivity(), "You already have this Node ID", Toast.LENGTH_LONG).show(); flag =1; Log.d("saveIfOnline", "You already have this Node, DB = " +i +" flag = " +flag); } } if(flag != 1) { Toast.makeText(getActivity(),"Add Node Successfully",Toast.LENGTH_LONG).show(); Log.d("saveIfOnline", "Add Node success, " +" flag = " +flag); nodeModel.setNid(NodeID); nodeModel.setOnline(messageReceive.get("online")); dbNodeRepo.insertDb(nodeModel); messageReceive.clear(); flagNodeAdd=0; doSubcribeIfOnline(); } } } private void doSubcribeIfOnline(){ String topic = "devices/" + inputResult + "/ int qos = 1; try { IMqttToken subToken = Connection.getClient().subscribe(topic, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { messageReceive.put("NodeId",inputResult); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } private void saveandpersist() { for(int i=0; i<dbNodeRepo.getNodeList().size(); i++) { if (data.get(i).getNid().equals(NodeID)) { String gNID = data.get(i).getNid(); Log.d("DB", "NodeID = " + NodeID + " + " + gNID); Log.d("DB", "index = " + i); Log.d("SaveandPersist", "Executed"); nodeModel.setNid(NodeID); nodeModel.setOnline(messageReceive.get("online")); nodeModel.setNodes(messageReceive.get("nodes")); nodeModel.setName(messageReceive.get("name")); nodeModel.setLocalip(messageReceive.get("localip")); nodeModel.setFwName(messageReceive.get("fwname")); nodeModel.setFwVersion(messageReceive.get("fwversion")); nodeModel.setSignal(messageReceive.get("signal")); nodeModel.setUptime(messageReceive.get("uptime")); nodeModel.setReset(messageReceive.get("reset")); nodeModel.setOta(messageReceive.get("ota")); dbNodeRepo.update(nodeModel); adapter = new OlmatixAdapter(dbNodeRepo.getNodeList()); mRecycleView.setAdapter(adapter); data.clear(); data.addAll(dbNodeRepo.getNodeList()); messageReceive.clear(); } } } @Override public void onStart() { Intent i = new Intent(getActivity(), OlmatixService.class); getActivity().startService(i); LocalBroadcastManager.getInstance(getActivity()).registerReceiver( mMessageReceiver, new IntentFilter("messageMQTT")); super.onStart(); } private View.OnClickListener mFabClickListener() { return new View.OnClickListener() { @Override public void onClick(View v) { final EditText mEditText = new EditText(getContext()); new AlertDialog.Builder(getContext()) .setTitle("Add Node") .setMessage("Please type Olmatix product ID!") .setView(mEditText) .setPositiveButton("ADD", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { inputResult =mEditText.getText().toString(); String topic = "devices/" + inputResult + "/$online"; int qos = 1; try { IMqttToken subToken = Connection.getClient().subscribe(topic, qos); subToken.setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { messageReceive.put("NodeId",inputResult); flagNodeAdd = 1; } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { } }); } catch (MqttException e) { e.printStackTrace(); } } }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }; } private void setupView() { mRecycleView = (RecyclerView) mView.findViewById(R.id.rv); mFab = (FloatingActionButton) mView.findViewById(R.id.fab); mRecycleView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(mView.getContext()); mRecycleView.setLayoutManager(layoutManager); mRecycleView.setItemAnimator(new DefaultItemAnimator()); data.addAll(dbNodeRepo.getNodeList()); adapter = new OlmatixAdapter(dbNodeRepo.getNodeList()); mRecycleView.setAdapter(adapter); initSwipe(); ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(adapter); mItemTouchHelper = new ItemTouchHelper(callback); mItemTouchHelper.attachToRecyclerView(mRecycleView); } private void initDialog(){ alertDialog = new AlertDialog.Builder(getActivity()); LayoutInflater myLayout = LayoutInflater.from(getActivity()); view = myLayout.inflate(R.layout.dialog_layout,null); alertDialog.setView(view); alertDialog.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { adapter.notifyDataSetChanged(); dialog.dismiss(); } }); etTopic = (TextView) view.findViewById(R.id.et_topic); version = (TextView) view.findViewById(R.id.version); icon_node = (ImageView) view.findViewById(R.id.icon_node); } private void initSwipe(){ ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { int position = viewHolder.getAdapterPosition(); if (direction == ItemTouchHelper.LEFT){ adapter.removeItem(position); } else { //removeView(); etTopic.setText(data.get(position).getName()); version.setText(data.get(position).getFwVersion()); icon_node.setImageResource(R.drawable.olmatixlogo); alertDialog.show(); } } @Override public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { Bitmap icon; if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){ View itemView = viewHolder.itemView; float height = (float) itemView.getBottom() - (float) itemView.getTop(); float width = height / 3; if(dX > 0){ p.setColor(Color.parseColor("#388E3C")); RectF background = new RectF((float) itemView.getLeft(), (float) itemView.getTop(), dX,(float) itemView.getBottom()); c.drawRect(background,p); icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_edit_white); RectF icon_dest = new RectF((float) itemView.getLeft() + width ,(float) itemView.getTop() + width,(float) itemView.getLeft()+ 2*width,(float)itemView.getBottom() - width); c.drawBitmap(icon,null,icon_dest,p); } else { p.setColor(Color.parseColor("#D32F2F")); RectF background = new RectF((float) itemView.getRight() + dX, (float) itemView.getTop(),(float) itemView.getRight(), (float) itemView.getBottom()); c.drawRect(background,p); icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_delete_white); RectF icon_dest = new RectF((float) itemView.getRight() - 2*width ,(float) itemView.getTop() + width,(float) itemView.getRight() - width,(float)itemView.getBottom() - width); c.drawBitmap(icon,null,icon_dest,p); } } super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); itemTouchHelper.attachToRecyclerView(mRecycleView); } @Override public void onStartDrag(RecyclerView.ViewHolder viewHolder) { mItemTouchHelper.startDrag(viewHolder); } }
package openmaple.net.common.utils; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation that denotes a parameter or field as being unsigned. * * @author Aaron Weiss * @version 1.0.0 * @since 2/10/14 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER, ElementType.FIELD}) public @interface Unsigned { }
import org.junit.Before; import org.junit.Test; import org.sdmlib.openbank.Account; import org.sdmlib.openbank.JsonPersistency; import org.sdmlib.openbank.Transaction; import org.sdmlib.openbank.User; import org.sdmlib.storyboards.Storyboard; import java.util.Date; import static org.junit.Assert.*; public class Test_Improving_Backend_Functionality { Transaction trans; @Before public void setUp() throws Exception{ // initiate transaction class trans = new org.sdmlib.openbank.Transaction(); } @Test(expected=IllegalArgumentException.class) // this will test for negative value in setAmount public void testSetAmountNegative()throws Exception{ trans.setAmount(-5); } @Test // setAmount and get the amount to make sure you get the correct amount public void setgetAmount(){ trans.setAmount(50.55); assertTrue(50.55 == trans.getAmount()); } @Test // setDate and get the date to make sure you get the correct date public void setgetDate(){ Date dt = new Date("03/19/2017"); // set date trans.setCreationdate(dt); assertTrue(dt == trans.getCreationdate()); } @Test(expected=IllegalArgumentException.class) public void setgetDateTestNULL(){ Date dt = new Date(null); // set date with null trans.setCreationdate(dt); } @Test // setNote and get the note to make sure you get the correct note public void setgetNote(){ String nt = "Testing Notes.."; // set note trans.setNote(nt); assertTrue(nt == trans.getNote()); } @Test // setNote and get the note to make sure you get the correct value public void setgetNoteNULL(){ String nt = null; // set note trans.setNote(nt); assertTrue(nt == trans.getNote()); } @Test // setNote and get the note to make sure you get the correct value public void setgetNoteEmpty(){ String nt = " "; // set note trans.setNote(nt); assertTrue(nt == trans.getNote()); } @Test(expected=IllegalArgumentException.class) public void setNullTransType(){ // set type trans.setTransType(null); } @Test // setTrans Type and get the type to make sure you get the correct type public void setgetTransTypeWithdraw(){ // set type trans.setTransType(org.sdmlib.openbank.TransactionTypeEnum.Withdraw); assertTrue(org.sdmlib.openbank.TransactionTypeEnum.Withdraw == trans.getTransType()); } @Test // setTrans Type and get the type to make sure you get the correct type public void setgetTransTypeDeposit(){ // set type trans.setTransType(org.sdmlib.openbank.TransactionTypeEnum.Deposit); assertTrue(org.sdmlib.openbank.TransactionTypeEnum.Deposit == trans.getTransType()); } // JSON Test Case @Test(expected=NullPointerException.class) // set user with null should throws NullPointerException exception public void testtoJsonWithNULL() { Account accnt = new Account(); JsonPersistency json = new JsonPersistency(); Transaction trans = new Transaction(); User usr1 = null; /* new User() .withName("tina") .withUserID("tina1"); */ accnt = new Account() .withOwner(usr1) .withAccountnum(1); Date dt = new Date("03/19/2017"); Date dtime = new Date("03/19/2017 13:13:26"); trans.setAmount(50.00); // set date trans.setCreationdate(dt); // set time //trans.setTime(dtime); trans.setNote("Deposit Trans 1"); Account accountBeforeJson = new Account().withOwner(usr1) .withBalance(550.00).withCreationdate(dt) .withCredit(trans); /* accountBeforeJson.withBalance(570.00).withCreationdate(dt); accountBeforeJson.withCredit(trans2); accountBeforeJson.withBalance(540.00).withCreationdate(dt); accountBeforeJson.withDebit(trans3); */ json.toJson(accountBeforeJson); } @Test(expected=NullPointerException.class) // set user with null should throws NullPointerException exception public void testFromJsonWithNULL() { Account accnt = new Account(); JsonPersistency json = new JsonPersistency(); Transaction trans = new Transaction(); User usr1 = null; Account accountAfterJson = json.fromJson(usr1.getUserID()); } @Test // set user with valid user should return account object public void testFromJson() { Account accnt = new Account(); JsonPersistency json = new JsonPersistency(); Transaction trans = new Transaction(); User usr1 = new User() .withName("tina") .withUserID("tina1"); Account accountAfterJson = json.fromJson(usr1.getUserID()); System.out.println("UserID: " + accountAfterJson.getOwner().getUserID().toString()); System.out.println("Name: " + accountAfterJson.getOwner().getName().toString()); assertEquals(usr1.getUserID().toString(),accountAfterJson.getOwner().getUserID().toString()); assertEquals(usr1.getName().toString(),accountAfterJson.getOwner().getName().toString()); assertTrue(540 == accountAfterJson.getBalance()); } /** * * @see <a href='../../../doc/2.html'>2.html</a> */ @Test public void testgetBalanceAndSetBalance() { System.out.println(account1.getBalance()); storyboard.assertEquals("Balance should be the same", 100.0, account1.getBalance()); } @Test public void testAccountToString(){ storyboard.assertEquals("Check for is the toString is correct","100.0 1 " + account1.getCreationdate(),account1.toString()); } @Test public void testgetAccountnum(){ storyboard.assertEquals("Check for if getAccountnum works", 1,account1.getAccountnum()); } @Test(expected = IllegalArgumentException.class) public void testwithAccountnumAndsetAccountnum(){ Account accountNumWithNegatve = new Account().withAccountnum(-1); } /* @Test public void testgetCreationDate(){ Date currentDate = new Date(); storyboard.assertEquals("Testing if date is working",new Date(),account1.getCreationdate()); }*/ @Test public void testgetOwner(){ storyboard.assertEquals("Testing if proper owner is in account",peter,account1.getOwner()); } @Test public void testsetOwner(){ Account accountTestOwner = new Account(); storyboard.assertEquals("Setting owner with null value should return false",false,accountTestOwner.setOwner(null)); } /* @Test public void testCreateOwner(){ User accountTestCreateOwner = new Account().withOwner(peter).createOwner(); storyboard.assertEquals("Testing createOwner",peter.getName(),accountTestCreateOwner.getName()); }*/ @Test public void testgetCredit(){ Account creditAccount = new Account().withCredit(); } @Test(expected = IllegalArgumentException.class) public void testTransferToAccount(){ Account receivingAccount = new Account().withBalance(100); account1.transferToAccount(-1,receivingAccount,"Testing negative"); } @Test(expected = IllegalArgumentException.class) public void testTransferToAccount2(){ Account receivingAccount = new Account().withBalance(100); account1.transferToAccount(100,null,"Testing null account"); } /*@Test public void testTransferToAccount3(){ User victor = new User() .withName("Victor") .withUserID("peter1") .withPassword("password") .withIsAdmin(false); Account receivingAccount = new Account() .withAccountnum(2) .withIsConnected(true) .withOwner(victor) .withBalance(100) .withCreationdate(new Date()) .withCredit() .withDebit(); storyboard.assertEquals("This should return false, since balance in account1 is 100", false,account1.transferToAccount(110,receivingAccount,"Testing amount greater than balance in account1")); }*/ @Test public void testTransferToAccount4(){ User victor = new User() .withName("Victor") .withUserID("peter1") .withPassword("password") .withIsAdmin(false); Account receivingAccount = new Account() .withAccountnum(2) .withIsConnected(true) .withOwner(victor) .withBalance(100) .withCreationdate(new Date()) .withCredit() .withDebit(); User tina = new User() .withName("Tina") .withUserID("peter1") .withPassword("password") .withIsAdmin(false); Account originAccount = new Account() .withAccountnum(1) .withIsConnected(true) .withOwner(victor) .withBalance(100) .withCreationdate(new Date()) .withCredit() .withDebit(); originAccount.transferToAccount(50,receivingAccount,"Testing balance after transfer amount account"); System.out.println(originAccount.getBalance()); System.out.println(receivingAccount.getBalance()); } @Test public void testReceiveFunds(){ //storyboard.assertEquals("Testing receive funds",true,account1.receiveFunds(100,"Testing receive funds")); } @Test public void testRecordTransaction(){ Account recordAccount = new Account(); } //Test for successful login @Test public void testLogin1(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); } //Unsuccessful login due to incorrect username @Test public void testLogin2(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby", "BillyB$b1"); assertFalse(bob.isLoggedIn()); } //Unsuccessful login due to incorrect password @Test public void testLogin3(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b"); assertFalse(bob.isLoggedIn()); } //Unsuccessful login due to incorrect username and password @Test public void testLogin4(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby", "BillyB$b"); assertFalse(bob.isLoggedIn()); } //Null username @Test (expected = IllegalArgumentException.class) public void testLogin5(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login(null, "BillyB$b1"); } //Null password @Test (expected = IllegalArgumentException.class) public void testLogin6(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", null); } //Null username and password @Test (expected = IllegalArgumentException.class) public void testLogin7(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login(null, null); } /* //Successful logout @Test public void testLogout(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.logout(); assertFalse(bob.isLoggedIn()); } //Logout without being attempting to log in @Test public void testLogout2(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); assertFalse(bob.isLoggedIn()); assertFalse(bob.logout()); } //Logout without successfully logging in @Test public void testLogout3(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby", "BillyB$b"); assertFalse(bob.isLoggedIn()); assertFalse(bob.logout()); } */ //SetName without logging in @Test (expected = Exception.class) public void testSetName(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.setName("Bobby"); } //Successful setName @Test public void testSetName2(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setName("Bobby"); assertEquals("Bobby", bob.getName()); } //SetName with null @Test (expected = IllegalArgumentException.class) public void testSetName3(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setName(null); } //SetName with digits @Test (expected = IllegalArgumentException.class) public void testSetName4(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setName("b0bby"); } //SetName with digits @Test (expected = IllegalArgumentException.class) public void testSetName5(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setName("Bobby!"); } //SetUserID @Test (expected = Exception.class) public void testSetUserID(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.setUserID("BuilderBob"); } //SetUserID null @Test (expected = IllegalArgumentException.class) public void testSetUserID2(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setUserID(null); } //SetUserID to the current UserID @Test (expected = IllegalArgumentException.class) public void testSetUserID3(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setUserID("bobby17"); } //Successfully SetUserID @Test public void testSetUserID4(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setUserID("BobBuilder"); assertEquals("BobBuilder", bob.getUserID()); } //SetUserID with a character string less than 4 @Test (expected = IllegalArgumentException.class) public void testSetUserID5(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setUserID("B"); } //SetUserID with a character string greater than 12 @Test (expected = IllegalArgumentException.class) public void testSetUserID6(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setUserID("Bobbbbbbbbbbbbbbbbbbbb17"); } //SetPassword without logging in @Test (expected = Exception.class) public void testSetPassword(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); assertFalse(bob.isLoggedIn()); bob.setPassword("Bob@123"); } //Successful setPassword @Test public void testSetPassword2(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPassword("Bob@123"); assertEquals("Bob@123", bob.getPassword()); } //SetPassword to the current password @Test (expected = IllegalArgumentException.class) public void testSetPassword3(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPassword("BillyB$b1"); } //SetPassword without special character @Test (expected = IllegalArgumentException.class) public void testSetPassword4(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPassword("BillyBob1"); } //SetPassword without digit @Test (expected = IllegalArgumentException.class) public void testSetPassword5(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPassword("BillyB$b"); } //SetPassword without uppercase @Test (expected = IllegalArgumentException.class) public void testSetPassword6(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPassword("billyb$b"); } //SetPassword without lowercase @Test (expected = IllegalArgumentException.class) public void testSetPassword7(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPassword("BILLYB$B"); } //SetPassword with less than 4 characters @Test (expected = IllegalArgumentException.class) public void testSetPassword8(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPassword("Bb$"); } //SetPassword with greater than 12 characters @Test (expected = IllegalArgumentException.class) public void testSetPassword9(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPassword("BillyB$$bby17"); } //SetEmail when not logged in @Test (expected = Exception.class) public void testSetEmail(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.setEmail("billybob@live.com"); } //Successful setEmail @Test public void testSetEmail2(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setEmail("billybob@live.com"); assertEquals("billybob@live.com", bob.getEmail()); } //SetEmail format broken: userid@address.domain @Test (expected = IllegalArgumentException.class) public void testSetEmail3(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setEmail("@live.com"); } //SetEmail format broken by address: userid@address.domain @Test (expected = IllegalArgumentException.class) public void testSetEmail4(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setEmail("billybob@.com"); } //SetEmail format broken by domain: userid@address.domain @Test (expected = IllegalArgumentException.class) public void testSetEmail5(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setEmail("billybob@live."); } //SetEmail format broken by excluding @: userid@address.domain @Test (expected = IllegalArgumentException.class) public void testSetEmail6(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setEmail("billyboblive.com"); } //SetEmail format broken by excluding all special characters: userid@address.domain @Test (expected = IllegalArgumentException.class) public void testSetEmail7(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setEmail("billyboblivecom"); } //SetEmail null @Test (expected = IllegalArgumentException.class) public void testSetEmail8(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setEmail(null); } //SetEmail to current Email @Test (expected = IllegalArgumentException.class) public void testSetEmail9(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setEmail("steverog@live.com"); } @Test (expected = Exception.class) public void testSetPhone(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.setPhone("7037654321"); } //Successful SetPhone @Test public void testSetPhone2(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPhone("7037654321"); assertEquals("7037654321", bob.getPhone()); } //SetPhone with invalid PhoneNo length @Test (expected = IllegalArgumentException.class) public void testSetPhone3(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPhone("703"); } //SetPhone with invalid PhoneNo length @Test (expected = IllegalArgumentException.class) public void testSetPhone4(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPhone("70312345678"); } //SetPhone with nondigit characters @Test (expected = IllegalArgumentException.class) public void testSetPhone5(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPhone("7o312E4567"); } //SetPhone with nondigit characters @Test (expected = IllegalArgumentException.class) public void testSetPhone6(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPhone("703!234$67"); } //SetPhone null @Test (expected = IllegalArgumentException.class) public void testSetPhone7(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPhone(null); } //SetPhone to current phone @Test (expected = IllegalArgumentException.class) public void testSetPhone8(){ User bob = new User() .withName("Bob") .withUserID("bobby17") .withPassword("BillyB$b1") .withEmail("steverog@live.com") .withPhone("7031234567"); bob.login("bobby17", "BillyB$b1"); assertTrue(bob.isLoggedIn()); bob.setPhone("7031234567"); } }
package org.spoofax.jsglr.client; import static org.spoofax.terms.Term.termAt; import static org.spoofax.jsglr.client.AbstractParseNode.*; import java.util.ArrayList; import java.util.List; import org.spoofax.NotImplementedException; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr.client.imploder.ProductionAttributeReader; import org.spoofax.jsglr.shared.SGLRException; import org.spoofax.jsglr.shared.Tools; /** * @author Karl Trygve Kalleberg <karltk near strategoxt.org> * @author Lennart Kats <lennart add lclnet.nl> */ public class Disambiguator { private static final int FILTER_DRAW = 1; private static final int FILTER_LEFT_WINS = 2; private static final int FILTER_RIGHT_WINS = 3; private boolean filterAny; private boolean filterCycles; private boolean filterDirectPreference; private boolean filterPreferenceCount; private boolean filterInjectionCount; private boolean filterTopSort; private boolean filterReject; private boolean filterAssociativity; private boolean filterPriorities; private boolean filterStrict; private boolean logStatistics; private boolean ambiguityIsError; /** * A parse node that was rejected in the current subtree, * or null if no parse node was rejected. */ private AbstractParseNode rejectedBranch; // Current parser state private AmbiguityManager ambiguityManager; private SGLR parser; private ParseTable parseTable; private ProductionAttributeReader prodReader; // private Map<AmbKey, IParseNode> resolvedTable = new HashMap<AmbKey, IParseNode>(); /** * Sets whether any filter should be applied at all (excluding the top sort filter). */ public final void setFilterAny(boolean filterAny) { this.filterAny = filterAny; } public final void setFilterDirectPreference(boolean filterDirectPreference) { this.filterDirectPreference = filterDirectPreference; } public boolean getFilterDirectPreference() { return filterDirectPreference; } /** * For preference count filtering, see {@link #setFilterPreferenceCount(boolean)}. */ @Deprecated public final void setFilterIndirectPreference(boolean filterIndirectPreference) { throw new UnsupportedOperationException(); } /** * For preference count filtering, see {@link #getFilterPreferenceCount()}. */ @Deprecated public boolean getFilterIndirectPreference() { throw new UnsupportedOperationException(); } public final void setFilterInjectionCount(boolean filterInjectionCount) { this.filterInjectionCount = filterInjectionCount; } public boolean getFilterInjectionCount() { return filterInjectionCount; } public final void setFilterPreferenceCount(boolean filterPreferenceCount) { this.filterPreferenceCount = filterPreferenceCount; } public boolean getFilterPreferenceCount() { return filterPreferenceCount; } public final void setFilterTopSort(boolean filterTopSort) { this.filterTopSort = filterTopSort; } public boolean getFilterTopSort() { return filterTopSort; } public void setFilterCycles(boolean filterCycles) { this.filterCycles = filterCycles; } public boolean isFilterCycles() { return filterCycles; } public void setFilterAssociativity(boolean filterAssociativity) { this.filterAssociativity = filterAssociativity; } public boolean getFilterAssociativity() { return filterAssociativity; } public void setFilterPriorities(boolean filterPriorities) { this.filterPriorities = filterPriorities; } public boolean getFilterPriorities() { return filterPriorities; } /** * Sets whether to enable strict filtering, triggering a * FilterException when the priorities filter encounters * an unfiltered ambiguity. */ public void setFilterStrict(boolean filterStrict) { this.filterStrict = filterStrict; } public boolean getFilterStrict() { return filterStrict; } public final void setHeuristicFilters(boolean heuristicFilters) { setFilterPreferenceCount(heuristicFilters); setFilterInjectionCount(heuristicFilters); } public void setFilterReject(boolean filterReject) { this.filterReject = filterReject; } public boolean getFilterReject() { return filterReject; } public void setLogStatistics(boolean logStatistics) { this.logStatistics = logStatistics; } public boolean getLogStatistics() { return logStatistics; } public void setAmbiguityIsError(boolean ambiguityIsError) { this.ambiguityIsError = ambiguityIsError; } public boolean getAmbiguityIsError() { return ambiguityIsError; } public final void setDefaultFilters() { filterAny = true; filterCycles = false; // TODO: filterCycles; enable by default filterDirectPreference = true; filterPreferenceCount = false; filterInjectionCount = false; filterTopSort = true; filterReject = true; filterAssociativity = true; filterPriorities = true; filterStrict = false; // TODO: disable filterStrict hack logStatistics = true; ambiguityIsError = false; } public Disambiguator() { setDefaultFilters(); } public Object applyFilters(SGLR parser, AbstractParseNode root, String sort, int inputLength) throws SGLRException, FilterException { AbstractParseNode t = root; if(Tools.debugging) { Tools.debug("applyFilters()"); } try { try { if(Tools.debugging) { Tools.debug("applyFilters()"); } initializeFromParser(parser); t = applyTopSortFilter(sort, t); if (filterAny) { t = applyCycleDetectFilter(t); // SG_FilterTree ambiguityManager.resetClustersVisitedCount(); t = filterTree(t, false); } if (filterReject && rejectedBranch != null && !parser.useIntegratedRecovery) throw new FilterException(parser, "Unexpected reject annotation in " + yieldTree(rejectedBranch)); } catch (RuntimeException e) { throw new FilterException(parser, "Runtime exception when applying filters", e); } finally { rejectedBranch = null; } return yieldTreeTop(t); } finally { initializeFromParser(null); } } private void initializeFromParser(SGLR parser) { if (parser == null) { this.parser = null; parseTable = null; ambiguityManager = null; } else { this.parser = parser; parseTable = parser.getParseTable(); prodReader = new ProductionAttributeReader(parseTable.getFactory()); ambiguityManager = parser.getAmbiguityManager(); } } private void logStatus() { Tools.logger("Number of rejects: ", parser.getRejectCount()); Tools.logger("Number of reductions: ", parser.getReductionCount()); Tools.logger("Number of ambiguities: ", ambiguityManager.getMaxNumberOfAmbiguities()); Tools.logger("Number of calls to Amb: ", ambiguityManager.getAmbiguityCallsCount()); Tools.logger("Count Eagerness Comparisons: ", ambiguityManager.getEagernessComparisonCount(), " / ", ambiguityManager.getEagernessSucceededCount()); Tools.logger("Number of Injection Counts: ", ambiguityManager.getInjectionCount()); } private Object yieldTree(AbstractParseNode t) { parser.getTreeBuilder().reset(); // in case yieldTree is used for debugging return parser.getTreeBuilder().buildTree(t); } private Object yieldTreeTop(AbstractParseNode t) throws SGLRException { int ambCount = ambiguityManager.getAmbiguitiesCount(); if (Tools.debugging) { Tools.debug("convertToATerm: ", t); } try { ambiguityManager.resetAmbiguityCount(); final Object r = yieldTree(t); if(logStatistics) logStatus(); if (Tools.debugging) { Tools.debug("yield: ", r); } if(ambiguityIsError && ambCount > 0) { throw new SGLRException(parser, "Ambiguities found") ; } else { return parser.getTreeBuilder().buildTreeTop(r, ambCount); } } finally { parser.getTreeBuilder().reset(); } } private AbstractParseNode applyCycleDetectFilter(AbstractParseNode t) throws FilterException { if (Tools.debugging) { Tools.debug("applyCycleDetectFilter() - ", t); } if (filterCycles) { if (ambiguityManager.getMaxNumberOfAmbiguities() > 0) { if (isCyclicTerm(t)) { throw new FilterException(parser, "Term is cyclic"); } } } return t; } private IStrategoTerm getProduction(AbstractParseNode t) { if (t.isParseNode()) { return parseTable.getProduction(((ParseNode) t).getLabel()); } else { return parseTable.getProduction(((ParseProductionNode) t).getProduction()); } } private AbstractParseNode applyTopSortFilter(String sort, AbstractParseNode t) throws SGLRException { if (Tools.debugging) { Tools.debug("applyTopSortFilter() - ", t); } if (sort != null && filterTopSort) { t = selectOnTopSort(t, sort); if (t == null) { throw new StartSymbolException(parser, "Desired start symbol not found: " + sort); } } return t; } private boolean matchProdOnTopSort(IStrategoTerm prod, String sort) throws FilterException { assert sort != null; /* sort = sort.replaceAll("\"", ""); return prod.match("prod([cf(opt(layout)),cf(sort(\"" + sort + "\")),cf(opt(layout))], sort(\"<START>\"),no-attrs)") != null || prod.match("prod([cf(sort(\"" + sort + "\"))], sort(\"<START>\"),no-attrs)") != null || prod.match("prod([lex(sort(\"" + sort + "\"))], sort(\"<START>\"),no-attrs)") != null || prod.match("prod([sort(\"" + sort + "\")], sort(\"<START>\"),no-attrs)") != null; */ IStrategoList lhs = termAt(prod, 0); IStrategoAppl rhs = termAt(prod, 1); String foundSort = prodReader.tryGetFirstSort(lhs); assert foundSort != null; assert "<START>".equals(prodReader.tryGetSort(rhs)); return sort.equals(foundSort); } private AbstractParseNode selectOnTopSort(AbstractParseNode t, String sort) throws FilterException { final List<AbstractParseNode> results = new ArrayList<AbstractParseNode>(); if (t.isAmbNode()) { addTopSortAlternatives(t, sort, results); switch (results.size()) { case 0: return null; case 1: return results.get(0); default: ambiguityManager.increaseAmbiguityCount(); return ParseNode.createAmbNode(results.toArray(new AbstractParseNode[results.size()])); } } else { final IStrategoTerm prod = getProduction(t); return matchProdOnTopSort(prod, sort) ? t : null; } } private void addTopSortAlternatives(AbstractParseNode t, String sort, List<AbstractParseNode> results) throws FilterException { for(final AbstractParseNode amb : t.getChildren()) { if (amb.isAmbNode()) { addTopSortAlternatives(amb, sort, results); } else { final IStrategoTerm prod = getProduction(amb); if (matchProdOnTopSort(prod, sort)) { results.add(amb); } } } } /** * @param inAmbiguityCluster We're inside an amb and can return null to reject this branch. */ private AbstractParseNode filterTree(AbstractParseNode t, boolean inAmbiguityCluster) throws FilterException { // SG_FilterTreeRecursive if (Tools.debugging) { Tools.debug("filterTree(node) - ", t); } // parseTable.setTreeBuilder(new Asfix2TreeBuilder()); switch (t.getNodeType()) { case AMBIGUITY: if (!inAmbiguityCluster) { // (some cycle stuff should be done here) final AbstractParseNode[] ambs = t.getChildren(); t = filterAmbiguities(ambs); } else { // FIXME: hasRejectProd(Amb) can never succeed? if (filterReject && parseTable.hasRejects() && hasRejectProd(t)) { return null; } final AbstractParseNode[] ambs = t.getChildren(); return filterAmbiguities(ambs); } break; case PARSENODE: case AVOID: case PREFER: case REJECT: final ParseNode node = (ParseNode) t; final AbstractParseNode[] args = node.getChildren(); final AbstractParseNode[] newArgs = t.isParseProductionChain() ? null : filterTree(args, false); // TODO: assert that parse production chains do not have reject nodes? if (filterReject && parseTable.hasRejects() && hasRejectProd(t)) { if (inAmbiguityCluster) { return null; } else { rejectedBranch = t; } } if (newArgs != null && args != newArgs) t = new ParseNode(node.getLabel(), newArgs, AbstractParseNode.PARSENODE); break; case PARSE_PRODUCTION_NODE: // leaf node -- do thing (cannot be any ambiguities here) return t; case CYCLE: return t; default: throw new IllegalStateException("Unknown node type: " + t); } if (filterAssociativity) { return applyAssociativityPriorityFilter(t); } else { return t; } } /** * Filters child parse nodes. * * @return An array of filtered child nodes, or null if no changes were made. */ private AbstractParseNode[] filterTree(AbstractParseNode[] args, boolean inAmbiguityCluster) throws FilterException { if(Tools.debugging) { Tools.debug("filterTree(<nodes>) - ", args); } // TODO: Optimize - combine these two loops AbstractParseNode[] newArgs = null; for (int i = 0, max = args.length; i < max; i++) { final AbstractParseNode n = args[i]; final AbstractParseNode filtered = filterTree(n, false); if (newArgs == null) { if (filtered != n) { newArgs = cloneArrayUpToIndex(args, i); newArgs[i] = filtered; } } else { newArgs[i] = filtered; } } // FIXME Shouldn't we do some filtering here? // if (!changed) { // Tools.debug("Dropping: ", args); // newArgs = getEmptyList(); if (filterAny) { if (newArgs != null) args = newArgs; newArgs = null; for (int i = 0, max = args.length; i < max; i++) { AbstractParseNode n = args[i]; AbstractParseNode filtered = applyAssociativityPriorityFilter(n); if (newArgs == null) { if (filtered != n) { newArgs = cloneArrayUpToIndex(args, i); newArgs[i] = filtered; } } else { newArgs[i] = filtered; } } } return newArgs == null ? args : newArgs; } private static AbstractParseNode[] cloneArrayUpToIndex(AbstractParseNode[] args, int index) { AbstractParseNode[] newArgs; newArgs = new AbstractParseNode[args.length]; System.arraycopy(args, 0, newArgs, 0, index); return newArgs; } private AbstractParseNode applyAssociativityPriorityFilter(AbstractParseNode t) throws FilterException { // SG_Associativity_Priority_Filter(pt, t) if(Tools.debugging) { Tools.debug("applyAssociativityPriorityFilter() - ", t); } AbstractParseNode r = t; if (t.isParseNode()) { final Label prodLabel = getProductionLabel(t); final ParseNode n = (ParseNode) t; if (filterAssociativity) { if (prodLabel.isLeftAssociative()) { r = applyLeftAssociativeFilter(n, prodLabel); } else if (prodLabel.isRightAssociative()) { r = applyRightAssociativeFilter(n, prodLabel); } } if (filterPriorities && parseTable.hasPriorities()) { if(Tools.debugging) { Tools.debug(" - about to look up : ", prodLabel.labelNumber); } if (!lookupGtrPriority(prodLabel).isEmpty()) { if(Tools.debugging) { Tools.debug(" - found"); } if (r.isAmbNode()) { return r; } return applyPriorityFilter((ParseNode) r, prodLabel); } if(Tools.debugging) { Tools.debug(" - not found"); } } } return r; } private AbstractParseNode applyRightAssociativeFilter(ParseNode t, Label prodLabel) throws FilterException { // SG_Right_Associativity_Filter(t, prodl) // - almost ok if(Tools.debugging) { Tools.debug("applyRightAssociativeFilter() - ", t); } final List<AbstractParseNode> newAmbiguities = new ArrayList<AbstractParseNode>(); final AbstractParseNode[] kids = t.getChildren(); final AbstractParseNode firstKid = kids[0]; if(firstKid.isAmbNode()) { for (final AbstractParseNode amb : firstKid.getChildren()) { if(((ParseNode)amb).getLabel() != prodLabel.labelNumber) { newAmbiguities.add(amb); } } final int additionalAmbNodes = newAmbiguities.isEmpty() ? 0 : 1; final AbstractParseNode[] restKids = new AbstractParseNode[t.getChildren().length - 1 + additionalAmbNodes]; for(int i = 0; i < restKids.length; i++) { restKids[i] = kids[i + 1]; } // FIXME is this correct? if(!newAmbiguities.isEmpty()) { AbstractParseNode extraAmb; if(newAmbiguities.size() > 1) { extraAmb = ParseNode.createAmbNode(newAmbiguities.toArray(new AbstractParseNode[newAmbiguities.size()])); ambiguityManager.increaseAmbiguityCount(); } else { extraAmb = newAmbiguities.get(0); } restKids[restKids.length - 1] = extraAmb; } else { throw new FilterException(parser); } // FIXME is this correct? return new ParseNode(t.getLabel(), restKids, AbstractParseNode.PARSENODE); } else if(firstKid.isParseNode()) { if(((ParseNode)firstKid).getLabel() == prodLabel.labelNumber) { throw new FilterException(parser); } } return t; } private AbstractParseNode applyPriorityFilter(ParseNode t, Label prodLabel) throws FilterException { // SG_Priority_Filter if(Tools.debugging) { Tools.debug("applyPriorityFilter() - ", t); } final List<AbstractParseNode> newAmbiguities = new ArrayList<AbstractParseNode>(); final List<AbstractParseNode> newKids = new ArrayList<AbstractParseNode>(); final int l0 = prodLabel.labelNumber; int kidnumber = 0; for (final AbstractParseNode kid : t.getChildren()) { AbstractParseNode newKid = kid; final AbstractParseNode injection = jumpOverInjections(kid); if (injection.isAmbNode()) { newAmbiguities.clear(); for (final AbstractParseNode amb : injection.getChildren()) { final AbstractParseNode injAmb = jumpOverInjections(amb); if (injAmb.isParseNode()) { final Label label = getProductionLabel(t); if(hasGreaterPriority(l0, label.labelNumber, kidnumber)) { newAmbiguities.add(amb); } } } if(!newAmbiguities.isEmpty()) { AbstractParseNode n = null; if(newAmbiguities.size() > 1) { n = ParseNode.createAmbNode(newAmbiguities.toArray(new AbstractParseNode[newAmbiguities.size()])); ambiguityManager.increaseAmbiguityCount(); } else { n = newAmbiguities.get(0); } newKid = replaceUnderInjections(kid, injection, n); } else { // fishy: another filter might be borked if (filterStrict) { throw new FilterException(parser); } else { // TODO: log or whatever? return t; } } } else if (injection.isParseNode()) { final int l1 = ((ParseNode) injection).getLabel(); if (hasGreaterPriority(l0, l1, kidnumber)) { throw new FilterException(parser); } } newKids.add(newKid); kidnumber++; } // FIXME (KTK) get rid of toArray by precomputing the necessary size of newKids earlier in the method return new ParseNode(t.getLabel(), newKids.toArray(new AbstractParseNode[newKids.size()]), AbstractParseNode.PARSENODE); } private AbstractParseNode replaceUnderInjections(AbstractParseNode alt, AbstractParseNode injection, AbstractParseNode n) throws FilterException { // SG_Replace_Under_Injections // - not ok throw new FilterException(parser, "replaceUnderInjections is not implemented", new NotImplementedException()); /* if (ATisEqual(t, injT)) { return newTree; } else { IStrategoList sons = (IStrategoList)ATgetArgument((ATerm) t, 1); tree newSon = SG_Replace_Under_Injections((tree)ATgetFirst(sons), injT, newTree); return ATsetArgument((ATermAppl)t, (ATerm)ATmakeList1((ATerm)newSon), 1); } */ } private AbstractParseNode jumpOverInjections(AbstractParseNode t) { if(Tools.debugging) { Tools.debug("jumpOverInjections() - ", t); } if (t.isParseNode()) { int prod = ((ParseNode) t).getLabel(); ParseNode n = (ParseNode)t; while (isUserDefinedLabel(prod)) { final AbstractParseNode x = n.kids[0]; if(x.isParseNode()) { n = (ParseNode)x; prod = n.getLabel(); } else { return x; } } } return t; } // TODO: shouldn't this be called isInjection? private boolean isUserDefinedLabel(int prod) { final Label l = parseTable.lookupInjection(prod); if(l == null) { return false; } return l.isInjection(); } private boolean hasGreaterPriority(int l0, int l1, int arg) { final List<Priority> prios = lookupGtrPriority(parseTable.getLabel(l0)); for (int i = 0, size = prios.size(); i < size; i++) { final Priority p = prios.get(i); if (l1 == p.right) { if (p.arg == -1 || p.arg == arg) { return true; } } } return false; } private List<Priority> lookupGtrPriority(Label prodLabel) { return parseTable.getPriorities(prodLabel); } private AbstractParseNode applyLeftAssociativeFilter(ParseNode t, Label prodLabel) throws FilterException { // SG_Right_Associativity_Filter() if(Tools.debugging) { Tools.debug("applyLeftAssociativeFilter() - ", t); } final List<AbstractParseNode> newAmbiguities = new ArrayList<AbstractParseNode>(); final AbstractParseNode[] kids = t.kids; AbstractParseNode last = kids[kids.length - 1]; if (last.isAmbNode()) { for (final AbstractParseNode amb : last.getChildren()) { if (amb.isAmbNode() || !parseTable.getLabel(((ParseNode) amb).getLabel()).equals(prodLabel)) { newAmbiguities.add(amb); } } if (!newAmbiguities.isEmpty()) { final AbstractParseNode[] rest = new AbstractParseNode[kids.length]; for(int i = 0; i < kids.length - 1; i++) { rest[i] = kids[i]; } if (newAmbiguities.size() > 1) { last = ParseNode.createAmbNode(newAmbiguities.toArray(new AbstractParseNode[newAmbiguities.size()])); ambiguityManager.increaseAmbiguityCount(); } else { last = newAmbiguities.get(0); } rest[rest.length - 1] = last; ambiguityManager.increaseAmbiguityCount(); return ParseNode.createAmbNode(rest); } else { throw new FilterException(parser); } } else if (last.isParseNode()) { final Label other = parseTable.getLabel(((ParseNode) last).getLabel()); if (prodLabel.equals(other)) { throw new FilterException(parser); } } return t; } private Label getProductionLabel(AbstractParseNode t) { if (t.isParseNode()) { return parseTable.getLabel(((ParseNode) t).getLabel()); } else if (t instanceof ParseProductionNode) { return parseTable.getLabel(((ParseProductionNode) t).getProduction()); } return null; } private boolean hasRejectProd(AbstractParseNode t) { return t.isParseRejectNode(); } private AbstractParseNode filterAmbiguities(AbstractParseNode[] ambs) throws FilterException { // SG_FilterAmb if(Tools.debugging) { Tools.debug("filterAmbiguities() - [", ambs.length, "]"); } List<AbstractParseNode> newAmbiguities = new ArrayList<AbstractParseNode>(); for (final AbstractParseNode amb : ambs) { final AbstractParseNode newAmb = filterTree(amb, true); if (newAmb != null && rejectedBranch == null) { newAmbiguities.add(newAmb); } rejectedBranch = null; } if (newAmbiguities.size() > 1) { /* Handle ambiguities inside this ambiguity cluster */ final List<AbstractParseNode> oldAmbiguities = new ArrayList<AbstractParseNode>(newAmbiguities); for (final AbstractParseNode amb : oldAmbiguities) { if (newAmbiguities.remove(amb)) { newAmbiguities = filterAmbiguityList(newAmbiguities, amb); } } } if (newAmbiguities.isEmpty()) { // All alternatives were rejected; // the outer context should be rejected as well return rejectedBranch = ParseNode.createAmbNode(ambs); } if (newAmbiguities.size() == 1) { return newAmbiguities.get(0); } ambiguityManager.increaseAmbiguityCount(); return ParseNode.createAmbNode(newAmbiguities.toArray(new AbstractParseNode[newAmbiguities.size()])); } private List<AbstractParseNode> filterAmbiguityList(List<AbstractParseNode> ambs, AbstractParseNode t) { // SG_FilterAmbList boolean keepT = true; final List<AbstractParseNode> r = new ArrayList<AbstractParseNode>(); if (ambs.isEmpty()) { r.add(t); return r; } for (int i = 0, max = ambs.size(); i < max; i++) { final AbstractParseNode amb = ambs.get(i); switch (filter(t, amb)) { case FILTER_DRAW: r.add(amb); break; case FILTER_RIGHT_WINS: r.add(amb); keepT = false; } } if (keepT) { r.add(t); } return r; } private int filter(AbstractParseNode left, AbstractParseNode right) { // SG_Filter(t0, t1) if(Tools.debugging) { Tools.debug("filter()"); } if (left.equals(right)) { return FILTER_LEFT_WINS; } /* UNDONE: direct eagerness filter seems to be disabled in reference SGLR if (filterDirectPreference && parseTable.hasPrefersOrAvoids()) { int r = filterOnDirectPrefers(left, right); if (r != FILTER_DRAW) return r; } */ // like C-SGLR, we use indirect preference filtering if the direct one is enabled if (filterDirectPreference && parseTable.hasPrefersOrAvoids()) { final int r = filterOnIndirectPrefers(left, right); if (r != FILTER_DRAW) { return r; } } if (filterPreferenceCount && parseTable.hasPrefersOrAvoids()) { final int r = filterOnPreferCount(left, right); if (r != FILTER_DRAW) { return r; } } if (filterInjectionCount) { final int r = filterOnInjectionCount(left, right); if (r != FILTER_DRAW) { return r; } } return filterPermissiveLiterals(left, right); } private int filterPermissiveLiterals(AbstractParseNode left, AbstractParseNode right) { if (left.isParseNode() && right.isParseNode()) { final AbstractParseNode[] leftKids = ((ParseNode) left).kids; final AbstractParseNode[] rightKids = ((ParseNode) right).kids; if (leftKids.length > 0 && rightKids.length == 1) { if (leftKids[0] instanceof ParseProductionNode && rightKids[0].equals(left)) { return FILTER_LEFT_WINS; } } } return FILTER_DRAW; } private int filterOnInjectionCount(AbstractParseNode left, AbstractParseNode right) { if(Tools.debugging) { Tools.debug("filterOnInjectionCount()"); } ambiguityManager.increaseInjectionCount(); final int leftInjectionCount = countAllInjections(left); final int rightInjectionCount = countAllInjections(right); if (leftInjectionCount != rightInjectionCount) { ambiguityManager.increaseInjectionFilterSucceededCount(); } if (leftInjectionCount > rightInjectionCount) { return FILTER_RIGHT_WINS; } else if (rightInjectionCount > leftInjectionCount) { return FILTER_LEFT_WINS; } return FILTER_DRAW; } private int countAllInjections(AbstractParseNode t) { // SG_CountAllInjectionsInTree if (t.isAmbNode()) { // Trick from forest.c return t.getChildren().length == 0 ? 0 : countAllInjections(t.getChildren()[0]); } else if (t.isParseNode()) { final int c = getProductionLabel(t).isInjection() ? 1 : 0; return c + countAllInjections(((ParseNode) t).kids); } return 0; } private int countAllInjections(AbstractParseNode[] ls) { // SG_CountAllInjectionsInTree int r = 0; for (int i = 0, max = ls.length; i < max; i++) { r += countAllInjections(ls[i]); } return r; } private int filterOnPreferCount(AbstractParseNode left, AbstractParseNode right) { if(Tools.debugging) { Tools.debug("filterOnPreferCount()"); } ambiguityManager.increaseEagernessFilterCalledCount(); int r = FILTER_DRAW; if (parseTable.hasPrefers() || parseTable.hasAvoids()) { final int leftPreferCount = countPrefers(left); final int rightPreferCount = countPrefers(right); final int leftAvoidCount = countAvoids(left); final int rightAvoidCount = countAvoids(right); if ((leftPreferCount > rightPreferCount && leftAvoidCount <= rightAvoidCount) || (leftPreferCount == rightPreferCount && leftAvoidCount < rightAvoidCount)) { Tools.logger("Eagerness priority: ", left, " > ", right); r = FILTER_LEFT_WINS; } if ((rightPreferCount > leftPreferCount && rightAvoidCount <= leftAvoidCount) || (rightPreferCount == leftPreferCount && rightAvoidCount < leftAvoidCount)) { if (r != FILTER_DRAW) { Tools.logger("Symmetric eagerness priority: ", left, " == ", right); r = FILTER_DRAW; } else { Tools.logger("Eagerness priority: ", right, " > ", left); r = FILTER_RIGHT_WINS; } } } if (r != FILTER_DRAW) { ambiguityManager.increaseEagernessFilterSucceededCount(); } return r; } private int countPrefers(AbstractParseNode t) { // SG_CountPrefersInTree if (t.isAmbNode()) { return countPrefers(t.getChildren()); } else if (t.isParseNode()) { final int type = getProductionType(t); if (type == ProductionType.PREFER) { return 1; } else if (type == ProductionType.AVOID) { return 0; } return countPrefers(((ParseNode) t).kids); } return 0; } private int countPrefers(AbstractParseNode[] ls) { // SG_CountPrefersInTree int r = 0; for (final AbstractParseNode n : ls) { r += countPrefers(n); } return r; } private int countAvoids(AbstractParseNode t) { // SG_CountAvoidsInTree if (t.isAmbNode()) { return countAvoids(t.getChildren()); } else if (t.isParseNode()) { final int type = getProductionType(t); if (type == ProductionType.PREFER) { return 0; } else if (type == ProductionType.AVOID) { return 1; } return countAvoids(((ParseNode) t).kids); } return 0; } private int countAvoids(AbstractParseNode[] ls) { // SG_CountAvoidsInTree int r = 0; for (final AbstractParseNode n : ls) { r += countAvoids(n); } return r; } private int filterOnIndirectPrefers(AbstractParseNode left, AbstractParseNode right) { // SG_Indirect_Eagerness_Filter if(Tools.debugging) { Tools.debug("filterOnIndirectPrefers()"); } if (left.isAmbNode() || right.isAmbNode()) { return FILTER_DRAW; } if (!getLabel(left).equals(getLabel(right))) { return filterOnDirectPrefers(left, right); } final ParseNode l = (ParseNode) left; final ParseNode r = (ParseNode) right; final AbstractParseNode[] leftArgs = l.kids; final AbstractParseNode[] rightArgs = r.kids; final int diffs = computeDistinctArguments(leftArgs, rightArgs); if (diffs == 1) { for (int i = 0; i < leftArgs.length; i++) { final AbstractParseNode leftArg = leftArgs[i]; final AbstractParseNode rightArg = rightArgs[i]; if (!leftArg.equals(rightArg)) { return filterOnIndirectPrefers(leftArg, rightArg); } } } return FILTER_DRAW; } private int filterOnDirectPrefers(AbstractParseNode left, AbstractParseNode right) { // SG_Direct_Eagerness_Filter if(Tools.debugging) { Tools.debug("filterOnDirectPrefers()"); } // TODO: optimize - move up the jumpOverInjectionsModuloEagerness calls if (isLeftMoreEager(left, right)) { return FILTER_LEFT_WINS; } if (isLeftMoreEager(right, left)) { return FILTER_RIGHT_WINS; } return FILTER_DRAW; } private boolean isLeftMoreEager(AbstractParseNode left, AbstractParseNode right) { assert !(left.isAmbNode() || right.isAmbNode()); if (isMoreEager(left, right)) { return true; } final AbstractParseNode newLeft = jumpOverInjectionsModuloEagerness(left); final AbstractParseNode newRight = jumpOverInjectionsModuloEagerness(right); if (newLeft.isParseNode() && newRight.isParseNode()) { return isMoreEager(newLeft, newRight); } return false; } private AbstractParseNode jumpOverInjectionsModuloEagerness(AbstractParseNode t) { if(Tools.debugging) { Tools.debug("jumpOverInjectionsModuloEagerness()"); } final int prodType = getProductionType(t); if (t.isParseNode() && prodType != ProductionType.PREFER && prodType != ProductionType.AVOID) { Label prod = getLabel(t); while (prod.isInjection()) { t = ((ParseNode) t).kids[0]; if (t.isParseNode()) { final int prodTypeX = getProductionType(t); if (prodTypeX != ProductionType.PREFER && prodTypeX != ProductionType.AVOID) { prod = getLabel(t); continue; } } return t; } } return t; } private Label getLabel(AbstractParseNode t) { if (t.isParseNode()) { final ParseNode n = (ParseNode) t; return parseTable.getLabel(n.getLabel()); } else if (t instanceof ParseProductionNode) { final ParseProductionNode n = (ParseProductionNode) t; return parseTable.getLabel(n.prod); } return null; } private int getProductionType(AbstractParseNode t) { return getLabel(t).getAttributes().getType(); } private boolean isMoreEager(AbstractParseNode left, AbstractParseNode right) { final int leftLabel = ((ParseNode) left).getLabel(); final int rightLabel = ((ParseNode) right).getLabel(); final Label leftProd = parseTable.getLabel(leftLabel); final Label rightProd = parseTable.getLabel(rightLabel); if (leftProd.isMoreEager(rightProd)) { return true; } return false; } private int computeDistinctArguments(AbstractParseNode[] leftArgs, AbstractParseNode[] rightArgs) { // countDistinctArguments int r = 0; for (int i = 0; i < leftArgs.length; i++) { if (!leftArgs[i].equals(rightArgs[i])) { r++; } } return r; } private boolean isCyclicTerm(AbstractParseNode t) { ambiguityManager.dumpIndexTable(); final List<AbstractParseNode> cycles = computeCyclicTerm(t); return cycles != null && cycles.size() > 0; } private List<AbstractParseNode> computeCyclicTerm(AbstractParseNode t) { // FIXME rewrite to use HashMap and object id final PositionMap visited = new PositionMap(ambiguityManager.getMaxNumberOfAmbiguities()); ambiguityManager.resetAmbiguityCount(); return computeCyclicTerm(t, false, visited); } private List<AbstractParseNode> computeCyclicTerm(AbstractParseNode t, boolean inAmbiguityCluster, PositionMap visited) { if (Tools.debugging) { Tools.debug("computeCyclicTerm() - ", t); } if (t instanceof ParseProductionNode) { if (Tools.debugging) { Tools.debug(" bumping"); } return null; } else if (t.isParseNode()) { //Amb ambiguities = null; List<AbstractParseNode> cycle = null; //int clusterIndex; final ParseNode n = (ParseNode) t; if (inAmbiguityCluster) { cycle = computeCyclicTerm(n.kids, false, visited); } else { /* if (ambiguityManager.isInputAmbiguousAt(parseTreePosition)) { ambiguityManager.increaseAmbiguityCount(); clusterIndex = ambiguityManager.getClusterIndex(t, parseTreePosition); if (SGLR.isDebugging()) { Tools.debug(" - clusterIndex : ", clusterIndex); } if (markMap.isMarked(clusterIndex)) { return new ArrayList<IParseNode>(); } ambiguities = ambiguityManager.getClusterOnIndex(clusterIndex); } else { clusterIndex = -1; }*/ throw new NotImplementedException(); /* if (ambiguities == null) { cycle = computeCyclicTerm(((ParseNode) t).getKids(), false, visited); } else { int length = visited.getValue(clusterIndex); int savePos = parseTreePosition; if (length == -1) { //markMap.mark(clusterIndex); cycle = computeCyclicTermInAmbiguityCluster(ambiguities, visited); visited.put(clusterIndex, parseTreePosition - savePos); //markMap.unmark(clusterIndex); } else { parseTreePosition += length; } } */ } return cycle; } else { throw new FatalException(); } } /* private List<IParseNode> computeCyclicTermInAmbiguityCluster(Amb ambiguities, PositionMap visited) { List<IParseNode> ambs = ambiguities.getAlternatives(); for (int i = 0, max = ambs.size(); i < max; i++) { IParseNode amb = ambs.get(i); List<IParseNode> cycle = computeCyclicTerm(amb, true, visited); if (cycle != null) return cycle; } return null; } */ private List<AbstractParseNode> computeCyclicTerm(AbstractParseNode[] kids, boolean b, PositionMap visited) { for (int i = 0, max = kids.length; i < max; i++) { final List<AbstractParseNode> cycle = computeCyclicTerm(kids[i], false, visited); if (cycle != null) { return cycle; } } return null; } }
package org.xtest.ui.outline; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.swt.widgets.Display; import org.eclipse.xtext.ui.editor.outline.IOutlineNode; import org.eclipse.xtext.ui.editor.outline.impl.OutlinePage; import org.eclipse.xtext.ui.editor.outline.impl.OutlineRefreshJob; import org.eclipse.xtext.ui.editor.outline.impl.OutlineTreeState; /** * Custom outline refresh job to grey-out the outline view while tests are running and automatically * expand failed tests. * * @author Michael Barry */ public class XtestOutlineRefreshJob extends OutlineRefreshJob { private OutlinePage outlinePage; /** * Executes a task in the UI thread to enable or disable the outline view * * @param enable * True to enable, false to disable */ public void setControlEnabled(final boolean enable) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { outlinePage.getTreeViewer().getControl().setEnabled(enable); } }); } @Override public void setOutlinePage(OutlinePage outlinePage) { this.outlinePage = outlinePage; super.setOutlinePage(outlinePage); } @Override protected IOutlineNode refreshOutlineModel(IProgressMonitor monitor, OutlineTreeState formerState, OutlineTreeState newState) { // TODO run while edit - refresh on annotation change // TODO run on save - refresh on new result IOutlineNode refreshOutlineModel = super .refreshOutlineModel(monitor, formerState, newState); if (!monitor.isCanceled()) { setControlEnabled(true); } return refreshOutlineModel; } @Override protected void restoreChildrenSelectionAndExpansion(IOutlineNode parent, Resource resource, OutlineTreeState formerState, OutlineTreeState newState) { super.restoreChildrenSelectionAndExpansion(parent, resource, formerState, newState); List<IOutlineNode> children = parent.getChildren(); for (IOutlineNode child : children) { if (child instanceof XTestEObjectNode && ((XTestEObjectNode) child).getFailed()) { // Show failed nodes newState.addExpandedNode(parent); } else if (containsUsingComparer(formerState.getExpandedNodes(), child)) { newState.addExpandedNode(child); } restoreChildrenSelectionAndExpansion(child, resource, formerState, newState); if (containsUsingComparer(formerState.getSelectedNodes(), child)) { newState.addSelectedNode(child); } } } @Override protected IStatus run(IProgressMonitor monitor) { IStatus status = org.eclipse.core.runtime.Status.OK_STATUS; if (outlinePage != null && outlinePage.getTreeViewer() != null) { status = super.run(monitor); } return status; } }
package seaweedfs.client; import com.google.common.base.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class FilerClient extends FilerGrpcClient { private static final Logger LOG = LoggerFactory.getLogger(FilerClient.class); public FilerClient(String host, int grpcPort) { super(host, grpcPort); } public static String toFileId(FilerProto.FileId fid) { if (fid == null) { return null; } return String.format("%d,%x%08x", fid.getVolumeId(), fid.getFileKey(), fid.getCookie()); } public static FilerProto.FileId toFileIdObject(String fileIdStr) { if (fileIdStr == null || fileIdStr.length() == 0) { return null; } int commaIndex = fileIdStr.lastIndexOf(','); String volumeIdStr = fileIdStr.substring(0, commaIndex); String fileKeyStr = fileIdStr.substring(commaIndex + 1, fileIdStr.length() - 8); String cookieStr = fileIdStr.substring(fileIdStr.length() - 8); return FilerProto.FileId.newBuilder() .setVolumeId(Integer.parseInt(volumeIdStr)) .setFileKey(Long.parseLong(fileKeyStr, 16)) .setCookie((int) Long.parseLong(cookieStr, 16)) .build(); } public static List<FilerProto.FileChunk> beforeEntrySerialization(List<FilerProto.FileChunk> chunks) { List<FilerProto.FileChunk> cleanedChunks = new ArrayList<>(); for (FilerProto.FileChunk chunk : chunks) { FilerProto.FileChunk.Builder chunkBuilder = chunk.toBuilder(); chunkBuilder.clearFileId(); chunkBuilder.clearSourceFileId(); chunkBuilder.setFid(toFileIdObject(chunk.getFileId())); FilerProto.FileId sourceFid = toFileIdObject(chunk.getSourceFileId()); if (sourceFid != null) { chunkBuilder.setSourceFid(sourceFid); } cleanedChunks.add(chunkBuilder.build()); } return cleanedChunks; } public static FilerProto.Entry afterEntryDeserialization(FilerProto.Entry entry) { if (entry.getChunksList().size() <= 0) { return entry; } String fileId = entry.getChunks(0).getFileId(); if (fileId != null && fileId.length() != 0) { return entry; } FilerProto.Entry.Builder entryBuilder = entry.toBuilder(); entryBuilder.clearChunks(); for (FilerProto.FileChunk chunk : entry.getChunksList()) { FilerProto.FileChunk.Builder chunkBuilder = chunk.toBuilder(); chunkBuilder.setFileId(toFileId(chunk.getFid())); String sourceFileId = toFileId(chunk.getSourceFid()); if (sourceFileId != null) { chunkBuilder.setSourceFileId(sourceFileId); } entryBuilder.addChunks(chunkBuilder); } return entryBuilder.build(); } public boolean mkdirs(String path, int mode) { String currentUser = System.getProperty("user.name"); return mkdirs(path, mode, 0, 0, currentUser, new String[]{}); } public boolean mkdirs(String path, int mode, String userName, String[] groupNames) { return mkdirs(path, mode, 0, 0, userName, groupNames); } public boolean mkdirs(String path, int mode, int uid, int gid, String userName, String[] groupNames) { if ("/".equals(path)) { return true; } File pathFile = new File(path); String parent = pathFile.getParent(); String name = pathFile.getName(); mkdirs(parent, mode, uid, gid, userName, groupNames); FilerProto.Entry existingEntry = lookupEntry(parent, name); if (existingEntry != null) { return true; } return createEntry( parent, newDirectoryEntry(name, mode, uid, gid, userName, groupNames).build() ); } public boolean mv(String oldPath, String newPath) { File oldPathFile = new File(oldPath); String oldParent = oldPathFile.getParent(); String oldName = oldPathFile.getName(); File newPathFile = new File(newPath); String newParent = newPathFile.getParent(); String newName = newPathFile.getName(); return atomicRenameEntry(oldParent, oldName, newParent, newName); } public boolean rm(String path, boolean isRecursive, boolean ignoreRecusiveError) { File pathFile = new File(path); String parent = pathFile.getParent(); String name = pathFile.getName(); return deleteEntry( parent, name, true, isRecursive, ignoreRecusiveError); } public boolean touch(String path, int mode) { String currentUser = System.getProperty("user.name"); return touch(path, mode, 0, 0, currentUser, new String[]{}); } public boolean touch(String path, int mode, int uid, int gid, String userName, String[] groupNames) { File pathFile = new File(path); String parent = pathFile.getParent(); String name = pathFile.getName(); FilerProto.Entry entry = lookupEntry(parent, name); if (entry == null) { return createEntry( parent, newFileEntry(name, mode, uid, gid, userName, groupNames).build() ); } long now = System.currentTimeMillis() / 1000L; FilerProto.FuseAttributes.Builder attr = entry.getAttributes().toBuilder() .setMtime(now) .setUid(uid) .setGid(gid) .setUserName(userName) .clearGroupName() .addAllGroupName(Arrays.asList(groupNames)); return updateEntry(parent, entry.toBuilder().setAttributes(attr).build()); } public FilerProto.Entry.Builder newDirectoryEntry(String name, int mode, int uid, int gid, String userName, String[] groupNames) { long now = System.currentTimeMillis() / 1000L; return FilerProto.Entry.newBuilder() .setName(name) .setIsDirectory(true) .setAttributes(FilerProto.FuseAttributes.newBuilder() .setMtime(now) .setCrtime(now) .setUid(uid) .setGid(gid) .setFileMode(mode | 1 << 31) .setUserName(userName) .clearGroupName() .addAllGroupName(Arrays.asList(groupNames))); } public FilerProto.Entry.Builder newFileEntry(String name, int mode, int uid, int gid, String userName, String[] groupNames) { long now = System.currentTimeMillis() / 1000L; return FilerProto.Entry.newBuilder() .setName(name) .setIsDirectory(false) .setAttributes(FilerProto.FuseAttributes.newBuilder() .setMtime(now) .setCrtime(now) .setUid(uid) .setGid(gid) .setFileMode(mode) .setUserName(userName) .clearGroupName() .addAllGroupName(Arrays.asList(groupNames))); } public List<FilerProto.Entry> listEntries(String path) { List<FilerProto.Entry> results = new ArrayList<FilerProto.Entry>(); String lastFileName = ""; for (int limit = Integer.MAX_VALUE; limit > 0; ) { List<FilerProto.Entry> t = listEntries(path, "", lastFileName, 1024, false); if (t == null) { break; } int nSize = t.size(); if (nSize > 0) { limit -= nSize; lastFileName = t.get(nSize - 1).getName(); } results.addAll(t); if (t.size() < 1024) { break; } } return results; } public List<FilerProto.Entry> listEntries(String path, String entryPrefix, String lastEntryName, int limit, boolean includeLastEntry) { Iterator<FilerProto.ListEntriesResponse> iter = this.getBlockingStub().listEntries(FilerProto.ListEntriesRequest.newBuilder() .setDirectory(path) .setPrefix(entryPrefix) .setStartFromFileName(lastEntryName) .setInclusiveStartFrom(includeLastEntry) .setLimit(limit) .build()); List<FilerProto.Entry> entries = new ArrayList<>(); while (iter.hasNext()) { FilerProto.ListEntriesResponse resp = iter.next(); entries.add(afterEntryDeserialization(resp.getEntry())); } return entries; } public FilerProto.Entry lookupEntry(String directory, String entryName) { try { FilerProto.Entry entry = this.getBlockingStub().lookupDirectoryEntry( FilerProto.LookupDirectoryEntryRequest.newBuilder() .setDirectory(directory) .setName(entryName) .build()).getEntry(); if (entry == null) { return null; } return afterEntryDeserialization(entry); } catch (Exception e) { if (e.getMessage().indexOf("filer: no entry is found in filer store") > 0) { return null; } LOG.warn("lookupEntry {}/{}: {}", directory, entryName, e); return null; } } public boolean createEntry(String parent, FilerProto.Entry entry) { try { FilerProto.CreateEntryResponse createEntryResponse = this.getBlockingStub().createEntry(FilerProto.CreateEntryRequest.newBuilder() .setDirectory(parent) .setEntry(entry) .build()); if (Strings.isNullOrEmpty(createEntryResponse.getError())) { return true; } LOG.warn("createEntry {}/{} error: {}", parent, entry.getName(), createEntryResponse.getError()); return false; } catch (Exception e) { LOG.warn("createEntry {}/{}: {}", parent, entry.getName(), e); return false; } } public boolean updateEntry(String parent, FilerProto.Entry entry) { try { this.getBlockingStub().updateEntry(FilerProto.UpdateEntryRequest.newBuilder() .setDirectory(parent) .setEntry(entry) .build()); } catch (Exception e) { LOG.warn("updateEntry {}/{}: {}", parent, entry.getName(), e); return false; } return true; } public boolean deleteEntry(String parent, String entryName, boolean isDeleteFileChunk, boolean isRecursive, boolean ignoreRecusiveError) { try { this.getBlockingStub().deleteEntry(FilerProto.DeleteEntryRequest.newBuilder() .setDirectory(parent) .setName(entryName) .setIsDeleteData(isDeleteFileChunk) .setIsRecursive(isRecursive) .setIgnoreRecursiveError(ignoreRecusiveError) .build()); } catch (Exception e) { LOG.warn("deleteEntry {}/{}: {}", parent, entryName, e); return false; } return true; } public boolean atomicRenameEntry(String oldParent, String oldName, String newParent, String newName) { try { this.getBlockingStub().atomicRenameEntry(FilerProto.AtomicRenameEntryRequest.newBuilder() .setOldDirectory(oldParent) .setOldName(oldName) .setNewDirectory(newParent) .setNewName(newName) .build()); } catch (Exception e) { LOG.warn("atomicRenameEntry {}/{} => {}/{}: {}", oldParent, oldName, newParent, newName, e); return false; } return true; } public Iterator<FilerProto.SubscribeMetadataResponse> watch(String prefix, String clientName, long sinceNs) { return this.getBlockingStub().subscribeMetadata(FilerProto.SubscribeMetadataRequest.newBuilder() .setPathPrefix(prefix) .setClientName(clientName) .setSinceNs(sinceNs) .build() ); } }
package com.egzosn.pay.wx.api; import com.alibaba.fastjson.JSONObject; import com.egzosn.pay.common.api.BasePayService; import com.egzosn.pay.common.api.Callback; import com.egzosn.pay.common.bean.*; import com.egzosn.pay.common.bean.result.PayException; import com.egzosn.pay.common.exception.PayErrorException; import com.egzosn.pay.common.http.HttpConfigStorage; import com.egzosn.pay.common.util.DateUtils; import com.egzosn.pay.common.util.MatrixToImageWriter; import com.egzosn.pay.common.util.Util; import com.egzosn.pay.common.util.sign.SignUtils; import com.egzosn.pay.common.util.sign.encrypt.RSA2; import com.egzosn.pay.common.util.str.StringUtils; import com.egzosn.pay.wx.bean.WxPayError; import com.egzosn.pay.wx.bean.WxTransactionType; import com.egzosn.pay.common.util.XML; import com.egzosn.pay.wx.bean.WxTransferType; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.net.URLEncoder; import java.util.*; import static com.egzosn.pay.wx.bean.WxTransferType.*; /** * * * @author egan * <pre> * email egzosn@gmail.com * date 2016-5-18 14:09:01 * </pre> */ public class WxPayService extends BasePayService<WxPayConfigStorage> { public static final String URI = "https://api.mch.weixin.qq.com/"; public static final String SANDBOXNEW = "sandboxnew/"; public static final String SUCCESS = "SUCCESS"; public static final String RETURN_CODE = "return_code"; public static final String SIGN = "sign"; public static final String CIPHER_ALGORITHM = "RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING"; public static final String FAILURE = "failure"; public static final String APPID = "appid"; private static final String HMAC_SHA256 = "HMAC-SHA256"; private static final String HMACSHA256 = "HMACSHA256"; private static final String RETURN_MSG_CODE = "return_msg"; private static final String RESULT_CODE = "result_code"; /** * * @param payConfigStorage */ public WxPayService(WxPayConfigStorage payConfigStorage) { super(payConfigStorage); } /** * * @param payConfigStorage * @param configStorage ssl */ public WxPayService(WxPayConfigStorage payConfigStorage, HttpConfigStorage configStorage) { super(payConfigStorage, configStorage); } /** * * @param payConfigStorage */ @Override public BasePayService setPayConfigStorage(WxPayConfigStorage payConfigStorage) { String signType = payConfigStorage.getSignType(); if (HMAC_SHA256.equals(signType)){ payConfigStorage.setSignType(HMACSHA256); } this.payConfigStorage = payConfigStorage; return this; } /** * url * * @param transactionType * * @return url */ private String getUrl(TransactionType transactionType) { return URI + (payConfigStorage.isTest() ? SANDBOXNEW : "") + transactionType.getMethod(); } /** * * * @param params * @return true */ @Override public boolean verify(Map<String, Object> params) { if (!(SUCCESS.equals(params.get(RETURN_CODE)) && SUCCESS.equals(params.get(RESULT_CODE)))){ LOG.debug(String.format("return_code=%s,=%s", params.get(RETURN_CODE), params)); return false; } if(null == params.get(SIGN)) { LOG.debug("out_trade_no=" + params.get("out_trade_no")); return false; } try { return signVerify(params, (String) params.get(SIGN)) && verifySource((String) params.get("out_trade_no")); } catch (PayErrorException e) { LOG.error(e); } return false; } /** * * * @param id * @return true */ @Override public boolean verifySource(String id) { return true; } /** * * * @param params * @param sign * @return */ @Override public boolean signVerify(Map<String, Object> params, String sign) { SignUtils signUtils = SignUtils.valueOf(payConfigStorage.getSignType()); String content = SignUtils.parameterText(params, "&", SIGN, "appId") + "&key=" + (signUtils == SignUtils.MD5 ? "" : payConfigStorage.getKeyPrivate()); return signUtils.verify(content, sign, payConfigStorage.getKeyPrivate(), payConfigStorage.getInputCharset()); } /** * * * @return */ private Map<String, Object> getPublicParameters() { Map<String, Object> parameters = new TreeMap<String, Object>(); parameters.put(APPID, payConfigStorage.getAppid()); parameters.put("mch_id", payConfigStorage.getMchId()); if (!StringUtils.isEmpty(payConfigStorage.getSubAppid()) && !StringUtils.isEmpty(payConfigStorage.getSubMchId())){ parameters.put("sub_appid", payConfigStorage.getSubAppid()); parameters.put("sub_mch_id", payConfigStorage.getSubMchId()); } parameters.put("nonce_str", SignUtils.randomStr()); return parameters; } /** * * * @param order * @return */ public JSONObject unifiedOrder(PayOrder order) { Map<String, Object> parameters = getPublicParameters(); parameters.put("body", order.getSubject()); // parameters.put("detail", order.getBody()); parameters.put("out_trade_no", order.getOutTradeNo()); parameters.put("spbill_create_ip", StringUtils.isEmpty(order.getSpbillCreateIp()) ? "192.168.1.150" : order.getSpbillCreateIp() ); parameters.put("total_fee", Util.conversionCentAmount( order.getPrice())); if (StringUtils.isNotEmpty(order.getAddition())){ parameters.put("attach", order.getAddition()); } parameters.put("notify_url", payConfigStorage.getNotifyUrl()); parameters.put("trade_type", order.getTransactionType().getType()); if (null != order.getExpirationTime()){ parameters.put("time_start", DateUtils.formatDate(new Date(), DateUtils.YYYYMMDDHHMMSS)); parameters.put("time_expire", DateUtils.formatDate(order.getExpirationTime(), DateUtils.YYYYMMDDHHMMSS)); } ((WxTransactionType) order.getTransactionType()).setAttribute(parameters, order); setSign(parameters); String requestXML = XML.getMap2Xml(parameters); LOG.debug("requestXML" + requestXML); JSONObject result = requestTemplate.postForObject(getUrl(order.getTransactionType()), requestXML, JSONObject.class); if (!SUCCESS.equals(result.get(RETURN_CODE))) { throw new PayErrorException(new WxPayError(result.getString(RETURN_CODE), result.getString(RETURN_MSG_CODE), result.toJSONString())); } return result; } /** * * * @param order * @return * @see PayOrder */ @Override public Map<String, Object> orderInfo(PayOrder order) { JSONObject result = unifiedOrder(order); if (verify(result)) { if (((WxTransactionType)order.getTransactionType()).isReturn()) { return result; } SortedMap<String, Object> params = new TreeMap<String, Object>(); if (WxTransactionType.JSAPI == order.getTransactionType()) { params.put("signType", payConfigStorage.getSignType()); params.put("appId", payConfigStorage.getAppid()); params.put("timeStamp", System.currentTimeMillis() / 1000); params.put("nonceStr", result.get("nonce_str")); params.put("package", "prepay_id=" + result.get("prepay_id")); } else if (WxTransactionType.APP == order.getTransactionType()) { params.put("partnerid", payConfigStorage.getPid()); params.put(APPID, payConfigStorage.getAppid()); params.put("prepayid", result.get("prepay_id")); params.put("timestamp", System.currentTimeMillis() / 1000); params.put("noncestr", result.get("nonce_str")); params.put("package", "Sign=WXPay"); } String paySign = createSign(SignUtils.parameterText(params), payConfigStorage.getInputCharset()); params.put(SIGN, paySign); return params; } throw new PayErrorException(new WxPayError(result.getString(RETURN_CODE), result.getString(RETURN_MSG_CODE), "Invalid sign value")); } /** * * * @param parameters * @return */ private Map<String, Object> setSign(Map<String, Object> parameters) { String signType = payConfigStorage.getSignType(); if (HMACSHA256.equals(signType)){ signType = HMAC_SHA256; } parameters.put("sign_type", signType); String sign = createSign(SignUtils.parameterText(parameters, "&", SIGN, "appId"), payConfigStorage.getInputCharset()); parameters.put(SIGN, sign); return parameters; } /** * * * @param content key * @param characterEncoding * @return */ @Override public String createSign(String content, String characterEncoding) { SignUtils signUtils = SignUtils.valueOf(payConfigStorage.getSignType().toUpperCase()); return signUtils.createSign(content + "&key=" + (signUtils == SignUtils.MD5 ? "" : payConfigStorage.getKeyPrivate()) , payConfigStorage.getKeyPrivate(), characterEncoding).toUpperCase(); } /** * Map * * @param parameterMap * @param is * @return */ @Override public Map<String, Object> getParameter2Map(Map<String, String[]> parameterMap, InputStream is) { TreeMap<String, Object> map = new TreeMap<String, Object>(); try { return XML.inputStream2Map(is, map); } catch (IOException e) { throw new PayErrorException(new PayException("IOException", e.getMessage())); } } /** * * * @param code * @param message * @return */ @Override public PayOutMessage getPayOutMessage(String code, String message) { return PayOutMessage.XML().code(code.toUpperCase()).content(message).build(); } /** * * * * @param payMessage * @return */ @Override public PayOutMessage successPayOutMessage(PayMessage payMessage) { return PayOutMessage.XML().code("Success").content("").build(); } /** * , web * * @param orderInfo * @param method "post" "get", * @return , web * @see MethodType */ @Override public String buildRequest(Map<String, Object> orderInfo, MethodType method) { if (!SUCCESS.equals(orderInfo.get(RETURN_CODE))) { throw new PayErrorException(new WxPayError((String) orderInfo.get(RETURN_CODE), (String) orderInfo.get(RETURN_MSG_CODE))); } if (WxTransactionType.MWEB.name().equals(orderInfo.get("trade_type"))) { return String.format("<script type=\"text/javascript\">location.href=\"%s%s\"</script>",orderInfo.get("mweb_url"), StringUtils.isEmpty(payConfigStorage.getReturnUrl()) ? "" : "&redirect_url=" + URLEncoder.encode(payConfigStorage.getReturnUrl())); } throw new UnsupportedOperationException(); } /** * , * * @param order * @return */ @Override public BufferedImage genQrPay(PayOrder order) { Map<String, Object> orderInfo = orderInfo(order); if (!SUCCESS.equals(orderInfo.get(RESULT_CODE))) { throw new PayErrorException(new WxPayError("-1", (String) orderInfo.get("err_code"))); } return MatrixToImageWriter.writeInfoToJpgBuff((String) orderInfo.get("code_url")); } /** * ,pos * * @param order * @return */ @Override public Map<String, Object> microPay(PayOrder order) { return orderInfo(order); } /** * * * @param transactionId * @param outTradeNo * @return */ @Override public Map<String, Object> query(String transactionId, String outTradeNo) { return secondaryInterface(transactionId, outTradeNo, WxTransactionType.QUERY); } /** * * * @param transactionId * @param outTradeNo * @return */ @Override public Map<String, Object> close(String transactionId, String outTradeNo) { return secondaryInterface(transactionId, outTradeNo, WxTransactionType.CLOSE); } /** * * * @param transactionId * @param outTradeNo * @return */ @Override public Map<String, Object> cancel(String transactionId, String outTradeNo) { return secondaryInterface(transactionId, outTradeNo, WxTransactionType.REVERSE); } /** * * * @param transactionId * @param outTradeNo * @param refundAmount * @param totalAmount * @return * @see #refund(RefundOrder, Callback) */ @Deprecated @Override public Map<String, Object> refund(String transactionId, String outTradeNo, BigDecimal refundAmount, BigDecimal totalAmount) { return refund(new RefundOrder(transactionId, outTradeNo, refundAmount, totalAmount)); } private Map<String, Object> setParameters(Map<String, Object> parameters, String key, String value){ if (!StringUtils.isEmpty(value)){ parameters.put(key, value); } return parameters; } /** * * * @param refundOrder * @return */ @Override public Map<String, Object> refund(RefundOrder refundOrder) { Map<String, Object> parameters = getPublicParameters(); setParameters(parameters, "transaction_id", refundOrder.getTradeNo()); setParameters(parameters, "out_trade_no", refundOrder.getOutTradeNo()); setParameters(parameters, "out_refund_no", refundOrder.getRefundNo()); parameters.put("total_fee", Util.conversionCentAmount(refundOrder.getTotalAmount())); parameters.put("refund_fee", Util.conversionCentAmount(refundOrder.getRefundAmount())); parameters.put("op_user_id", payConfigStorage.getPid()); setSign(parameters); return requestTemplate.postForObject(getUrl(WxTransactionType.REFUND), XML.getMap2Xml(parameters), JSONObject.class); } /** * * * @param transactionId * @param outTradeNo * @return */ @Override public Map<String, Object> refundquery(String transactionId, String outTradeNo) { return secondaryInterface(transactionId, outTradeNo, WxTransactionType.REFUNDQUERY); } /** * * * @param refundOrder * @return */ @Override public Map<String, Object> refundquery(RefundOrder refundOrder) { Map<String, Object> parameters = getPublicParameters(); setParameters(parameters, "transaction_id", refundOrder.getTradeNo()); setParameters(parameters, "out_trade_no", refundOrder.getOutTradeNo()); setParameters(parameters, "out_refund_no", refundOrder.getRefundNo()); setSign(parameters); return requestTemplate.postForObject(getUrl( WxTransactionType.REFUNDQUERY), XML.getMap2Xml(parameters) , JSONObject.class); } /** * * * @param billDate tradesigncustomertradesigncustomer * @param billType yyyy-MM-ddyyyy-MM * @return */ @Override public Map<String, Object> downloadbill(Date billDate, String billType) { Map<String, Object> parameters = getPublicParameters(); parameters.put("bill_type", billType); parameters.put("bill_date", DateUtils.formatDate(billDate, DateUtils.YYYYMMDD)); setSign(parameters); String respStr = requestTemplate.postForObject(getUrl(WxTransactionType.DOWNLOADBILL), XML.getMap2Xml(parameters), String.class); if (respStr.indexOf("<") == 0) { return XML.toJSONObject(respStr); } Map<String,Object> ret = new HashMap<String, Object>(); ret.put(RETURN_CODE, SUCCESS); ret.put(RETURN_MSG_CODE, "ok"); ret.put("data", respStr); return ret; } /** * @param transactionIdOrBillDate {@link String } {@link Date }{@link PayErrorException} * @param outTradeNoBillType * @param transactionType * @return */ @Override public Map<String, Object> secondaryInterface(Object transactionIdOrBillDate, String outTradeNoBillType, TransactionType transactionType) { if (transactionType == WxTransactionType.REFUND) { throw new PayErrorException(new PayException(FAILURE, ":" + transactionType)); } if (transactionType == WxTransactionType.DOWNLOADBILL){ if (transactionIdOrBillDate instanceof Date){ return downloadbill((Date) transactionIdOrBillDate, outTradeNoBillType); } throw new PayErrorException(new PayException(FAILURE, ":" + transactionIdOrBillDate.getClass())); } if (!(null == transactionIdOrBillDate || transactionIdOrBillDate instanceof String)){ throw new PayErrorException(new PayException(FAILURE, ":" + transactionIdOrBillDate.getClass())); } Map<String, Object> parameters = getPublicParameters(); if (StringUtils.isEmpty((String)transactionIdOrBillDate)){ parameters.put("out_trade_no", outTradeNoBillType); }else { parameters.put("transaction_id", transactionIdOrBillDate); } setSign(parameters); return requestTemplate.postForObject(getUrl(transactionType), XML.getMap2Xml(parameters) , JSONObject.class); } @Override public Map<String, Object> transfer(TransferOrder order) { Map<String, Object> parameters = new TreeMap<String, Object>(); parameters.put("partner_trade_no", order.getOutNo()); parameters.put("amount", Util.conversionCentAmount(order.getAmount())); if (!StringUtils.isEmpty(order.getRemark())){ parameters.put("desc", order.getRemark()); } parameters.put("nonce_str", SignUtils.randomStr()); if (null != order.getTransferType() && TRANSFERS == order.getTransferType()){ transfers(parameters, order); parameters.put("mchid", payConfigStorage.getPid()); }else { parameters.put("mch_id", payConfigStorage.getPid()); order.setTransferType(WxTransferType.PAY_BANK); payBank(parameters, order); } parameters.put(SIGN, createSign(SignUtils.parameterText(parameters, "&", SIGN), payConfigStorage.getInputCharset())); return getHttpRequestTemplate().postForObject(getUrl(order.getTransferType()), XML.getMap2Xml(parameters), JSONObject.class); } public Map<String, Object> transfers(Map<String, Object> parameters, TransferOrder order){ //, appidappid parameters.put("mch_appid", payConfigStorage.getAppid()); parameters.put("openid", order.getPayeeAccount()); parameters.put("check_name", "NO_CHECK"); if (!StringUtils.isEmpty(order.getPayeeName())){ parameters.put("check_name", "FORCE_CHECK"); parameters.put("re_user_name", order.getPayeeName()); } return parameters; } /** * * @param parameters * @param order * @return */ public Map<String, Object> payBank(Map<String, Object> parameters, TransferOrder order){ parameters.put("enc_bank_no", keyPublic(order.getPayeeAccount())); parameters.put("enc_true_name", keyPublic(order.getPayeeName())); parameters.put("bank_code", order.getBank().getCode()); return parameters; } @Override public Map<String, Object> transferQuery(String outNo, String wxTransferType) { Map<String, Object> parameters = new TreeMap<String, Object>(); parameters.put("mch_id", payConfigStorage.getPid()); parameters.put("partner_trade_no", outNo); parameters.put("nonce_str", SignUtils.randomStr()); parameters.put(SIGN, createSign(SignUtils.parameterText(parameters, "&", SIGN), payConfigStorage.getInputCharset())); if (StringUtils.isEmpty(wxTransferType)){ throw new PayErrorException(new WxPayError(FAILURE, " #transferQuery(String outNo, String wxTransferType) com.egzosn.pay.wx.bean.WxTransferType")); } if (TRANSFERS.getType().equals(wxTransferType) || GETTRANSFERINFO.getType().equals(wxTransferType)){ return getHttpRequestTemplate().postForObject(getUrl(GETTRANSFERINFO), XML.getMap2Xml(parameters), JSONObject.class); } return getHttpRequestTemplate().postForObject(getUrl(QUERY_BANK), XML.getMap2Xml(parameters), JSONObject.class); } public String keyPublic(String content){ try { return RSA2.encrypt(content, payConfigStorage.getKeyPublic(), CIPHER_ALGORITHM, payConfigStorage.getInputCharset()); } catch (Exception e) { throw new PayErrorException(new WxPayError(FAILURE, e.getLocalizedMessage())); } } }
package com.intellij.diagnostic; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.util.io.FileUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * @author yole */ public class PerformanceWatcher implements ApplicationComponent { private Thread myThread; private int myLoopCounter; private int mySwingThreadCounter; private Semaphore myShutdownSemaphore = new Semaphore(1); private ThreadMXBean myThreadMXBean; private Method myDumpAllThreadsMethod; private DateFormat myDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss"); private DateFormat myPrintDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); private File myLogDir; private int myUnresponsiveDuration = 0; @NotNull public String getComponentName() { return "PerformanceWatcher"; } public void initComponent() { if (shallNotWatch()) return; deleteOldThreadDumps(); myLogDir = new File(PathManager.getSystemPath() + "/log/threadDumps-" + myDateFormat.format(new Date())); myLogDir.mkdirs(); myThreadMXBean = ManagementFactory.getThreadMXBean(); // this method was added in JDK 1.6 so we have to all it through reflection try { myDumpAllThreadsMethod = ThreadMXBean.class.getMethod("dumpAllThreads", boolean.class, boolean.class); } catch (NoSuchMethodException e) { myDumpAllThreadsMethod = null; } try { myShutdownSemaphore.acquire(); } catch (InterruptedException e) { // ignore } myThread = new Thread(new Runnable() { public void run() { checkEDTResponsiveness(); } }, "Performance watcher"); myThread.start(); } private static void deleteOldThreadDumps() { File allLogsDir = new File(PathManager.getSystemPath(), "log"); final String[] dirs = allLogsDir.list(new FilenameFilter() { public boolean accept(final File dir, final String name) { return name.startsWith("threadDumps-"); } }); Arrays.sort(dirs); for (int i = 0; i < dirs.length - 10; i++) { FileUtil.delete(new File(allLogsDir, dirs [i])); } } public void disposeComponent() { if (shallNotWatch()) return; myShutdownSemaphore.release(); try { myThread.join(); } catch (InterruptedException e) { // ignore } } private static boolean shallNotWatch() { return ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isHeadlessEnvironment(); } private void checkEDTResponsiveness() { while(true) { try { if (myShutdownSemaphore.tryAcquire(1, TimeUnit.SECONDS)) { break; } } catch (InterruptedException e) { break; } if (mySwingThreadCounter != myLoopCounter) { if (myUnresponsiveDuration == 0) { System.out.println("EDT is not responding at " + myPrintDateFormat.format(new Date())); } myUnresponsiveDuration++; dumpThreads(); } else if (myUnresponsiveDuration > 0) { System.out.println("EDT was unresponsive for " + myUnresponsiveDuration + " seconds"); myUnresponsiveDuration = 0; } myLoopCounter++; SwingUtilities.invokeLater(new SwingThreadRunnable(myLoopCounter)); } } private void dumpThreads() { File f = new File(myLogDir, "threadDump-" + myDateFormat.format(new Date()) + ".txt"); FileOutputStream fos; try { fos = new FileOutputStream(f); } catch (FileNotFoundException e) { return; } OutputStreamWriter writer = new OutputStreamWriter(fos); try { dumpThreadsToFile(writer); } finally { try { writer.close(); } catch (IOException e) { // ignore } } } private void dumpThreadsToFile(final OutputStreamWriter f) { boolean dumpSuccessful = false; if (myDumpAllThreadsMethod != null) { try { ThreadInfo[] threads = (ThreadInfo[])myDumpAllThreadsMethod.invoke(myThreadMXBean, false, false); for(ThreadInfo info: threads) { dumpCallStack(info, f); } dumpSuccessful = true; } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } private static void dumpCallStack(final ThreadInfo info, final OutputStreamWriter f) throws IOException { f.write("\"" + info.getThreadName() + "\"\n"); StackTraceElement[] stackTraceElements = info.getStackTrace(); for(StackTraceElement element: stackTraceElements) { f.write("\tat " + element.toString() + "\n"); } f.write("\n"); } private class SwingThreadRunnable implements Runnable { private int myCount; private SwingThreadRunnable(final int count) { myCount = count; } public void run() { mySwingThreadCounter = myCount; } } }
package com.intellij.util.ui.tree; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.ScrollingUtil; import com.intellij.ui.SimpleColoredComponent; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.scale.JBUIScale; import com.intellij.ui.tree.TreeVisitor; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ObjectUtils; import com.intellij.util.Range; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.JBIterable; import com.intellij.util.containers.JBTreeTraverser; import com.intellij.util.containers.TreeTraversal; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.concurrency.Promise; import org.jetbrains.concurrency.Promises; import javax.accessibility.AccessibleContext; import javax.swing.*; import javax.swing.plaf.TreeUI; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.tree.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.lang.reflect.Method; import java.util.List; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.intellij.util.ReflectionUtil.getDeclaredMethod; import static com.intellij.util.ReflectionUtil.getField; import static java.util.stream.Collectors.toList; public final class TreeUtil { public static final TreePath[] EMPTY_TREE_PATH = new TreePath[0]; private static final Logger LOG = Logger.getInstance(TreeUtil.class); private static final String TREE_UTIL_SCROLL_TIME_STAMP = "TreeUtil.scrollTimeStamp"; private static final JBIterable<Integer> NUMBERS = JBIterable.generate(0, i -> i + 1); private TreeUtil() {} @NotNull public static JBTreeTraverser<Object> treeTraverser(@NotNull JTree tree) { TreeModel model = tree.getModel(); Object root = model.getRoot(); return JBTreeTraverser.from(node -> nodeChildren(node, model)).withRoot(root); } @NotNull public static JBTreeTraverser<TreePath> treePathTraverser(@NotNull JTree tree) { TreeModel model = tree.getModel(); Object root = model.getRoot(); TreePath rootPath = root == null ? null : new TreePath(root); return JBTreeTraverser.<TreePath>from(path -> nodeChildren(path.getLastPathComponent(), model) .map(o -> path.pathByAddingChild(o))) .withRoot(rootPath); } @NotNull public static JBIterable<Object> nodeChildren(@Nullable Object node, @NotNull TreeModel model) { int count = model.getChildCount(node); return count == 0 ? JBIterable.empty() : NUMBERS.take(count).map(index -> model.getChild(node, index)); } @NotNull public static JBTreeTraverser<TreeNode> treeNodeTraverser(@Nullable TreeNode treeNode) { return JBTreeTraverser.<TreeNode>from(node -> nodeChildren(node)).withRoot(treeNode); } @NotNull public static JBIterable<TreeNode> nodeChildren(@Nullable TreeNode treeNode) { int count = treeNode == null ? 0 : treeNode.getChildCount(); return count == 0 ? JBIterable.empty() : NUMBERS.take(count).map(index -> treeNode.getChildAt(index)); } /** * @param tree a tree, which viewable paths are processed * @return a list of expanded paths */ @NotNull public static List<TreePath> collectExpandedPaths(@NotNull JTree tree) { return collectExpandedObjects(tree, Function.identity()); } /** * @param tree a tree, which viewable paths are processed * @return a list of user objects which correspond to expanded paths under the specified root node */ @NotNull public static List<Object> collectExpandedUserObjects(@NotNull JTree tree) { return collectExpandedObjects(tree, TreeUtil::getLastUserObject); } /** * @param tree a tree, which viewable paths are processed * @param mapper a function to convert a expanded tree path to a corresponding object * @return a list of objects which correspond to expanded paths under the specified root node */ @NotNull public static <T> List<T> collectExpandedObjects(@NotNull JTree tree, @NotNull Function<? super TreePath, ? extends T> mapper) { return collectVisibleRows(tree, tree::isExpanded, mapper); } @Nullable public static <T> T findObjectInPath(@Nullable TreePath path, @NotNull Class<T> clazz) { while (path != null) { T object = getLastUserObject(clazz, path); if (object != null) return object; path = path.getParentPath(); } return null; } /** * @param tree a tree, which selection is processed * @param type a {@code Class} object to filter selected user objects * @return a list of user objects of the specified type retrieved from all selected paths */ @NotNull public static <T> List<T> collectSelectedObjectsOfType(@NotNull JTree tree, @NotNull Class<? extends T> type) { return collectSelectedObjects(tree, path -> getLastUserObject(type, path)); } /** * @param tree a tree, which viewable paths are processed * @param root an ascendant tree path to filter expanded tree paths * @return a list of expanded paths under the specified root node */ @NotNull public static List<TreePath> collectExpandedPaths(@NotNull JTree tree, @NotNull TreePath root) { return collectExpandedObjects(tree, root, Function.identity()); } /** * @param tree a tree, which viewable paths are processed * @param root an ascendant tree path to filter expanded tree paths * @return a list of user objects which correspond to expanded paths under the specified root node */ @NotNull public static List<Object> collectExpandedUserObjects(@NotNull JTree tree, @NotNull TreePath root) { return collectExpandedObjects(tree, root, TreeUtil::getLastUserObject); } /** * @param tree a tree, which viewable paths are processed * @param root an ascendant tree path to filter expanded tree paths * @param mapper a function to convert a expanded tree path to a corresponding object * @return a list of objects which correspond to expanded paths under the specified root node */ @NotNull public static <T> List<T> collectExpandedObjects(@NotNull JTree tree, @NotNull TreePath root, @NotNull Function<? super TreePath, ? extends T> mapper) { if (!tree.isVisible(root)) return Collections.emptyList(); // invisible path should not be expanded return collectVisibleRows(tree, path -> tree.isExpanded(path) && root.isDescendant(path), mapper); } /** * Expands specified paths. * @param tree JTree to apply expansion status to * @param paths to expand. See {@link #collectExpandedPaths(JTree, TreePath)} */ public static void restoreExpandedPaths(@NotNull final JTree tree, @NotNull final List<? extends TreePath> paths){ for(int i = paths.size() - 1; i >= 0; i tree.expandPath(paths.get(i)); } } @NotNull public static TreePath getPath(@NotNull TreeNode aRootNode, @NotNull TreeNode aNode) { TreeNode[] nodes = getPathFromRootTo(aRootNode, aNode, true); return new TreePath(nodes); } public static boolean isAncestor(@NotNull TreeNode ancestor, @NotNull TreeNode node) { TreeNode parent = node; while (parent != null) { if (parent == ancestor) return true; parent = parent.getParent(); } return false; } private static boolean isAncestor(@NotNull final TreePath ancestor, @NotNull final TreePath path) { if (path.getPathCount() < ancestor.getPathCount()) return false; for (int i = 0; i < ancestor.getPathCount(); i++) if (!path.getPathComponent(i).equals(ancestor.getPathComponent(i))) return false; return true; } private static boolean isDescendants(@NotNull final TreePath path, final TreePath @NotNull [] paths) { for (final TreePath ancestor : paths) { if (isAncestor(ancestor, path)) return true; } return false; } @NotNull public static TreePath getPathFromRoot(@NotNull TreeNode node) { TreeNode[] path = getPathFromRootTo(null, node, false); return new TreePath(path); } private static TreeNode @NotNull [] getPathFromRootTo(@Nullable TreeNode root, @NotNull TreeNode node, boolean includeRoot) { int height = 0; for (TreeNode n = node; n != root; n = n.getParent()) { height++; } TreeNode[] path = new TreeNode[includeRoot ? height+1 : height]; int i = path.length-1; for (TreeNode n = node; i>=0; n = n.getParent()) { path[i } return path; } @Nullable public static TreeNode findNodeWithObject(final Object object, @NotNull final TreeModel model, final Object parent) { for (int i = 0; i < model.getChildCount(parent); i++) { final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) model.getChild(parent, i); if (childNode.getUserObject().equals(object)) return childNode; } return null; } /** * Removes last component in the current selection path. * * @param tree to remove selected node from. */ public static void removeSelected(@NotNull final JTree tree) { TreePath[] paths = tree.getSelectionPaths(); if (paths == null) { return; } for (TreePath path : paths) { removeLastPathComponent((DefaultTreeModel) tree.getModel(), path).restoreSelection(tree); } } public static void removeLastPathComponent(@NotNull final JTree tree, @NotNull final TreePath pathToBeRemoved){ removeLastPathComponent((DefaultTreeModel)tree.getModel(), pathToBeRemoved).restoreSelection(tree); } @Nullable public static DefaultMutableTreeNode findNodeWithObject(@NotNull final DefaultMutableTreeNode aRoot, final Object aObject) { return findNode(aRoot, node -> Comparing.equal(node.getUserObject(), aObject)); } @Nullable public static DefaultMutableTreeNode findNode(@NotNull final DefaultMutableTreeNode aRoot, @NotNull final Condition<? super DefaultMutableTreeNode> condition) { if (condition.value(aRoot)) { return aRoot; } else { for (int i = 0; i < aRoot.getChildCount(); i++) { final DefaultMutableTreeNode candidate = findNode((DefaultMutableTreeNode)aRoot.getChildAt(i), condition); if (null != candidate) { return candidate; } } return null; } } /** * @deprecated use TreePathUtil#findCommonAncestor(TreePath...) instead */ @NotNull @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2020.2") public static TreePath findCommonPath(final TreePath @NotNull [] treePaths) { LOG.assertTrue(areComponentsEqual(treePaths, 0)); TreePath result = new TreePath(treePaths[0].getPathComponent(0)); int pathIndex = 1; while (areComponentsEqual(treePaths, pathIndex)) { result = result.pathByAddingChild(treePaths[0].getPathComponent(pathIndex)); pathIndex++; } return result; } /** * Tries to select the first node in the specified tree as soon as possible. * * @param tree a tree, which node should be selected * @return a callback that will be done when first visible node is selected * @see #promiseSelectFirst */ @NotNull public static ActionCallback selectFirstNode(@NotNull JTree tree) { return Promises.toActionCallback(promiseSelectFirst(tree)); } @NotNull public static TreePath getFirstNodePath(@NotNull JTree tree) { TreeModel model = tree.getModel(); Object root = model.getRoot(); TreePath selectionPath = new TreePath(root); if (!tree.isRootVisible() && model.getChildCount(root) > 0) { selectionPath = selectionPath.pathByAddingChild(model.getChild(root, 0)); } return selectionPath; } /** * @deprecated use {@link #promiseSelectFirstLeaf} */ @Deprecated @NotNull public static TreePath getFirstLeafNodePath(@NotNull JTree tree) { final TreeModel model = tree.getModel(); Object root = model.getRoot(); TreePath selectionPath = new TreePath(root); while (model.getChildCount(root) > 0) { final Object child = model.getChild(root, 0); selectionPath = selectionPath.pathByAddingChild(child); root = child; } return selectionPath; } @NotNull private static IndexTreePathState removeLastPathComponent(@NotNull final DefaultTreeModel model, @NotNull final TreePath pathToBeRemoved) { final IndexTreePathState selectionState = new IndexTreePathState(pathToBeRemoved); if (((MutableTreeNode) pathToBeRemoved.getLastPathComponent()).getParent() == null) return selectionState; model.removeNodeFromParent((MutableTreeNode)pathToBeRemoved.getLastPathComponent()); return selectionState; } private static boolean areComponentsEqual(final TreePath @NotNull [] paths, final int componentIndex) { if (paths[0].getPathCount() <= componentIndex) return false; final Object pathComponent = paths[0].getPathComponent(componentIndex); for (final TreePath treePath : paths) { if (treePath.getPathCount() <= componentIndex) return false; if (!pathComponent.equals(treePath.getPathComponent(componentIndex))) return false; } return true; } private static TreePath @NotNull [] removeDuplicates(final TreePath @NotNull [] paths) { final ArrayList<TreePath> result = new ArrayList<>(); for (final TreePath path : paths) { if (!result.contains(path)) result.add(path); } return result.toArray(EMPTY_TREE_PATH); } /** * @deprecated use TreeCollector.TreePathRoots#collect(TreePath...) instead */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2020.2") public static TreePath @NotNull [] selectMaximals(final TreePath @Nullable [] paths) { if (paths == null) return EMPTY_TREE_PATH; final TreePath[] noDuplicates = removeDuplicates(paths); final ArrayList<TreePath> result = new ArrayList<>(); for (final TreePath path : noDuplicates) { final ArrayList<TreePath> otherPaths = new ArrayList<>(Arrays.asList(noDuplicates)); otherPaths.remove(path); if (!isDescendants(path, otherPaths.toArray(EMPTY_TREE_PATH))) result.add(path); } return result.toArray(EMPTY_TREE_PATH); } public static void sort(@NotNull final DefaultTreeModel model, @Nullable Comparator comparator) { sort((DefaultMutableTreeNode) model.getRoot(), comparator); } public static void sort(@NotNull final DefaultMutableTreeNode node, @Nullable Comparator comparator) { sortRecursively(node, comparator); } public static <T extends MutableTreeNode> void sortRecursively(@NotNull T node, @Nullable Comparator<? super T> comparator) { sortChildren(node, comparator); for (int i = 0; i < node.getChildCount(); i++) { //noinspection unchecked sortRecursively((T) node.getChildAt(i), comparator); } } public static <T extends MutableTreeNode> void sortChildren(@NotNull T node, @Nullable Comparator<? super T> comparator) { //noinspection unchecked final List<T> children = (List)listChildren(node); Collections.sort(children, comparator); for (int i = node.getChildCount() - 1; i >= 0; i node.remove(i); } addChildrenTo(node, children); } public static void addChildrenTo(@NotNull final MutableTreeNode node, @NotNull final List<? extends TreeNode> children) { for (final Object aChildren : children) { final MutableTreeNode child = (MutableTreeNode)aChildren; node.insert(child, node.getChildCount()); } } /** @deprecated use TreeUtil#treeTraverser() or TreeUtil#treeNodeTraverser() directly */ @Deprecated public static boolean traverse(@NotNull TreeNode node, @NotNull Traverse traverse) { return treeNodeTraverser(node).traverse(TreeTraversal.POST_ORDER_DFS).processEach(traverse::accept); } /** @deprecated use TreeUtil#treeTraverser() or TreeUtil#treeNodeTraverser() directly */ @Deprecated public static boolean traverseDepth(@NotNull TreeNode node, @NotNull Traverse traverse) { return treeNodeTraverser(node).traverse(TreeTraversal.PRE_ORDER_DFS).processEach(traverse::accept); } /** * Makes visible specified tree paths and select them. * It does not clear selection if there are no paths to select. * * @param tree a tree to select in * @param paths a collection of paths to select * @see JTree#clearSelection */ @ApiStatus.Internal public static void selectPaths(@NotNull JTree tree, @NotNull Collection<? extends TreePath> paths) { if (paths.isEmpty()) return; paths.forEach(tree::makeVisible); internalSelect(tree, paths); } /** * @deprecated use {{@link #selectPaths(JTree, Collection)}} instead */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2020.2") public static void selectPaths(@NotNull JTree tree, TreePath @NotNull ... paths) { if (paths.length == 0) return; for (TreePath path : paths) { tree.makeVisible(path); } tree.setSelectionPaths(paths); tree.scrollPathToVisible(paths[0]); } @NotNull public static ActionCallback selectPath(@NotNull final JTree tree, final TreePath path) { return selectPath(tree, path, true); } @NotNull public static ActionCallback selectPath(@NotNull final JTree tree, final TreePath path, boolean center) { tree.makeVisible(path); Rectangle bounds = tree.getPathBounds(path); if (bounds == null) return ActionCallback.REJECTED; if (center) { Rectangle visible = tree.getVisibleRect(); if (visible.y < bounds.y + bounds.height && bounds.y < visible.y + visible.height) { center = false; // disable centering if the given path is already visible } } if (center) { return showRowCentred(tree, tree.getRowForPath(path)); } else { final int row = tree.getRowForPath(path); return showAndSelect(tree, row - ScrollingUtil.ROW_PADDING, row + ScrollingUtil.ROW_PADDING, row, -1); } } @NotNull public static ActionCallback moveDown(@NotNull final JTree tree) { final int size = tree.getRowCount(); int row = tree.getLeadSelectionRow(); if (row < size - 1) { row++; return showAndSelect(tree, row, row + 2, row, getSelectedRow(tree), false, true, true); } else { return ActionCallback.DONE; } } @NotNull public static ActionCallback moveUp(@NotNull final JTree tree) { int row = tree.getLeadSelectionRow(); if (row > 0) { row return showAndSelect(tree, row - 2, row, row, getSelectedRow(tree), false, true, true); } else { return ActionCallback.DONE; } } @NotNull public static ActionCallback movePageUp(@NotNull final JTree tree) { final int visible = getVisibleRowCount(tree); if (visible <= 0){ return moveHome(tree); } final int decrement = visible - 1; final int row = Math.max(getSelectedRow(tree) - decrement, 0); final int top = getFirstVisibleRow(tree) - decrement; final int bottom = top + visible - 1; return showAndSelect(tree, top, bottom, row, getSelectedRow(tree)); } @NotNull public static ActionCallback movePageDown(@NotNull final JTree tree) { final int visible = getVisibleRowCount(tree); if (visible <= 0){ return moveEnd(tree); } final int size = tree.getRowCount(); final int increment = visible - 1; final int index = Math.min(getSelectedRow(tree) + increment, size - 1); final int top = getFirstVisibleRow(tree) + increment; final int bottom = top + visible - 1; return showAndSelect(tree, top, bottom, index, getSelectedRow(tree)); } @NotNull private static ActionCallback moveHome(@NotNull final JTree tree) { return showRowCentred(tree, 0); } @NotNull private static ActionCallback moveEnd(@NotNull final JTree tree) { return showRowCentred(tree, tree.getRowCount() - 1); } @NotNull private static ActionCallback showRowCentred(@NotNull final JTree tree, final int row) { return showRowCentered(tree, row, true); } @NotNull public static ActionCallback showRowCentered(@NotNull final JTree tree, final int row, final boolean centerHorizontally) { return showRowCentered(tree, row, centerHorizontally, true); } @NotNull public static ActionCallback showRowCentered(@NotNull final JTree tree, final int row, final boolean centerHorizontally, boolean scroll) { final int visible = getVisibleRowCount(tree); final int top = visible > 0 ? row - (visible - 1)/ 2 : row; final int bottom = visible > 0 ? top + visible - 1 : row; return showAndSelect(tree, top, bottom, row, -1, false, scroll, false); } @NotNull public static ActionCallback showAndSelect(@NotNull final JTree tree, int top, int bottom, final int row, final int previous) { return showAndSelect(tree, top, bottom, row, previous, false); } @NotNull public static ActionCallback showAndSelect(@NotNull final JTree tree, int top, int bottom, final int row, final int previous, boolean addToSelection) { return showAndSelect(tree, top, bottom, row, previous, addToSelection, true, false); } @NotNull public static ActionCallback showAndSelect(@NotNull final JTree tree, int top, int bottom, final int row, final int previous, final boolean addToSelection, final boolean scroll) { return showAndSelect(tree, top, bottom, row, previous, addToSelection, scroll, false); } @NotNull public static ActionCallback showAndSelect(@NotNull final JTree tree, int top, int bottom, final int row, final int previous, final boolean addToSelection, final boolean scroll, final boolean resetSelection) { final TreePath path = tree.getPathForRow(row); if (path == null) return ActionCallback.DONE; final int size = tree.getRowCount(); if (size == 0) { tree.clearSelection(); return ActionCallback.DONE; } if (top < 0){ top = 0; } if (bottom >= size){ bottom = size - 1; } if (row >= tree.getRowCount()) return ActionCallback.DONE; boolean okToScroll = true; if (tree.isShowing()) { if (!tree.isValid()) { tree.validate(); } } else { Application app = ApplicationManager.getApplication(); if (app != null && app.isUnitTestMode()) { okToScroll = false; } } Runnable selectRunnable = () -> { if (!tree.isRowSelected(row)) { if (addToSelection) { tree.getSelectionModel().addSelectionPath(tree.getPathForRow(row)); } else { tree.setSelectionRow(row); } } else if (resetSelection) { if (!addToSelection) { tree.setSelectionRow(row); } } }; if (!okToScroll || !scroll) { selectRunnable.run(); return ActionCallback.DONE; } final Rectangle rowBounds = tree.getRowBounds(row); if (rowBounds == null) return ActionCallback.DONE; Rectangle topBounds = tree.getRowBounds(top); if (topBounds == null) { topBounds = rowBounds; } Rectangle bottomBounds = tree.getRowBounds(bottom); if (bottomBounds == null) { bottomBounds = rowBounds; } Rectangle bounds = topBounds.union(bottomBounds); bounds.x = rowBounds.x; bounds.width = rowBounds.width; final Rectangle visible = tree.getVisibleRect(); if (visible.contains(bounds)) { selectRunnable.run(); return ActionCallback.DONE; } final Component comp = tree.getCellRenderer().getTreeCellRendererComponent(tree, path.getLastPathComponent(), true, true, false, row, false); if (comp instanceof SimpleColoredComponent) { final SimpleColoredComponent renderer = (SimpleColoredComponent)comp; final Dimension scrollableSize = renderer.computePreferredSize(true); bounds.width = scrollableSize.width; } final ActionCallback callback = new ActionCallback(); selectRunnable.run(); final Range<Integer> range = getExpandControlRange(tree, path); if (range != null) { int delta = bounds.x - range.getFrom().intValue(); bounds.x -= delta; bounds.width -= delta; } if (visible.width < bounds.width) { bounds.width = visible.width; } if (tree instanceof Tree && !((Tree)tree).isHorizontalAutoScrollingEnabled()) { bounds.x = tree.getVisibleRect().x; } LOG.debug("tree scroll: ", path); tree.scrollRectToVisible(bounds); // try to scroll later when the tree is ready Object property = tree.getClientProperty(TREE_UTIL_SCROLL_TIME_STAMP); long stamp = property instanceof Long ? (Long)property + 1L : Long.MIN_VALUE; tree.putClientProperty(TREE_UTIL_SCROLL_TIME_STAMP, stamp); // store relative offset because the row can be moved during the tree updating int offset = rowBounds.y - bounds.y; AbstractTreeBuilder builder = AbstractTreeBuilder.getBuilderFor(tree); scrollToVisible(tree, path, bounds, offset, stamp, callback::setDone, builder, 3); return callback; } private static void scrollToVisible(JTree tree, TreePath path, Rectangle bounds, int offset, long expected, Runnable done, AbstractTreeBuilder builder, int attempt) { Runnable scroll = () -> { Rectangle pathBounds = attempt <= 0 ? null : tree.getPathBounds(path); if (pathBounds != null) { Object property = tree.getClientProperty(TREE_UTIL_SCROLL_TIME_STAMP); long stamp = property instanceof Long ? (Long)property : Long.MAX_VALUE; LOG.debug("tree scroll ", attempt, stamp == expected ? ": try again: " : ": ignore: ", path); if (stamp == expected) { bounds.y = pathBounds.y - offset; // restore bounds according to the current row Rectangle visible = tree.getVisibleRect(); if (bounds.y < visible.y || bounds.y > visible.y + Math.max(0, visible.height - bounds.height)) { tree.scrollRectToVisible(bounds); scrollToVisible(tree, path, bounds, offset, expected, done, builder, attempt - 1); return; // try to scroll again } } } done.run(); }; //noinspection SSBasedInspection SwingUtilities.invokeLater(builder == null ? scroll : () -> builder.getReady(TreeUtil.class).doWhenDone(scroll)); } // this method returns FIRST selected row but not LEAD private static int getSelectedRow(@NotNull final JTree tree) { return tree.getRowForPath(tree.getSelectionPath()); } private static int getFirstVisibleRow(@NotNull final JTree tree) { final Rectangle visible = tree.getVisibleRect(); int row = -1; for (int i=0; i < tree.getRowCount(); i++) { final Rectangle bounds = tree.getRowBounds(i); if (visible.y <= bounds.y && visible.y + visible.height >= bounds.y + bounds.height) { row = i; break; } } return row; } /** * Returns a number of tree rows currently visible. Do not mix with {@link JTree#getVisibleRowCount()} * which returns a preferred number of rows to be displayed within a scroll pane. * * @param tree tree to get the number of visible rows * @return number of visible rows, including partially visible ones. Not more than total number of tree rows. */ public static int getVisibleRowCount(@NotNull final JTree tree) { final Rectangle visible = tree.getVisibleRect(); if (visible == null) return 0; int rowCount = tree.getRowCount(); if (rowCount <= 0) return 0; int firstRow; int lastRow; int rowHeight = tree.getRowHeight(); if (rowHeight > 0) { Insets insets = tree.getInsets(); int top = visible.y - insets.top; int bottom = visible.y + visible.height - insets.top; firstRow = Math.max(0, Math.min(top / rowHeight, rowCount - 1)); lastRow = Math.max(0, Math.min(bottom / rowHeight, rowCount - 1)); } else { firstRow = tree.getClosestRowForLocation(visible.x, visible.y); lastRow = tree.getClosestRowForLocation(visible.x, visible.y + visible.height); } return lastRow - firstRow + 1; } @SuppressWarnings("HardCodedStringLiteral") public static void installActions(@NotNull final JTree tree) { TreeUI ui = tree.getUI(); if (ui != null && ui.getClass().getName().equals("com.intellij.ui.tree.ui.DefaultTreeUI")) return; tree.getActionMap().put("scrollUpChangeSelection", new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { movePageUp(tree); } }); tree.getActionMap().put("scrollDownChangeSelection", new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { movePageDown(tree); } }); tree.getActionMap().put("selectPrevious", new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { moveUp(tree); } }); tree.getActionMap().put("selectNext", new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { moveDown(tree); } }); copyAction(tree, "selectLast", "selectLastChangeLead"); copyAction(tree, "selectFirst", "selectFirstChangeLead"); InputMap inputMap = tree.getInputMap(JComponent.WHEN_FOCUSED); UIUtil.maybeInstall(inputMap, "scrollUpChangeSelection", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0)); UIUtil.maybeInstall(inputMap, "scrollDownChangeSelection", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0)); UIUtil.maybeInstall(inputMap, "selectNext", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)); UIUtil.maybeInstall(inputMap, "selectPrevious", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)); UIUtil.maybeInstall(inputMap, "selectLast", KeyStroke.getKeyStroke(KeyEvent.VK_END, 0)); UIUtil.maybeInstall(inputMap, "selectFirst", KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0)); } private static void copyAction(@NotNull final JTree tree, String original, String copyTo) { final Action action = tree.getActionMap().get(original); if (action != null) { tree.getActionMap().put(copyTo, action); } } /** * @param tree a tree, which nodes should be collapsed * @param keepSelectionLevel a minimal path count of a lead selection path or {@code -1} to restore old selection */ public static void collapseAll(@NotNull JTree tree, final int keepSelectionLevel) { assert EventQueue.isDispatchThread(); int row = tree.getRowCount(); if (row <= 1) return; // nothing to collapse final TreePath leadSelectionPath = tree.getLeadSelectionPath(); int threshold = 1; // allowed path count to collapse if (!tree.isRootVisible()) threshold++; if (!tree.getShowsRootHandles()) threshold++; // Collapse all boolean strict = false; // do not allow to collapse a top level node if is only one while (0 < row if (!strict && row == 0) break; TreePath path = tree.getPathForRow(row); assert path != null : "path is not found at row " + row; int count = path.getPathCount(); if (count == threshold && row > 0) strict = true; if (count >= threshold) tree.collapsePath(path); } if (!strict) threshold++; // top level node is not collapsed if (leadSelectionPath != null) { TreePath path = leadSelectionPath; if (keepSelectionLevel >= 0) { int count = path.getPathCount() - Math.max(keepSelectionLevel, threshold); while (0 < count--) path = path.getParentPath(); // normalize to given level } selectPath(tree, path); } } public static void selectNode(@NotNull final JTree tree, final TreeNode node) { selectPath(tree, getPathFromRoot(node)); } public static void moveSelectedRow(@NotNull final JTree tree, final int direction){ final TreePath selectionPath = tree.getSelectionPath(); final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent(); final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)treeNode.getParent(); final int idx = parent.getIndex(treeNode); ((DefaultTreeModel)tree.getModel()).removeNodeFromParent(treeNode); ((DefaultTreeModel)tree.getModel()).insertNodeInto(treeNode, parent, idx + direction); selectNode(tree, treeNode); } @NotNull public static List<TreeNode> listChildren(@NotNull final TreeNode node) { //ApplicationManager.getApplication().assertIsDispatchThread(); int size = node.getChildCount(); ArrayList<TreeNode> result = new ArrayList<>(size); for(int i = 0; i < size; i++){ TreeNode child = node.getChildAt(i); LOG.assertTrue(child != null); result.add(child); } return result; } public static void expandRootChildIfOnlyOne(@Nullable final JTree tree) { if (tree == null) return; Runnable runnable = () -> { TreeModel model = tree.getModel(); Object root = model.getRoot(); if (root == null) return; TreePath rootPath = new TreePath(root); tree.expandPath(rootPath); if (model.getChildCount(root) == 1) { Object firstChild = model.getChild(root, 0); tree.expandPath(rootPath.pathByAddingChild(firstChild)); } }; UIUtil.invokeLaterIfNeeded(runnable); } public static void expandAll(@NotNull JTree tree) { promiseExpandAll(tree); } /** * Expands all nodes in the specified tree and runs the specified task on done. * * @param tree a tree, which nodes should be expanded * @param onDone a task to run on EDT after expanding nodes */ public static void expandAll(@NotNull JTree tree, @NotNull Runnable onDone) { promiseExpandAll(tree).onSuccess(result -> UIUtil.invokeLaterIfNeeded(onDone)); } /** * Promises to expand all nodes in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be expanded * @return a promise that will be succeed when all nodes are expanded */ @NotNull public static Promise<?> promiseExpandAll(@NotNull JTree tree) { return promiseExpand(tree, Integer.MAX_VALUE); } /** * Expands n levels of the tree counting from the root * @param tree to expand nodes of * @param levels depths of the expantion */ public static void expand(@NotNull JTree tree, int levels) { promiseExpand(tree, levels); } /** * Expands some nodes in the specified tree and runs the specified task on done. * * @param tree a tree, which nodes should be expanded * @param depth a depth starting from the root node * @param onDone a task to run on EDT after expanding nodes */ public static void expand(@NotNull JTree tree, int depth, @NotNull Runnable onDone) { promiseExpand(tree, depth).onSuccess(result -> UIUtil.invokeLaterIfNeeded(onDone)); } /** * Promises to expand some nodes in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be expanded * @param depth a depth starting from the root node * @return a promise that will be succeed when all needed nodes are expanded */ @NotNull public static Promise<?> promiseExpand(@NotNull JTree tree, int depth) { AsyncPromise<?> promise = new AsyncPromise<>(); promiseMakeVisible(tree, path -> depth < path.getPathCount() ? TreeVisitor.Action.SKIP_SIBLINGS : TreeVisitor.Action.CONTINUE, promise) .onError(promise::setError) .onSuccess(path -> { if (promise.isCancelled()) return; promise.setResult(null); }); return promise; } @NotNull public static ActionCallback selectInTree(DefaultMutableTreeNode node, boolean requestFocus, @NotNull JTree tree) { return selectInTree(node, requestFocus, tree, true); } @NotNull public static ActionCallback selectInTree(@Nullable DefaultMutableTreeNode node, boolean requestFocus, @NotNull JTree tree, boolean center) { if (node == null) return ActionCallback.DONE; final TreePath treePath = new TreePath(node.getPath()); tree.expandPath(treePath); if (requestFocus) { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(tree, true)); } return selectPath(tree, treePath, center); } @NotNull public static ActionCallback selectInTree(Project project, @Nullable DefaultMutableTreeNode node, boolean requestFocus, @NotNull JTree tree, boolean center) { if (node == null) return ActionCallback.DONE; final TreePath treePath = new TreePath(node.getPath()); tree.expandPath(treePath); if (requestFocus) { ActionCallback result = new ActionCallback(2); IdeFocusManager.getInstance(project).requestFocus(tree, true).notifyWhenDone(result); selectPath(tree, treePath, center).notifyWhenDone(result); return result; } return selectPath(tree, treePath, center); } /** * Returns {@code true} if the node identified by the {@code path} is currently viewable in the {@code tree}. * The difference from the {@link JTree#isVisible(TreePath)} method is that this method * returns {@code false} for the hidden root node, when {@link JTree#isRootVisible()} returns {@code false}. * * @param tree a tree, to which the given path belongs * @param path a path whose visibility in the given tree is checking * @return {@code true} if {@code path} is viewable in {@code tree} * @see JTree#isRootVisible() * @see JTree#isVisible(TreePath) */ private static boolean isViewable(@NotNull JTree tree, @NotNull TreePath path) { TreePath parent = path.getParentPath(); return parent != null ? tree.isExpanded(parent) : tree.isRootVisible(); } /** * @param tree a tree, which selection is processed * @return a list of all selected paths */ @NotNull public static List<TreePath> collectSelectedPaths(@NotNull JTree tree) { return collectSelectedObjects(tree, Function.identity()); } /** * @param tree a tree, which selection is processed * @return a list of user objects which correspond to all selected paths */ @NotNull public static List<Object> collectSelectedUserObjects(@NotNull JTree tree) { return collectSelectedObjects(tree, TreeUtil::getLastUserObject); } /** * @param tree a tree, which selection is processed * @param mapper a function to convert a selected tree path to a corresponding object * @return a list of objects which correspond to all selected paths */ @NotNull public static <T> List<T> collectSelectedObjects(@NotNull JTree tree, @NotNull Function<? super TreePath, ? extends T> mapper) { return getSelection(tree, path -> isViewable(tree, path), mapper); } /** * @param tree a tree, which selection is processed * @param root an ascendant tree path to filter selected tree paths * @return a list of selected paths under the specified root node */ @NotNull public static List<TreePath> collectSelectedPaths(@NotNull JTree tree, @NotNull TreePath root) { return collectSelectedObjects(tree, root, Function.identity()); } /** * @param tree a tree, which selection is processed * @param root an ascendant tree path to filter selected tree paths * @return a list of user objects which correspond to selected paths under the specified root node */ @NotNull public static List<Object> collectSelectedUserObjects(@NotNull JTree tree, @NotNull TreePath root) { return collectSelectedObjects(tree, root, TreeUtil::getLastUserObject); } /** * @param tree a tree, which selection is processed * @param root an ascendant tree path to filter selected tree paths * @param mapper a function to convert a selected tree path to a corresponding object * @return a list of objects which correspond to selected paths under the specified root node */ @NotNull public static <T> List<T> collectSelectedObjects(@NotNull JTree tree, @NotNull TreePath root, @NotNull Function<? super TreePath, ? extends T> mapper) { if (!tree.isVisible(root)) return Collections.emptyList(); // invisible path should not be selected return getSelection(tree, path -> isViewable(tree, path) && root.isDescendant(path), mapper); } @NotNull private static <T> List<T> getSelection(@NotNull JTree tree, @NotNull Predicate<? super TreePath> filter, @NotNull Function<? super TreePath, ? extends T> mapper) { TreePath[] paths = tree.getSelectionPaths(); if (paths == null || paths.length == 0) return Collections.emptyList(); // nothing is selected return Stream.of(paths).filter(filter).map(mapper).filter(Objects::nonNull).collect(toList()); } public static void unselectPath(@NotNull JTree tree, @Nullable TreePath path) { if (path == null) return; TreePath[] selectionPaths = tree.getSelectionPaths(); if (selectionPaths == null) return; for (TreePath selectionPath : selectionPaths) { if (selectionPath.getPathCount() > path.getPathCount() && path.isDescendant(selectionPath)) { tree.removeSelectionPath(selectionPath); } } } @Nullable public static Range<Integer> getExpandControlRange(@NotNull final JTree aTree, @Nullable final TreePath path) { TreeModel treeModel = aTree.getModel(); final BasicTreeUI basicTreeUI = (BasicTreeUI)aTree.getUI(); Icon expandedIcon = basicTreeUI.getExpandedIcon(); Range<Integer> box = null; if (path != null && !treeModel.isLeaf(path.getLastPathComponent())) { int boxWidth; Insets i = aTree.getInsets(); boxWidth = expandedIcon != null ? expandedIcon.getIconWidth() : 8; int boxLeftX = i != null ? i.left : 0; boolean leftToRight = aTree.getComponentOrientation().isLeftToRight(); int depthOffset = getDepthOffset(aTree); int totalChildIndent = basicTreeUI.getLeftChildIndent() + basicTreeUI.getRightChildIndent(); if (leftToRight) { boxLeftX += (path.getPathCount() + depthOffset - 2) * totalChildIndent + basicTreeUI.getLeftChildIndent() - boxWidth / 2; } int boxRightX = boxLeftX + boxWidth; box = new Range<>(boxLeftX, boxRightX); } return box; } public static int getDepthOffset(@NotNull JTree aTree) { if (aTree.isRootVisible()) { return aTree.getShowsRootHandles() ? 1 : 0; } else { return aTree.getShowsRootHandles() ? 0 : -1; } } public static int getNodeDepth(@NotNull JTree tree, @NotNull TreePath path) { int depth = path.getPathCount(); if (!tree.isRootVisible()) depth if (!tree.getShowsRootHandles()) depth return depth; } private static final class LazyRowX { static final Method METHOD = getDeclaredMethod(BasicTreeUI.class, "getRowX", int.class, int.class); } @ApiStatus.Experimental public static int getNodeRowX(@NotNull JTree tree, int row) { if (LazyRowX.METHOD == null) return -1; // system error TreePath path = tree.getPathForRow(row); if (path == null) return -1; // path does not exist int depth = getNodeDepth(tree, path); if (depth < 0) return -1; // root is not visible try { return (Integer)LazyRowX.METHOD.invoke(tree.getUI(), row, depth); } catch (Exception exception) { LOG.error(exception); return -1; // unexpected } } private static final class LazyLocationInExpandControl { static final Method METHOD = getDeclaredMethod(BasicTreeUI.class, "isLocationInExpandControl", TreePath.class, int.class, int.class); } @ApiStatus.Experimental public static boolean isLocationInExpandControl(@NotNull JTree tree, int x, int y) { if (LazyLocationInExpandControl.METHOD == null) return false; // system error return isLocationInExpandControl(tree, tree.getClosestPathForLocation(x, y), x, y); } @ApiStatus.Experimental public static boolean isLocationInExpandControl(@NotNull JTree tree, @Nullable TreePath path, int x, int y) { if (LazyLocationInExpandControl.METHOD == null || path == null) return false; // system error or undefined path try { return (Boolean)LazyLocationInExpandControl.METHOD.invoke(tree.getUI(), path, x, y); } catch (Exception exception) { LOG.error(exception); return false; // unexpected } } @ApiStatus.Experimental public static void invalidateCacheAndRepaint(@Nullable TreeUI ui) { if (ui instanceof BasicTreeUI) { BasicTreeUI basic = (BasicTreeUI)ui; if (null == getField(BasicTreeUI.class, ui, JTree.class, "tree")) { LOG.warn(new IllegalStateException("tree is not properly initialized yet")); return; } UIUtil.invokeLaterIfNeeded(() -> basic.setLeftChildIndent(basic.getLeftChildIndent())); } } @NotNull public static RelativePoint getPointForSelection(@NotNull JTree aTree) { final int[] rows = aTree.getSelectionRows(); if (rows == null || rows.length == 0) { return RelativePoint.getCenterOf(aTree); } return getPointForRow(aTree, rows[rows.length - 1]); } @NotNull public static RelativePoint getPointForRow(@NotNull JTree aTree, int aRow) { return getPointForPath(aTree, aTree.getPathForRow(aRow)); } @NotNull public static RelativePoint getPointForPath(@NotNull JTree aTree, TreePath path) { final Rectangle rowBounds = aTree.getPathBounds(path); rowBounds.x += 20; return getPointForBounds(aTree, rowBounds); } @NotNull public static RelativePoint getPointForBounds(JComponent aComponent, @NotNull final Rectangle aBounds) { return new RelativePoint(aComponent, new Point(aBounds.x, (int)aBounds.getMaxY())); } public static boolean isOverSelection(@NotNull final JTree tree, @NotNull final Point point) { TreePath path = tree.getPathForLocation(point.x, point.y); return path != null && tree.getSelectionModel().isPathSelected(path); } public static void dropSelectionButUnderPoint(@NotNull JTree tree, @NotNull Point treePoint) { final TreePath toRetain = tree.getPathForLocation(treePoint.x, treePoint.y); if (toRetain == null) return; TreePath[] selection = tree.getSelectionModel().getSelectionPaths(); selection = selection == null ? EMPTY_TREE_PATH : selection; for (TreePath each : selection) { if (toRetain.equals(each)) continue; tree.getSelectionModel().removeSelectionPath(each); } } @Nullable public static Object getUserObject(@Nullable Object node) { return node instanceof DefaultMutableTreeNode ? ((DefaultMutableTreeNode)node).getUserObject() : node; } @Nullable public static <T> T getUserObject(@NotNull Class<T> type, @Nullable Object node) { node = getUserObject(node); return type.isInstance(node) ? type.cast(node) : null; } /** * @return an user object retrieved from the last component of the specified {@code path} */ @Nullable public static Object getLastUserObject(@Nullable TreePath path) { return path == null ? null : getUserObject(path.getLastPathComponent()); } @Nullable public static <T> T getLastUserObject(@NotNull Class<T> type, @Nullable TreePath path) { return path == null ? null : getUserObject(type, path.getLastPathComponent()); } @Nullable public static TreePath getSelectedPathIfOne(@NotNull JTree tree) { TreePath[] paths = tree.getSelectionPaths(); return paths != null && paths.length == 1 ? paths[0] : null; } /** @deprecated use TreeUtil#treePathTraverser() */ @Deprecated @FunctionalInterface public interface Traverse{ boolean accept(Object node); } public static void ensureSelection(@NotNull JTree tree) { final TreePath[] paths = tree.getSelectionPaths(); if (paths != null) { for (TreePath each : paths) { if (tree.getRowForPath(each) >= 0 && tree.isVisible(each)) { return; } } } for (int eachRow = 0; eachRow < tree.getRowCount(); eachRow++) { TreePath eachPath = tree.getPathForRow(eachRow); if (eachPath != null && tree.isVisible(eachPath)) { tree.setSelectionPath(eachPath); break; } } } public static <T extends MutableTreeNode> void insertNode(@NotNull T child, @NotNull T parent, @Nullable DefaultTreeModel model, @NotNull Comparator<? super T> comparator) { insertNode(child, parent, model, false, comparator); } public static <T extends MutableTreeNode> void insertNode(@NotNull T child, @NotNull T parent, @Nullable DefaultTreeModel model, boolean allowDuplication, @NotNull Comparator<? super T> comparator) { int index = indexedBinarySearch(parent, child, comparator); if (index >= 0 && !allowDuplication) { LOG.error("Node " + child + " is already added to " + parent); return; } int insertionPoint = index >= 0 ? index : -(index + 1); if (model != null) { model.insertNodeInto(child, parent, insertionPoint); } else { parent.insert(child, insertionPoint); } } public static <T extends TreeNode> int indexedBinarySearch(@NotNull T parent, @NotNull T key, @NotNull Comparator<? super T> comparator) { return ObjectUtils.binarySearch(0, parent.getChildCount(), mid -> comparator.compare((T)parent.getChildAt(mid), key)); } @NotNull public static Comparator<TreePath> getDisplayOrderComparator(@NotNull final JTree tree) { return Comparator.comparingInt(tree::getRowForPath); } private static void expandPathWithDebug(@NotNull JTree tree, @NotNull TreePath path) { LOG.debug("tree expand path: ", path); tree.expandPath(path); } /** * Expands a node in the specified tree. * * @param tree a tree, which nodes should be expanded * @param visitor a visitor that controls expanding of tree nodes * @param consumer a path consumer called on EDT if path is found and expanded */ public static void expand(@NotNull JTree tree, @NotNull TreeVisitor visitor, @NotNull Consumer<? super TreePath> consumer) { promiseMakeVisibleOne(tree, visitor, path -> { expandPathWithDebug(tree, path); consumer.accept(path); }); } /** * Promises to expand a node in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be expanded * @param visitor a visitor that controls expanding of tree nodes * @return a promise that will be succeed only if path is found and expanded */ @NotNull public static Promise<TreePath> promiseExpand(@NotNull JTree tree, @NotNull TreeVisitor visitor) { return promiseMakeVisibleOne(tree, visitor, path -> expandPathWithDebug(tree, path)); } /** * Promises to expand several nodes in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be expanded * @param visitors visitors to control expanding of tree nodes * @return a promise that will be succeed only if paths are found and expanded */ @NotNull public static Promise<List<TreePath>> promiseExpand(@NotNull JTree tree, @NotNull Stream<? extends TreeVisitor> visitors) { return promiseMakeVisibleAll(tree, visitors, paths -> paths.forEach(path -> expandPathWithDebug(tree, path))); } /** * Makes visible a node in the specified tree. * * @param tree a tree, which nodes should be made visible * @param visitor a visitor that controls expanding of tree nodes * @param consumer a path consumer called on EDT if path is found and made visible */ public static void makeVisible(@NotNull JTree tree, @NotNull TreeVisitor visitor, @NotNull Consumer<? super TreePath> consumer) { promiseMakeVisibleOne(tree, visitor, consumer); } /** * Promises to make visible a node in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be made visible * @param visitor a visitor that controls expanding of tree nodes * @return a promise that will be succeed only if path is found and made visible */ @NotNull public static Promise<TreePath> promiseMakeVisible(@NotNull JTree tree, @NotNull TreeVisitor visitor) { return promiseMakeVisibleOne(tree, visitor, null); } @NotNull private static Promise<TreePath> promiseMakeVisibleOne(@NotNull JTree tree, @NotNull TreeVisitor visitor, @Nullable Consumer<? super TreePath> consumer) { AsyncPromise<TreePath> promise = new AsyncPromise<>(); promiseMakeVisible(tree, visitor, promise) .onError(promise::setError) .onSuccess(path -> { if (promise.isCancelled()) return; UIUtil.invokeLaterIfNeeded(() -> { if (promise.isCancelled()) return; if (tree.isVisible(path)) { if (consumer != null) consumer.accept(path); promise.setResult(path); } else { promise.cancel(); } }); }); return promise; } /** * Promises to make visible several nodes in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be made visible * @param visitors visitors to control expanding of tree nodes * @return a promise that will be succeed only if path are found and made visible */ @NotNull @SuppressWarnings("unused") public static Promise<List<TreePath>> promiseMakeVisible(@NotNull JTree tree, @NotNull Stream<? extends TreeVisitor> visitors) { return promiseMakeVisibleAll(tree, visitors, null); } private static Promise<List<TreePath>> promiseMakeVisibleAll(@NotNull JTree tree, @NotNull Stream<? extends TreeVisitor> visitors, @Nullable Consumer<? super List<TreePath>> consumer) { AsyncPromise<List<TreePath>> promise = new AsyncPromise<>(); List<Promise<TreePath>> promises = visitors .filter(Objects::nonNull) .map(visitor -> promiseMakeVisible(tree, visitor, promise)) .collect(toList()); Promises.collectResults(promises, true) .onError(promise::setError) .onSuccess(paths -> { if (promise.isCancelled()) return; if (!ContainerUtil.isEmpty(paths)) { UIUtil.invokeLaterIfNeeded(() -> { if (promise.isCancelled()) return; List<TreePath> visible = ContainerUtil.filter(paths, tree::isVisible); if (!ContainerUtil.isEmpty(visible)) { if (consumer != null) consumer.accept(visible); promise.setResult(visible); } else { promise.cancel(); } }); } else { promise.cancel(); } }); return promise; } @NotNull private static Promise<TreePath> promiseMakeVisible(@NotNull JTree tree, @NotNull TreeVisitor visitor, @NotNull AsyncPromise<?> promise) { return promiseVisit(tree, path -> { if (promise.isCancelled()) return TreeVisitor.Action.SKIP_SIBLINGS; TreeVisitor.Action action = visitor.visit(path); if (action == TreeVisitor.Action.CONTINUE || action == TreeVisitor.Action.INTERRUPT) { // do not expand children if parent path is collapsed if (!tree.isVisible(path)) { if (!promise.isCancelled()) { LOG.debug("tree expand canceled"); promise.cancel(); } return TreeVisitor.Action.SKIP_SIBLINGS; } if (action == TreeVisitor.Action.CONTINUE) expandPathWithDebug(tree, path); } return action; }); } /** * Selects a node in the specified tree. * * @param tree a tree, which nodes should be selected * @param visitor a visitor that controls expanding of tree nodes * @param consumer a path consumer called on EDT if path is found and selected * @deprecated use {@code promiseSelect(tree, visitor).onSuccess(consumer)} instead */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.1") public static void select(@NotNull JTree tree, @NotNull TreeVisitor visitor, @NotNull Consumer<? super TreePath> consumer) { promiseMakeVisibleOne(tree, visitor, path -> { internalSelect(tree, path); consumer.accept(path); }); } /** * Promises to select a node in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be selected * @param visitor a visitor that controls expanding of tree nodes * @return a promise that will be succeed only if path is found and selected */ @NotNull public static Promise<TreePath> promiseSelect(@NotNull JTree tree, @NotNull TreeVisitor visitor) { return promiseMakeVisibleOne(tree, visitor, path -> internalSelect(tree, path)); } /** * Promises to select several nodes in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be selected * @param visitors visitors to control expanding of tree nodes * @return a promise that will be succeed only if paths are found and selected */ @NotNull public static Promise<List<TreePath>> promiseSelect(@NotNull JTree tree, @NotNull Stream<? extends TreeVisitor> visitors) { return promiseMakeVisibleAll(tree, visitors, paths -> internalSelect(tree, paths)); } private static void internalSelect(@NotNull JTree tree, @NotNull Collection<? extends TreePath> paths) { assert EventQueue.isDispatchThread(); if (paths.isEmpty()) return; internalSelect(tree, paths.toArray(EMPTY_TREE_PATH)); } private static void internalSelect(@NotNull JTree tree, TreePath @NotNull ... paths) { assert EventQueue.isDispatchThread(); if (paths.length == 0) return; tree.setSelectionPaths(paths); for (TreePath path : paths) { if (scrollToVisible(tree, path, true)) { break; } } } /** * @param tree a tree to scroll * @param path a visible tree path to scroll * @param centered {@code true} to show the specified path * @return {@code false} if a path is hidden (under a collapsed parent) */ public static boolean scrollToVisible(@NotNull JTree tree, @NotNull TreePath path, boolean centered) { assert EventQueue.isDispatchThread(); Rectangle bounds = tree.getPathBounds(path); if (bounds == null) { LOG.debug("cannot scroll to: ", path); return false; } Container parent = tree.getParent(); if (parent instanceof JViewport) { if (centered) { Rectangle visible = tree.getVisibleRect(); if (visible.y < bounds.y + bounds.height && bounds.y < visible.y + visible.height) { centered = false; // disable centering if the given path is already visible } } int width = parent.getWidth(); if (!centered && tree instanceof Tree && !((Tree)tree).isHorizontalAutoScrollingEnabled()) { bounds.x = -tree.getX(); bounds.width = width; } else { bounds.width = Math.min(bounds.width, width / 2); bounds.x -= JBUIScale.scale(20); // TODO: calculate a control width if (bounds.x < 0) { bounds.width += bounds.x; bounds.x = 0; } } int height = parent.getHeight(); if (height > bounds.height && height < tree.getHeight()) { if (centered || height < bounds.height * 5) { bounds.y -= (height - bounds.height) / 2; bounds.height = height; } else { bounds.y -= bounds.height * 2; bounds.height *= 5; } if (bounds.y < 0) { bounds.height += bounds.y; bounds.y = 0; } int y = bounds.y + bounds.height - tree.getHeight(); if (y > 0) bounds.height -= y; } } scrollToVisibleWithAccessibility(tree, bounds); return true; } private static void scrollToVisibleWithAccessibility(@NotNull JTree tree, @NotNull Rectangle bounds) { tree.scrollRectToVisible(bounds); AccessibleContext context = tree.getAccessibleContext(); if (context != null) context.firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, false, true); } /** * Promises to select the first node in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which node should be selected * @return a promise that will be succeed when first visible node is selected */ @NotNull public static Promise<TreePath> promiseSelectFirst(@NotNull JTree tree) { return promiseSelect(tree, path -> isHiddenRoot(tree, path) ? TreeVisitor.Action.CONTINUE : TreeVisitor.Action.INTERRUPT); } private static boolean isHiddenRoot(@NotNull JTree tree, @NotNull TreePath path) { return !tree.isRootVisible() && path.getParentPath() == null; } /** * Promises to select the first leaf node in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which node should be selected * @return a promise that will be succeed when first leaf node is made visible and selected */ @NotNull public static Promise<TreePath> promiseSelectFirstLeaf(@NotNull JTree tree) { AtomicReference<TreePath> reference = new AtomicReference<>(); AsyncPromise<TreePath> promise = new AsyncPromise<>(); promiseMakeVisible(tree, path -> { TreePath parent = reference.getAndSet(path); if (getPathCount(parent) == getPathCount(path.getParentPath())) return TreeVisitor.Action.CONTINUE; internalSelect(tree, parent); promise.setResult(parent); return TreeVisitor.Action.INTERRUPT; }, promise) .onError(promise::setError) .onSuccess(path -> { if (!promise.isDone()) { TreePath tail = reference.get(); if (tail == null || isHiddenRoot(tree, tail)) { promise.cancel(); } else { internalSelect(tree, tail); promise.setResult(tail); } } }); return promise; } private static int getPathCount(@Nullable TreePath path) { return path == null ? 0 : path.getPathCount(); } /** * Processes nodes in the specified tree. * * @param tree a tree, which nodes should be processed * @param visitor a visitor that controls processing of tree nodes * @param consumer a path consumer called on done */ public static void visit(@NotNull JTree tree, @NotNull TreeVisitor visitor, @NotNull Consumer<? super TreePath> consumer) { promiseVisit(tree, visitor).onSuccess(path -> UIUtil.invokeLaterIfNeeded(() -> consumer.accept(path))); } /** * Promises to process nodes in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be processed * @param visitor a visitor that controls processing of tree nodes * @return a promise that will be succeed when visiting is finished */ @NotNull public static Promise<TreePath> promiseVisit(@NotNull JTree tree, @NotNull TreeVisitor visitor) { TreeModel model = tree.getModel(); if (model instanceof TreeVisitor.Acceptor) { TreeVisitor.Acceptor acceptor = (TreeVisitor.Acceptor)model; return acceptor.accept(visitor); } if (model == null) return Promises.rejectedPromise("tree model is not set"); AsyncPromise<TreePath> promise = new AsyncPromise<>(); UIUtil.invokeLaterIfNeeded(() -> promise.setResult(visitModel(model, visitor))); return promise; } /** * Processes nodes in the specified tree model. * * @param model a tree model, which nodes should be processed * @param visitor a visitor that controls processing of tree nodes */ private static TreePath visitModel(@NotNull TreeModel model, @NotNull TreeVisitor visitor) { Object root = model.getRoot(); if (root == null) return null; TreePath path = new TreePath(root); switch (visitor.visit(path)) { case INTERRUPT: return path; // root path is found case CONTINUE: break; // visit children default: return null; // skip children } Deque<Deque<TreePath>> stack = new ArrayDeque<>(); stack.push(children(model, path)); while (path != null) { Deque<TreePath> siblings = stack.peek(); if (siblings == null) return null; // nothing to process TreePath next = siblings.poll(); if (next == null) { LOG.assertTrue(siblings == stack.poll()); path = path.getParentPath(); } else { switch (visitor.visit(next)) { case INTERRUPT: return next; // path is found case CONTINUE: path = next; stack.push(children(model, path)); break; case SKIP_SIBLINGS: siblings.clear(); break; case SKIP_CHILDREN: break; } } } LOG.assertTrue(stack.isEmpty()); return null; } @NotNull private static Deque<TreePath> children(@NotNull TreeModel model, @NotNull TreePath path) { Object object = path.getLastPathComponent(); int count = model.getChildCount(object); Deque<TreePath> deque = new ArrayDeque<>(count); for (int i = 0; i < count; i++) { deque.add(path.pathByAddingChild(model.getChild(object, i))); } return deque; } /** * Processes visible nodes in the specified tree. * * @param tree a tree, which nodes should be processed * @param visitor a visitor that controls processing of tree nodes */ public static TreePath visitVisibleRows(@NotNull JTree tree, @NotNull TreeVisitor visitor) { TreePath parent = null; int count = tree.getRowCount(); for (int row = 0; row < count; row++) { if (count != tree.getRowCount()) { throw new ConcurrentModificationException("tree is modified"); } TreePath path = tree.getPathForRow(row); if (path == null) { throw new NullPointerException("path is not found at row " + row); } if (parent == null || !parent.isDescendant(path)) { switch (visitor.visit(path)) { case INTERRUPT: return path; // path is found case CONTINUE: parent = null; break; case SKIP_CHILDREN: parent = path; break; case SKIP_SIBLINGS: parent = path.getParentPath(); if (parent == null) return null; break; } } } return null; } /** * Processes visible nodes in the specified tree. * * @param tree a tree, which nodes should be processed * @param mapper a function to convert a visible tree path to a corresponding object * @param consumer a visible path processor */ public static <T> void visitVisibleRows(@NotNull JTree tree, @NotNull Function<? super TreePath, ? extends T> mapper, @NotNull Consumer<? super T> consumer) { visitVisibleRows(tree, path -> { T object = mapper.apply(path); if (object != null) consumer.accept(object); return TreeVisitor.Action.CONTINUE; }); } /** * @param tree a tree, which visible paths are processed * @param filter a predicate to filter visible tree paths * @param mapper a function to convert a visible tree path to a corresponding object * @return a list of objects which correspond to filtered visible paths */ @NotNull private static <T> List<T> collectVisibleRows(@NotNull JTree tree, @NotNull Predicate<? super TreePath> filter, @NotNull Function<? super TreePath, ? extends T> mapper) { int count = tree.getRowCount(); if (count == 0) return Collections.emptyList(); List<T> list = new ArrayList<>(count); visitVisibleRows(tree, path -> filter.test(path) ? mapper.apply(path) : null, list::add); return list; } }
package org.jimmutable.platform_test; import org.apache.log4j.BasicConfigurator; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.WebAppContext; import org.jimmutable.cloud.ApplicationId; import org.jimmutable.cloud.CloudExecutionEnvironment; /** * Hello world! * */ public class App { public static void main(String[] args) throws Exception { BasicConfigurator.configure(); CloudExecutionEnvironment.startup(new ApplicationId("platform_test")); // 1. Creating the server on port 8080 Server server = new Server(8080); // 2. Creating the WebAppContext for the created content WebAppContext ctx = new WebAppContext(); ctx.setResourceBase("src/main/webapp"); ctx.setContextPath("/"); //3. Including the JSTL jars for the webapp. ctx.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/[^/]*jstl.*\\.jar$"); //4. Enabling the Annotation based configuration org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server); classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration"); classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration"); System.setProperty("org.mortbay.log.class", "com.example.JettyLog"); //5. Setting the handler and starting the Server server.setHandler(ctx); server.start(); server.join(); } }
package org.jetbrains.idea.devkit.dom.index; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.impl.LibraryScopeCache; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScopesCore; import com.intellij.psi.xml.XmlFile; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.JBIterable; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.ID; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; import com.intellij.util.io.VoidDataExternalizer; import com.intellij.util.xml.DomElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.devkit.dom.IdeaPlugin; import org.jetbrains.idea.devkit.dom.PluginModule; import org.jetbrains.idea.devkit.util.DescriptorUtil; import java.util.*; public class PluginIdModuleIndex extends PluginXmlIndexBase<String, Void> { private static final ID<String, Void> NAME = ID.create("PluginIdModuleIndex"); @NotNull @Override public ID<String, Void> getName() { return NAME; } @NotNull @Override public DataExternalizer<Void> getValueExternalizer() { return VoidDataExternalizer.INSTANCE; } @Override protected Map<String, Void> performIndexing(IdeaPlugin plugin) { List<String> ids = new ArrayList<>(); ids.add(StringUtil.notNullize(plugin.getPluginId())); for (DomElement module : getChildrenWithoutIncludes(plugin, "module")) { ContainerUtil.addIfNotNull(ids, ((PluginModule)module).getValue().getStringValue()); } return ContainerUtil.newHashMap(ids, Collections.nCopies(ids.size(), null)); } @NotNull @Override public KeyDescriptor<String> getKeyDescriptor() { return EnumeratorStringDescriptor.INSTANCE; } @Override public int getVersion() { return 2; } public static Collection<VirtualFile> getFiles(@NotNull Project project, @NotNull String idOrModule) { GlobalSearchScope scope = GlobalSearchScopesCore.projectProductionScope(project) .union(LibraryScopeCache.getInstance(project).getLibrariesOnlyScope()); return FileBasedIndex.getInstance().getContainingFiles(NAME, idOrModule, scope); } public static List<IdeaPlugin> findPlugins(@NotNull DomElement place, @NotNull String idOrModule) { Project project = place.getManager().getProject(); Collection<VirtualFile> vFiles = getFiles(project, idOrModule); return JBIterable.from(vFiles) .map(PsiManager.getInstance(project)::findFile) .filter(XmlFile.class) .map(DescriptorUtil::getIdeaPlugin) .filter(Conditions.notNull()) .toList(); } }
package org.jetbrains.idea.svn; import com.intellij.openapi.components.*; import com.intellij.openapi.progress.util.BackgroundTaskUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.changes.VcsAnnotationRefresher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.auth.*; import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationManager; import org.jetbrains.idea.svn.config.SvnServerFileKeys; import org.jetbrains.idea.svn.diff.DiffOptions; import org.jetbrains.idea.svn.update.MergeRootInfo; import org.jetbrains.idea.svn.update.UpdateRootInfo; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.internal.wc.SVNConfigFile; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.wc.ISVNOptions; import org.tmatesoft.svn.core.wc.SVNWCUtil; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.TreeSet; import static com.intellij.util.containers.ContainerUtil.newHashMap; import static com.intellij.util.containers.ContainerUtil.newTreeSet; @State(name = "SvnConfiguration", storages = {@Storage(StoragePathMacros.WORKSPACE_FILE)}) public class SvnConfiguration implements PersistentStateComponent<SvnConfigurationState> { public final static int ourMaxAnnotateRevisionsDefault = 500; private final static long UPGRADE_TO_15_VERSION_ASKED = 123; private final static long CHANGELIST_SUPPORT = 124; private final static long UPGRADE_TO_16_VERSION_ASKED = 125; private final Project myProject; @NotNull private SvnConfigurationState myState = new SvnConfigurationState(); private ISVNOptions myOptions; private SvnAuthenticationManager myAuthManager; private SvnAuthenticationManager myPassiveAuthManager; private SvnAuthenticationManager myInteractiveManager; public static final AuthStorage RUNTIME_AUTH_CACHE = new AuthStorage(); private final Map<File, MergeRootInfo> myMergeRootInfos = new HashMap<>(); private final Map<File, UpdateRootInfo> myUpdateRootInfos = new HashMap<>(); private SvnInteractiveAuthenticationProvider myInteractiveProvider; private IdeaSVNConfigFile myServersFile; private SVNConfigFile myConfigFile; @Deprecated // Required for compatibility with external plugins. public boolean isCommandLine() { return true; } @NotNull @Override public SvnConfigurationState getState() { return myState; } @Override public void loadState(@NotNull SvnConfigurationState state) { myState = state; } public long getHttpTimeout() { final String timeout = getServersFile().getDefaultGroup().getTimeout(); try { return Long.parseLong(timeout) * 1000; } catch (NumberFormatException e) { return 0; } } @NotNull public DiffOptions getMergeOptions() { return new DiffOptions(isIgnoreSpacesInMerge(), isIgnoreSpacesInMerge(), isIgnoreSpacesInMerge()); } @NotNull private IdeaSVNConfigFile getServersFile() { if (myServersFile == null) { myServersFile = new IdeaSVNConfigFile(new File(getConfigurationDirectory(), IdeaSVNConfigFile.SERVERS_FILE_NAME)); } myServersFile.updateGroups(); return myServersFile; } @NotNull public SVNConfigFile getConfigFile() { if (myConfigFile == null) { myConfigFile = new SVNConfigFile(new File(getConfigurationDirectory(), IdeaSVNConfigFile.CONFIG_FILE_NAME)); } return myConfigFile; } @NotNull public String getSshTunnelSetting() { // TODO: Check SVNCompositeConfigFile - to utilize both system and user settings return StringUtil.notNullize(getConfigFile().getPropertyValue("tunnels", "ssh")); } public void setSshTunnelSetting(@Nullable String value) { getConfigFile().setPropertyValue("tunnels", "ssh", value, true); } // uses configuration directory property - it should be saved first public void setHttpTimeout(final long value) { long cut = value / 1000; getServersFile().setValue("global", SvnServerFileKeys.TIMEOUT, String.valueOf(cut)); getServersFile().save(); } public static SvnConfiguration getInstance(final Project project) { return ServiceManager.getService(project, SvnConfiguration.class); } public SvnConfiguration(final Project project) { myProject = project; } public void setIgnoreSpacesInAnnotate(final boolean value) { final boolean changed = myState.IGNORE_SPACES_IN_ANNOTATE != value; myState.IGNORE_SPACES_IN_ANNOTATE = value; if (changed) { BackgroundTaskUtil.syncPublisher(getProject(), VcsAnnotationRefresher.LOCAL_CHANGES_CHANGED).configurationChanged(SvnVcs.getKey()); } } public long getSshConnectionTimeout() { return myState.sshConnectionTimeout; } public void setSshConnectionTimeout(long sshConnectionTimeout) { myState.sshConnectionTimeout = sshConnectionTimeout; } public long getSshReadTimeout() { return myState.sshReadTimeout; } public void setSshReadTimeout(long sshReadTimeout) { myState.sshReadTimeout = sshReadTimeout; } public Project getProject() { return myProject; } public Boolean isKeepNewFilesAsIsForTreeConflictMerge() { return myState.keepNewFilesAsIsForTreeConflictMerge; } public void setKeepNewFilesAsIsForTreeConflictMerge(Boolean keepNewFilesAsIsForTreeConflictMerge) { myState.keepNewFilesAsIsForTreeConflictMerge = keepNewFilesAsIsForTreeConflictMerge; } public SSLProtocols getSslProtocols() { return myState.sslProtocols; } public void setSslProtocols(SSLProtocols sslProtocols) { myState.sslProtocols = sslProtocols; } public Depth getUpdateDepth() { return myState.UPDATE_DEPTH; } public void setUpdateDepth(Depth updateDepth) { myState.UPDATE_DEPTH = updateDepth; } public boolean isRunUnderTerminal() { return myState.runUnderTerminal; } public void setRunUnderTerminal(boolean value) { myState.runUnderTerminal = value; } public boolean isIgnoreExternals() { return myState.IGNORE_EXTERNALS; } public void setIgnoreExternals(boolean ignoreExternals) { myState.IGNORE_EXTERNALS = ignoreExternals; } public boolean isMergeDryRun() { return myState.MERGE_DRY_RUN; } public void setMergeDryRun(boolean mergeDryRun) { myState.MERGE_DRY_RUN = mergeDryRun; } public boolean isMergeDiffUseAncestry() { return myState.MERGE_DIFF_USE_ANCESTRY; } public void setMergeDiffUseAncestry(boolean mergeDiffUseAncestry) { myState.MERGE_DIFF_USE_ANCESTRY = mergeDiffUseAncestry; } public boolean isUpdateLockOnDemand() { return myState.UPDATE_LOCK_ON_DEMAND; } public void setUpdateLockOnDemand(boolean updateLockOnDemand) { myState.UPDATE_LOCK_ON_DEMAND = updateLockOnDemand; } public boolean isIgnoreSpacesInMerge() { return myState.IGNORE_SPACES_IN_MERGE; } public void setIgnoreSpacesInMerge(boolean ignoreSpacesInMerge) { myState.IGNORE_SPACES_IN_MERGE = ignoreSpacesInMerge; } public boolean isCheckNestedForQuickMerge() { return myState.CHECK_NESTED_FOR_QUICK_MERGE; } public void setCheckNestedForQuickMerge(boolean checkNestedForQuickMerge) { myState.CHECK_NESTED_FOR_QUICK_MERGE = checkNestedForQuickMerge; } public boolean isIgnoreSpacesInAnnotate() { return myState.IGNORE_SPACES_IN_ANNOTATE; } public boolean isShowMergeSourcesInAnnotate() { return myState.SHOW_MERGE_SOURCES_IN_ANNOTATE; } public void setShowMergeSourcesInAnnotate(boolean showMergeSourcesInAnnotate) { myState.SHOW_MERGE_SOURCES_IN_ANNOTATE = showMergeSourcesInAnnotate; } public boolean isForceUpdate() { return myState.FORCE_UPDATE; } public void setForceUpdate(boolean forceUpdate) { myState.FORCE_UPDATE = forceUpdate; } private static Long fixSupportedVersion(final Long version) { return version == null || version.longValue() < CHANGELIST_SUPPORT ? UPGRADE_TO_15_VERSION_ASKED : version; } public boolean changeListsSynchronized() { ensureSupportedVersion(); return myState.supportedVersion != null && myState.supportedVersion >= CHANGELIST_SUPPORT; } public void upgrade() { myState.supportedVersion = UPGRADE_TO_16_VERSION_ASKED; } private void ensureSupportedVersion() { if (myState.supportedVersion == null) { myState.supportedVersion = fixSupportedVersion(SvnBranchConfigurationManager.getInstance(myProject).getSupportValue()); } } public String getConfigurationDirectory() { if (myState.directory.path == null || isUseDefaultConfiguation()) { myState.directory.path = IdeaSubversionConfigurationDirectory.getPath(); } return myState.directory.path; } public boolean isUseDefaultConfiguation() { return myState.directory.useDefault; } public void setConfigurationDirParameters(final boolean newUseDefault, final String newConfigurationDirectory) { final String defaultPath = IdeaSubversionConfigurationDirectory.getPath(); final String oldEffectivePath = isUseDefaultConfiguation() ? defaultPath : getConfigurationDirectory(); final String newEffectivePath = newUseDefault ? defaultPath : newConfigurationDirectory; boolean directoryChanged = !Comparing.equal(getConfigurationDirectory(), newConfigurationDirectory); if (directoryChanged) { setConfigurationDirectory(newConfigurationDirectory); } boolean usageChanged = isUseDefaultConfiguation() != newUseDefault; if (usageChanged) { setUseDefaultConfiguation(newUseDefault); } if (directoryChanged || usageChanged) { if (! Comparing.equal(oldEffectivePath, newEffectivePath)) { clear(); } } } private void setConfigurationDirectory(String path) { myState.directory.path = path; File dir = path == null ? new File(IdeaSubversionConfigurationDirectory.getPath()) : new File(path); SVNConfigFile.createDefaultConfiguration(dir); } public void clear() { myOptions = null; myAuthManager = null; myPassiveAuthManager = null; myInteractiveManager = null; myInteractiveProvider = null; RUNTIME_AUTH_CACHE.clear(); } private void setUseDefaultConfiguation(boolean useDefault) { myState.directory.useDefault = useDefault; } public ISVNOptions getOptions() { if (myOptions == null) { File path = new File(getConfigurationDirectory()); myOptions = SVNWCUtil.createDefaultOptions(path.getAbsoluteFile(), true); } return myOptions; } public SvnAuthenticationManager getAuthenticationManager(@NotNull SvnVcs svnVcs) { if (myAuthManager == null) { // reloaded when configuration directory changes myAuthManager = new SvnAuthenticationManager(svnVcs, new File(getConfigurationDirectory())); Disposer.register(svnVcs.getProject(), () -> myAuthManager = null); getInteractiveManager(svnVcs); // to init myAuthManager.setAuthenticationProvider(new SvnAuthenticationProvider(svnVcs, myInteractiveProvider, myAuthManager)); } return myAuthManager; } public SvnAuthenticationManager getPassiveAuthenticationManager(@NotNull SvnVcs svnVcs) { if (myPassiveAuthManager == null) { myPassiveAuthManager = new SvnAuthenticationManager(svnVcs, new File(getConfigurationDirectory())); myPassiveAuthManager.setAuthenticationProvider(new AuthenticationProvider() { @Override public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, boolean canCache) { return null; } @Override public AcceptResult acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean canCache) { return AcceptResult.REJECTED; } }); } return myPassiveAuthManager; } public SvnAuthenticationManager getInteractiveManager(@NotNull SvnVcs svnVcs) { if (myInteractiveManager == null) { myInteractiveManager = new SvnAuthenticationManager(svnVcs, new File(getConfigurationDirectory())); myInteractiveProvider = new SvnInteractiveAuthenticationProvider(svnVcs, myInteractiveManager); myInteractiveManager.setAuthenticationProvider(myInteractiveProvider); } return myInteractiveManager; } public void getServerFilesManagers(final Ref<SvnServerFileManager> systemManager, final Ref<SvnServerFileManager> userManager) { final File dir = new File(getConfigurationDirectory()); if (! dir.exists()) { SVNConfigFile.createDefaultConfiguration(dir); } systemManager.set(new SvnServerFileManagerImpl(new IdeaSVNConfigFile(new File(SVNFileUtil.getSystemConfigurationDirectory(), IdeaSVNConfigFile.SERVERS_FILE_NAME)))); userManager.set(new SvnServerFileManagerImpl(getServersFile())); } public boolean isAutoUpdateAfterCommit() { return myState.autoUpdateAfterCommit; } public void setAutoUpdateAfterCommit(boolean autoUpdateAfterCommit) { myState.autoUpdateAfterCommit = autoUpdateAfterCommit; } public boolean isKeepLocks() { return myState.keepLocks; } public void setKeepLocks(boolean keepLocks) { myState.keepLocks = keepLocks; } public boolean isIsUseDefaultProxy() { return myState.useDefaultProxy; } public void setIsUseDefaultProxy(final boolean isUseDefaultProxy) { myState.useDefaultProxy = isUseDefaultProxy; } // TODO: Rewrite AutoStorage to use MemoryPasswordSafe at least public static class AuthStorage { @NotNull private final TreeSet<String> myKeys = newTreeSet(); @NotNull private final Map<String, Object> myStorage = newHashMap(); @NotNull public static String getKey(@NotNull String type, @NotNull String realm) { return type + "$" + realm; } public synchronized void clear() { myStorage.clear(); myKeys.clear(); } public synchronized void putData(@NotNull String kind, @NotNull String realm, @Nullable Object data) { String key = getKey(kind, realm); if (data == null) { myStorage.remove(key); myKeys.remove(key); } else { myStorage.put(key, data); myKeys.add(key); } } @Nullable public synchronized Object getDataWithLowerCheck(@NotNull String kind, @NotNull String realm) { String key = getKey(kind, realm); Object result = myStorage.get(key); if (result == null) { String lowerKey = myKeys.lower(key); if (lowerKey != null && key.startsWith(lowerKey)) { result = myStorage.get(lowerKey); } } return result; } } @NotNull public MergeRootInfo getMergeRootInfo(final File file, final SvnVcs svnVcs) { if (!myMergeRootInfos.containsKey(file)) { myMergeRootInfos.put(file, new MergeRootInfo(file, svnVcs)); } return myMergeRootInfos.get(file); } public UpdateRootInfo getUpdateRootInfo(File file, final SvnVcs svnVcs) { if (!myUpdateRootInfos.containsKey(file)) { myUpdateRootInfos.put(file, new UpdateRootInfo(file, svnVcs)); } return myUpdateRootInfos.get(file); } // TODO: Check why SvnUpdateEnvironment.validationOptions is fully commented and then remove this method if necessary public Map<File, UpdateRootInfo> getUpdateInfosMap() { return Collections.unmodifiableMap(myUpdateRootInfos); } public void acknowledge(@NotNull String kind, @NotNull String realm, @Nullable Object object) { RUNTIME_AUTH_CACHE.putData(kind, realm, object); } public void clearCredentials(@NotNull String kind, @NotNull String realm) { RUNTIME_AUTH_CACHE.putData(kind, realm, null); } public void clearRuntimeStorage() { RUNTIME_AUTH_CACHE.clear(); } public int getMaxAnnotateRevisions() { return myState.maxAnnotateRevisions; } public void setMaxAnnotateRevisions(int maxAnnotateRevisions) { myState.maxAnnotateRevisions = maxAnnotateRevisions; } public boolean isCleanupRun() { return myState.cleanupOnStartRun; } public void setCleanupRun(boolean cleanupRun) { myState.cleanupOnStartRun = cleanupRun; } public enum SSLProtocols { sslv3, tlsv1, all } public enum SshConnectionType { PASSWORD, PRIVATE_KEY, SUBVERSION_CONFIG } }
package com.opengamma.util; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.opengamma.OpenGammaRuntimeException; /** * Class utilities */ public final class ClassUtils { /** * A per-thread cache of loaded classes. */ private static final ConcurrentMap<String, Class<?>> s_classCache = new ConcurrentHashMap<>(); /** * Method for resolving a class. */ private static final Method RESOLVE_METHOD; static { try { RESOLVE_METHOD = ClassLoader.class.getDeclaredMethod("resolveClass", Class.class); RESOLVE_METHOD.setAccessible(true); } catch (NoSuchMethodException | SecurityException ex) { throw new ExceptionInInitializerError(ex); } } /** * Prevents instantiation. */ private ClassUtils() { } /** * Loads a class from a class name, or fetches one from the calling thread's cache. * The calling thread's class loader is used. * <p> * Some class loaders involve quite heavy synchronization overheads which can impact * performance on multi-core systems if called heavy (for example as part of decoding a Fudge message). * <p> * The class will be fully initialized (static initializers invoked). * * @param className the class name, not null * @return the class object, not null * @throws ClassNotFoundException */ public static Class<?> loadClass(String className) throws ClassNotFoundException { Class<?> clazz = s_classCache.get(className); if (clazz == null) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, true, loader); } s_classCache.putIfAbsent(className, clazz); } return clazz; } /** * Initializes a class to ensure it is fully loaded. * <p> * The JVM has two separate steps in class loading, the initial load * followed by the initialization. * Static initializers are invoked in the second step. * This method forces the second step. * * @param <T> the type * @param clazz the class to initialize, not null * @return the input class, not null */ public static <T> Class<T> initClass(Class<T> clazz) { String className = clazz.getName(); if (s_classCache.containsKey(className) == false) { try { Class.forName(className, true, clazz.getClassLoader()); } catch (ClassNotFoundException ex) { throw new OpenGammaRuntimeException(ex.getMessage(), ex); } s_classCache.putIfAbsent(className, clazz); } return clazz; } }
package ca.concordia.cssanalyser.cssmodel; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.w3c.dom.Document; import ca.concordia.cssanalyser.cssmodel.declaration.Declaration; import ca.concordia.cssanalyser.cssmodel.declaration.ShorthandDeclaration; import ca.concordia.cssanalyser.cssmodel.media.MediaQueryList; import ca.concordia.cssanalyser.cssmodel.selectors.BaseSelector; import ca.concordia.cssanalyser.cssmodel.selectors.GroupingSelector; import ca.concordia.cssanalyser.cssmodel.selectors.Selector; import ca.concordia.cssanalyser.dom.DOMNodeWrapper; import ca.concordia.cssanalyser.dom.DOMNodeWrapperList; import ca.concordia.cssanalyser.refactoring.dependencies.CSSDependencyDetector; import ca.concordia.cssanalyser.refactoring.dependencies.CSSValueOverridingDependencyList; /** * This class is the main class storing all CSS data in the memory * * @author Davood Mazinanian */ public class StyleSheet extends CSSModelObject { private Map<Selector, Integer> selectors; private String cssFilePath; private CSSValueOverridingDependencyList orderDependencies; public StyleSheet() { selectors = new LinkedHashMap<>(); } public void setPath(String path) { cssFilePath = path; } /** * Adds a new selector (whether single or grouped) to the selectors list of * this style sheet. * * @param selector */ public void addSelector(Selector selector) { if (!selectors.containsKey(selector)) { selectors.put(selector, selectors.size() + 1); } selector.setParentStyleSheet(this); } /** * Returns all the selectors, whether single or grouped in the style sheet. * * @return List<Selector> */ public Iterable<Selector> getAllSelectors() { return selectors.keySet(); } /** * This method returns all the single selectors in the style sheet, in * addition to the all single selectors inside the grouped selectors. It * preserves the order of single selectors. * * @return List<BaseSelector> */ public List<BaseSelector> getAllBaseSelectors() { List<BaseSelector> allBaseSelectors = new ArrayList<>(); for (Selector selector : selectors.keySet()) { // Look inside all selectors if (selector instanceof BaseSelector) { allBaseSelectors.add((BaseSelector) selector); } else if (selector instanceof GroupingSelector) { for (BaseSelector bs : ((GroupingSelector)selector).getBaseSelectors()) { allBaseSelectors.add(bs); } } } return allBaseSelectors; } /** * This method returns all the declarations inside a style sheet, preserving * their order in which they have been defined. * * @return List<Declaration> */ public Set<Declaration> getAllDeclarations() { //if (listOfDeclarations == null) { Set<Declaration> listOfDeclarations = new LinkedHashSet<>(); for (Selector selector : selectors.keySet()) for (Declaration declaration : selector.getDeclarations()) listOfDeclarations.add(declaration); return listOfDeclarations; } @Override public String toString() { StringBuilder toReturn = new StringBuilder(); Set<MediaQueryList> lastMediaQueryLists = null; Iterator<Selector> selectorIterator = selectors.keySet().iterator(); int currentIndentation = 0; if (selectorIterator.hasNext()) { Selector s = selectorIterator.next(); while(true) { if (lastMediaQueryLists == null || (lastMediaQueryLists != null && !lastMediaQueryLists.equals(s.getMediaQueryLists()))) { for (Iterator<MediaQueryList> mediaQueryList = s.getMediaQueryLists().iterator(); mediaQueryList.hasNext();) { MediaQueryList mql = mediaQueryList.next(); if (lastMediaQueryLists == null || (lastMediaQueryLists != null && !lastMediaQueryLists.contains(mql))) { toReturn.append(getIndentsString(currentIndentation)); toReturn.append(mql + " {" + System.lineSeparator() + System.lineSeparator()); // Open media query currentIndentation++; } } lastMediaQueryLists = s.getMediaQueryLists(); } toReturn.append(getIndentsString(currentIndentation) + s + " {" + System.lineSeparator()); for (Declaration d : s.getDeclarations()) { if (d instanceof ShorthandDeclaration) { if (((ShorthandDeclaration)d).isVirtual()) continue; } toReturn.append(getIndentsString(currentIndentation + 1) + d); if (d.isImportant()) toReturn.append(" !important"); toReturn.append(";" + System.lineSeparator()); } toReturn.append(getIndentsString(currentIndentation) + "}" + System.lineSeparator() + System.lineSeparator()); if (selectorIterator.hasNext()) { s = selectorIterator.next(); if (lastMediaQueryLists != null) { if (!lastMediaQueryLists.equals(s.getMediaQueryLists())) { // For each MediaQueryList which is not in the new selector, close the MediaQuery for (MediaQueryList mq : lastMediaQueryLists) { if (!s.getMediaQueryLists().contains(mq)) { currentIndentation toReturn.append(getIndentsString(currentIndentation) + "}" + System.lineSeparator() + System.lineSeparator()); // close media query } } } } } else { break; } } while (currentIndentation > 0) { // unclosed media queries currentIndentation toReturn.append(getIndentsString(currentIndentation) + "}" + System.lineSeparator()); // close media query } } return toReturn.toString(); } private String getIndentsString(int currentIndentation) { String s = ""; for (int i = 0; i < currentIndentation; i++) s += "\t"; return s; } public void addSelectors(StyleSheet s) { for (Selector selector : s.getAllSelectors()) addSelector(selector); } public String getFilePath() { return cssFilePath; } @Override public StyleSheet clone() { StyleSheet styleSheet = new StyleSheet(); styleSheet.cssFilePath = cssFilePath; for (Selector s : this.selectors.keySet()) styleSheet.addSelector(s.clone()); return styleSheet; } /** * Maps every base selector to a node list in the stylesheet * @param document * @param styleSheet * @return */ public Map<BaseSelector, DOMNodeWrapperList> mapStylesheetOnDocument(Document document) { List<BaseSelector> allSelectors = getAllBaseSelectors(); Map<BaseSelector, DOMNodeWrapperList> selectorNodeListMap = new LinkedHashMap<>(); for (BaseSelector selector : allSelectors) { selectorNodeListMap.put(selector, selector.getSelectedNodes(document)); } return selectorNodeListMap; } /** * Returns a list of documents' node in addition to the CSS selectors which * select each node * @param document * @param styleSheet * @return */ public Map<DOMNodeWrapper, List<BaseSelector>> getCSSClassesForDOMNodes(Document document) { // Map every node in the DOM tree to a list of selectors in the stylesheet Map<DOMNodeWrapper, List<BaseSelector>> nodeToSelectorsMapping = new HashMap<>(); for (BaseSelector selector : getAllBaseSelectors()) { DOMNodeWrapperList matchedNodes = selector.getSelectedNodes(document); for (DOMNodeWrapper domNodeWrapper : matchedNodes) { List<BaseSelector> correspondingSelectors = nodeToSelectorsMapping.get(domNodeWrapper); if (correspondingSelectors == null) { correspondingSelectors = new ArrayList<>(); } correspondingSelectors.add(selector); nodeToSelectorsMapping.put(domNodeWrapper, correspondingSelectors); } } return nodeToSelectorsMapping; } public void addMediaQueryList(MediaQueryList forMedia) { for (Selector s : selectors.keySet()) s.addMediaQueryList(forMedia); } public CSSValueOverridingDependencyList getLastComputetOrderDependencies() { return orderDependencies; } public CSSValueOverridingDependencyList getValueOverridingDependencies(Document dom) { CSSDependencyDetector dependencyDetector; if (dom != null) { dependencyDetector = new CSSDependencyDetector(this, dom); } else { dependencyDetector = new CSSDependencyDetector(this); } orderDependencies = dependencyDetector.findOverridingDependancies(); return orderDependencies; } public CSSValueOverridingDependencyList getValueOverridingDependencies() { return getValueOverridingDependencies(null); } public int getNumberOfSelectors() { return selectors.size(); } public void removeSelectors(List<Selector> selectorsToBeRemoved) { for (Selector s : selectorsToBeRemoved) selectors.remove(s); // Update the numbers associated with every declaration int i = 1; for (Selector s : selectors.keySet()) selectors.put(s, i++); } public int getSelectorNumber(Selector selector) { return selectors.get(selector); } public boolean containsSelector(Selector selector) { return selectors.containsKey(selector); } public StyleSheet getStyleSheetWithIntraSelectorDependenciesRemoved() { StyleSheet styleSheetToReturn = new StyleSheet(); styleSheetToReturn.cssFilePath = this.cssFilePath; for (Selector selector : getAllSelectors()) { Selector newSelector = selector.copyEmptySelector(); newSelector.setOriginalSelector(selector); for (Declaration declaration : selector.getDeclarationsWithIntraSelectorDependenciesRemoved()) { newSelector.addDeclaration(declaration); styleSheetToReturn.addSelector(newSelector); } } return styleSheetToReturn; } }
package ca.ilanguage.oprime.ui; import java.util.Locale; import ca.ilanguage.oprime.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.Toast; import android.text.format.Time; public class RunExperimentActivity extends Activity implements TextToSpeech.OnInitListener { private static final String TAG = "PDFtoAudioBookHomeActivity"; /** Talk to the user */ private TextToSpeech mTts; // private Time startTime = new Time(); // private Time endTime = new Time(); // private Time reactionTime = new Time(); private Long startTime; private Long endTime; private Long reactionTime; //implement on Init for the text to speech public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { // Set preferred language to US english. // Note that a language may not be available, and the result will // indicate this. int result = mTts.setLanguage(Locale.US); // Try this someday for some interesting results. // int result mTts.setLanguage(Locale.FRANCE); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { // Language data is missing or the language is not supported. Log.e(TAG, "Language is not available."); } else { // mSpeakButton.setEnabled(true); // mPauseButton.setEnabled(true); // Greet the user. // sayHello(); // mTts.speak("Click on the dog with a coat.", // TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue. // null); } } else { // Initialization failed. Log.e(TAG, "Could not initialize TextToSpeech."); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this)); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { //endTime = System.currentTimeMillis(); endTime = System.currentTimeMillis(); //Long reactionTimeMilliseconds = endTime.normalize(false) - startTime.normalize(false); //http://developer.android.com/reference/android/text/format/Time.html#toMillis(boolean) Long reactionTimeMilliseconds = endTime-startTime; mTts.speak("The participant clicked on picture "+position+", in "+reactionTimeMilliseconds+" milliseconds. This has been recorded in the Google Spreadsheet.", TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue. null); Toast.makeText(RunExperimentActivity.this, "Picture" + position +", in "+reactionTimeMilliseconds+" milliseconds", Toast.LENGTH_LONG).show(); } }); mTts = new TextToSpeech(this, this); playAudio(); } public void playAudio(){ try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block //e.printStackTrace(); Toast.makeText(RunExperimentActivity.this, "The experiment was interupted. Invalid reaction time.", Toast.LENGTH_LONG).show(); } MediaPlayer mp = MediaPlayer.create(this, R.raw.click_on_dog_coat); mp.start(); //startTime.setToNow(); startTime = System.currentTimeMillis(); } public void onRunExperimentClick(View v){ mTts.speak("This would run the experiment.", TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue. null); startActivity(new Intent(this, RunExperimentActivity.class)); } public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(285, 285)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } // references to our images private Integer[] mThumbIds = { // R.drawable.sample_2, R.drawable.sample_3, // R.drawable.sample_4, R.drawable.sample_5, // R.drawable.sample_6, R.drawable.sample_7, // R.drawable.sample_0, R.drawable.sample_1, // R.drawable.sample_2, R.drawable.sample_3, // R.drawable.sample_4, R.drawable.sample_5, // R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3 // R.drawable.sample_4, R.drawable.sample_5, // R.drawable.sample_6, R.drawable.sample_7 }; } }
package com.esotericsoftware.kryonet.rmi; import static com.esotericsoftware.minlog.Log.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoException; import com.esotericsoftware.kryo.KryoSerializable; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.serializers.FieldSerializer; import com.esotericsoftware.kryo.util.IntMap; import com.esotericsoftware.kryo.util.Util; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.EndPoint; import com.esotericsoftware.kryonet.FrameworkMessage; import com.esotericsoftware.kryonet.KryoNetException; import com.esotericsoftware.kryonet.Listener; import com.esotericsoftware.kryonet.util.ObjectIntMap; import com.esotericsoftware.reflectasm.MethodAccess; /** Allows methods on objects to be invoked remotely over TCP or UDP. Objects are {@link #register(int, Object) registered} with * an ID. The remote end of connections that have been {@link #addConnection(Connection) added} are allowed to * {@link #getRemoteObject(Connection, int, Class) access} registered objects. * <p> * It costs at least 2 bytes more to use remote method invocation than just sending the parameters. If the method has a return * value which is not {@link RemoteObject#setNonBlocking(boolean) ignored}, an extra byte is written. If the type of a parameter * is not final (note primitives are final) then an extra byte is written for that parameter. * @author Nathan Sweet <misc@n4te.com> */ public class ObjectSpace { static private final int returnValueMask = 1 << 7; static private final int returnExceptionMask = 1 << 6; static private final int responseIdMask = 0xff & ~returnValueMask & ~returnExceptionMask; static private final Object instancesLock = new Object(); static ObjectSpace[] instances = new ObjectSpace[0]; static private final HashMap<Class, CachedMethod[]> methodCache = new HashMap(); static private boolean asm = true; final IntMap idToObject = new IntMap(); final ObjectIntMap objectToID = new ObjectIntMap(); Connection[] connections = {}; final Object connectionsLock = new Object(); Executor executor; private final Listener invokeListener = new Listener() { public void received (final Connection connection, Object object) { if (!(object instanceof InvokeMethod)) return; if (connections != null) { int i = 0, n = connections.length; for (; i < n; i++) if (connection == connections[i]) break; if (i == n) return; // The InvokeMethod message is not for a connection in this ObjectSpace. } final InvokeMethod invokeMethod = (InvokeMethod)object; final Object target = idToObject.get(invokeMethod.objectID); if (target == null) { if (WARN) warn("kryonet", "Ignoring remote invocation request for unknown object ID: " + invokeMethod.objectID); return; } if (executor == null) invoke(connection, target, invokeMethod); else { executor.execute(new Runnable() { public void run () { invoke(connection, target, invokeMethod); } }); } } public void disconnected (Connection connection) { removeConnection(connection); } }; /** Creates an ObjectSpace with no connections. Connections must be {@link #addConnection(Connection) added} to allow the * remote end of the connections to access objects in this ObjectSpace. */ public ObjectSpace () { synchronized (instancesLock) { ObjectSpace[] instances = ObjectSpace.instances; ObjectSpace[] newInstances = new ObjectSpace[instances.length + 1]; newInstances[0] = this; System.arraycopy(instances, 0, newInstances, 1, instances.length); ObjectSpace.instances = newInstances; } } /** Creates an ObjectSpace with the specified connection. More connections can be {@link #addConnection(Connection) added}. */ public ObjectSpace (Connection connection) { this(); addConnection(connection); } /** Sets the executor used to invoke methods when an invocation is received from a remote endpoint. By default, no executor is * set and invocations occur on the network thread, which should not be blocked for long. * @param executor May be null. */ public void setExecutor (Executor executor) { this.executor = executor; } /** Registers an object to allow the remote end of the ObjectSpace's connections to access it using the specified ID. * <p> * If a connection is added to multiple ObjectSpaces, the same object ID should not be registered in more than one of those * ObjectSpaces. * @param objectID Must not be Integer.MAX_VALUE. * @see #getRemoteObject(Connection, int, Class...) */ public void register (int objectID, Object object) { if (objectID == Integer.MAX_VALUE) throw new IllegalArgumentException("objectID cannot be Integer.MAX_VALUE."); if (object == null) throw new IllegalArgumentException("object cannot be null."); idToObject.put(objectID, object); objectToID.put(object, objectID); if (TRACE) trace("kryonet", "Object registered with ObjectSpace as " + objectID + ": " + object); } /** Removes an object. The remote end of the ObjectSpace's connections will no longer be able to access it. */ public void remove (int objectID) { Object object = idToObject.remove(objectID); if (object != null) objectToID.remove(object, 0); if (TRACE) trace("kryonet", "Object " + objectID + " removed from ObjectSpace: " + object); } /** Removes an object. The remote end of the ObjectSpace's connections will no longer be able to access it. */ public void remove (Object object) { if (!idToObject.containsValue(object, true)) return; int objectID = idToObject.findKey(object, true, -1); idToObject.remove(objectID); objectToID.remove(object, 0); if (TRACE) trace("kryonet", "Object " + objectID + " removed from ObjectSpace: " + object); } /** Causes this ObjectSpace to stop listening to the connections for method invocation messages. */ public void close () { Connection[] connections = this.connections; for (int i = 0; i < connections.length; i++) connections[i].removeListener(invokeListener); synchronized (instancesLock) { ArrayList<ObjectSpace> temp = new ArrayList(Arrays.asList(instances)); temp.remove(this); instances = temp.toArray(new ObjectSpace[temp.size()]); } if (TRACE) trace("kryonet", "Closed ObjectSpace."); } /** Allows the remote end of the specified connection to access objects registered in this ObjectSpace. */ public void addConnection (Connection connection) { if (connection == null) throw new IllegalArgumentException("connection cannot be null."); synchronized (connectionsLock) { Connection[] newConnections = new Connection[connections.length + 1]; newConnections[0] = connection; System.arraycopy(connections, 0, newConnections, 1, connections.length); connections = newConnections; } connection.addListener(invokeListener); if (TRACE) trace("kryonet", "Added connection to ObjectSpace: " + connection); } /** Removes the specified connection, it will no longer be able to access objects registered in this ObjectSpace. */ public void removeConnection (Connection connection) { if (connection == null) throw new IllegalArgumentException("connection cannot be null."); connection.removeListener(invokeListener); synchronized (connectionsLock) { ArrayList<Connection> temp = new ArrayList(Arrays.asList(connections)); temp.remove(connection); connections = temp.toArray(new Connection[temp.size()]); } if (TRACE) trace("kryonet", "Removed connection from ObjectSpace: " + connection); } /** Invokes the method on the object and, if necessary, sends the result back to the connection that made the invocation * request. This method is invoked on the update thread of the {@link EndPoint} for this ObjectSpace and unless an * {@link #setExecutor(Executor) executor} has been set. * @param connection The remote side of this connection requested the invocation. */ protected void invoke (Connection connection, Object target, InvokeMethod invokeMethod) { if (DEBUG) { String argString = ""; if (invokeMethod.args != null) { argString = Arrays.deepToString(invokeMethod.args); argString = argString.substring(1, argString.length() - 1); } debug("kryonet", connection + " received: " + target.getClass().getSimpleName() + " + invokeMethod.cachedMethod.method.getName() + "(" + argString + ")"); } byte responseData = invokeMethod.responseData; boolean transmitReturnValue = (responseData & returnValueMask) == returnValueMask; boolean transmitExceptions = (responseData & returnExceptionMask) == returnExceptionMask; int responseID = responseData & responseIdMask; CachedMethod cachedMethod = invokeMethod.cachedMethod; Object result = null; try { result = cachedMethod.invoke(target, invokeMethod.args); } catch (InvocationTargetException ex) { if (transmitExceptions) result = ex.getCause(); else throw new KryoNetException("Error invoking method: " + cachedMethod.method.getDeclaringClass().getName() + "." + cachedMethod.method.getName(), ex); } catch (Exception ex) { throw new KryoNetException( "Error invoking method: " + cachedMethod.method.getDeclaringClass().getName() + "." + cachedMethod.method.getName(), ex); } if (responseID == 0) return; InvokeMethodResult invokeMethodResult = new InvokeMethodResult(); invokeMethodResult.objectID = invokeMethod.objectID; invokeMethodResult.responseID = (byte)responseID; // Do not return non-primitives if transmitReturnValue is false. if (!transmitReturnValue && !invokeMethod.cachedMethod.method.getReturnType().isPrimitive()) { invokeMethodResult.result = null; } else { invokeMethodResult.result = result; } int length = connection.sendTCP(invokeMethodResult); if (DEBUG) debug("kryonet", connection + " sent TCP: " + result + " (" + length + ")"); } /** Identical to {@link #getRemoteObject(Connection, int, Class...)} except returns the object cast to the specified interface * type. The returned object still implements {@link RemoteObject}. */ static public <T> T getRemoteObject (final Connection connection, int objectID, Class<T> iface) { return (T)getRemoteObject(connection, objectID, new Class[] {iface}); } /** Returns a proxy object that implements the specified interfaces. Methods invoked on the proxy object will be invoked * remotely on the object with the specified ID in the ObjectSpace for the specified connection. If the remote end of the * connection has not {@link #addConnection(Connection) added} the connection to the ObjectSpace, the remote method invocations * will be ignored. * <p> * Methods that return a value will throw {@link TimeoutException} if the response is not received with the * {@link RemoteObject#setResponseTimeout(int) response timeout}. * <p> * If {@link RemoteObject#setNonBlocking(boolean) non-blocking} is false (the default), then methods that return a value must * not be called from the update thread for the connection. An exception will be thrown if this occurs. Methods with a void * return value can be called on the update thread. * <p> * If a proxy returned from this method is part of an object graph sent over the network, the object graph on the receiving * side will have the proxy object replaced with the registered object. * @see RemoteObject */ static public RemoteObject getRemoteObject (Connection connection, int objectID, Class... ifaces) { if (connection == null) throw new IllegalArgumentException("connection cannot be null."); if (ifaces == null) throw new IllegalArgumentException("ifaces cannot be null."); Class[] temp = new Class[ifaces.length + 1]; temp[0] = RemoteObject.class; System.arraycopy(ifaces, 0, temp, 1, ifaces.length); return (RemoteObject)Proxy.newProxyInstance(ObjectSpace.class.getClassLoader(), temp, new RemoteInvocationHandler(connection, objectID)); } /** Handles network communication when methods are invoked on a proxy. */ static private class RemoteInvocationHandler implements InvocationHandler { private final Connection connection; final int objectID; private int timeoutMillis = 3000; private boolean nonBlocking; private boolean transmitReturnValue = true; private boolean transmitExceptions = true; private boolean remoteToString; private boolean udp; private Byte lastResponseID; private byte nextResponseId = 1; private Listener responseListener; final ReentrantLock lock = new ReentrantLock(); final Condition responseCondition = lock.newCondition(); final InvokeMethodResult[] responseTable = new InvokeMethodResult[64]; final boolean[] pendingResponses = new boolean[64]; public RemoteInvocationHandler (Connection connection, final int objectID) { super(); this.connection = connection; this.objectID = objectID; responseListener = new Listener() { public void received (Connection connection, Object object) { if (!(object instanceof InvokeMethodResult)) return; InvokeMethodResult invokeMethodResult = (InvokeMethodResult)object; if (invokeMethodResult.objectID != objectID) return; int responseID = invokeMethodResult.responseID; synchronized (this) { if (pendingResponses[responseID]) responseTable[responseID] = invokeMethodResult; } lock.lock(); try { responseCondition.signalAll(); } finally { lock.unlock(); } } public void disconnected (Connection connection) { close(); } }; connection.addListener(responseListener); } public Object invoke (Object proxy, Method method, Object[] args) throws Exception { Class declaringClass = method.getDeclaringClass(); if (declaringClass == RemoteObject.class) { String name = method.getName(); if (name.equals("close")) { close(); return null; } else if (name.equals("setResponseTimeout")) { timeoutMillis = (Integer)args[0]; return null; } else if (name.equals("setNonBlocking")) { nonBlocking = (Boolean)args[0]; return null; } else if (name.equals("setTransmitReturnValue")) { transmitReturnValue = (Boolean)args[0]; return null; } else if (name.equals("setUDP")) { udp = (Boolean)args[0]; return null; } else if (name.equals("setTransmitExceptions")) { transmitExceptions = (Boolean)args[0]; return null; } else if (name.equals("setRemoteToString")) { remoteToString = (Boolean)args[0]; return null; } else if (name.equals("waitForLastResponse")) { if (lastResponseID == null) throw new IllegalStateException("There is no last response to wait for."); return waitForResponse(lastResponseID); } else if (name.equals("getLastResponseID")) { if (lastResponseID == null) throw new IllegalStateException("There is no last response ID."); return lastResponseID; } else if (name.equals("waitForResponse")) { if (!transmitReturnValue && !transmitExceptions && nonBlocking) throw new IllegalStateException("This RemoteObject is currently set to ignore all responses."); return waitForResponse((Byte)args[0]); } else if (name.equals("getConnection")) { return connection; } // Should never happen, for debugging purposes only throw new KryoNetException("Invocation handler could not find RemoteObject method. Check ObjectSpace.java"); } else if (!remoteToString && declaringClass == Object.class && method.getName().equals("toString")) return "<proxy>"; InvokeMethod invokeMethod = new InvokeMethod(); invokeMethod.objectID = objectID; invokeMethod.args = args; CachedMethod[] cachedMethods = getMethods(connection.getEndPoint().getKryo(), method.getDeclaringClass()); for (int i = 0, n = cachedMethods.length; i < n; i++) { CachedMethod cachedMethod = cachedMethods[i]; if (cachedMethod.method.equals(method)) { invokeMethod.cachedMethod = cachedMethod; break; } } if (invokeMethod.cachedMethod == null) throw new KryoNetException("Method not found: " + method); // A invocation doesn't need a response if it's async and no return values or exceptions are wanted back. boolean needsResponse = !udp && (transmitReturnValue || transmitExceptions || !nonBlocking); byte responseID = 0; if (needsResponse) { synchronized (this) { // Increment the response counter and put it into the low bits of the responseID. responseID = nextResponseId++; if (nextResponseId > responseIdMask) nextResponseId = 1; pendingResponses[responseID] = true; } // Pack other data into the high bits. byte responseData = responseID; if (transmitReturnValue) responseData |= returnValueMask; if (transmitExceptions) responseData |= returnExceptionMask; invokeMethod.responseData = responseData; } else { invokeMethod.responseData = 0; // A response data of 0 means to not respond. } int length = udp ? connection.sendUDP(invokeMethod) : connection.sendTCP(invokeMethod); if (DEBUG) { String argString = ""; if (args != null) { argString = Arrays.deepToString(args); argString = argString.substring(1, argString.length() - 1); } debug("kryonet", connection + " sent " + (udp ? "UDP" : "TCP") + ": " + method.getDeclaringClass().getSimpleName() + "#" + method.getName() + "(" + argString + ") (" + length + ")"); } lastResponseID = (byte)(invokeMethod.responseData & responseIdMask); if (nonBlocking || udp) { Class returnType = method.getReturnType(); if (returnType.isPrimitive()) { if (returnType == int.class) return 0; if (returnType == boolean.class) return Boolean.FALSE; if (returnType == float.class) return 0f; if (returnType == char.class) return (char)0; if (returnType == long.class) return 0l; if (returnType == short.class) return (short)0; if (returnType == byte.class) return (byte)0; if (returnType == double.class) return 0d; } return null; } try { Object result = waitForResponse(lastResponseID); if (result != null && result instanceof Exception) throw (Exception)result; else return result; } catch (TimeoutException ex) { throw new TimeoutException("Response timed out: " + method.getDeclaringClass().getName() + "." + method.getName()); } finally { synchronized (this) { pendingResponses[responseID] = false; responseTable[responseID] = null; } } } private Object waitForResponse (byte responseID) { if (connection.getEndPoint().getUpdateThread() == Thread.currentThread()) throw new IllegalStateException("Cannot wait for an RMI response on the connection's update thread."); long endTime = System.currentTimeMillis() + timeoutMillis; while (true) { long remaining = endTime - System.currentTimeMillis(); InvokeMethodResult invokeMethodResult; synchronized (this) { invokeMethodResult = responseTable[responseID]; } if (invokeMethodResult != null) { lastResponseID = null; return invokeMethodResult.result; } else { if (remaining <= 0) throw new TimeoutException("Response timed out."); lock.lock(); try { responseCondition.await(remaining, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new KryoNetException(e); } finally { lock.unlock(); } } } } void close () { connection.removeListener(responseListener); } } /** Internal message to invoke methods remotely. */ static public class InvokeMethod implements FrameworkMessage, KryoSerializable { public int objectID; public CachedMethod cachedMethod; public Object[] args; // The top bits of the ID indicate if the remote invocation should respond with return values and exceptions, respectively. // The remaining bites are a counter. This means up to 63 responses can be stored before undefined behavior occurs due to // possible duplicate IDs. A response data of 0 means to not respond. public byte responseData; public void write (Kryo kryo, Output output) { output.writeInt(objectID, true); output.writeInt(cachedMethod.methodClassID, true); output.writeByte(cachedMethod.methodIndex); Serializer[] serializers = cachedMethod.serializers; Object[] args = this.args; for (int i = 0, n = serializers.length; i < n; i++) { Serializer serializer = serializers[i]; if (serializer != null) kryo.writeObjectOrNull(output, args[i], serializer); else kryo.writeClassAndObject(output, args[i]); } output.writeByte(responseData); } public void read (Kryo kryo, Input input) { objectID = input.readInt(true); int methodClassID = input.readInt(true); Class methodClass = kryo.getRegistration(methodClassID).getType(); byte methodIndex = input.readByte(); try { cachedMethod = getMethods(kryo, methodClass)[methodIndex]; } catch (IndexOutOfBoundsException ex) { throw new KryoException("Invalid method index " + methodIndex + " for class: " + methodClass.getName()); } Serializer[] serializers = cachedMethod.serializers; Class[] parameterTypes = cachedMethod.method.getParameterTypes(); Object[] args = new Object[serializers.length]; this.args = args; for (int i = 0, n = args.length; i < n; i++) { Serializer serializer = serializers[i]; if (serializer != null) args[i] = kryo.readObjectOrNull(input, parameterTypes[i], serializer); else args[i] = kryo.readClassAndObject(input); } responseData = input.readByte(); } } /** Internal message to return the result of a remotely invoked method. */ static public class InvokeMethodResult implements FrameworkMessage { public int objectID; public byte responseID; public Object result; } static CachedMethod[] getMethods (Kryo kryo, Class type) { CachedMethod[] cachedMethods = methodCache.get(type); // Maybe should cache per Kryo instance? if (cachedMethods != null) return cachedMethods; ArrayList<Method> allMethods = new ArrayList(); Class nextClass = type; while (nextClass != null) { Collections.addAll(allMethods, nextClass.getDeclaredMethods()); nextClass = nextClass.getSuperclass(); if (nextClass == Object.class) break; } ArrayList<Method> methods = new ArrayList(Math.max(1, allMethods.size())); for (int i = 0, n = allMethods.size(); i < n; i++) { Method method = allMethods.get(i); int modifiers = method.getModifiers(); if (Modifier.isStatic(modifiers)) continue; if (Modifier.isPrivate(modifiers)) continue; if (method.isSynthetic()) continue; methods.add(method); } Collections.sort(methods, new Comparator<Method>() { public int compare (Method o1, Method o2) { // Methods are sorted so they can be represented as an index. int diff = o1.getName().compareTo(o2.getName()); if (diff != 0) return diff; Class[] argTypes1 = o1.getParameterTypes(); Class[] argTypes2 = o2.getParameterTypes(); if (argTypes1.length > argTypes2.length) return 1; if (argTypes1.length < argTypes2.length) return -1; for (int i = 0; i < argTypes1.length; i++) { diff = argTypes1[i].getName().compareTo(argTypes2[i].getName()); if (diff != 0) return diff; } throw new RuntimeException("Two methods with same signature!"); // Impossible. } }); Object methodAccess = null; if (asm && !Util.isAndroid && Modifier.isPublic(type.getModifiers())) methodAccess = MethodAccess.get(type); int n = methods.size(); cachedMethods = new CachedMethod[n]; for (int i = 0; i < n; i++) { Method method = methods.get(i); Class[] parameterTypes = method.getParameterTypes(); CachedMethod cachedMethod = null; if (methodAccess != null) { try { AsmCachedMethod asmCachedMethod = new AsmCachedMethod(); asmCachedMethod.methodAccessIndex = ((MethodAccess)methodAccess).getIndex(method.getName(), parameterTypes); asmCachedMethod.methodAccess = (MethodAccess)methodAccess; cachedMethod = asmCachedMethod; } catch (RuntimeException ignored) { } } if (cachedMethod == null) cachedMethod = new CachedMethod(); cachedMethod.method = method; cachedMethod.methodClassID = kryo.getRegistration(method.getDeclaringClass()).getId(); cachedMethod.methodIndex = i; // Store the serializer for each final parameter. cachedMethod.serializers = new Serializer[parameterTypes.length]; for (int ii = 0, nn = parameterTypes.length; ii < nn; ii++) if (kryo.isFinal(parameterTypes[ii])) cachedMethod.serializers[ii] = kryo.getSerializer(parameterTypes[ii]); cachedMethods[i] = cachedMethod; } methodCache.put(type, cachedMethods); return cachedMethods; } /** Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs * to. */ static Object getRegisteredObject (Connection connection, int objectID) { ObjectSpace[] instances = ObjectSpace.instances; for (int i = 0, n = instances.length; i < n; i++) { ObjectSpace objectSpace = instances[i]; // Check if the connection is in this ObjectSpace. Connection[] connections = objectSpace.connections; for (int j = 0; j < connections.length; j++) { if (connections[j] != connection) continue; // Find an object with the objectID. Object object = objectSpace.idToObject.get(objectID); if (object != null) return object; } } return null; } /** Returns the first ID registered for the specified object with any of the ObjectSpaces the specified connection belongs to, * or Integer.MAX_VALUE if not found. */ static int getRegisteredID (Connection connection, Object object) { ObjectSpace[] instances = ObjectSpace.instances; for (int i = 0, n = instances.length; i < n; i++) { ObjectSpace objectSpace = instances[i]; // Check if the connection is in this ObjectSpace. Connection[] connections = objectSpace.connections; for (int j = 0; j < connections.length; j++) { if (connections[j] != connection) continue; // Find an ID with the object. int id = objectSpace.objectToID.get(object, Integer.MAX_VALUE); if (id != Integer.MAX_VALUE) return id; } } return Integer.MAX_VALUE; } /** Registers the classes needed to use ObjectSpaces. This should be called before any connections are opened. * @see Kryo#register(Class, Serializer) */ static public void registerClasses (final Kryo kryo) { kryo.register(Object[].class); kryo.register(InvokeMethod.class); FieldSerializer<InvokeMethodResult> resultSerializer = new FieldSerializer<InvokeMethodResult>(kryo, InvokeMethodResult.class) { public void write (Kryo kryo, Output output, InvokeMethodResult result) { super.write(kryo, output, result); output.writeInt(result.objectID, true); } public InvokeMethodResult read (Kryo kryo, Input input, Class<InvokeMethodResult> type) { InvokeMethodResult result = super.read(kryo, input, type); result.objectID = input.readInt(true); return result; } }; resultSerializer.removeField("objectID"); kryo.register(InvokeMethodResult.class, resultSerializer); kryo.register(InvocationHandler.class, new Serializer() { public void write (Kryo kryo, Output output, Object object) { RemoteInvocationHandler handler = (RemoteInvocationHandler)Proxy.getInvocationHandler(object); output.writeInt(handler.objectID, true); } public Object read (Kryo kryo, Input input, Class type) { int objectID = input.readInt(true); Connection connection = (Connection)kryo.getContext().get("connection"); Object object = getRegisteredObject(connection, objectID); if (WARN && object == null) warn("kryonet", "Unknown object ID " + objectID + " for connection: " + connection); return object; } }); } /** If true, an attempt will be made to use ReflectASM for invoking methods. Default is true. */ static public void setAsm (boolean asm) { ObjectSpace.asm = asm; } static class CachedMethod { Method method; int methodClassID; int methodIndex; Serializer[] serializers; public Object invoke (Object target, Object[] args) throws IllegalAccessException, InvocationTargetException { return method.invoke(target, args); } } static class AsmCachedMethod extends CachedMethod { MethodAccess methodAccess; int methodAccessIndex = -1; public Object invoke (Object target, Object[] args) throws IllegalAccessException, InvocationTargetException { try { return methodAccess.invoke(target, methodAccessIndex, args); } catch (Exception ex) { throw new InvocationTargetException(ex); } } } /** Serializes an object registered with an ObjectSpace so the receiving side gets a {@link RemoteObject} proxy rather than the * bytes for the serialized object. * @author Nathan Sweet <misc@n4te.com> */ static public class RemoteObjectSerializer extends Serializer { public void write (Kryo kryo, Output output, Object object) { Connection connection = (Connection)kryo.getContext().get("connection"); int id = getRegisteredID(connection, object); if (id == Integer.MAX_VALUE) throw new KryoNetException("Object not found in an ObjectSpace: " + object); output.writeInt(id, true); } public Object read (Kryo kryo, Input input, Class type) { int objectID = input.readInt(true); Connection connection = (Connection)kryo.getContext().get("connection"); return ObjectSpace.getRemoteObject(connection, objectID, type); } } }
package com.hp.hpl.jena.graph.test; import com.hp.hpl.jena.util.CollectionFactory; import com.hp.hpl.jena.util.iterator.*; import com.hp.hpl.jena.graph.*; import com.hp.hpl.jena.graph.query.*; import com.hp.hpl.jena.shared.*; import java.util.*; /** AbstractTestGraph provides a bunch of basic tests for something that purports to be a Graph. The abstract method getGraph must be overridden in subclasses to deliver a Graph of interest. @author kers */ public/* abstract */class AbstractTestGraph extends GraphTestBase { public AbstractTestGraph( String name ) { super( name ); } /** Returns a Graph to take part in the test. Must be overridden in a subclass. */ // public abstract Graph getGraph(); public Graph getGraph() { return Factory.createGraphMem(); } public Graph getGraphWith( String facts ) { Graph g = getGraph(); graphAdd( g, facts ); return g; } public void testCloseSetsIsClosed() { Graph g = getGraph(); assertFalse( "unclosed Graph shouild not be isClosed()", g.isClosed() ); g.close(); assertTrue( "closed Graph should be isClosed()", g.isClosed() ); } /** This test case was generated by Ian and was caused by GraphMem not keeping up with changes to the find interface. */ public void testFindAndContains() { Graph g = getGraph(); Node r = Node.create( "r" ), s = Node.create( "s" ), p = Node.create( "P" ); g.add( Triple.create( r, p, s ) ); assertTrue( g.contains( r, p, Node.ANY ) ); assertEquals( 1, g.find( r, p, Node.ANY ).toList().size() ); } public void testRepeatedSubjectDoesNotConceal() { Graph g = getGraphWith( "s P o; s Q r" ); assertTrue( g.contains( triple( "s P o" ) ) ); assertTrue( g.contains( triple( "s Q r" ) ) ); assertTrue( g.contains( triple( "?? P o" ) ) ); assertTrue( g.contains( triple( "?? Q r" ) ) ); assertTrue( g.contains( triple( "?? P ??" ) ) ); assertTrue( g.contains( triple( "?? Q ??" ) ) ); } public void testFindByFluidTriple() { Graph g = getGraphWith( "x y z " ); Set expect = tripleSet( "x y z" ); assertEquals( expect, g.find( triple( "?? y z" ) ).toSet() ); assertEquals( expect, g.find( triple( "x ?? z" ) ).toSet() ); assertEquals( expect, g.find( triple( "x y ??" ) ).toSet() ); } public void testContainsConcrete() { Graph g = getGraphWith( "s P o; _x _R _y; x S 0" ); assertTrue( g.contains( triple( "s P o" ) ) ); assertTrue( g.contains( triple( "_x _R _y" ) ) ); assertTrue( g.contains( triple( "x S 0" ) ) ); assertFalse( g.contains( triple( "s P Oh" ) ) ); assertFalse( g.contains( triple( "S P O" ) ) ); assertFalse( g.contains( triple( "s p o" ) ) ); assertFalse( g.contains( triple( "_x _r _y" ) ) ); assertFalse( g.contains( triple( "x S 1" ) ) ); } public void testContainsFluid() { Graph g = getGraphWith( "x R y; a P b" ); assertTrue( g.contains( triple( "?? R y" ) ) ); assertTrue( g.contains( triple( "x ?? y" ) ) ); assertTrue( g.contains( triple( "x R ??" ) ) ); assertTrue( g.contains( triple( "?? P b" ) ) ); assertTrue( g.contains( triple( "a ?? b" ) ) ); assertTrue( g.contains( triple( "a P ??" ) ) ); assertTrue( g.contains( triple( "?? R y" ) ) ); assertFalse( g.contains( triple( "?? R b" ) ) ); assertFalse( g.contains( triple( "a ?? y" ) ) ); assertFalse( g.contains( triple( "x P ??" ) ) ); assertFalse( g.contains( triple( "?? R x" ) ) ); assertFalse( g.contains( triple( "x ?? R" ) ) ); assertFalse( g.contains( triple( "a S ??" ) ) ); } /** Check that contains respects by-value semantics. */ public void testContainsByValue() { if (getGraph().getCapabilities().handlesLiteralTyping()) { // TODO fix the adhocness of this Graph g1 = getGraphWith( "x P '1'xsd:integer" ); assertTrue( g1.contains( triple( "x P '01'xsd:int" ) ) ); Graph g2 = getGraphWith( "x P '1'xsd:int" ); assertTrue( g2.contains( triple( "x P '1'xsd:integer" ) ) ); Graph g3 = getGraphWith( "x P '123'xsd:string" ); assertTrue( g3.contains( triple( "x P '123'" ) ) ); } } public void testMatchLanguagedLiteralCaseInsensitive() { Graph m = graphWith( "a p 'chat'en" ); // TODO: should be Graph m = getGraphWith( "a p 'chat'en" ); if (m.getCapabilities().handlesLiteralTyping()) { Node chaten = node( "'chat'en" ), chatEN = node( "'chat'EN" ); assertDiffer( chaten, chatEN ); assertTrue( chaten.sameValueAs( chatEN ) ); assertEquals( chaten.getIndexingValue(), chatEN.getIndexingValue() ); assertEquals( 1, m.find( Node.ANY, Node.ANY, chaten ).toList().size() ); assertEquals( 1, m.find( Node.ANY, Node.ANY, chatEN ).toList().size() ); } } public void testMatchBothLanguagedLiteralsCaseInsensitive() { Graph m = graphWith( "a p 'chat'en; a p 'chat'EN" ); // TODO: should be Graph m = getGraphWith( "a p 'chat'en; a p 'chat'EN" ); if (m.getCapabilities().handlesLiteralTyping()) { Node chaten = node( "'chat'en" ), chatEN = node( "'chat'EN" ); assertDiffer( chaten, chatEN ); assertTrue( chaten.sameValueAs( chatEN ) ); assertEquals( chaten.getIndexingValue(), chatEN.getIndexingValue() ); assertEquals( 2, m.find( Node.ANY, Node.ANY, chaten ).toList().size() ); assertEquals( 2, m.find( Node.ANY, Node.ANY, chatEN ).toList().size() ); } } public void testNoMatchAgainstUnlanguagesLiteral() { Graph m = graphWith( "a p 'chat'en; a p 'chat'" ); // TODO: should be Graph m = getGraphWith( "a p 'chat'en; a p 'chat'" ); if (m.getCapabilities().handlesLiteralTyping()) { Node chaten = node( "'chat'en" ), chatEN = node( "'chat'EN" ); assertDiffer( chaten, chatEN ); assertTrue( chaten.sameValueAs( chatEN ) ); assertEquals( chaten.getIndexingValue(), chatEN.getIndexingValue() ); assertEquals( 1, m.find( Node.ANY, Node.ANY, chaten ).toList().size() ); assertEquals( 1, m.find( Node.ANY, Node.ANY, chatEN ).toList().size() ); } } /** test isEmpty - moved from the QueryHandler code. */ public void testIsEmpty() { Graph g = getGraph(); if (canBeEmpty( g )) { assertTrue( g.isEmpty() ); g.add( Triple.create( "S P O" ) ); assertFalse( g.isEmpty() ); g.add( Triple.create( "A B C" ) ); assertFalse( g.isEmpty() ); g.add( Triple.create( "S P O" ) ); assertFalse( g.isEmpty() ); g.delete( Triple.create( "S P O" ) ); assertFalse( g.isEmpty() ); g.delete( Triple.create( "A B C" ) ); assertTrue( g.isEmpty() ); } } public void testAGraph() { String title = this.getClass().getName(); Graph g = getGraph(); int baseSize = g.size(); graphAdd( g, "x R y; p S q; a T b" ); assertContainsAll( title + ": simple graph", g, "x R y; p S q; a T b" ); assertEquals( title + ": size", baseSize + 3, g.size() ); graphAdd( g, "spindizzies lift cities; Diracs communicate instantaneously" ); assertEquals( title + ": size after adding", baseSize + 5, g.size() ); g.delete( triple( "x R y" ) ); g.delete( triple( "a T b" ) ); assertEquals( title + ": size after deleting", baseSize + 3, g.size() ); assertContainsAll( title + ": modified simple graph", g, "p S q; spindizzies lift cities; Diracs communicate instantaneously" ); assertOmitsAll( title + ": modified simple graph", g, "x R y; a T b" ); ClosableIterator it = g.find( Node.ANY, node("lift"), Node.ANY ); assertTrue( title + ": finds some triple(s)", it.hasNext() ); assertEquals( title + ": finds a 'lift' triple", triple("spindizzies lift cities"), it.next() ); assertFalse( title + ": finds exactly one triple", it.hasNext() ); it.close(); } // public void testStuff() //// testAGraph( "StoreMem", new GraphMem() ); //// testAGraph( "StoreMemBySubject", new GraphMem() ); //// String [] empty = new String [] {}; //// Graph g = graphWith( "x R y; p S q; a T b" ); //// //// assertContainsAll( "simple graph", g, "x R y; p S q; a T b" ); //// graphAdd( g, "spindizzies lift cities; Diracs communicate instantaneously" ); //// g.delete( triple( "x R y" ) ); //// g.delete( triple( "a T b" ) ); //// assertContainsAll( "modified simple graph", g, "p S q; spindizzies lift cities; Diracs communicate instantaneously" ); //// assertOmitsAll( "modified simple graph", g, "x R y; a T b" ); /** Test that Graphs have transaction support methods, and that if they fail on some g they fail because they do not support the operation. */ public void testHasTransactions() { Graph g = getGraph(); TransactionHandler th = g.getTransactionHandler(); th.transactionsSupported(); try { th.begin(); } catch (UnsupportedOperationException x) {} try { th.abort(); } catch (UnsupportedOperationException x) {} try { th.commit(); } catch (UnsupportedOperationException x) {} Command cmd = new Command() { public Object execute() { return null; } }; try { th.executeInTransaction( cmd ); } catch (UnsupportedOperationException x) {} } public void testExecuteInTransactionCatchesThrowable() {Graph g = getGraph(); TransactionHandler th = g.getTransactionHandler(); if (th.transactionsSupported()) { Command cmd = new Command() { public Object execute() throws Error { throw new Error(); } }; try { th.executeInTransaction( cmd ); } catch (JenaException x) {} } } static final Triple [] tripleArray = tripleArray( "S P O; A R B; X Q Y" ); static final List tripleList = Arrays.asList( tripleArray( "i lt j; p equals q" ) ); static final Triple [] setTriples = tripleArray ( "scissors cut paper; paper wraps stone; stone breaks scissors" ); static final Set tripleSet = CollectionFactory.createHashedSet( Arrays.asList( setTriples ) ); public void testBulkUpdate() { Graph g = getGraph(); BulkUpdateHandler bu = g.getBulkUpdateHandler(); Graph items = graphWith( "pigs might fly; dead can dance" ); int initialSize = g.size(); bu.add( tripleArray ); testContains( g, tripleArray ); testOmits( g, tripleList ); bu.add( tripleList ); testContains( g, tripleList ); testContains( g, tripleArray ); bu.add( tripleSet.iterator() ); testContains( g, tripleSet.iterator() ); testContains( g, tripleList ); testContains( g, tripleArray ); bu.add( items ); testContains( g, items ); testContains( g, tripleSet.iterator() ); testContains( g, tripleArray ); testContains( g, tripleList ); bu.delete( tripleArray ); testOmits( g, tripleArray ); testContains( g, tripleList ); testContains( g, tripleSet.iterator() ); testContains( g, items ); bu.delete( tripleSet.iterator() ); testOmits( g, tripleSet.iterator() ); testOmits( g, tripleArray ); testContains( g, tripleList ); testContains( g, items ); bu.delete( items ); testOmits( g, tripleSet.iterator() ); testOmits( g, tripleArray ); testContains( g, tripleList ); testOmits( g, items ); bu.delete( tripleList ); assertEquals( "graph has original size", initialSize, g.size() ); } public void testBulkAddWithReification() { testBulkAddWithReification( false ); testBulkAddWithReification( true ); } public void testBulkAddWithReificationPreamble() { Graph g = getGraph(); xSPO( g.getReifier() ); assertFalse( getReificationTriples( g.getReifier() ).isEmpty() ); } public void testBulkAddWithReification( boolean withReifications ) { Graph graphToUpdate = getGraph(); BulkUpdateHandler bu = graphToUpdate.getBulkUpdateHandler(); Graph graphToAdd = graphWith( "pigs might fly; dead can dance" ); Reifier updatedReifier = graphToUpdate.getReifier(); Reifier addedReifier = graphToAdd.getReifier(); xSPOyXYZ( addedReifier ); bu.add( graphToAdd, withReifications ); assertIsomorphic ( withReifications ? getReificationTriples( addedReifier ) : graphWith( "" ), getReificationTriples( updatedReifier ) ); } protected void xSPOyXYZ( Reifier r ) { xSPO( r ); r.reifyAs( Node.create( "y" ), Triple.create( "X Y Z" ) ); } protected void aABC( Reifier r ) { r.reifyAs( Node.create( "a" ), Triple.create( "A B C" ) ); } protected void xSPO( Reifier r ) { r.reifyAs( Node.create( "x" ), Triple.create( "S P O" ) ); } public void testRemove() { testRemove( "?? ?? ??", "?? ?? ??" ); testRemove( "S ?? ??", "S ?? ??" ); testRemove( "S ?? ??", "?? P ??" ); testRemove( "S ?? ??", "?? ?? O" ); testRemove( "?? P ??", "S ?? ??" ); testRemove( "?? P ??", "?? P ??" ); testRemove( "?? P ??", "?? ?? O" ); testRemove( "?? ?? O", "S ?? ??" ); testRemove( "?? ?? O", "?? P ??" ); testRemove( "?? ?? O", "?? ?? O" ); } public void testRemove( String findRemove, String findCheck ) { Graph g = getGraphWith( "S P O" ); ExtendedIterator it = g.find( Triple.create( findRemove ) ); try { it.next(); it.remove(); it.close(); assertEquals( "remove with " + findRemove + ":", 0, g.size() ); assertFalse( g.contains( Triple.create( findCheck ) ) ); } catch (UnsupportedOperationException e) { it.close(); assertFalse( g.getCapabilities().iteratorRemoveAllowed() ); } it.close(); } public void testBulkRemoveWithReification() { testBulkUpdateRemoveWithReification( true ); testBulkUpdateRemoveWithReification( false ); } public void testBulkUpdateRemoveWithReification( boolean withReifications ) { Graph g = getGraph(); BulkUpdateHandler bu = g.getBulkUpdateHandler(); Graph items = graphWith( "pigs might fly; dead can dance" ); Reifier gr = g.getReifier(), ir = items.getReifier(); xSPOyXYZ( ir ); xSPO( gr ); aABC( gr ); bu.delete( items, withReifications ); Graph answer = graphWith( "" ); Reifier ar = answer.getReifier(); if (withReifications) aABC( ar ); else { xSPO( ar ); aABC( ar ); } assertIsomorphic( getReificationTriples( ar ), getReificationTriples( gr ) ); } public void testHasCapabilities() { Graph g = getGraph(); Capabilities c = g.getCapabilities(); boolean sa = c.sizeAccurate(); boolean aaSome = c.addAllowed(); boolean aaAll = c.addAllowed( true ); boolean daSome = c.deleteAllowed(); boolean daAll = c.deleteAllowed( true ); boolean cbe = c.canBeEmpty(); } public void testFind() { Graph g = getGraph(); graphAdd( g, "S P O" ); assertDiffer( new HashSet(), g.find( Node.ANY, Node.ANY, Node.ANY ).toSet() ); assertDiffer( new HashSet(), g.find( Triple.ANY ).toSet() ); } protected boolean canBeEmpty( Graph g ) { return g.isEmpty(); } public void testEventRegister() { Graph g = getGraph(); GraphEventManager gem = g.getEventManager(); assertSame( gem, gem.register( new RecordingListener() ) ); } /** Test that we can safely unregister a listener that isn't registered. */ public void testEventUnregister() { getGraph().getEventManager().unregister( L ); } /** Handy triple for test purposes. */ protected Triple SPO = Triple.create( "S P O" ); protected RecordingListener L = new RecordingListener(); /** Utility: get a graph, register L with its manager, return the graph. */ protected Graph getAndRegister( GraphListener gl ) { Graph g = getGraph(); g.getEventManager().register( gl ); return g; } public void testAddTriple() { Graph g = getAndRegister( L ); g.add( SPO ); L.assertHas( new Object[] {"add", g, SPO} ); } public void testDeleteTriple() { Graph g = getAndRegister( L ); g.delete( SPO ); L.assertHas( new Object[] { "delete", g, SPO} ); } public void testListSubjects() { Set emptySubjects = listSubjects( getGraphWith( "" ) ); Graph g = getGraphWith( "x P y; y Q z" ); assertEquals( nodeSet( "x y" ), remove( listSubjects( g ), emptySubjects ) ); g.delete( triple( "x P y" ) ); assertEquals( nodeSet( "y" ), remove( listSubjects( g ), emptySubjects ) ); } protected Set listSubjects( Graph g ) { return iteratorToSet( g.queryHandler().subjectsFor( Node.ANY, Node.ANY ) ); } public void testListPredicates() { Set emptyPredicates = listPredicates( getGraphWith( "" ) ); Graph g = getGraphWith( "x P y; y Q z" ); assertEquals( nodeSet( "P Q" ), remove( listPredicates( g ), emptyPredicates ) ); g.delete( triple( "x P y" ) ); assertEquals( nodeSet( "Q" ), remove( listPredicates( g ), emptyPredicates ) ); } protected Set listPredicates( Graph g ) { return iteratorToSet( g.queryHandler().predicatesFor( Node.ANY, Node.ANY ) ); } public void testListObjects() { Set emptyObjects = listObjects( getGraphWith( "" ) ); Graph g = getGraphWith( "x P y; y Q z" ); assertEquals( nodeSet( "y z" ), remove( listObjects( g ), emptyObjects ) ); g.delete( triple( "x P y" ) ); assertEquals( nodeSet( "z" ), remove( listObjects( g ), emptyObjects ) ); } protected Set listObjects( Graph g ) { return iteratorToSet( g.queryHandler().objectsFor( Node.ANY, Node.ANY ) ); } /** Answer a set with all the elements of <code>A</code> except those in <code>B</code>. */ private Set remove( Set A, Set B ) { Set result = new HashSet( A ); result.removeAll( B ); return result; } /** Ensure that triples removed by calling .remove() on the iterator returned by a find() will generate deletion notifications. */ public void testEventDeleteByFind() { Graph g = getAndRegister( L ); if (g.getCapabilities().iteratorRemoveAllowed()) { Triple toRemove = triple( "remove this triple" ); g.add( toRemove ); ExtendedIterator rtr = g.find( toRemove ); assertTrue( "ensure a(t least) one triple", rtr.hasNext() ); rtr.next(); rtr.remove(); rtr.close(); L.assertHas( new Object[] { "add", g, toRemove, "delete", g, toRemove} ); } } public void testTwoListeners() { RecordingListener L1 = new RecordingListener(); RecordingListener L2 = new RecordingListener(); Graph g = getGraph(); GraphEventManager gem = g.getEventManager(); gem.register( L1 ).register( L2 ); g.add( SPO ); L2.assertHas( new Object[] {"add", g, SPO} ); L1.assertHas( new Object[] {"add", g, SPO} ); } public void testUnregisterWorks() { Graph g = getGraph(); GraphEventManager gem = g.getEventManager(); gem.register( L ).unregister( L ); g.add( SPO ); L.assertHas( new Object[] {} ); } public void testRegisterTwice() { Graph g = getAndRegister( L ); g.getEventManager().register( L ); g.add( SPO ); L.assertHas( new Object[] {"add", g, SPO, "add", g, SPO} ); } public void testUnregisterOnce() { Graph g = getAndRegister( L ); g.getEventManager().register( L ).unregister( L ); g.delete( SPO ); L.assertHas( new Object[] {"delete", g, SPO} ); } public void testBulkAddArrayEvent() { Graph g = getAndRegister( L ); Triple [] triples = tripleArray( "x R y; a P b" ); g.getBulkUpdateHandler().add( triples ); L.assertHas( new Object[] {"add[]", g, triples} ); } public void testBulkAddList() { Graph g = getAndRegister( L ); List elems = Arrays.asList( tripleArray( "bells ring loudly; pigs might fly" ) ); g.getBulkUpdateHandler().add( elems ); L.assertHas( new Object[] {"addList", g, elems} ); } public void testBulkDeleteArray() { Graph g = getAndRegister( L ); Triple [] triples = tripleArray( "x R y; a P b" ); g.getBulkUpdateHandler().delete( triples ); L.assertHas( new Object[] {"delete[]", g, triples} ); } public void testBulkDeleteList() { Graph g = getAndRegister( L ); List elems = Arrays.asList( tripleArray( "bells ring loudly; pigs might fly" ) ); g.getBulkUpdateHandler().delete( elems ); L.assertHas( new Object[] {"deleteList", g, elems} ); } public void testBulkAddIterator() { Graph g = getAndRegister( L ); Triple [] triples = tripleArray( "I wrote this; you read that; I wrote this" ); g.getBulkUpdateHandler().add( asIterator( triples ) ); L.assertHas( new Object[] {"addIterator", g, Arrays.asList( triples )} ); } public void testBulkDeleteIterator() { Graph g = getAndRegister( L ); Triple [] triples = tripleArray( "I wrote this; you read that; I wrote this" ); g.getBulkUpdateHandler().delete( asIterator( triples ) ); L.assertHas( new Object[] {"deleteIterator", g, Arrays.asList( triples )} ); } public Iterator asIterator( Triple [] triples ) { return Arrays.asList( triples ).iterator(); } public void testBulkAddGraph() { Graph g = getAndRegister( L ); Graph triples = graphWith( "this type graph; I type slowly" ); g.getBulkUpdateHandler().add( triples ); L.assertHas( new Object[] {"addGraph", g, triples} ); } public void testBulkDeleteGraph() { Graph g = getAndRegister( L ); Graph triples = graphWith( "this type graph; I type slowly" ); g.getBulkUpdateHandler().delete( triples ); L.assertHas( new Object[] {"deleteGraph", g, triples} ); } public void testGeneralEvent() { Graph g = getAndRegister( L ); Object value = new int[]{}; g.getEventManager().notifyEvent( g, value ); L.assertHas( new Object[] { "someEvent", g, value } ); } public void testRemoveAllEvent() { Graph g = getAndRegister( L ); g.getBulkUpdateHandler().removeAll(); L.assertHas( new Object[] { "someEvent", g, GraphEvents.removeAll } ); } public void testRemoveSomeEvent() { Graph g = getAndRegister( L ); Node S = node( "S" ), P = node( "?P" ), O = node( "??" ); g.getBulkUpdateHandler().remove( S, P, O ); Object event = GraphEvents.remove( S, P, O ); L.assertHas( new Object[] { "someEvent", g, event } ); } /** * Test that nodes can be found in all triple positions. * However, testing for literals in subject positions is suppressed * at present to avoid problems with InfGraphs which try to prevent * such constructs leaking out to the RDF layer. */ public void testContainsNode() { Graph g = getGraph(); graphAdd( g, "a P b; _c _Q _d; a 11 12" ); QueryHandler qh = g.queryHandler(); assertTrue( qh.containsNode( node( "a" ) ) ); assertTrue( qh.containsNode( node( "P" ) ) ); assertTrue( qh.containsNode( node( "b" ) ) ); assertTrue( qh.containsNode( node( "_c" ) ) ); assertTrue( qh.containsNode( node( "_Q" ) ) ); assertTrue( qh.containsNode( node( "_d" ) ) ); // assertTrue( qh.containsNode( node( "10" ) ) ); assertTrue( qh.containsNode( node( "11" ) ) ); assertTrue( qh.containsNode( node( "12" ) ) ); assertFalse( qh.containsNode( node( "x" ) ) ); assertFalse( qh.containsNode( node( "_y" ) ) ); assertFalse( qh.containsNode( node( "99" ) ) ); } public void testSubjectsFor() { Graph g = getGraphWith( "a P b; a Q c; a P d; b P x; c Q y" ); testSameSubjects( g, Node.ANY, Node.ANY ); testSameSubjects( g, node( "P" ), Node.ANY ); testSameSubjects( g, node( "Q" ), node( "c" ) ); } protected void testSameSubjects( Graph g, Node p, Node o ) { Set bis = iteratorToSet( SimpleQueryHandler.subjectsFor( g, p, o ) ); Set qhs = iteratorToSet( g.queryHandler().subjectsFor( p, o ) ); assertEquals( bis, qhs ); } public void testListSubjectsNoRemove() { Graph g = getGraphWith( "a P b; b Q c; c R a" ); Iterator it = g.queryHandler().subjectsFor( Node.ANY, Node.ANY ); it.next(); try { it.remove(); fail( "listSubjects for " + g.getClass() + " should not support .remove()" ); } catch (UnsupportedOperationException e) { pass(); } } public void testObjectsFor() { Graph g = getGraphWith( "b P a; c Q a; d P a; x P b; y Q c" ); testSameObjects( g, Node.ANY, Node.ANY ); testSameObjects( g, node( "P" ), Node.ANY ); testSameObjects( g, node( "Q" ), node( "c" ) ); } protected void testSameObjects( Graph g, Node s, Node p ) { Set bis = iteratorToSet( SimpleQueryHandler.objectsFor( g, s, p ) ); Set qhs = iteratorToSet( g.queryHandler().objectsFor( s, p ) ); assertEquals( bis, qhs ); } public void testListObjectsNoRemove() { Graph g = getGraphWith( "a P b; b Q c; c R a" ); Iterator it = g.queryHandler().objectsFor( Node.ANY, Node.ANY ); it.next(); try { it.remove(); fail( "listObjects for " + g.getClass() + " should not support .remove()" ); } catch (UnsupportedOperationException e) { pass(); } } public void testListObjectNoDuplicates() { Graph g = getGraphWith( "a P 1; b P 1" ); int count = 0; Node one = node( "1" ); Iterator it = g.queryHandler().objectsFor( Node.ANY, Node.ANY ); while (it.hasNext()) if (it.next().equals( one )) count += 1; assertEquals( 1, count ); } public void testPredicatesFor() { Graph g = getGraphWith( "a P b; c Q d; e R f; g P b; h Q i" ); testSamePredicates( g, Node.ANY, Node.ANY ); testSamePredicates( g, Node.ANY, node( "b" ) ); testSamePredicates( g, node( "g" ), Node.ANY ); testSamePredicates( g, node( "e" ), node( "f" ) ); } protected void testSamePredicates( Graph g, Node s, Node o ) { Set bis = iteratorToSet( SimpleQueryHandler.predicatesFor( g, s, o ) ); Set qhs = iteratorToSet( g.queryHandler().predicatesFor( s, o ) ); assertEquals( bis, qhs ); } public void testListPredicatesNoRemove() { Graph g = getGraphWith( "a P b; b Q c; c R a" ); Iterator it = g.queryHandler().predicatesFor( Node.ANY, Node.ANY ); it.next(); try { it.remove(); fail( "listPredicates for " + g.getClass() + " should not support .remove()" ); } catch (UnsupportedOperationException e) { pass(); } } public void testRemoveAll() { testRemoveAll( "" ); testRemoveAll( "a R b" ); testRemoveAll( "c S d; e:ff GGG hhhh; _i J 27; Ell Em 'en'" ); } public void testRemoveAll( String triples ) { Graph g = getGraph(); graphAdd( g, triples ); g.getBulkUpdateHandler().removeAll(); assertTrue( g.isEmpty() ); } /** Test cases for RemoveSPO(); each entry is a triple (add, remove, result). <ul> <li>add - the triples to add to the graph to start with <li>remove - the pattern to use in the removal <li>result - the triples that should remain in the graph </ul> */ protected String[][] cases = { { "x R y", "x R y", "" }, { "x R y; a P b", "x R y", "a P b" }, { "x R y; a P b", "?? R y", "a P b" }, { "x R y; a P b", "x R ??", "a P b" }, { "x R y; a P b", "x ?? y", "a P b" }, { "x R y; a P b", "?? ?? ??", "" }, { "x R y; a P b; c P d", "?? P ??", "x R y" }, { "x R y; a P b; x S y", "x ?? ??", "a P b" }, }; /** Test that remove(s, p, o) works, in the presence of inferencing graphs that mean emptyness isn't available. This is why we go round the houses and test that expected ~= initialContent + addedStuff - removed - initialContent. */ public void testRemoveSPO() { for (int i = 0; i < cases.length; i += 1) for (int j = 0; j < 3; j += 1) { Graph content = getGraph(); Graph baseContent = copy( content ); graphAdd( content, cases[i][0] ); Triple remove = triple( cases[i][1] ); Graph expected = graphWith( cases[i][2] ); content.getBulkUpdateHandler().remove( remove.getSubject(), remove.getPredicate(), remove.getObject() ); Graph finalContent = remove( copy( content ), baseContent ); assertIsomorphic( cases[i][1], expected, finalContent ); } } protected void add( Graph toUpdate, Graph toAdd ) { toUpdate.getBulkUpdateHandler().add( toAdd ); } protected Graph remove( Graph toUpdate, Graph toRemove ) { toUpdate.getBulkUpdateHandler().delete( toRemove ); return toUpdate; } protected Graph copy( Graph g ) { Graph result = Factory.createDefaultGraph(); result.getBulkUpdateHandler().add( g ); return result; } protected Graph getClosed() { Graph result = getGraph(); result.close(); return result; } // public void testClosedDelete() // try { getClosed().delete( triple( "x R y" ) ); fail( "delete when closed" ); } // catch (ClosedException c) { /* as required */ } // public void testClosedAdd() // try { getClosed().add( triple( "x R y" ) ); fail( "add when closed" ); } // catch (ClosedException c) { /* as required */ } // public void testClosedContainsTriple() // try { getClosed().contains( triple( "x R y" ) ); fail( "contains[triple] when closed" ); } // catch (ClosedException c) { /* as required */ } // public void testClosedContainsSPO() // Node a = Node.ANY; // try { getClosed().contains( a, a, a ); fail( "contains[SPO] when closed" ); } // catch (ClosedException c) { /* as required */ } // public void testClosedFindTriple() // try { getClosed().find( triple( "x R y" ) ); fail( "find [triple] when closed" ); } // catch (ClosedException c) { /* as required */ } // public void testClosedFindSPO() // Node a = Node.ANY; // try { getClosed().find( a, a, a ); fail( "find[SPO] when closed" ); } // catch (ClosedException c) { /* as required */ } // public void testClosedSize() // try { getClosed().size(); fail( "size when closed (" + this.getClass() + ")" ); } // catch (ClosedException c) { /* as required */ } }
package com.ilya.sergeev.potlach; import java.util.Collection; import java.util.List; import retrofit.RetrofitError; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import com.google.common.collect.Lists; import com.ilya.sergeev.potlach.client.Gift; import com.ilya.sergeev.potlach.client.GiftInfo; import com.ilya.sergeev.potlach.client.GiftSvcApi; import com.ilya.sergeev.potlach.client.ServerSvc; import com.ilya.sergeev.potlach.client.Vote; import com.ilya.sergeev.potlach.image_loader.GiftImageLoader; public abstract class ListOfGiftsFragment extends MainContentFragment { private ListView mListView; private ProgressBar mProgressBar; private View mNoGiftsView; private AsyncTask<Void, Void, List<GiftInfo>> mReloadTask = null; private GiftImageLoader mImageLoader; private GiftsAdapter mAdapter; private GiftsAdapter.VoteListener mVoteListener = new GiftsAdapter.VoteListener() { @Override public void pressLike(GiftInfo giftInfo) { long giftId = giftInfo.getGift().getId(); Vote vote = giftInfo.getVote(); if (vote == null) { vote = new Vote(null, giftId); giftInfo.setVote(vote); } vote.setVote(1); Activity activity = getActivity(); if (activity != null) { Intent voteUpIntent = TasksMaker.getVoteUpIntent(activity, giftId); activity.startService(voteUpIntent); } } @Override public void pressDislike(GiftInfo giftInfo) { long giftId = giftInfo.getGift().getId(); Vote vote = giftInfo.getVote(); if (vote == null) { vote = new Vote(null, giftId); giftInfo.setVote(vote); } vote.setVote(-1); Activity activity = getActivity(); if (activity != null) { Intent voteDownIntent = TasksMaker.getVoteDownIntent(activity, giftId); activity.startService(voteDownIntent); } } }; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); mImageLoader = new GiftImageLoader(inflater.getContext(), ServerSvc.getServerApi().getApi(GiftSvcApi.class)); View view = inflater.inflate(R.layout.fragment_gift_list, container, false); mListView = (ListView) view.findViewById(R.id.list_view); mListView.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Object obj = parent.getAdapter().getItem((int) id); if (obj instanceof GiftInfo) { GiftInfo giftInfo = (GiftInfo) obj; if (giftInfo.isWasTouched()) { return; } giftInfo.setWasTouched(true); Gift gift = giftInfo.getGift(); Activity activity = getActivity(); if (activity != null) { Intent touchIntent = TasksMaker.getTouchIntent(activity, gift.getId()); activity.startService(touchIntent); } mAdapter.updateView(view, giftInfo); // TODO show single gift } } }); mListView.setOnScrollListener(new ListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mImageLoader.setCanUpdate(scrollState == SCROLL_STATE_IDLE); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar); mNoGiftsView = view.findViewById(R.id.no_gifts_view); return view; } @Override public void onResume() { super.onResume(); if (mReloadTask == null) { reloadGifts(); showProgress(false); } else { showProgress(true); } } protected void reloadGifts() { if (mReloadTask != null) { mReloadTask.cancel(false); } mReloadTask = new AsyncTask<Void, Void, List<GiftInfo>>() { @Override protected void onPreExecute() { super.onPreExecute(); showProgress(true); } @Override protected List<GiftInfo> doInBackground(Void... params) { List<GiftInfo> gifts = null; try { Collection<GiftInfo> giftsOrigin = getGifts(); if (giftsOrigin != null) { gifts = Lists.newArrayList(giftsOrigin); } } catch (RetrofitError ex) { // TODO make some logic ex.printStackTrace(); gifts = null; } return gifts; } @Override protected void onPostExecute(List<GiftInfo> gifts) { super.onPostExecute(gifts); showProgress(false); mReloadTask = null; if (mListView != null) { mAdapter = new GiftsAdapter(gifts, mImageLoader, mVoteListener); mListView.setAdapter(mAdapter); if (gifts == null || gifts.size() == 0) { mNoGiftsView.setVisibility(View.VISIBLE); } } } }; mReloadTask.execute(); } protected abstract Collection<GiftInfo> getGifts(); private void showProgress(boolean progressEnable) { if (mListView != null) { mListView.setVisibility(progressEnable ? View.GONE : View.VISIBLE); } if (mProgressBar != null) { mProgressBar.setVisibility(progressEnable ? View.VISIBLE : View.GONE); } mNoGiftsView.setVisibility(View.GONE); } }
package com.lukechenshui.jresume.themes; import com.lukechenshui.jresume.resume.Resume; import com.lukechenshui.jresume.resume.items.Person; import com.lukechenshui.jresume.resume.items.Project; import com.lukechenshui.jresume.resume.items.Skill; import com.lukechenshui.jresume.resume.items.education.Education; import com.lukechenshui.jresume.resume.items.education.Examination; import com.lukechenshui.jresume.resume.items.education.ExaminationSubject; import com.lukechenshui.jresume.resume.items.education.School; import com.lukechenshui.jresume.resume.items.work.JobWork; import com.lukechenshui.jresume.resume.items.work.VolunteerWork; import j2html.tags.ContainerTag; import j2html.tags.EmptyTag; import j2html.tags.Tag; import org.apache.commons.lang3.StringUtils; import pl.allegro.finance.tradukisto.ValueConverters; import java.util.ArrayList; import static j2html.TagCreator.*; public class DefaultTheme extends BaseTheme { public DefaultTheme(String themeName) { super(themeName); } protected void generateHead() { ArrayList<Tag> children = new ArrayList<>(); Person person = resumeBeingOperatedOn.getPerson(); ContainerTag head = head(); EmptyTag firstSemanticUI = link().withRel("stylesheet").withHref(getResource("semantic/dist/semantic.min.css")); ContainerTag secondSemanticUI = script().withSrc(getResource("semantic/dist/semantic.min.js")); EmptyTag ratingSemanticCSSComponent = link().withRel("stylesheet").withHref(getResource("semantic/dist/components/rating.min.css")); ContainerTag jquery = script().withSrc(getResource("jquery-3.1.1.min.js")); ContainerTag ratingSemanticJSComponent = script().withSrc(getResource("semantic/dist/components/rating.min.js")); ContainerTag initializeRating = script().withType("text/javascript").withText("$(document).ready(function(){$('.rating').rating('disable');});"); ContainerTag regularSizeTextCSS = style().withText(".regularText{font-size:14px;}"); children.add(jquery); children.add(firstSemanticUI); children.add(secondSemanticUI); children.add(ratingSemanticJSComponent); children.add(ratingSemanticCSSComponent); children.add(initializeRating); children.add(regularSizeTextCSS); if (person != null && person.getName() != null) { children.add(title(person.getName())); } head.with(children); head.with(meta().withCharset("UTF-8")); html = html.with(head); } protected void generateBody() { super.generateBody(); } protected ContainerTag generatePerson() { ContainerTag personHtml = div().withId("person").withClass("ui very padded text container"); ArrayList<Tag> children = new ArrayList<>(); Person person = resumeBeingOperatedOn.getPerson(); children.add(person.checkForAndGeneratePrecedingLineBreaks()); if (person != null) { if (person.getName() != null) { children.add(h1(person.getName()).withClass("ui header centered")); } if (person.getJobTitle() != null) { children.add(h3(person.getJobTitle()).withClass("ui header centered")); children.add(br()); } ValueConverters converter = ValueConverters.ENGLISH_INTEGER; String numberOfPersonalDetailsColumns = converter.asWords(resumeBeingOperatedOn.getNumPersonalDetailsColumns()); ContainerTag centeredGrid = div().withClass("ui grid " + numberOfPersonalDetailsColumns + " column centered"); if (person.getAddress() != null) { ContainerTag address = div().withText(person.getAddress()).withClass("ui center aligned column regularText"); centeredGrid.with(address); } if (person.getEmail() != null) { ContainerTag email = div().withText(person.getEmail()).withClass("ui center aligned column regularText"); centeredGrid.with(email); } if (person.getPhoneNumber() != null) { ContainerTag phoneNumber = div().withText(person.getPhoneNumber()).withClass("ui center aligned column regularText"); centeredGrid.with(phoneNumber); } if (person.getWebsite() != null) { ContainerTag address = a(person.getWebsite()) .withHref(person.getWebsite()).withTarget("_blank").withClass("ui center aligned column regularText"); centeredGrid.with(address); } children.add(centeredGrid); } children.add(person.checkForAndGenerateFollowingLineBreaks()); personHtml.with(children); return personHtml; } protected ContainerTag generateJobWork() { ContainerTag workHtml = div().withId("work").withClass("ui very padded text container"); ArrayList<Tag> workChildren = new ArrayList<>(); ArrayList<Tag> workItemsChildren = new ArrayList<>(); ArrayList<JobWork> jobWork = resumeBeingOperatedOn.getJobWork(); if (resumeBeingOperatedOn != null && jobWork != null) { if (jobWork.size() > 0) { if (StringUtils.isNotBlank(resumeBeingOperatedOn.getJobWorkHeading())) { workChildren.add(h2(resumeBeingOperatedOn.getJobWorkHeading()).withClass("ui header centered")); } else { workChildren.add(h2("Work Experience").withClass("ui header centered")); } } for (JobWork work : jobWork) { workChildren.add(work.checkForAndGeneratePrecedingLineBreaks()); ContainerTag content = div().withClass("ui content"); if (work.getCompany() != null) { ContainerTag companyName = div().withClass("ui header").withText(work.getCompany()); content.with(companyName); } if (work.getPosition() != null) { ContainerTag position = div().withClass("ui gray small label").withText(work.getPosition()); content.with(position); } if (work.getStartDate() != null || work.getEndDate() != null) { ContainerTag timeLine = div().withClass("ui gray small label"); String text = ""; if (work.getStartDate() != null) { text += work.getStartDate(); } if (work.getEndDate() != null) { if (work.getStartDate() != null) { text += " - "; } text += work.getEndDate(); } timeLine = timeLine.withText(text); content.with(timeLine); } if (work.getSummary() != null) { ContainerTag summary = div().withText(work.getSummary()).withClass("regularText"); content.with(summary); } if (work.getHighlights() != null && work.getHighlights().size() > 0) { ContainerTag highlightHeading = h4("Highlights").withClass("ui header"); content.with(highlightHeading); ContainerTag highlights = div().withClass("ui bulleted list"); for (String highlight : work.getHighlights()) { ContainerTag item = div().withText(highlight).withClass("ui item regularText"); highlights.with(item); } content.with(highlights); } if (work.getKeywords() != null && work.getKeywords().size() > 0) { ContainerTag keywords = div().withClass("ui centered container"); for (String keyword : work.getKeywords()) { ContainerTag item = a(keyword).withClass("ui blue small label"); keywords.with(item); } content.with(keywords); } workChildren.add(content); workChildren.add(work.checkForAndGenerateFollowingLineBreaks()); } } workHtml.with(workChildren); return workHtml; } protected ContainerTag generateVolunteerWork() { ContainerTag workHtml = div().withId("volunteerWork").withClass("ui very padded text container"); ArrayList<Tag> workChildren = new ArrayList<>(); ArrayList<Tag> workItemsChildren = new ArrayList<>(); ArrayList<VolunteerWork> volunteerWork = resumeBeingOperatedOn.getVolunteerWork(); if (resumeBeingOperatedOn != null && volunteerWork != null) { if (volunteerWork.size() > 0) { if (StringUtils.isNoneEmpty(resumeBeingOperatedOn.getVolunteerWorkHeading())) { workChildren.add(h2(resumeBeingOperatedOn.getVolunteerWorkHeading()).withClass("ui header centered")); } else { workChildren.add(h2("Volunteer Work Experience").withClass("ui header centered")); } } for (VolunteerWork work : volunteerWork) { workChildren.add(work.checkForAndGeneratePrecedingLineBreaks()); ContainerTag content = div().withClass("ui content"); if (work.getCompany() != null) { ContainerTag companyName = div().withClass("ui header").withText(work.getCompany()); content.with(companyName); } if (work.getPosition() != null) { ContainerTag position = div().withClass("ui gray small label").withText(work.getPosition()); content.with(position); } if (work.getStartDate() != null || work.getEndDate() != null) { ContainerTag timeLine = div().withClass("ui gray small label"); String text = ""; if (work.getStartDate() != null) { text += work.getStartDate(); } if (work.getEndDate() != null) { if (work.getStartDate() != null) { text += " - "; } text += work.getEndDate(); } timeLine = timeLine.withText(text); content.with(timeLine); } if (work.getSummary() != null) { ContainerTag summary = div().withText(work.getSummary()).withClass("regularText"); content.with(summary); } if (work.getHighlights() != null && work.getHighlights().size() > 0) { ContainerTag highlightHeading = h4("Highlights").withClass("ui header"); content.with(highlightHeading); ContainerTag highlights = div().withClass("ui bulleted list"); for (String highlight : work.getHighlights()) { ContainerTag item = div().withText(highlight).withClass("ui item regularText"); highlights.with(item); } content.with(highlights); } if (work.getKeywords() != null && work.getKeywords().size() > 0) { ContainerTag keywords = div().withClass("ui centered container"); for (String keyword : work.getKeywords()) { ContainerTag item = a(keyword).withClass("ui blue small label"); keywords.with(item); } content.with(keywords); } content.with(br()); workChildren.add(work.checkForAndGenerateFollowingLineBreaks()); workChildren.add(content); } } workHtml.with(workChildren); return workHtml; } public ContainerTag generateSkills() { ContainerTag skills = div().withId("skills").withClass("ui very padded text container"); ArrayList<Tag> children = new ArrayList<>(); ValueConverters converter = ValueConverters.ENGLISH_INTEGER; String numberOfSkillColumns = converter.asWords(resumeBeingOperatedOn.getNumSkillColumns()); ContainerTag list = div().withClass("ui " + numberOfSkillColumns + " column grid container relaxed centered"); if (resumeBeingOperatedOn.getSkills().size() > 0) { if (StringUtils.isNotBlank(resumeBeingOperatedOn.getSkillsHeading())){ children.add(h2(resumeBeingOperatedOn.getSkillsHeading()).withClass("ui header centered")); } else{ children.add(h2("Skills").withClass("ui header centered")); } } for (Skill skill : resumeBeingOperatedOn.getSkills()) { ContainerTag skillItem = div().withClass("ui center aligned column"); list.with(skill.checkForAndGeneratePrecedingLineBreaks()); if (skill.getName() != null) { String text = skill.getName(); if (skill.getCompetence() != null) { text += " - " + skill.getCompetence(); } ContainerTag skillContent = div().withText(text).withClass("content centered"); skillItem.with(skillContent); } if (skill.getCompetence() != null) { ContainerTag skillRating = div().withClass("ui rating").attr("data-max-rating", "5"); String competence = skill.getCompetence(); switch (competence.toLowerCase()) { case "beginner": skillRating.attr("data-rating", String.valueOf(Skill.competenceToStarHashMap.get("beginner"))); break; case "intermediate": skillRating.attr("data-rating", String.valueOf(Skill.competenceToStarHashMap.get("intermediate"))); break; case "advanced": skillRating.attr("data-rating", String.valueOf(Skill.competenceToStarHashMap.get("advanced"))); break; default: System.out.println("Skill " + skill.getName() + " has invalid competence - " + skill.getCompetence() + ". Valid competence levels" + " are beginner, intermediate and advanced."); break; } skillItem.with(skillRating); } list.with(skillItem); list.with(skill.checkForAndGenerateFollowingLineBreaks()); } children.add(list); skills.with(children); return skills; } public ContainerTag generateProjects() { ContainerTag projects = div().withId("projects").withClass("ui very padded text container"); ArrayList<Tag> children = new ArrayList<>(); if (resumeBeingOperatedOn.getProjects().size() > 0) { if (StringUtils.isNotBlank(resumeBeingOperatedOn.getProjectsHeading())){ children.add(h2(resumeBeingOperatedOn.getProjectsHeading()).withClass("ui header centered")); } else { children.add(h2("Projects").withClass("ui header centered")); } } for (Project project : resumeBeingOperatedOn.getProjects()) { children.add(project.checkForAndGeneratePrecedingLineBreaks()); ContainerTag content = div().withClass("ui content"); if (project.getName() != null) { ContainerTag projectName = div().withClass("ui header").withText(project.getName()); content.with(projectName); } if (project.getUrl() != null) { ContainerTag projectURL = a(project.getUrl()).withClass("ui").withHref(project.getUrl()); content.with(projectURL); } if (project.getDescription() != null) { ContainerTag description = div().withText(project.getDescription()).withClass("regularText"); content.with(description); } if (project.getHighlights() != null && project.getHighlights().size() > 0) { ContainerTag highlightHeading = h4("Highlights").withClass("ui header"); content.with(highlightHeading); ContainerTag highlights = div().withClass("ui bulleted list"); for (String highlight : project.getHighlights()) { ContainerTag item = div().withText(highlight).withClass("ui item regularText"); highlights.with(item); } content.with(highlights); } if (project.getKeywords() != null && project.getKeywords().size() > 0) { ContainerTag keywords = div().withClass("ui centered container"); for (String keyword : project.getKeywords()) { ContainerTag item = a(keyword).withClass("ui blue small label"); keywords.with(item); } content.with(keywords); } content.with(br()); children.add(content); children.add(project.checkForAndGenerateFollowingLineBreaks()); } projects.with(children); return projects; } @Override protected ContainerTag generateEducation() { ContainerTag educationDiv = div().withId("education").withClass("ui very padded text container"); ArrayList<Tag> children = new ArrayList<>(); Education education = resumeBeingOperatedOn.getEducation(); children.add(education.checkForAndGeneratePrecedingLineBreaks()); if(education.getExaminations() != null || education.getSchools() != null){ if (StringUtils.isNotBlank(resumeBeingOperatedOn.getEducationHeading())){ children.add(h2(resumeBeingOperatedOn.getEducationHeading()).withClass("ui header centered")); } else { children.add(h2("Education").withClass("ui header centered")); } } for(School school : education.getSchools()){ children.add(school.checkForAndGeneratePrecedingLineBreaks()); ContainerTag schoolDiv = div().withClass("ui container"); if (school.getName() != null) { ContainerTag schoolName = div().withClass("ui header").withText(school.getName()); schoolDiv.with(schoolName); } if (school.getStartDate() != null || school.getEndDate() != null) { ContainerTag timeLine = div().withClass("ui gray small label"); String text = ""; if (school.getStartDate() != null) { text += school.getStartDate(); } if (school.getEndDate() != null) { if (school.getStartDate() != null) { text += " - "; } text += school.getEndDate(); } timeLine = timeLine.withText(text); schoolDiv.with(timeLine); } if(school.getGpa() != null){ ContainerTag gpa = div().withClass("ui blue small label").withText(school.getGpa() + " GPA"); schoolDiv.with(gpa); } if(school.getSummary() != null){ schoolDiv.with(br()).with(br()); ContainerTag summary = div().withClass("regularText").withText(school.getSummary()); schoolDiv.with(summary); } schoolDiv.with(generateExaminations(school.getExaminations())); children.add(schoolDiv); children.add(school.checkForAndGenerateFollowingLineBreaks()); } children.add(generateExaminations(education.getExaminations())); children.add(education.checkForAndGenerateFollowingLineBreaks()); educationDiv.with(children); return educationDiv; } private ContainerTag generateExaminations(ArrayList<Examination> examinations) { ContainerTag examinationDiv = div().withClass("ui container"); if (examinations != null) { for (Examination examination : examinations) { examinationDiv.with(examination.checkForAndGeneratePrecedingLineBreaks()); if (examination.getName() != null) { examinationDiv.with(br()); ContainerTag examinationName = div().withClass("ui header").withText(examination.getName()); examinationDiv.with(examinationName); } if (examination.getStartDate() != null || examination.getEndDate() != null) { ContainerTag timeLine = div().withClass("ui gray small label"); String text = ""; if (examination.getStartDate() != null) { text += examination.getStartDate(); } if (examination.getEndDate() != null) { if (examination.getStartDate() != null) { text += " - "; } text += examination.getEndDate(); } timeLine = timeLine.withText(text); examinationDiv.with(timeLine); ContainerTag subjectDiv = div().withClass("ui two column grid centered"); if (examination.getSubjects() != null) { examinationDiv.with(h4().withClass("ui header").withText("Results")); } for (ExaminationSubject subject : examination.getSubjects()) { subjectDiv.with(subject.checkForAndGeneratePrecedingLineBreaks()); ContainerTag row = div().withClass("ui row"); ContainerTag subjectName = div().withClass("ui column regularText"); ContainerTag subjectResult = div().withClass("ui column regularText"); if (subject.getName() != null) { subjectName.withText(subject.getName()); } if (subject.getResult() != null) { subjectResult.withText(subject.getResult()); } row.with(subjectName); row.with(subjectResult); subjectDiv.with(row); subjectDiv.with(subject.checkForAndGenerateFollowingLineBreaks()); } examinationDiv.with(subjectDiv); examinationDiv.with(examination.checkForAndGenerateFollowingLineBreaks()); } } } return examinationDiv; } public String generate(Resume resume) { html = html(); html.with(document()); resumeBeingOperatedOn = resume; generateHead(); generateBody(); htmlString = html.render(); System.out.println(htmlString); return htmlString; } }
package com.mareksebera.simpledilbert; import org.joda.time.DateMidnight; import org.joda.time.DateTimeZone; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.view.View; import android.widget.RemoteViews; import android.widget.Toast; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; public class WidgetProvider extends AppWidgetProvider { public static final String TAG = "Dilbert Widget"; static { /** * Set default time-zone, because strips are published in New York * timezone on midnight * */ DateTimeZone.setDefault(DilbertPreferences.TIME_ZONE); } private static final String INTENT_PREVIOUS = "com.mareksebera.simpledilbert.widget.PREVIOUS"; private static final String INTENT_NEXT = "com.mareksebera.simpledilbert.widget.NEXT"; private static final String INTENT_LATEST = "com.mareksebera.simpledilbert.widget.LATEST"; private static final String INTENT_RANDOM = "com.mareksebera.simpledilbert.widget.RANDOM"; private static final String INTENT_REFRESH = "com.mareksebera.simpledilbert.widget.REFRESH"; private static final String INTENT_DISPLAY = "com.mareksebera.simpledilbert.widget.DISPLAY"; private static Toast currentToast = null; private static PendingIntent getPendingIntent(String INTENT, Context context, int appWidgetId) { Intent intent = new Intent(INTENT); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } static void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId) { final DilbertPreferences prefs = new DilbertPreferences(context); final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); views.setInt(R.id.widget_layout, "setBackgroundColor", prefs.isDarkWidgetLayoutEnabled() ? Color.BLACK : Color.WHITE); views.setOnClickPendingIntent(R.id.widget_previous, getPendingIntent(INTENT_PREVIOUS, context, appWidgetId)); views.setOnClickPendingIntent(R.id.widget_next, getPendingIntent(INTENT_NEXT, context, appWidgetId)); views.setOnClickPendingIntent(R.id.widget_latest, getPendingIntent(INTENT_LATEST, context, appWidgetId)); views.setOnClickPendingIntent(R.id.widget_random, getPendingIntent(INTENT_RANDOM, context, appWidgetId)); views.setOnClickPendingIntent(R.id.widget_image, getPendingIntent(INTENT_DISPLAY, context, appWidgetId)); views.setOnClickPendingIntent(R.id.widget_refresh, getPendingIntent(INTENT_REFRESH, context, appWidgetId)); final DateMidnight currentDate = prefs.getDateForWidgetId(appWidgetId); final String cachedUrl = prefs.getCachedUrl(currentDate); views.setViewVisibility(R.id.widget_progress, View.VISIBLE); views.setTextViewText( R.id.widget_title, prefs.getDateForWidgetId(appWidgetId) .toString( DilbertPreferences.DATE_FORMATTER)); appWidgetManager.updateAppWidget(appWidgetId, views); if (cachedUrl == null) { new GetStripUrl(new GetStripUrlInterface() { @Override public void imageLoadFailed(String url, FailReason reason) { Toast.makeText(context, "Image Loading failed", Toast.LENGTH_SHORT).show(); views.setImageViewResource(R.id.widget_image, R.drawable.cancel); views.setViewVisibility(R.id.widget_progress, View.GONE); appWidgetManager.updateAppWidget(appWidgetId, views); } @Override public void displayImage(String url) { updateAppWidget(context, appWidgetManager, appWidgetId); } }, prefs, currentDate).execute(); } else { ImageLoader.getInstance().loadImage(cachedUrl, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (imageUri.equals(prefs.getCachedUrl(prefs .getDateForWidgetId(appWidgetId)))) { views.setViewVisibility(R.id.widget_progress, View.GONE); views.setImageViewBitmap(R.id.widget_image, loadedImage); appWidgetManager.updateAppWidget(appWidgetId, views); } } }); } } @Override public void onEnabled(Context context) { super.onEnabled(context); AppController.configureImageLoader(context); } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); final int appWidgetId = intent .hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID) ? intent .getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID) : -1; final DilbertPreferences preferences = new DilbertPreferences(context); if (action == null || appWidgetId == -1) { super.onReceive(context, intent); return; } if (currentToast != null) currentToast.cancel(); if (INTENT_PREVIOUS.equals(action)) { preferences.saveDateForWidgetId(appWidgetId, preferences .getDateForWidgetId(appWidgetId).minusDays(1)); } else if (INTENT_NEXT.equals(action)) { preferences.saveDateForWidgetId(appWidgetId, preferences .getDateForWidgetId(appWidgetId).plusDays(1)); } else if (INTENT_LATEST.equals(action)) { preferences.saveDateForWidgetId(appWidgetId, DateMidnight.now(DilbertPreferences.TIME_ZONE)); } else if (INTENT_RANDOM.equals(action)) { preferences.saveDateForWidgetId(appWidgetId, DilbertPreferences.getRandomDateMidnight()); } else if (INTENT_REFRESH.equals(action)) { preferences .removeCache(preferences.getDateForWidgetId(appWidgetId)); } else if (INTENT_DISPLAY.equals(action)) { preferences.saveCurrentDate(preferences .getDateForWidgetId(appWidgetId)); Intent display = new Intent(context, DilbertFragmentActivity.class); display.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(display); } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { DateMidnight current = preferences.getDateForWidgetId(appWidgetId); if (current.equals(DateMidnight.now(DilbertPreferences.TIME_ZONE) .minusDays(1))) { preferences.saveDateForWidgetId(appWidgetId, DateMidnight.now(DilbertPreferences.TIME_ZONE)); } } updateAppWidget(context, AppWidgetManager.getInstance(context), appWidgetId); if (currentToast != null) currentToast.show(); super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final int widgetCount = appWidgetIds.length; for (int i = 0; i < widgetCount; i++) { updateAppWidget(context, appWidgetManager, appWidgetIds[i]); } } @Override public void onDeleted(Context context, int[] appWidgetIds) { if (appWidgetIds == null) return; DilbertPreferences prefs = new DilbertPreferences(context); for (int widgetId : appWidgetIds) { prefs.deleteDateForWidgetId(widgetId); } } }
package com.readytalk.oss.dbms.imp; import static com.readytalk.oss.dbms.util.Util.expect; import static com.readytalk.oss.dbms.util.Util.list; import static com.readytalk.oss.dbms.util.Util.copy; import static com.readytalk.oss.dbms.ExpressionFactory.reference; import static com.readytalk.oss.dbms.ExpressionFactory.isNull; import static com.readytalk.oss.dbms.ExpressionFactory.and; import static com.readytalk.oss.dbms.ExpressionFactory.equal; import static com.readytalk.oss.dbms.SourceFactory.reference; import static com.readytalk.oss.dbms.SourceFactory.leftJoin; import com.readytalk.oss.dbms.RevisionBuilder; import com.readytalk.oss.dbms.TableBuilder; import com.readytalk.oss.dbms.RowBuilder; import com.readytalk.oss.dbms.Index; import com.readytalk.oss.dbms.Table; import com.readytalk.oss.dbms.Column; import com.readytalk.oss.dbms.Revision; import com.readytalk.oss.dbms.DuplicateKeyResolution; import com.readytalk.oss.dbms.Resolution; import com.readytalk.oss.dbms.DuplicateKeyException; import com.readytalk.oss.dbms.PatchTemplate; import com.readytalk.oss.dbms.TableReference; import com.readytalk.oss.dbms.Constant; import com.readytalk.oss.dbms.QueryResult; import com.readytalk.oss.dbms.UpdateTemplate; import com.readytalk.oss.dbms.InsertTemplate; import com.readytalk.oss.dbms.DeleteTemplate; import com.readytalk.oss.dbms.ColumnList; import com.readytalk.oss.dbms.ForeignKey; import com.readytalk.oss.dbms.ForeignKeyResolver; import com.readytalk.oss.dbms.ForeignKeyResolvers; import com.readytalk.oss.dbms.ForeignKeyException; import com.readytalk.oss.dbms.Expression; import com.readytalk.oss.dbms.QueryTemplate; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.Arrays; import java.util.Iterator; import java.util.Collections; class MyRevisionBuilder implements RevisionBuilder { private static final Map<Class, PatchTemplateAdapter> adapters = new HashMap<Class, PatchTemplateAdapter>(); static { adapters.put(UpdateTemplate.class, new UpdateTemplateAdapter()); adapters.put(InsertTemplate.class, new InsertTemplateAdapter()); adapters.put(DeleteTemplate.class, new DeleteTemplateAdapter()); } public Object token; public final NodeStack stack; public final Comparable[] keys; public final Node[] blazedRoots; public final Node[] blazedLeaves; public final Node[] found; public final Node.BlazeResult blazeResult = new Node.BlazeResult(); public NodeStack indexUpdateBaseStack; public NodeStack indexUpdateForkStack; public MyRevision base; public MyRevision indexBase; public MyRevision result; public int max = -1; public boolean dirtyIndexes; public MyRevisionBuilder(Object token, MyRevision base, NodeStack stack) { this.token = token; this.base = base; this.indexBase = base; this.result = base; this.stack = stack; keys = new Comparable[Constants.MaxDepth + 1]; blazedRoots = new Node[Constants.MaxDepth + 1]; blazedLeaves = new Node[Constants.MaxDepth + 1]; found = new Node[Constants.MaxDepth + 1]; } public void setToken(Object token) { if (token != this.token) { this.token = token; for (int i = 0; i < max; ++i) { found[i] = null; blazedLeaves[i] = null; blazedRoots[i + 1] = null; } } } public void setKey(int index, Comparable key) { if (max < index || ! Compare.equal(key, keys[index])) { max = index; keys[index] = key; found[index] = null; blazedLeaves[index] = null; blazedRoots[index + 1] = null; } } public Node blaze(int index, Comparable key) { setKey(index, key); return blaze(index); } public void insertOrUpdate(int index, Comparable key, Object value) { blaze(index, key).value = value; } public void delete(int index, Comparable key) { setKey(index, key); delete(index); } public void deleteAll() { result = MyRevision.Empty; max = -1; } private void delete(int index) { Node root = blazedRoots[index]; if (root == null) { if (index == 0) { root = Node.delete(token, stack, result.root, keys[0]); if (root != result.root) { result = getRevision(token, result, root); } } else { Node original = find(index); Node originalRoot = (Node) find(index - 1).value; if (original == Node.Null) { return; } else if (original == originalRoot && original.left == Node.Null && original.right == Node.Null) { delete(index - 1); } else { root = Node.delete (token, stack, (Node) blaze(index - 1).value, keys[index]); blazedLeaves[index - 1].value = root; blazedRoots[index] = root; blazedLeaves[index] = null; } } } else { deleteBlazed(index); } if (max >= index) { max = index - 1; } } private Node find(int index) { Node n = blazedLeaves[index]; if (n == null) { n = found[index]; if (n == null) { if (index == 0) { n = Node.find(result.root, keys[0]); found[0] = n; } else { n = Node.find((Node) find(index - 1).value, keys[index]); found[index] = n; } } } return n; } private void deleteBlazed(int index) { blazedLeaves[index] = null; Node root = Node.delete(token, stack, blazedRoots[index], keys[index]); blazedRoots[index] = root; blazedLeaves[index] = null; if (root == null) { if (index == 0) { result.root = Node.delete(token, stack, result.root, keys[0]); } else { deleteBlazed(index - 1); } } else { if (index == 0) { result.root = root; } else { blazedLeaves[index - 1].value = root; } } } private Node blaze(int index) { Node n = blazedLeaves[index]; if (n == null) { if (index == 0) { Node root = Node.blaze (blazeResult, token, stack, result.root, keys[0]); if (root != result.root) { result = getRevision(token, result, root); } blazedRoots[0] = root; blazedLeaves[0] = blazeResult.node; blazedRoots[1] = (Node) blazeResult.node.value; return blazeResult.node; } else { Node root = Node.blaze (blazeResult, token, stack, (Node) blaze(index - 1).value, keys[index]); blazedLeaves[index - 1].value = root; blazedRoots[index] = root; blazedLeaves[index] = blazeResult.node; return blazeResult.node; } } else { return n; } } public void updateIndexTree(Index index, MyRevision base, NodeStack baseStack, NodeStack forkStack) { expect(! index.equals(index.table.primaryKey)); List<Column> keyColumns = index.columns; TableIterator iterator = new TableIterator (reference(index.table), base, baseStack, result, forkStack, ConstantAdapter.True, new ExpressionContext(null), false); setKey(Constants.TableDataDepth, index.table); setKey(Constants.IndexDataDepth, index); boolean done = false; while (! done) { QueryResult.Type type = iterator.nextRow(); switch (type) { case End: done = true; break; case Inserted: { Node tree = (Node) iterator.pair.fork.value; int i = 0; for (; i < keyColumns.size() - 1; ++i) { setKey (i + Constants.IndexDataBodyDepth, (Comparable) Node.find(tree, keyColumns.get(i)).value); } Node n = blaze (i + Constants.IndexDataBodyDepth, (Comparable) Node.find(tree, keyColumns.get(i)).value); expect(n.value == Node.Null); n.value = tree; } break; case Deleted: { Node tree = (Node) iterator.pair.base.value; int i = 0; for (; i < keyColumns.size() - 1; ++i) { setKey (i + Constants.IndexDataBodyDepth, (Comparable) Node.find(tree, keyColumns.get(i)).value); } delete (i + Constants.IndexDataBodyDepth, (Comparable) Node.find(tree, keyColumns.get(i)).value); } break; default: throw new RuntimeException("unexpected result type: " + type); } } } private void updateIndexes() { if (dirtyIndexes && indexBase != result) { if (indexUpdateBaseStack == null) { indexUpdateBaseStack = new NodeStack(); indexUpdateForkStack = new NodeStack(); } DiffIterator iterator = new DiffIterator (indexBase.root, indexUpdateBaseStack, result.root, indexUpdateForkStack, list(Interval.Unbounded).iterator(), false); DiffIterator.DiffPair pair = new DiffIterator.DiffPair(); while (iterator.next(pair)) { if (pair.fork != null) { for (NodeIterator indexes = new NodeIterator (indexUpdateBaseStack, Node.pathFind (result.root, Constants.IndexTable, Constants.IndexTable.primaryKey, (Table) pair.fork.key)); indexes.hasNext();) { updateIndexTree ((Index) indexes.next().key, indexBase, indexUpdateBaseStack, indexUpdateForkStack); } } } } dirtyIndexes = false; indexBase = result; } public void updateIndex(Index index) { if (! Compare.equal(index.table.primaryKey, index)) { updateIndexes(); } } private void checkForeignKeys(ForeignKeyResolver resolver) { // todo: is there a performance problem with creating new // NodeStacks every time this method is called? If so, are there // common cases were we can avoid creating them, or should we try // to recycle them somehow? ForeignKeys.checkForeignKeys (new NodeStack(), base, new NodeStack(), this, new NodeStack(), resolver, null); } public void prepareForUpdate(Table table) { // since we update non-primary-key indexes lazily, we may need to // freeze a copy of the last revision which contained up-to-date // indexes so we can do a diff later and use it to update them if (Node.pathFind(result.root, Constants.IndexTable, Constants.IndexTable.primaryKey, table) != Node.Null) { dirtyIndexes = true; if (indexBase == result) { setToken(new Object()); } } } public void buildIndexTree(Index index) { TableIterator iterator = new TableIterator (reference(index.table), MyRevision.Empty, NodeStack.Null, result, new NodeStack(), ConstantAdapter.True, new ExpressionContext(null), false); setKey(Constants.TableDataDepth, index.table); setKey(Constants.IndexDataDepth, index); List<Column> keyColumns = index.columns; boolean done = false; while (! done) { QueryResult.Type type = iterator.nextRow(); switch (type) { case End: done = true; break; case Inserted: { Node tree = (Node) iterator.pair.fork.value; int i = 0; for (; i < keyColumns.size() - 1; ++i) { setKey (i + Constants.IndexDataBodyDepth, (Comparable) Node.find(tree, keyColumns.get(i)).value); } insertOrUpdate (i + Constants.IndexDataBodyDepth, (Comparable) Node.find(tree, keyColumns.get(i)).value, tree); } break; default: throw new RuntimeException("unexpected result type: " + type); } } } private void pathInsert(Table table, Comparable ... path) { setKey(Constants.TableDataDepth, table); setKey(Constants.IndexDataDepth, table.primaryKey); Node tree = Node.Null; Node.BlazeResult result = new Node.BlazeResult(); List<Column> columns = table.primaryKey.columns; for (int i = 0; i < columns.size(); ++i) { tree = Node.blaze(result, token, stack, tree, columns.get(i)); result.node.value = path[i]; if (i == columns.size() - 1) { insertOrUpdate(Constants.IndexDataBodyDepth + i, path[i], tree); } else { setKey(Constants.IndexDataBodyDepth + i, path[i]); } } } private void pathDelete(Table table, Comparable ... path) { setKey(Constants.TableDataDepth, table); setKey(Constants.IndexDataDepth, table.primaryKey); List<Column> columns = table.primaryKey.columns; for (int i = 0; i < columns.size(); ++i) { if (i == columns.size() - 1) { delete(Constants.IndexDataBodyDepth + i, path[i]); } else { setKey(Constants.IndexDataBodyDepth + i, path[i]); } } } private void addIndex(Index index) { if (index.equals(index.table.primaryKey) || Node.pathFind (result.root, Constants.IndexTable, Constants.IndexTable.primaryKey, index.table, index) != Node.Null) { // the specified index is already present -- ignore return; } // flush any changes out to the existing indexes, since we don't // want to get confused later when some indexes are up-to-date and // some aren't: updateIndexes(); buildIndexTree(index); pathInsert(Constants.IndexTable, index.table, index); } private void removeIndex(Index index) { if (index.equals(index.table.primaryKey)) { throw new IllegalArgumentException("cannot remove primary key"); } pathDelete(Constants.IndexTable, index.table, index); setKey(Constants.TableDataDepth, index.table); delete(Constants.IndexDataDepth, index); } private void addForeignKey(ForeignKey constraint) { if (Node.pathFind (result.root, Constants.ForeignKeyTable, Constants.ForeignKeyTable.primaryKey, constraint) != Node.Null) { // the specified foreign key is already present -- ignore return; } insert(DuplicateKeyResolution.Throw, Constants.ForeignKeyTable, constraint, Constants.ForeignKeyRefererColumn, constraint.refererTable); insert(DuplicateKeyResolution.Throw, Constants.ForeignKeyTable, constraint, Constants.ForeignKeyReferentColumn, constraint.referentTable); add(Constants.ForeignKeyRefererIndex); add(Constants.ForeignKeyReferentIndex); dirtyIndexes = true; updateIndexes(); } private void removeForeignKey(ForeignKey constraint) { pathDelete(Constants.ForeignKeyTable, constraint); if (Node.pathFind(result.root, Constants.ForeignKeyTable) == Node.Null) { // the last foreign key constraint has been removed -- remove // the indexes remove(Constants.ForeignKeyRefererIndex); remove(Constants.ForeignKeyReferentIndex); } else { dirtyIndexes = true; updateIndexes(); } } private void delete(Comparable[] keys) { if (keys.length == 0) { deleteAll(); return; } Table table = (Table) keys[0]; if (keys.length == 1) { delete(Constants.TableDataDepth, table); return; } prepareForUpdate(table); setKey(Constants.TableDataDepth, table); setKey(Constants.IndexDataDepth, table.primaryKey); int i = 1; for (; i < keys.length - 1; ++i) { setKey(i - 1 + Constants.IndexDataBodyDepth, keys[i]); } delete(i - 1 + Constants.IndexDataBodyDepth, keys[i]); } private void insert(int depth, List<Column> columns, Comparable[] path) { for (int i = 0; i < path.length; ++i) { blaze(depth, columns.get(i)).value = path[i]; } } private void insert(DuplicateKeyResolution duplicateKeyResolution, Table table, Column column, Object value, Comparable[] path) { prepareForUpdate(table); setKey(Constants.TableDataDepth, table); setKey(Constants.IndexDataDepth, table.primaryKey); for (int i = 0; i < path.length; ++i) { setKey(i + Constants.IndexDataBodyDepth, path[i]); } Node n; if (column == null) { n = blaze((path.length - 1) + Constants.IndexDataBodyDepth); } else { n = blaze(path.length + Constants.IndexDataBodyDepth, column); } if (n.value == Node.Null) { if (column != null) { n.value = value; } insert(path.length + Constants.IndexDataBodyDepth, table.primaryKey.columns, path); } else { switch (duplicateKeyResolution) { case Skip: break; case Overwrite: if (column != null) { n.value = value; } insert(path.length + Constants.IndexDataBodyDepth, table.primaryKey.columns, path); break; case Throw: throw new DuplicateKeyException(); default: throw new RuntimeException ("unexpected resolution: " + duplicateKeyResolution); } } } private class MyTableBuilder implements TableBuilder { private class MyRowBuilder implements RowBuilder { private Object[] path; public MyRowBuilder() { path = new Object[3 + table.primaryKey.columns.size()]; path[0] = table; } public void init(Comparable[] keys) { for(int i = 0; i < keys.length; i++) { path[i + 1] = keys[i]; } } public <T> RowBuilder column(Column<T> key, T value) { path[path.length - 2] = key; path[path.length - 1] = value; insert(DuplicateKeyResolution.Overwrite, path); return this; } public RowBuilder columns(ColumnList columns, Object ... values) { // TODO: optimize if(columns.columns.size() != values.length) { throw new IllegalArgumentException ("wrong number of parameters (expected " + columns.columns.size() + "; got " + values.length + ")"); } for(int i = 0; i < values.length; i++) { column(columns.columns.get(i), values[i]); } return this; } public RowBuilder delete(Column<?> key) { throw new RuntimeException("not implemented"); //return this; } public TableBuilder up() { MyTableBuilder.this.row = this; return MyTableBuilder.this; } } private Table table; public MyRowBuilder row; public MyTableBuilder(Table table) { this.table = table; } public RowBuilder row(Comparable ... key) { if(row != null) { row.init(key); MyRowBuilder ret = row; row = null; return ret; } MyRowBuilder ret = new MyRowBuilder(); ret.init(key); return ret; } public TableBuilder delete(Comparable ... key) { return this; } public RevisionBuilder up() { return MyRevisionBuilder.this; } } public TableBuilder table(Table table) { return new MyTableBuilder(table); } public void drop(Table table) { } public int apply(PatchTemplate template, Object ... parameters) { if (token == null) { throw new IllegalStateException("builder already committed"); } try { if (parameters.length != template.parameterCount()) { throw new IllegalArgumentException ("wrong number of parameters (expected " + template.parameterCount() + "; got " + parameters.length + ")"); } return adapters.get (template.getClass()).apply(this, template, copy(parameters)); } catch (RuntimeException e) { token = null; throw e; } } public void delete(Object[] path, int pathOffset, int pathLength) { Comparable[] myPath = new Comparable[pathLength]; for (int i = 0; i < pathLength; ++i) { myPath[i] = (Comparable) path[pathOffset + i]; } delete(myPath); } public void delete(Object ... path) { delete(path, 0, path.length); } public void insert(DuplicateKeyResolution duplicateKeyResolution, Object[] path, int pathOffset, int pathLength) { Table table; try { table = (Table) path[pathOffset]; } catch (ClassCastException e) { throw new IllegalArgumentException ("expected table as first path element"); } List<Column> columns = table.primaryKey.columns; if (pathLength == columns.size() + 1) { Comparable[] myPath = new Comparable[columns.size()]; for (int i = 0; i < myPath.length; ++i) { myPath[i] = (Comparable) path[pathOffset + i + 1]; } insert(duplicateKeyResolution, table, null, null, myPath); } else if (pathLength == columns.size() + 3) { Column column; try { column = (Column) path[pathOffset + columns.size() + 1]; } catch (ClassCastException e) { throw new IllegalArgumentException ("expected column as second-to-last path element"); } Object value = path[pathOffset + columns.size() + 2]; if (value != null && ! column.type.isInstance(value)) { throw new ClassCastException (value.getClass() + " cannot be cast to " + column.type); } Comparable[] myPath = new Comparable[columns.size()]; for (int i = 0; i < myPath.length; ++i) { Comparable c = (Comparable) path[pathOffset + i + 1]; if (columns.get(i) == column) { throw new IllegalArgumentException ("cannot use insert to update a primary key column"); } myPath[i] = c; } insert(duplicateKeyResolution, table, column, value, myPath); } else { throw new IllegalArgumentException ("wrong number of parameters for primary key"); } } public void insert(DuplicateKeyResolution duplicateKeyResolution, Object ... path) { insert(duplicateKeyResolution, path, 0, path.length); } public void add(Index index) { if (token == null) { throw new IllegalStateException("builder already committed"); } try { addIndex(index); } catch (RuntimeException e) { token = null; throw e; } } public void remove(Index index) { if (token == null) { throw new IllegalStateException("builder already committed"); } try { removeIndex(index); } catch (RuntimeException e) { token = null; throw e; } } public void add(ForeignKey constraint) { if (token == null) { throw new IllegalStateException("builder already committed"); } try { addForeignKey(constraint); } catch (RuntimeException e) { token = null; throw e; } } public void remove(ForeignKey constraint) { if (token == null) { throw new IllegalStateException("builder already committed"); } try { removeForeignKey(constraint); } catch (RuntimeException e) { token = null; throw e; } } public boolean committed() { return token != null; } public Revision commit() { return commit(ForeignKeyResolvers.Restrict); } public Revision commit(ForeignKeyResolver foreignKeyResolver) { if (token == null) { return result; } updateIndexes(); checkForeignKeys(foreignKeyResolver); token = null; return result; } private static MyRevision getRevision(Object token, MyRevision basis, Node root) { if (token == basis.token) { basis.root = root; return basis; } else { return new MyRevision(token, root); } } }
package com.tactfactory.mda.plateforme; import java.lang.reflect.Field; import com.tactfactory.mda.annotation.Column; import com.tactfactory.mda.annotation.Column.Type; import com.tactfactory.mda.meta.FieldMetadata; import com.tactfactory.mda.utils.ConsoleUtils; /** * SQliteAdapter. */ public abstract class SqliteAdapter { /** Prefix for column name generation. */ private static final String PREFIX = "COL_"; /** Suffix for column name generation. */ private static final String SUFFIX = "_ID"; /** * Generate field's structure for database creation schema. * @param fm The field * @return The field's structure */ public static String generateStructure(final FieldMetadata fm) { final StringBuilder builder = new StringBuilder(); builder.append(' '); builder.append(generateColumnType(fm.getColumnDefinition())); if (fm.isId()) { builder.append(" PRIMARY KEY"); if (fm.getColumnDefinition().equals("integer")) { builder.append(" AUTOINCREMENT"); } } else { // Set Length final Type fieldType = Type.fromName(fm.getType()); if (fieldType != null) { if (fm.getLength() != null && fm.getLength() != fieldType.getLength()) { builder.append('('); builder.append(fm.getLength()); builder.append(')'); } else if (fm.getPrecision() != null && fm.getPrecision() != fieldType.getPrecision()) { builder.append('('); builder.append(fm.getPrecision()); if (fm.getScale() != null && fm.getScale() != fieldType.getScale()) { builder.append(','); builder.append(fm.getScale()); } builder.append(')'); } } // Set Unique if (fm.isUnique() != null && fm.isUnique()) { builder.append(" UNIQUE"); } // Set Nullable if (fm.isNullable() == null || !fm.isNullable()) { builder.append(" NOT NULL"); } } return builder.toString(); } /** * Generate the column type for a given harmony type. * @param fieldType The harmony type of a field. * @return The columnType for SQLite */ public static String generateColumnType(final String fieldType) { String type = fieldType; if (type.equals(Column.Type.STRING.getValue()) || type.equals(Column.Type.TEXT.getValue()) || type.equals(Column.Type.LOGIN.getValue()) || type.equals(Column.Type.PHONE.getValue())) { type = "VARCHAR"; } else if (type.equals(Column.Type.PASSWORD.getValue())) { type = "VARCHAR"; } else if (type.equals(Column.Type.DATETIME.getValue())) { type = "VARCHAR"; } return type; } /** * Generate a column name. * @param fieldName The original field's name * @return the generated column name */ public static String generateColumnName(final String fieldName) { return PREFIX + fieldName.toUpperCase(); } /** * Generate a relation column name. * @param fieldName The original field's name * @return the generated column name */ public static String generateRelationColumnName(final String fieldName) { return PREFIX + fieldName.toUpperCase() + SUFFIX; } /** * Generate a column definition. * @param type The original field's type * @return the generated column definition */ public static String generateColumnDefinition(final String type) { String ret = type; if (type.equals("int")) { ret = "integer"; } return ret; } /** * SQLite Reserved keywords. */ public static enum Keywords { // CHECKSTYLE:OFF ABORT, ACTION, ADD, AFTER, ALL, ALTER, ANALYZE, AND, AS, ASC, ATTACH, AUTOINCREMENT, BEFORE, BEGIN, BETWEEN, BY, CASCADE, CASE, CAST, CHECK, COLLATE, COLUMN, COMMIT, CONFLICT, CONSTRAINT, CREATE, CROSS, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, DATABASE, DEFAULT, DEFERRABLE, DEFERRED, DELETE, DESC, DETACH, DISTINCT, DROP, EACH, ELSE, END, ESCAPE, EXCEPT, EXCLUSIVE, EXISTS, EXPLAIN, FAIL, FOR, FOREIGN, FROM, FULL, GLOB, GROUP, HAVING, IF, IGNORE, IMMEDIATE, IN, INDEX, INDEXED, INITIALLY, INNER, INSERT, INSTEAD, INTERSECT, INTO, IS, ISNULL, JOIN, KEY, LEFT, LIKE, LIMIT, MATCH, NATURAL, NO, NOT, NOTNULL, NULL, OF, OFFSET, ON, OR, ORDER, OUTER, PLAN, PRAGMA, PRIMARY, QUERY, RAISE, REFERENCES, REGEXP, REINDEX, RELEASE, RENAME, REPLACE, RESTRICT, RIGHT, ROLLBACK, ROW, SAVEPOINT, SELECT, SET, TABLE, TEMP, TEMPORARY, THEN, TO, TRANSACTION, TRIGGER, UNION, UNIQUE, UPDATE, USING, VACUUM, VALUES, VIEW, VIRTUAL, WHEN, WHERE; // CHECKSTYLE:ON /** * Tests if the given String is a reserverd SQLite keyword. * @param name The string * @return True if it is */ public static boolean exists(final String name) { boolean exists = false; try { final Field field = Keywords.class.getField(name.toUpperCase()); if (field.isEnumConstant()) { ConsoleUtils.displayWarning( name + " is a reserved SQLite keyword." + " You may have problems with" + " your database schema."); exists = true; } else { exists = false; } } catch (final NoSuchFieldException e) { exists = false; } return exists; } } }
package com.tellmas.android.permissions; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.text.format.Time; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.tellmas.android.permissions.AppListFragment.AppListFragmentListener; public class MainActivity extends Activity implements AppListFragmentListener { private ProgressBar progressBar = null; private FragmentManager fragmentManager; private final Fragment fragments[] = new Fragment[2]; private int currentlyDisplayedFragmentIndex; private String[] slideoutMenuItems; private DrawerLayout drawerLayout; private ListView slideOutList; private ActionBarDrawerToggle drawerToggle; /** * Sets the: * - main layout * - "hourglass" * - navigation menu * - initial content Fragment * * @param savedInstanceState data to start with * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onCreate()"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.fragmentManager = this.getFragmentManager(); this.progressBar = (ProgressBar)findViewById(R.id.progress); this.progressBar.setProgress(0); this.progressBar.setVisibility(View.VISIBLE); this.slideoutMenuItems = getResources().getStringArray(R.array.slideout_menu_items); this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); this.slideOutList = (ListView) findViewById(R.id.slideout_drawer); // Set the adapter for the list view (of the slide-out menu) this.slideOutList.setAdapter( new ArrayAdapter<String>( this, R.layout.drawer_item, this.slideoutMenuItems ) ); // Set the list's click listener this.slideOutList.setOnItemClickListener(new DrawerItemClickListener()); this.getActionBar().setDisplayHomeAsUpEnabled(true); this.getActionBar().setHomeButtonEnabled(true); final CharSequence activityTitle = this.getTitle(); // Tie together the the proper interactions between the sliding drawer and the ActionBar app icon this.drawerToggle = new ActionBarDrawerToggle( this, this.drawerLayout, R.drawable.ic_navigation_drawer, R.string.drawer_open, R.string.drawer_close ) { // Called when a drawer has settled in a completely closed state. @Override public void onDrawerClosed(View view) { getActionBar().setTitle(activityTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } // Called when a drawer has settled in a completely open state. @Override public void onDrawerOpened(View drawerView) { getActionBar().setTitle(activityTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; // set the just defined ActionBarDrawerToggle as the drawer listener this.drawerLayout.setDrawerListener(drawerToggle); // if a Fragment is indicated to be restored... if (savedInstanceState != null) { this.currentlyDisplayedFragmentIndex = savedInstanceState.getInt(GlobalDefines.BUNDLE_KEY_FRAGMENT_INDEX); this.fragments[this.currentlyDisplayedFragmentIndex] = this.fragmentManager.findFragmentByTag(savedInstanceState.getString(GlobalDefines.BUNDLE_KEY_FRAGMENT_TAG)); FragmentTransaction fragmentTransaction = this.fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content, this.fragments[this.currentlyDisplayedFragmentIndex], new Time().toString()); fragmentTransaction.commit(); Log.v(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onCreate(): saved Fragment index: " + Integer.toString(savedInstanceState.getInt(GlobalDefines.BUNDLE_KEY_FRAGMENT_INDEX))); Log.v(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onCreate(): saved Fragment tag: " + savedInstanceState.getString(GlobalDefines.BUNDLE_KEY_FRAGMENT_TAG)); Log.v(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onCreate(): Fragment has retain instance set: " + Boolean.toString(this.fragments[this.currentlyDisplayedFragmentIndex].getRetainInstance())); // ...else create the default starting Fragment... } else { this.fragments[GlobalDefines.STARTING_FRAGMENT_INDEX] = this.instantiateFragment(GlobalDefines.STARTING_FRAGMENT_INDEX); this.currentlyDisplayedFragmentIndex = GlobalDefines.STARTING_FRAGMENT_INDEX; FragmentTransaction fragmentTransaction = this.fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.content, this.fragments[this.currentlyDisplayedFragmentIndex], new Time().toString()); fragmentTransaction.commit(); } } /** * Tells the current Fragment to turn off retaining its state since it only needs that if this Activity was recreated. * * @param savedInstanceState data used to restore the previous state * @see android.app.Activity#onRestoreInstanceState(android.os.Bundle) */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onRestoreInstanceState()"); super.onRestoreInstanceState(savedInstanceState); this.fragments[currentlyDisplayedFragmentIndex].setRetainInstance(false); } /** * Syncs the toggle state of the ActionBarDrawerToggle * * @param savedInstanceState data used to restore the previous state * @see android.app.Activity#onPostCreate(android.os.Bundle) */ @Override protected void onPostCreate(Bundle savedInstanceState) { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onPostCreate()"); super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. this.drawerToggle.syncState(); } /** * (see @return) * * @param the menu item that was selected * @return true if the ActionBarDrawerToggle handled the app icon touch event, false otherwise * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onOptionsItemSelected()"); // if ActionBarDrawerToggle returns true... if (this.drawerToggle.onOptionsItemSelected(item)) { // ...then it has handled the app icon touch event. return true; } return super.onOptionsItemSelected(item); } /** * Saves the current Fragment's tag and index, and tells the Fragment to retain its instance state in case currently undergoing a configuration change. * * @param outState the Bundle in which to store the data to restore the state * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState (Bundle outState) { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onSaveInstanceState()"); super.onSaveInstanceState(outState); // Save the tag and index of the current Fragment in case we are doing a configuration change. // (and want to restore the Fragment easily) Fragment fragment = this.fragments[currentlyDisplayedFragmentIndex]; outState.putString(GlobalDefines.BUNDLE_KEY_FRAGMENT_TAG, fragment.getTag()); outState.putInt(GlobalDefines.BUNDLE_KEY_FRAGMENT_INDEX, this.currentlyDisplayedFragmentIndex); fragment.setRetainInstance(true); } @Override protected void onStart() { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onStart()"); super.onStart(); } @Override protected void onResume() { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onResume()"); super.onResume(); } @Override public void onWindowFocusChanged(boolean hasFocus) { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onWindowFocusChanged(): has focus: " + Boolean.toString(hasFocus)); super.onWindowFocusChanged(hasFocus); } @Override protected void onPause() { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onPause()"); super.onPause(); } @Override protected void onStop() { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onStop()"); super.onStop(); } @Override protected void onRestart() { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onRestart()"); super.onRestart(); } @Override protected void onDestroy() { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": onDestroy()"); super.onDestroy(); } /** * Updates the ProgressBar. * Also sets the max value for the ProgressBar if the @param 'soFar' is 1 or less * (the idea being when this method is first called) * * @param soFar how far along the app list we are * @param total total number of apps in the list */ @Override public void updateProgress(int soFar, int total) { if (soFar <= 1) { this.progressBar.setMax(total); } this.progressBar.setProgress(soFar); } /** * Remove the "hourglass"/Progressbar and set the number of found apps. * Called when the active Fragment has finished loading its data. * * @param numOfApps the number of apps to be displayed * @param itemType list type as defined in GlobalDefines */ @Override public void setFinished(int numOfItems, int itemType) { Log.i(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": setFinished()"); this.progressBar.setVisibility(View.GONE); // TODO: convert this to be more automatic TextView numOfItemsLabel = (TextView) this.findViewById(R.id.number_of_apps_label); if (itemType == GlobalDefines.LIST_TYPE_APPS) { numOfItemsLabel.setText(getResources().getString(R.string.number_of_apps)); } else if (itemType == GlobalDefines.LIST_TYPE_PERMS) { numOfItemsLabel.setText(getResources().getString(R.string.number_of_perms)); } numOfItemsLabel.setVisibility(View.VISIBLE); TextView numOfItemsInList = (TextView) this.findViewById(R.id.number_of_items_num); numOfItemsInList.setText(Integer.toString(numOfItems)); numOfItemsInList.setVisibility(View.VISIBLE); } /* * Creates a new instance of the requested Class. * * @param fragmentClassNamesIndex index of the desired Class name in GlobalDefines.FRAGMENT_CLASS_NAMES * @return an instance of the requested Class (a sub-class of Fragment) * (non-Javadoc) */ private Fragment instantiateFragment(int fragmentClassNamesIndex) { String fragmentClassName = null; try { fragmentClassName = GlobalDefines.FRAGMENT_CLASS_NAMES[fragmentClassNamesIndex]; } catch (ArrayIndexOutOfBoundsException aioobe) { Log.e(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": instantiateFragment(): passed in index not valid: " + Integer.toString(fragmentClassNamesIndex) ); // TODO pop up an error message to the user instead of exiting? // (shouldn't reach this point in production though) System.exit(GlobalDefines.EXIT_STATUS_ERROR); } Object theInstance = null; if (fragmentClassName.equals("AppListFragment")) { theInstance = new AppListFragment(); } else if (fragmentClassName.equals("PermListFragment")) { theInstance = new PermListFragment(); } // Reflection code which doesn't quite work yet. To be used in the future. /* try { Class<?> classObj = Class.forName(fragmentClassName); Constructor<?> constructor = classObj.getConstructor(); theInstance = constructor.newInstance(); } catch (Exception e) { Log.e(GlobalDefines.LOG_TAG, this.getClass().getSimpleName() + ": instantiateFragment(): Class not recognized: " + fragmentClassName + " - " + e.getClass().getSimpleName() ); // TODO pop up an error message to the user instead of exiting? System.exit(GlobalDefines.EXIT_STATUS_ERROR); } */ return (Fragment) theInstance; } /* * Replaces the Fragment in the content View. Handles instantiating a new Fragment object if necessary. * (non-Javadoc) */ private void swapContent(int position, long id) { boolean keepLastTransaction = true; boolean replaceFragment = true; Fragment removeMe = null; Fragment currentlyDisplayedFragment = this.fragmentManager.findFragmentById(R.id.content); this.currentlyDisplayedFragmentIndex = position; this.progressBar.setProgress(0); this.progressBar.setVisibility(View.VISIBLE); TextView numOfItemsNum = (TextView) findViewById(R.id.number_of_items_num); numOfItemsNum.setVisibility(View.INVISIBLE); // if the user chose a Fragment which hasn't been displayed yet... if (this.fragments[position] == null) { TextView numOfItemsText = (TextView) findViewById(R.id.number_of_apps_label); numOfItemsText.setVisibility(View.INVISIBLE); // ...create a new instance so it can be displayed. this.fragments[position] = this.instantiateFragment(position); // else if user selected the same menu item as what's displayed... } else if (currentlyDisplayedFragment == this.fragments[position]) { // TODO need to use reflection here 'cause if there's more than a few classes... // TODO or maybe define an interface with getTheDataAndDisplayIt() required. // Update the Fragment's data/display and keep it there. if (currentlyDisplayedFragment instanceof AppListFragment) { ((AppListFragment)currentlyDisplayedFragment).getTheDataAndDisplayIt(); } else if (currentlyDisplayedFragment instanceof PermListFragment) { ((PermListFragment)currentlyDisplayedFragment).getTheDataAndDisplayIt(); } replaceFragment = false; // else if user selected something different (AND it's been displayed before)... } else if (currentlyDisplayedFragment != this.fragments[position]) { // ...keep a reference to the old one so it can be deleted. removeMe = this.fragments[position]; // Create a new instance to be displayed. this.fragments[position] = this.instantiateFragment(position); TextView numOfItemsText = (TextView) findViewById(R.id.number_of_apps_label); numOfItemsText.setVisibility(View.INVISIBLE); } // if need to do a transaction... if (replaceFragment) { FragmentTransaction transaction = this.fragmentManager.beginTransaction(); if (removeMe != null) { transaction.remove(removeMe); } transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); transaction.replace(R.id.content, this.fragments[position], new Time().toString()); if (keepLastTransaction && transaction.isAddToBackStackAllowed()) { transaction.addToBackStack(null); } transaction.commit(); } // hide the slide-out menu this.drawerLayout.closeDrawer(this.slideOutList); } /* * Click listener for each item in the Navigation drawer * @see android.widget.AdapterView.OnItemClickListener * (non-Javadoc) */ private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { swapContent(position, id); } } }