answer
stringlengths 17
10.2M
|
|---|
package mod._typemgr.uno;
import com.sun.star.beans.XPropertySet;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.XInterface;
import java.io.PrintWriter;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
public class TypeDescriptionManager extends TestCase {
protected void initialize ( TestParameters Param, PrintWriter log) {
}
/**
* creating a Testenvironment for the interfaces to be tested
*/
protected TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) {
XInterface oObj = null;
Object oInterface = null;
try {
XMultiServiceFactory xMSF = (XMultiServiceFactory)Param.getMSF();
XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(
XPropertySet.class, xMSF);
// get context
XComponentContext xContext = (XComponentContext)
UnoRuntime.queryInterface(XComponentContext.class,
xProp.getPropertyValue("DefaultContext"));
// get the type description manager from context
oInterface = xContext.getValueByName("/singletons/" +
"com.sun.star.reflection.theTypeDescriptionManager");
}
catch( Exception e ) {
log.println("Introspection Service not available" );
}
oObj = (XInterface) oInterface;
log.println( " creating a new environment for Introspection object" );
TestEnvironment tEnv = new TestEnvironment( oObj );
// Object relation for XHierarchicalNameAccess ifc
// Name of the existing object
tEnv.addObjRelation("ElementName", "com.sun.star.container.XNameAccess") ;
tEnv.addObjRelation("SearchString", "com.sun.star.loader");
return tEnv;
} // finish method getTestEnvironment
} // finish class TypeDescriptionManager
|
package me.echeung.moemoekyun.util;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v7.graphics.Palette;
import android.util.DisplayMetrics;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import java.util.ArrayList;
import java.util.List;
import me.echeung.moemoekyun.App;
import me.echeung.moemoekyun.R;
import me.echeung.moemoekyun.client.model.Song;
public final class AlbumArtUtil {
private static final int MAX_SCREEN_SIZE = getMaxScreenLength();
private static List<Callback> listeners = new ArrayList<>();
private static Bitmap defaultAlbumArt;
private static boolean isDefaultAlbumArt = true;
private static Bitmap currentAlbumArt;
private static int currentAccentColor;
private static int currentBodyColor;
public static void registerListener(Callback callback) {
listeners.add(callback);
}
public static void unregisterListener(Callback callback) {
if (listeners.contains(callback)) {
listeners.remove(callback);
}
}
public static Bitmap getCurrentAlbumArt() {
return currentAlbumArt;
}
public static Bitmap getCurrentAlbumArt(int maxSize) {
if (currentAlbumArt == null) {
return null;
}
return Bitmap.createScaledBitmap(currentAlbumArt, maxSize, maxSize, false);
}
public static boolean isDefaultAlbumArt() {
return isDefaultAlbumArt;
}
public static void updateAlbumArt(Context context, Song song) {
if (App.getPreferenceUtil().shouldDownloadImage(context) && song != null) {
String albumArtUrl = song.getAlbumArtUrl();
// Get event image if available when there's no regular album art
if (albumArtUrl == null && App.getRadioViewModel().getEvent() != null) {
String eventImageUrl = App.getRadioViewModel().getEvent().getImage();
if (eventImageUrl != null) {
downloadAlbumArtBitmap(context, eventImageUrl);
return;
}
}
if (albumArtUrl != null) {
downloadAlbumArtBitmap(context, albumArtUrl);
return;
}
}
updateListeners(getDefaultAlbumArt(context));
}
public static int getCurrentAccentColor() {
return currentAccentColor;
}
public static int getCurrentBodyColor() {
return currentBodyColor;
}
private static void updateListeners(Bitmap bitmap) {
currentAlbumArt = bitmap;
for (Callback listener : listeners) {
listener.onAlbumArtReady(bitmap);
}
}
private static void downloadAlbumArtBitmap(Context context, String url) {
new Handler(Looper.getMainLooper()).post(() -> {
if (context == null) {
return;
}
Glide.with(context.getApplicationContext())
.asBitmap()
.load(url)
.apply(new RequestOptions().centerCrop())
.into(new SimpleTarget<Bitmap>(MAX_SCREEN_SIZE, MAX_SCREEN_SIZE) {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
isDefaultAlbumArt = false;
Palette.Swatch swatch = Palette.from(resource).generate().getVibrantSwatch();
if (swatch == null) {
swatch = Palette.from(resource).generate().getMutedSwatch();
}
if (swatch != null) {
currentAccentColor = swatch.getRgb();
currentBodyColor = swatch.getBodyTextColor();
}
updateListeners(resource);
}
});
});
}
private static Bitmap getDefaultAlbumArt(Context context) {
if (defaultAlbumArt == null) {
defaultAlbumArt = BitmapFactory.decodeResource(context.getResources(), R.drawable.blank);
}
isDefaultAlbumArt = true;
currentAccentColor = Color.BLACK;
currentBodyColor = Color.WHITE;
return defaultAlbumArt;
}
private static int getMaxScreenLength() {
DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
return Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels);
}
public interface Callback {
void onAlbumArtReady(Bitmap bitmap);
}
}
|
package org.gdg.frisbee.android.gde;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import org.gdg.frisbee.android.Const;
import org.gdg.frisbee.android.R;
import org.gdg.frisbee.android.api.Callback;
import org.gdg.frisbee.android.api.model.Gde;
import org.gdg.frisbee.android.api.model.GdeList;
import org.gdg.frisbee.android.app.App;
import org.gdg.frisbee.android.cache.ModelCache;
import org.gdg.frisbee.android.common.GdgNavDrawerActivity;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import butterknife.BindView;
public class GdeActivity extends GdgNavDrawerActivity implements ViewPager.OnPageChangeListener {
@BindView(R.id.pager)
ViewPager mViewPager;
@BindView(R.id.tabs)
TabLayout mTabLayout;
private Handler mHandler = new Handler();
private GdeCategoryPagerAdapter mViewPagerAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gde);
Toolbar toolbar = getActionBarToolbar();
toolbar.setTitle(R.string.gde);
App.getInstance().getModelCache().getAsync(Const.CACHE_KEY_GDE_LIST, new ModelCache.CacheListener() {
@Override
public void onGet(Object item) {
GdeList directory = (GdeList) item;
setupGdeViewPager(directory);
}
@Override
public void onNotFound(String key) {
fetchGdeDirectory();
}
});
}
private void fetchGdeDirectory() {
App.getInstance().getGdeDirectory().getDirectory().enqueue(new Callback<GdeList>() {
@Override
public void success(final GdeList directory) {
App.getInstance().getModelCache().putAsync(Const.CACHE_KEY_GDE_LIST,
directory,
DateTime.now().plusDays(4),
new ModelCache.CachePutListener() {
@Override
public void onPutIntoCache() {
setupGdeViewPager(directory);
}
});
}
@Override
public void failure(Throwable error) {
showError(R.string.fetch_gde_failed);
}
@Override
public void networkFailure(Throwable error) {
showError(R.string.offline_alert);
}
});
}
private void setupGdeViewPager(GdeList directory) {
SortedMap<String, GdeList> gdeMap = new TreeMap<>();
gdeMap.putAll(extractCategoriesFromGdeList(directory));
List<GdeCategory> gdeCategoryList = convertCategoryMapToList(gdeMap);
mViewPagerAdapter = new GdeCategoryPagerAdapter(
getSupportFragmentManager(),
getString(R.string.about),
gdeCategoryList
);
mViewPager.setAdapter(mViewPagerAdapter);
mViewPager.addOnPageChangeListener(this);
mTabLayout.setupWithViewPager(mViewPager);
getAchievementActionHandler().handleLookingForExperts();
}
private HashMap<String, GdeList> extractCategoriesFromGdeList(GdeList directory) {
HashMap<String, GdeList> gdeMap = new HashMap<>();
for (Gde gde : directory) {
if (gde.getProduct() == null) {
continue;
}
for (String p : gde.getProduct()) {
String product = p.trim();
if (!gdeMap.containsKey(product)) {
gdeMap.put(product, new GdeList());
}
gdeMap.get(product).add(gde);
}
}
return gdeMap;
}
private List<GdeCategory> convertCategoryMapToList(SortedMap<String, GdeList> gdeMap) {
List<GdeCategory> gdeCategoryList = new ArrayList<>();
for (String category : gdeMap.keySet()) {
GdeList gdeList = gdeMap.get(category);
gdeCategoryList.add(new GdeCategory(category, gdeList));
}
return gdeCategoryList;
}
@Override
protected String getTrackedViewName() {
return null;
}
@Override
public void onPageScrolled(int i, float v, int i2) {
}
@Override
public void onPageSelected(int position) {
trackView("GDE/" + mViewPagerAdapter.getPageTitle(position));
}
@Override
public void onPageScrollStateChanged(int i) {
}
}
|
package ve.com.abicelis.chefbuddy.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.pdf.PdfDocument;
import android.os.Build;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import ve.com.abicelis.chefbuddy.app.ChefBuddyApplication;
import ve.com.abicelis.chefbuddy.app.Constants;
public class FileUtil {
/**
* Creates the specified <code>toFile</code> as a byte for byte copy of the
* <code>fromFile</code>. If <code>toFile</code> already exists, then it
* will be replaced with a copy of <code>fromFile</code>. The name and path
* of <code>toFile</code> will be that of <code>toFile</code>.<br/>
* <br/>
* <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
* this function.</i>
*
* @param fromFile
* - FileInputStream for the file to copy from.
* @param toFile
* - FileInputStream for the file to copy to.
*/
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
public static File getImageFilesDir() {
return new File(ChefBuddyApplication.getContext().getExternalFilesDir(null), Constants.IMAGE_FILES_DIR);
}
public static File getExternalStorageDir() {
return new File(Environment.getExternalStorageDirectory().getPath());
}
public static void createDirIfNotExists(File directory) throws IOException, SecurityException {
if (directory.mkdirs()){
File nomedia = new File(directory, ".nomedia");
nomedia.createNewFile();
}
}
/**
* Creates an empty file at the specified directory, with the given name if it doesn't already exist
*
*/
public static File createNewFileIfNotExistsInDir(File directory, String fileName) throws IOException {
File file = new File(directory, fileName);
file.createNewFile();
return file;
}
public static void deleteImageAttachment(Activity activity, String filename) {
if(filename != null && !filename.isEmpty()) { //Delete file
File file = new File(FileUtil.getImageFilesDir(), filename);
file.delete();
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
public static File savePdfDocumentToSD(PdfDocument pdfDocument, String filename) throws IOException {
File filePath = new File(getExternalStorageDir(), filename.replaceAll("[^A-Za-z0-9\\s]", "") + Constants.CHEFF_BUDDY + Constants.PDF_FILE_EXTENSION);
pdfDocument.writeTo(new FileOutputStream(filePath));
return filePath;
}
// public static File createTempImageFileInDir(File directory, String fileExtension) throws IOException, SecurityException {
// if(fileExtension.toCharArray()[0] != '.')
// fileExtension = "." + fileExtension;
// //String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// String fileName = "TEMP_" + UUID.randomUUID().toString() + "_";
// File file = File.createTempFile(fileName, fileExtension, directory);
// return file;
}
|
package host.exp.exponent;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Debug;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.util.LruCache;
import com.amplitude.api.Amplitude;
import expolib_v1.okhttp3.CacheControl;
import host.exp.exponent.analytics.Analytics;
import host.exp.exponent.analytics.EXL;
import host.exp.exponent.exceptions.ManifestException;
import host.exp.exponent.generated.ExponentBuildConstants;
import host.exp.exponent.kernel.Crypto;
import host.exp.exponent.kernel.ExponentUrls;
import host.exp.exponent.kernel.KernelProvider;
import host.exp.exponent.network.ExponentHttpClient;
import host.exp.exponent.network.ExponentNetwork;
import host.exp.exponent.storage.ExponentDB;
import host.exp.exponent.storage.ExponentSharedPreferences;
import host.exp.exponent.utils.ColorParser;
import host.exp.expoview.Exponent;
import host.exp.expoview.R;
import expolib_v1.okhttp3.Call;
import expolib_v1.okhttp3.Callback;
import expolib_v1.okhttp3.Headers;
import expolib_v1.okhttp3.Request;
import expolib_v1.okhttp3.Response;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Singleton
public class ExponentManifest {
public interface ManifestListener {
void onCompleted(JSONObject manifest);
void onError(Exception e);
void onError(String e);
}
public interface BitmapListener {
void onLoadBitmap(Bitmap bitmap);
}
private static final String TAG = ExponentManifest.class.getSimpleName();
public static final String MANIFEST_STRING_KEY = "manifestString";
public static final String MANIFEST_SIGNATURE_KEY = "signature";
public static final String MANIFEST_ID_KEY = "id";
public static final String MANIFEST_NAME_KEY = "name";
public static final String MANIFEST_APP_KEY_KEY = "appKey";
public static final String MANIFEST_SDK_VERSION_KEY = "sdkVersion";
public static final String MANIFEST_IS_VERIFIED_KEY = "isVerified";
public static final String MANIFEST_ICON_URL_KEY = "iconUrl";
public static final String MANIFEST_PRIMARY_COLOR_KEY = "primaryColor";
public static final String MANIFEST_ORIENTATION_KEY = "orientation";
public static final String MANIFEST_DEVELOPER_KEY = "developer";
public static final String MANIFEST_PACKAGER_OPTS_KEY = "packagerOpts";
public static final String MANIFEST_PACKAGER_OPTS_DEV_KEY = "dev";
public static final String MANIFEST_BUNDLE_URL_KEY = "bundleUrl";
public static final String MANIFEST_SHOW_EXPONENT_NOTIFICATION_KEY = "androidShowExponentNotificationInShellApp";
public static final String MANIFEST_REVISION_ID_KEY = "revisionId";
public static final String MANIFEST_PUBLISHED_TIME_KEY = "publishedTime";
public static final String MANIFEST_LOADED_FROM_CACHE_KEY = "loadedFromCache";
// Statusbar
public static final String MANIFEST_STATUS_BAR_KEY = "androidStatusBar";
public static final String MANIFEST_STATUS_BAR_APPEARANCE = "barStyle";
public static final String MANIFEST_STATUS_BAR_BACKGROUND_COLOR = "backgroundColor";
@Deprecated
public static final String MANIFEST_STATUS_BAR_COLOR = "androidStatusBarColor";
// Notification
public static final String MANIFEST_NOTIFICATION_INFO_KEY = "notification";
public static final String MANIFEST_NOTIFICATION_ICON_URL_KEY = "iconUrl";
public static final String MANIFEST_NOTIFICATION_COLOR_KEY = "color";
public static final String MANIFEST_NOTIFICATION_ANDROID_MODE = "androidMode";
public static final String MANIFEST_NOTIFICATION_ANDROID_COLLAPSED_TITLE = "androidCollapsedTitle";
// Debugging
public static final String MANIFEST_DEBUGGER_HOST_KEY = "debuggerHost";
public static final String MANIFEST_MAIN_MODULE_NAME_KEY = "mainModuleName";
// Loading
public static final String MANIFEST_LOADING_INFO_KEY = "loading";
public static final String MANIFEST_LOADING_ICON_URL = "iconUrl";
public static final String MANIFEST_LOADING_EXPONENT_ICON_COLOR = "exponentIconColor";
public static final String MANIFEST_LOADING_EXPONENT_ICON_GRAYSCALE = "exponentIconGrayscale";
public static final String MANIFEST_LOADING_BACKGROUND_IMAGE_URL = "backgroundImageUrl";
public static final String MANIFEST_LOADING_BACKGROUND_COLOR = "backgroundColor";
// Splash
public static final String MANIFEST_SPLASH_INFO_KEY = "splash";
public static final String MANIFEST_SPLASH_IMAGE_URL = "imageUrl";
public static final String MANIFEST_SPLASH_RESIZE_MODE = "resizeMode";
public static final String MANIFEST_SPLASH_BACKGROUND_COLOR = "backgroundColor";
// Updates
public static final String MANIFEST_UPDATES_INFO_KEY = "updates";
public static final String MANIFEST_UPDATES_TIMEOUT_KEY = "fallbackToCacheTimeout";
public static final String MANIFEST_UPDATES_CHECK_AUTOMATICALLY_KEY = "checkAutomatically";
public static final String MANIFEST_UPDATES_CHECK_AUTOMATICALLY_LAUNCH = "launch";
public static final String MANIFEST_UPDATES_CHECK_AUTOMATICALLY_NEVER = "never";
private static final int MAX_BITMAP_SIZE = 192;
private static final String REDIRECT_SNIPPET = "exp.host/--/to-exp/";
private static final String ANONYMOUS_EXPERIENCE_PREFIX = "@anonymous/";
private static final String EMBEDDED_KERNEL_MANIFEST_ASSET = "kernel-manifest.json";
private static final String EXPONENT_SERVER_HEADER = "Exponent-Server";
private static boolean hasShownKernelManifestLog = false;
Context mContext;
ExponentNetwork mExponentNetwork;
Crypto mCrypto;
private LruCache<String, Bitmap> mMemoryCache;
ExponentSharedPreferences mExponentSharedPreferences;
@Inject
public ExponentManifest(Context context, ExponentNetwork exponentNetwork, Crypto crypto, ExponentSharedPreferences exponentSharedPreferences) {
mContext = context;
mExponentNetwork = exponentNetwork;
mCrypto = crypto;
mExponentSharedPreferences = exponentSharedPreferences;
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/16th of the available memory for this memory cache.
final int cacheSize = maxMemory / 16;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024;
}
};
}
public void fetchManifest(final String manifestUrl, final ManifestListener listener) {
fetchManifest(manifestUrl, listener, false);
}
public void fetchManifest(final String manifestUrl, final ManifestListener listener, final boolean forceNetwork) {
Analytics.markEvent(Analytics.TimedEvent.STARTED_FETCHING_MANIFEST);
String realManifestUrl = manifestUrl;
if (manifestUrl.contains(REDIRECT_SNIPPET)) {
// Android is crazy and catches this url with this intent filter:
// <data
// android:host="*.exp.direct"
// android:pathPattern=".*"
// android:scheme="http"/>
// <data
// android:host="*.exp.direct"
// android:pathPattern=".*"
// android:scheme="https"/>
// so we have to add some special logic to handle that. This is than handling arbitrary HTTP 301s and 302
// because we need to add /index.exp to the paths.
realManifestUrl = Uri.decode(realManifestUrl.substring(realManifestUrl.indexOf(REDIRECT_SNIPPET) + REDIRECT_SNIPPET.length()));
}
String httpManifestUrl = ExponentUrls.toHttp(realManifestUrl);
// Append index.exp to path
Uri uri = Uri.parse(httpManifestUrl);
String newPath = uri.getPath();
if (newPath == null) {
newPath = "";
}
if (!newPath.endsWith("/")) {
newPath += "/";
}
newPath += "index.exp";
httpManifestUrl = uri.buildUpon().encodedPath(newPath).build().toString();
// Fetch manifest
Request.Builder requestBuilder = ExponentUrls.addExponentHeadersToUrl(httpManifestUrl, manifestUrl.equals(Constants.INITIAL_URL), false);
requestBuilder.header("Exponent-Accept-Signature", "true");
requestBuilder.header("Expo-JSON-Error", "true");
Analytics.markEvent(Analytics.TimedEvent.STARTED_MANIFEST_NETWORK_REQUEST);
if (Constants.DEBUG_MANIFEST_METHOD_TRACING) {
Debug.startMethodTracing("manifest");
}
boolean isDevelopment = false;
if (uri.getHost().equals("localhost") || uri.getHost().endsWith(".exp.direct")) {
isDevelopment = true;
}
if (isDevelopment || forceNetwork) {
requestBuilder.cacheControl(CacheControl.FORCE_NETWORK);
// If we're sure this is a development url, don't cache. Note that LAN development urls
// might still be cached
mExponentNetwork.getClient().callSafe(requestBuilder.build(), new ExponentHttpClient.SafeCallback() {
private void handleResponse(Response response, boolean isCached) {
if (!response.isSuccessful()) {
ManifestException exception;
try {
final JSONObject errorJSON = new JSONObject(response.body().string());
exception = new ManifestException(null, manifestUrl, errorJSON);
} catch (JSONException | IOException e) {
exception = new ManifestException(null, manifestUrl);
}
listener.onError(exception);
return;
}
try {
String manifestString = response.body().string();
fetchManifestStep2(manifestUrl, manifestString, response.headers(), listener, false, isCached);
} catch (JSONException e) {
listener.onError(e);
} catch (IOException e) {
listener.onError(e);
}
}
@Override
public void onFailure(Call call, IOException e) {
listener.onError(new ManifestException(e, manifestUrl));
}
@Override
public void onResponse(Call call, Response response) {
// OkHttp sometimes decides to use the cache anyway here
boolean isCached = false;
if (response.networkResponse() == null) {
isCached = true;
}
handleResponse(response, isCached);
}
@Override
public void onCachedResponse(Call call, Response response, boolean isEmbedded) {
// this is only called if network is unavailable for some reason
handleResponse(response, true);
}
});
} else {
final Request request = requestBuilder.build();
final String finalUri = request.url().toString();
mExponentNetwork.getClient().callDefaultCache(request, new ExponentHttpClient.SafeCallback() {
private void handleResponse(ManifestListener listener, Response response, boolean isEmbedded, boolean isCached) {
if (!response.isSuccessful()) {
listener.onError(new ManifestException(null, manifestUrl));
return;
}
try {
String manifestString = response.body().string();
fetchManifestStep2(manifestUrl, manifestString, response.headers(), listener, isEmbedded, isCached);
} catch (JSONException e) {
listener.onError(e);
} catch (IOException e) {
listener.onError(e);
}
}
@Override
public void onFailure(Call call, IOException e) {
listener.onError(new ManifestException(e, manifestUrl));
}
@Override
public void onResponse(Call call, Response response) {
// OkHttp sometimes decides to use the cache anyway here
boolean isCached = false;
if (response.networkResponse() == null) {
isCached = true;
}
handleResponse(listener, response, false, isCached);
}
@Override
public void onCachedResponse(Call call, Response response, final boolean isEmbedded) {
EXL.d(TAG, "Using cached or embedded response.");
ManifestListener newListener = listener;
final String embeddedResponse = mExponentNetwork.getClient().getHardCodedResponse(finalUri);
if (embeddedResponse != null) {
// use newer of two responses
newListener = new ManifestListener() {
@Override
public void onCompleted(JSONObject manifest) {
if (isEmbedded) {
// When offline it is possible that the embedded manifest is returned but we have
// a more recent one available in shared preferences. Make sure to use the most
// recent one to avoid regressing manifest versions.
try {
ExponentSharedPreferences.ManifestAndBundleUrl manifestAndBundleUrl = mExponentSharedPreferences.getManifest(manifestUrl);
String cachedManifestTimestamp = manifestAndBundleUrl.manifest.getString(MANIFEST_PUBLISHED_TIME_KEY);
String embeddedManifestTimestamp = manifest.getString(MANIFEST_PUBLISHED_TIME_KEY);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date cachedManifestDate = formatter.parse(cachedManifestTimestamp);
Date embeddedManifestDate = formatter.parse(embeddedManifestTimestamp);
if (embeddedManifestDate.before(cachedManifestDate)) {
listener.onCompleted(manifestAndBundleUrl.manifest);
} else {
listener.onCompleted(manifest);
}
} catch (Throwable ex) {
listener.onCompleted(manifest);
}
} else {
try {
JSONObject embeddedManifest = new JSONObject(embeddedResponse);
embeddedManifest.put("loadedFromCache", true);
String cachedManifestTimestamp = manifest.getString(MANIFEST_PUBLISHED_TIME_KEY);
String embeddedManifestTimestamp = embeddedManifest.getString(MANIFEST_PUBLISHED_TIME_KEY);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date cachedManifestDate = formatter.parse(cachedManifestTimestamp);
Date embeddedManifestDate = formatter.parse(embeddedManifestTimestamp);
if (embeddedManifestDate.after(cachedManifestDate)) {
fetchManifestStep3(manifestUrl, embeddedManifest, true, listener);
} else {
listener.onCompleted(manifest);
}
} catch (Throwable e) {
listener.onCompleted(manifest);
}
}
}
@Override
public void onError(Exception e) {
listener.onError(e);
}
@Override
public void onError(String e) {
listener.onError(e);
}
};
}
final ManifestListener finalManifestListener = newListener;
handleResponse(new ManifestListener() {
@Override
public void onCompleted(JSONObject manifest) {
finalManifestListener.onCompleted(manifest);
AsyncTask.execute(new Runnable() {
@Override
public void run() {
Exponent.getInstance().preloadManifestAndBundle(manifestUrl);
}
});
}
@Override
public void onError(Exception e) {
finalManifestListener.onError(e);
}
@Override
public void onError(String e) {
finalManifestListener.onError(e);
}
}, response, isEmbedded, true);
}
});
}
}
public boolean fetchCachedManifest(final String manifestUrl, final ManifestListener listener) {
// Analytics.markEvent(Analytics.TimedEvent.STARTED_FETCHING_MANIFEST);
String realManifestUrl = manifestUrl;
if (manifestUrl.contains(REDIRECT_SNIPPET)) {
// Android is crazy and catches this url with this intent filter:
// <data
// android:host="*.exp.direct"
// android:pathPattern=".*"
// android:scheme="http"/>
// <data
// android:host="*.exp.direct"
// android:pathPattern=".*"
// android:scheme="https"/>
// so we have to add some special logic to handle that. This is than handling arbitrary HTTP 301s and 302
// because we need to add /index.exp to the paths.
realManifestUrl = Uri.decode(realManifestUrl.substring(realManifestUrl.indexOf(REDIRECT_SNIPPET) + REDIRECT_SNIPPET.length()));
}
String httpManifestUrl = ExponentUrls.toHttp(realManifestUrl);
// Append index.exp to path
Uri uri = Uri.parse(httpManifestUrl);
String newPath = uri.getPath();
if (newPath == null) {
newPath = "";
}
if (!newPath.endsWith("/")) {
newPath += "/";
}
newPath += "index.exp";
httpManifestUrl = uri.buildUpon().encodedPath(newPath).build().toString();
if (uri.getHost().equals("localhost") || uri.getHost().endsWith(".exp.direct")) {
// if we're in development mode, we don't ever want to fetch a cached manifest
return false;
}
// Fetch manifest
Request.Builder requestBuilder = ExponentUrls.addExponentHeadersToUrl(httpManifestUrl, manifestUrl.equals(Constants.INITIAL_URL), false);
requestBuilder.header("Exponent-Accept-Signature", "true");
requestBuilder.header("Expo-JSON-Error", "true");
// Analytics.markEvent(Analytics.TimedEvent.STARTED_MANIFEST_NETWORK_REQUEST);
// if (Constants.DEBUG_MANIFEST_METHOD_TRACING) {
// Debug.startMethodTracing("manifest");
Request request = requestBuilder.build();
mExponentNetwork.getClient().tryForcedCachedResponse(request.url().toString(), request, new ExponentHttpClient.SafeCallback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onError(new ManifestException(e, manifestUrl));
}
@Override
public void onResponse(Call call, Response response) {
if (!response.isSuccessful()) {
ManifestException exception;
try {
final JSONObject errorJSON = new JSONObject(response.body().string());
exception = new ManifestException(null, manifestUrl, errorJSON);
} catch (JSONException | IOException e) {
exception = new ManifestException(null, manifestUrl);
}
listener.onError(exception);
return;
}
try {
String manifestString = response.body().string();
fetchManifestStep2(manifestUrl, manifestString, response.headers(), listener, false, true);
} catch (JSONException e) {
listener.onError(e);
} catch (IOException e) {
listener.onError(e);
}
}
@Override
public void onCachedResponse(Call call, Response response, boolean isEmbedded) {
onResponse(call, response);
}
}, null, null);
return true;
}
private void fetchManifestStep2(final String manifestUrl, final String manifestString, final Headers headers, final ManifestListener listener, final boolean isEmbedded, boolean isCached) throws JSONException {
if (Constants.DEBUG_MANIFEST_METHOD_TRACING) {
Debug.stopMethodTracing();
}
Analytics.markEvent(Analytics.TimedEvent.FINISHED_MANIFEST_NETWORK_REQUEST);
final JSONObject manifest = new JSONObject(manifestString);
final boolean isMainShellAppExperience = manifestUrl.equals(Constants.INITIAL_URL);
if (manifest.has(MANIFEST_STRING_KEY) && manifest.has(MANIFEST_SIGNATURE_KEY)) {
final JSONObject innerManifest = new JSONObject(manifest.getString(MANIFEST_STRING_KEY));
innerManifest.put(MANIFEST_LOADED_FROM_CACHE_KEY, isCached);
final boolean isOffline = !ExponentNetwork.isNetworkAvailable(mContext);
if (isAnonymousExperience(innerManifest) || isMainShellAppExperience) {
// Automatically verified.
fetchManifestStep3(manifestUrl, innerManifest, true, listener);
} else {
mCrypto.verifyPublicRSASignature(Constants.API_HOST + "/--/manifest-public-key",
manifest.getString(MANIFEST_STRING_KEY), manifest.getString(MANIFEST_SIGNATURE_KEY), new Crypto.RSASignatureListener() {
@Override
public void onError(String errorMessage, boolean isNetworkError) {
if (isOffline && isNetworkError) {
// automatically validate if offline and don't have public key
// TODO: we need to evict manifest from the cache if it doesn't pass validation when online
fetchManifestStep3(manifestUrl, innerManifest, true, listener);
} else {
Log.w(TAG, errorMessage);
fetchManifestStep3(manifestUrl, innerManifest, false, listener);
}
}
@Override
public void onCompleted(boolean isValid) {
fetchManifestStep3(manifestUrl, innerManifest, isValid, listener);
}
});
}
} else {
manifest.put(MANIFEST_LOADED_FROM_CACHE_KEY, isCached);
if (isEmbedded || isMainShellAppExperience) {
fetchManifestStep3(manifestUrl, manifest, true, listener);
} else {
fetchManifestStep3(manifestUrl, manifest, false, listener);
}
}
final String exponentServerHeader = headers.get(EXPONENT_SERVER_HEADER);
if (exponentServerHeader != null) {
try {
JSONObject eventProperties = new JSONObject(exponentServerHeader);
Amplitude.getInstance().logEvent(Analytics.LOAD_DEVELOPER_MANIFEST, eventProperties);
} catch (Throwable e) {
EXL.e(TAG, e);
}
}
}
private void fetchManifestStep3(final String manifestUrl, final JSONObject manifest, final boolean isVerified, final ManifestListener listener) {
String bundleUrl;
if (!manifest.has(MANIFEST_BUNDLE_URL_KEY)) {
listener.onError("No bundleUrl in manifest");
return;
}
try {
manifest.put(MANIFEST_IS_VERIFIED_KEY, isVerified);
} catch (JSONException e) {
listener.onError(e);
return;
}
listener.onCompleted(manifest);
}
public JSONObject normalizeManifest(final String manifestUrl, final JSONObject manifest) throws JSONException {
if (!manifest.has(MANIFEST_ID_KEY)) {
manifest.put(MANIFEST_ID_KEY, manifestUrl);
}
if (!manifest.has(MANIFEST_NAME_KEY)) {
manifest.put(MANIFEST_NAME_KEY, "My New Experience");
}
if (!manifest.has(MANIFEST_PRIMARY_COLOR_KEY)) {
manifest.put(MANIFEST_PRIMARY_COLOR_KEY, "#023C69");
}
if (!manifest.has(MANIFEST_ICON_URL_KEY)) {
manifest.put(MANIFEST_ICON_URL_KEY, "https://d3lwq5rlu14cro.cloudfront.net/ExponentEmptyManifest_192.png");
}
if (!manifest.has(MANIFEST_ORIENTATION_KEY)) {
manifest.put(MANIFEST_ORIENTATION_KEY, "default");
}
return manifest;
}
public void loadIconBitmap(final String iconUrl, final BitmapListener listener) {
if (iconUrl != null && !iconUrl.isEmpty()) {
Bitmap cachedBitmap = mMemoryCache.get(iconUrl);
if (cachedBitmap != null) {
listener.onLoadBitmap(cachedBitmap);
return;
}
new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
try {
// TODO: inject shared OkHttp client
URL url = new URL(iconUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
if (width <= MAX_BITMAP_SIZE && height <= MAX_BITMAP_SIZE) {
mMemoryCache.put(iconUrl, bitmap);
return bitmap;
}
int maxDimension = Math.max(width, height);
float scaledWidth = (((float) width) * MAX_BITMAP_SIZE) / maxDimension;
float scaledHeight = (((float) height) * MAX_BITMAP_SIZE) / maxDimension;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int) scaledWidth, (int) scaledHeight, true);
mMemoryCache.put(iconUrl, scaledBitmap);
return scaledBitmap;
} catch (IOException e) {
EXL.e(TAG, e);
return BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
} catch (Throwable e) {
EXL.e(TAG, e);
return BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
}
}
@Override
protected void onPostExecute(Bitmap result) {
listener.onLoadBitmap(result);
}
}.execute();
} else {
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
listener.onLoadBitmap(bitmap);
}
}
public int getColorFromManifest(final JSONObject manifest) {
String colorString = manifest.optString(MANIFEST_PRIMARY_COLOR_KEY);
if (colorString != null && ColorParser.isValid(colorString)) {
return Color.parseColor(colorString);
} else {
return R.color.colorPrimary;
}
}
private boolean isAnonymousExperience(final JSONObject manifest) {
if (manifest.has(MANIFEST_ID_KEY)) {
final String id = manifest.optString(MANIFEST_ID_KEY);
if (id != null && id.startsWith(ANONYMOUS_EXPERIENCE_PREFIX)) {
return true;
}
}
return false;
}
private JSONObject getLocalKernelManifest() {
try {
JSONObject manifest = new JSONObject(ExponentBuildConstants.BUILD_MACHINE_KERNEL_MANIFEST);
manifest.put(MANIFEST_IS_VERIFIED_KEY, true);
return manifest;
} catch (JSONException e) {
throw new RuntimeException("Can't get local manifest: " + e.toString());
}
}
private JSONObject getRemoteKernelManifest() {
try {
InputStream inputStream = mContext.getAssets().open(EMBEDDED_KERNEL_MANIFEST_ASSET);
String jsonString = IOUtils.toString(inputStream);
JSONObject manifest = new JSONObject(jsonString);
manifest.put(MANIFEST_IS_VERIFIED_KEY, true);
return manifest;
} catch (Exception e) {
KernelProvider.getInstance().handleError(e);
return null;
}
}
public JSONObject getKernelManifest() {
JSONObject manifest;
String log;
if (mExponentSharedPreferences.shouldUseInternetKernel()) {
log = "Using remote Expo kernel manifest";
manifest = getRemoteKernelManifest();
} else {
log = "Using local Expo kernel manifest";
manifest = getLocalKernelManifest();
}
if (!hasShownKernelManifestLog) {
hasShownKernelManifestLog = true;
EXL.d(TAG, log + ": " + manifest.toString());
}
return manifest;
}
public String getKernelManifestField(final String fieldName) {
try {
return getKernelManifest().getString(fieldName);
} catch (JSONException e) {
KernelProvider.getInstance().handleError(e);
return null;
}
}
public static boolean isDebugModeEnabled(final JSONObject manifest) {
try {
return (manifest != null &&
manifest.has(ExponentManifest.MANIFEST_DEVELOPER_KEY) &&
manifest.has(ExponentManifest.MANIFEST_PACKAGER_OPTS_KEY) &&
manifest.getJSONObject(ExponentManifest.MANIFEST_PACKAGER_OPTS_KEY)
.optBoolean(ExponentManifest.MANIFEST_PACKAGER_OPTS_DEV_KEY, false));
} catch (JSONException e) {
return false;
}
}
}
|
package ti.modules.titanium.xml;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiContext;
import org.w3c.dom.CDATASection;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
@Kroll.proxy(parentModule=XMLModule.class)
public class ElementProxy extends NodeProxy {
private Element element;
public ElementProxy(Element element)
{
super(element);
this.element = element;
}
public ElementProxy(TiContext context, Element element)
{
this(element);
}
@Kroll.getProperty @Kroll.method
public String getText()
{
StringBuilder sb = new StringBuilder();
getTextImpl(element, sb);
return sb.toString();
}
private void getTextImpl(Node node, StringBuilder builder)
{
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
{
Node child = children.item(i);
switch (child.getNodeType()) {
case Node.TEXT_NODE:
builder.append(((Text)child).getNodeValue()); break;
case Node.CDATA_SECTION_NODE:
builder.append(((CDATASection)child).getData()); break;
case Node.ENTITY_NODE:
case Node.ELEMENT_NODE:
getTextImpl(child, builder); break;
default: break;
}
}
}
@Kroll.method
public String getAttribute(String name)
{
return element.getAttribute(name);
}
@Kroll.method
public AttrProxy getAttributeNode(String name)
{
return getProxy(element.getAttributeNode(name));
}
@Kroll.method
public AttrProxy getAttributeNodeNS(String namespaceURI, String localName)
throws DOMException
{
return getProxy(element.getAttributeNodeNS(namespaceURI, localName));
}
@Kroll.method
public String getAttributeNS(String namespaceURI, String localName)
throws DOMException
{
return element.getAttributeNS(namespaceURI, localName);
}
protected NodeListProxy filterThisFromNodeList(NodeList list)
{
// Android's Harmony XML impl adds the "this" node
// to the front if it matches the tag name,
// but DOM 2 says only descendant nodes should return.
int offset = 0;
if (list.getLength() > 0 && list.item(0).equals(element)) {
offset = 1;
}
return new NodeListProxy(list, offset);
}
@Kroll.method
public NodeListProxy getElementsByTagName(String name)
{
return filterThisFromNodeList(element.getElementsByTagName(name));
}
@Kroll.method
public NodeListProxy getElementsByTagNameNS(String namespaceURI, String localName)
throws DOMException
{
return filterThisFromNodeList(element.getElementsByTagNameNS(namespaceURI, localName));
}
@Kroll.getProperty @Kroll.method
public String getTagName()
{
return element.getTagName();
}
@Kroll.method
public boolean hasAttribute(String name)
{
return element.hasAttribute(name);
}
@Kroll.method
public boolean hasAttributeNS(String namespaceURI, String localName)
throws DOMException
{
return element.hasAttributeNS(namespaceURI, localName);
}
@Kroll.method
public void removeAttribute(String name)
throws DOMException
{
element.removeAttribute(name);
}
@Kroll.method
public AttrProxy removeAttributeNode(AttrProxy oldAttr)
throws DOMException
{
return getProxy(element.removeAttributeNode(oldAttr.getAttr()));
}
@Kroll.method
public void removeAttributeNS(String namespaceURI, String localName)
throws DOMException
{
element.removeAttributeNS(namespaceURI, localName);
}
@Kroll.method
public void setAttribute(String name, String value)
throws DOMException
{
element.setAttribute(name, value);
}
@Kroll.method
public AttrProxy setAttributeNode(AttrProxy newAttr)
throws DOMException
{
// The node name of newAttr
String newAttrName = newAttr.getNodeName();
// The existed attribute with the node name of newAttr in this element.
// If there is no existed attribute, it's set as null.
AttrProxy existedAttr = this.getAttributeNode(newAttrName);
// Per spec, replacing an attribute node by itself has no effect.
if (existedAttr != null && existedAttr.getAttr() == newAttr.getAttr()) {
return null;
}
// Per spec, setAttributeNode returns null if an attribute
// with the same name did NOT already exist. If it did, it
// returns the replaced attribute.
// A workaround for a harmony bug, TIMOB-6534.
// First, remove the already existed attribute if there is one,
// so that it's no longer attached to this element.
// Then, call the native setAttributeNode function so it will raise
// DOMEexception if there is anything wrong with newAttr. If raising
// any exception, add the removed attribute back to this element.
// Finally, return the existed attribute which we removed.
if (existedAttr != null) {
this.removeAttributeNode(existedAttr);
}
try {
element.setAttributeNode(newAttr.getAttr());
} catch (DOMException e) {
if (existedAttr != null) {
element.setAttributeNode(existedAttr.getAttr());
}
throw e;
}
return existedAttr;
}
@Kroll.method
public AttrProxy setAttributeNodeNS(AttrProxy newAttr)
throws DOMException
{
AttrProxy existedAttr = this.getAttributeNodeNS(newAttr.getNamespaceURI(), newAttr.getLocalName());
// Per spec, replacing an attribute node by itself has no effect.
if (existedAttr != null && existedAttr.getAttr() == newAttr.getAttr()) {
return null;
}
// Per spec, setAttributeNode returns null if an attribute
// with the same name did NOT already exist. If it did, it
// returns the replaced attribute.
// A workaround for a harmony bug, TIMOB-6534.
if (existedAttr != null) {
this.removeAttributeNode(existedAttr);
}
try {
element.setAttributeNodeNS(newAttr.getAttr());
} catch (DOMException e) {
if (existedAttr != null) {
element.setAttributeNodeNS(existedAttr.getAttr());
}
throw e;
}
return existedAttr;
}
@Kroll.method
public void setAttributeNS(String namespaceURI, String qualifiedName, String value)
throws DOMException
{
element.setAttributeNS(namespaceURI, qualifiedName, value);
}
}
|
package org.appcelerator.titanium.view;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollPropertyChange;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.KrollProxyListener;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiMessenger;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.util.TiAnimationBuilder;
import org.appcelerator.titanium.util.TiAnimationBuilder.TiMatrixAnimation;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiUIHelper;
import org.appcelerator.titanium.view.TiCompositeLayout.LayoutParams;
import org.appcelerator.titanium.view.TiGradientDrawable.GradientType;
import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.Pair;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
/**
* This class is for Titanium View implementations, that correspond with TiViewProxy.
* A TiUIView is responsible for creating and maintaining a native Android View instance.
*/
public abstract class TiUIView
implements KrollProxyListener, OnFocusChangeListener
{
private static final boolean HONEYCOMB_OR_GREATER = (Build.VERSION.SDK_INT >= 11);
private static final int LAYER_TYPE_SOFTWARE = 1;
private static final String TAG = "TiUIView";
private static AtomicInteger idGenerator;
// When distinguishing twofingertap and pinch events, minimum motion (in pixels)
// to qualify as a scale event.
private static final float SCALE_THRESHOLD = 6.0f;
public static final int SOFT_KEYBOARD_DEFAULT_ON_FOCUS = 0;
public static final int SOFT_KEYBOARD_HIDE_ON_FOCUS = 1;
public static final int SOFT_KEYBOARD_SHOW_ON_FOCUS = 2;
protected View nativeView; // Native View object
protected TiViewProxy proxy;
protected TiViewProxy parent;
protected ArrayList<TiUIView> children = new ArrayList<TiUIView>();
protected LayoutParams layoutParams;
protected TiAnimationBuilder animBuilder;
protected TiBackgroundDrawable background;
// Since Android doesn't have a property to check to indicate
// the current animated x/y scale (from a scale animation), we track it here
// so if another scale animation is done we can gleen the fromX and fromY values
// rather than starting the next animation always from scale 1.0f (i.e., normal scale).
// This gives us parity with iPhone for scale animations that use the 2-argument variant
// of Ti2DMatrix.scale().
private Pair<Float, Float> animatedScaleValues = Pair.create(Float.valueOf(1f), Float.valueOf(1f)); // default = full size (1f)
// Same for rotation animation and for alpha animation.
private float animatedRotationDegrees = 0f; // i.e., no rotation.
private float animatedAlpha = Float.MIN_VALUE; // i.e., no animated alpha.
private KrollDict lastUpEvent = new KrollDict(2);
// In the case of heavy-weight windows, the "nativeView" is null,
// so this holds a reference to the view which is used for touching,
// i.e., the view passed to registerForTouch.
private WeakReference<View> touchView = null;
private Method mSetLayerTypeMethod = null; // Honeycomb, for turning off hw acceleration.
private boolean zIndexChanged = false;
private TiBorderWrapperView borderView;
// For twofingertap detection
private boolean didScale = false;
/**
* Constructs a TiUIView object with the associated proxy.
* @param proxy the associated proxy.
* @module.api
*/
public TiUIView(TiViewProxy proxy)
{
if (idGenerator == null) {
idGenerator = new AtomicInteger(0);
}
this.proxy = proxy;
this.layoutParams = new TiCompositeLayout.LayoutParams();
}
/**
* Adds a child view into the ViewGroup.
* @param child the view to be added.
*/
public void add(TiUIView child)
{
if (child != null) {
View cv = child.getOuterView();
if (cv != null) {
View nv = getNativeView();
if (nv instanceof ViewGroup) {
if (cv.getParent() == null) {
((ViewGroup) nv).addView(cv, child.getLayoutParams());
}
children.add(child);
child.parent = proxy;
}
}
}
}
/**
* Removes the child view from the ViewGroup, if child exists.
* @param child the view to be removed.
*/
public void remove(TiUIView child)
{
if (child != null) {
View cv = child.getOuterView();
if (cv != null) {
View nv = getNativeView();
if (nv instanceof ViewGroup) {
((ViewGroup) nv).removeView(cv);
children.remove(child);
child.parent = null;
}
}
}
}
/**
* @return list of views added.
*/
public List<TiUIView> getChildren()
{
return children;
}
/**
* @return the view proxy.
* @module.api
*/
public TiViewProxy getProxy()
{
return proxy;
}
/**
* Sets the view proxy.
* @param proxy the proxy to set.
* @module.api
*/
public void setProxy(TiViewProxy proxy)
{
this.proxy = proxy;
}
public TiViewProxy getParent()
{
return parent;
}
public void setParent(TiViewProxy parent)
{
this.parent = parent;
}
/**
* @return the view's layout params.
* @module.api
*/
public LayoutParams getLayoutParams()
{
return layoutParams;
}
/**
* @return the Android native view.
* @module.api
*/
public View getNativeView()
{
return nativeView;
}
/**
* Sets the nativeView to view.
* @param view the view to set
* @module.api
*/
protected void setNativeView(View view)
{
if (view.getId() == View.NO_ID) {
view.setId(idGenerator.incrementAndGet());
}
this.nativeView = view;
boolean clickable = true;
if (proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) {
clickable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED));
}
doSetClickable(nativeView, clickable);
nativeView.setOnFocusChangeListener(this);
applyAccessibilityProperties();
}
protected void setLayoutParams(LayoutParams layoutParams)
{
this.layoutParams = layoutParams;
}
/**
* Animates the view if there are pending animations.
*/
public void animate()
{
if (nativeView == null) {
return;
}
// Pre-honeycomb, if one animation clobbers another you get a problem whereby the background of the
// animated view's parent (or the grandparent) bleeds through. It seems to improve if you cancel and clear
// the older animation. So here we cancel and clear, then re-queue the desired animation.
if (Build.VERSION.SDK_INT < TiC.API_LEVEL_HONEYCOMB) {
Animation currentAnimation = nativeView.getAnimation();
if (currentAnimation != null && currentAnimation.hasStarted() && !currentAnimation.hasEnded()) {
// Cancel existing animation and
// re-queue desired animation.
currentAnimation.cancel();
nativeView.clearAnimation();
proxy.handlePendingAnimation(true);
return;
}
}
TiAnimationBuilder builder = proxy.getPendingAnimation();
if (builder == null) {
return;
}
proxy.clearAnimation(builder);
AnimationSet as = builder.render(proxy, nativeView);
// If a view is "visible" but not currently seen (such as because it's covered or
// its position is currently set to be fully outside its parent's region),
// then Android might not animate it immediately because by default it animates
// "on first frame" and apparently "first frame" won't happen right away if the
// view has no visible rectangle on screen. In that case invalidate its parent, which will
// kick off the pending animation.
boolean invalidateParent = false;
ViewParent viewParent = nativeView.getParent();
if (nativeView.getVisibility() == View.VISIBLE && viewParent instanceof View) {
int width = nativeView.getWidth();
int height = nativeView.getHeight();
if (width == 0 || height == 0) {
// Could be animating from nothing to something
invalidateParent = true;
} else {
Rect r = new Rect(0, 0, width, height);
Point p = new Point(0, 0);
invalidateParent = !(viewParent.getChildVisibleRect(nativeView, r, p));
}
}
Log.d(TAG, "starting animation: " + as, Log.DEBUG_MODE);
nativeView.startAnimation(as);
if (invalidateParent) {
((View) viewParent).postInvalidate();
}
}
public void listenerAdded(String type, int count, KrollProxy proxy) {
}
public void listenerRemoved(String type, int count, KrollProxy proxy){
}
private boolean hasImage(KrollDict d)
{
return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_IMAGE)
|| d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE)
|| d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE)
|| d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE);
}
private boolean hasRepeat(KrollDict d)
{
return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_REPEAT);
}
private boolean hasGradient(KrollDict d)
{
return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_GRADIENT);
}
private boolean hasBorder(KrollDict d)
{
return d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR)
|| d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS)
|| d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH);
}
private boolean hasColorState(KrollDict d)
{
return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR)
|| d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR)
|| d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR);
}
protected void applyTransform(Ti2DMatrix matrix)
{
layoutParams.optionTransform = matrix;
if (animBuilder == null) {
animBuilder = new TiAnimationBuilder();
}
if (nativeView != null) {
if (matrix != null) {
TiMatrixAnimation matrixAnimation = animBuilder.createMatrixAnimation(matrix);
matrixAnimation.interpolate = false;
matrixAnimation.setDuration(1);
matrixAnimation.setFillAfter(true);
nativeView.startAnimation(matrixAnimation);
} else {
nativeView.clearAnimation();
}
}
}
public void forceLayoutNativeView(boolean imformParent)
{
layoutNativeView(imformParent);
}
protected void layoutNativeView()
{
if (!this.proxy.isLayoutStarted()) {
layoutNativeView(false);
}
}
protected void layoutNativeView(boolean informParent)
{
if (nativeView != null) {
Animation a = nativeView.getAnimation();
if (a != null && a instanceof TiMatrixAnimation) {
TiMatrixAnimation matrixAnimation = (TiMatrixAnimation) a;
matrixAnimation.invalidateWithMatrix(nativeView);
}
if (informParent) {
if (parent != null) {
TiUIView uiv = parent.peekView();
if (uiv != null) {
View v = uiv.getNativeView();
if (v instanceof TiCompositeLayout) {
((TiCompositeLayout) v).resort();
}
}
}
}
nativeView.requestLayout();
}
}
public boolean iszIndexChanged()
{
return zIndexChanged;
}
public void setzIndexChanged(boolean zIndexChanged)
{
this.zIndexChanged = zIndexChanged;
}
public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy)
{
if (key.equals(TiC.PROPERTY_LEFT)) {
resetPostAnimationValues();
if (newValue != null) {
layoutParams.optionLeft = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_LEFT);
} else {
layoutParams.optionLeft = null;
}
layoutNativeView();
} else if (key.equals(TiC.PROPERTY_TOP)) {
resetPostAnimationValues();
if (newValue != null) {
layoutParams.optionTop = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_TOP);
} else {
layoutParams.optionTop = null;
}
layoutNativeView();
} else if (key.equals(TiC.PROPERTY_CENTER)) {
resetPostAnimationValues();
TiConvert.updateLayoutCenter(newValue, layoutParams);
layoutNativeView();
} else if (key.equals(TiC.PROPERTY_RIGHT)) {
resetPostAnimationValues();
if (newValue != null) {
layoutParams.optionRight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_RIGHT);
} else {
layoutParams.optionRight = null;
}
layoutNativeView();
} else if (key.equals(TiC.PROPERTY_BOTTOM)) {
resetPostAnimationValues();
if (newValue != null) {
layoutParams.optionBottom = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_BOTTOM);
} else {
layoutParams.optionBottom = null;
}
layoutNativeView();
} else if (key.equals(TiC.PROPERTY_SIZE)) {
if (newValue instanceof HashMap) {
HashMap<String, Object> d = (HashMap) newValue;
propertyChanged(TiC.PROPERTY_WIDTH, oldValue, d.get(TiC.PROPERTY_WIDTH), proxy);
propertyChanged(TiC.PROPERTY_HEIGHT, oldValue, d.get(TiC.PROPERTY_HEIGHT), proxy);
}else if (newValue != null){
Log.w(TAG, "Unsupported property type ("+(newValue.getClass().getSimpleName())+") for key: " + key+". Must be an object/dictionary");
}
} else if (key.equals(TiC.PROPERTY_HEIGHT)) {
resetPostAnimationValues();
if (newValue != null) {
layoutParams.optionHeight = null;
layoutParams.sizeOrFillHeightEnabled = true;
if (newValue.equals(TiC.LAYOUT_SIZE)) {
layoutParams.autoFillsHeight = false;
} else if (newValue.equals(TiC.LAYOUT_FILL)) {
layoutParams.autoFillsHeight = true;
} else if (!newValue.equals(TiC.SIZE_AUTO)) {
layoutParams.optionHeight = TiConvert.toTiDimension(TiConvert.toString(newValue),
TiDimension.TYPE_HEIGHT);
layoutParams.sizeOrFillHeightEnabled = false;
}
} else {
layoutParams.optionHeight = null;
}
layoutNativeView();
} else if (key.equals(TiC.PROPERTY_HORIZONTAL_WRAP)) {
if (nativeView instanceof TiCompositeLayout) {
((TiCompositeLayout) nativeView).setEnableHorizontalWrap(TiConvert.toBoolean(newValue));
}
layoutNativeView();
} else if (key.equals(TiC.PROPERTY_WIDTH)) {
resetPostAnimationValues();
if (newValue != null) {
layoutParams.optionWidth = null;
layoutParams.sizeOrFillWidthEnabled = true;
if (newValue.equals(TiC.LAYOUT_SIZE)) {
layoutParams.autoFillsWidth = false;
} else if (newValue.equals(TiC.LAYOUT_FILL)) {
layoutParams.autoFillsWidth = true;
} else if (!newValue.equals(TiC.SIZE_AUTO)) {
layoutParams.optionWidth = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_WIDTH);
layoutParams.sizeOrFillWidthEnabled = false;
}
} else {
layoutParams.optionWidth = null;
}
layoutNativeView();
} else if (key.equals(TiC.PROPERTY_ZINDEX)) {
if (newValue != null) {
layoutParams.optionZIndex = TiConvert.toInt(newValue);
} else {
layoutParams.optionZIndex = 0;
}
if (!this.proxy.isLayoutStarted()) {
layoutNativeView(true);
} else {
setzIndexChanged(true);
}
} else if (key.equals(TiC.PROPERTY_FOCUSABLE) && newValue != null) {
registerForKeyPress(nativeView, TiConvert.toBoolean(newValue));
} else if (key.equals(TiC.PROPERTY_TOUCH_ENABLED)) {
doSetClickable(TiConvert.toBoolean(newValue));
} else if (key.equals(TiC.PROPERTY_VISIBLE)) {
nativeView.setVisibility(TiConvert.toBoolean(newValue) ? View.VISIBLE : View.INVISIBLE);
} else if (key.equals(TiC.PROPERTY_ENABLED)) {
nativeView.setEnabled(TiConvert.toBoolean(newValue));
} else if (key.startsWith(TiC.PROPERTY_BACKGROUND_PADDING)) {
Log.i(TAG, key + " not yet implemented.");
} else if (key.equals(TiC.PROPERTY_OPACITY)
|| key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX)
|| key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) {
// Update first before querying.
proxy.setProperty(key, newValue);
KrollDict d = proxy.getProperties();
boolean hasImage = hasImage(d);
boolean hasRepeat = hasRepeat(d);
boolean hasColorState = hasColorState(d);
boolean hasBorder = hasBorder(d);
boolean hasGradient = hasGradient(d);
boolean nativeViewNull = (nativeView == null);
boolean requiresCustomBackground = hasImage || hasRepeat || hasColorState || hasBorder || hasGradient;
if (!requiresCustomBackground) {
if (background != null) {
background.releaseDelegate();
background.setCallback(null);
background = null;
}
if (d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_COLOR)) {
Integer bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR);
if (!nativeViewNull) {
nativeView.setBackgroundColor(bgColor);
nativeView.postInvalidate();
}
} else {
if (key.equals(TiC.PROPERTY_OPACITY)) {
setOpacity(TiConvert.toFloat(newValue, 1f));
}
if (!nativeViewNull) {
nativeView.setBackgroundDrawable(null);
nativeView.postInvalidate();
}
}
} else {
boolean newBackground = background == null;
if (newBackground) {
background = new TiBackgroundDrawable();
}
Integer bgColor = null;
if (!hasColorState && !hasGradient) {
if (d.get(TiC.PROPERTY_BACKGROUND_COLOR) != null) {
bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR);
if (newBackground || (key.equals(TiC.PROPERTY_OPACITY) || key.equals(TiC.PROPERTY_BACKGROUND_COLOR))) {
background.setBackgroundColor(bgColor);
}
}
}
if (hasImage || hasRepeat || hasColorState || hasGradient) {
if (newBackground || key.equals(TiC.PROPERTY_OPACITY) || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX)) {
handleBackgroundImage(d);
}
}
if (hasBorder) {
if (borderView == null && parent != null) {
// Since we have to create a new border wrapper view, we need to remove this view, and re-add it.
// This will ensure the border wrapper view is added correctly.
TiUIView parentView = parent.getOrCreateView();
parentView.remove(this);
initializeBorder(d, bgColor);
parentView.add(this);
} else if (key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) {
handleBorderProperty(key, newValue);
}
}
applyCustomBackground();
if (key.equals(TiC.PROPERTY_OPACITY)) {
setOpacity(TiConvert.toFloat(newValue, 1f));
}
}
if (!nativeViewNull) {
nativeView.postInvalidate();
}
} else if (key.equals(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS)) {
Log.w(TAG, "Focus state changed to " + TiConvert.toString(newValue) + " not honored until next focus event.",
Log.DEBUG_MODE);
} else if (key.equals(TiC.PROPERTY_TRANSFORM)) {
if (nativeView != null) {
applyTransform((Ti2DMatrix)newValue);
}
} else if (key.equals(TiC.PROPERTY_KEEP_SCREEN_ON)) {
if (nativeView != null) {
nativeView.setKeepScreenOn(TiConvert.toBoolean(newValue));
}
} else if (key.indexOf("accessibility") == 0 && !key.equals(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)) {
composeContentDescription();
} else if (key.equals(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)) {
applyAccessibilityHidden(newValue);
} else {
Log.d(TAG, "Unhandled property key: " + key, Log.DEBUG_MODE);
}
}
public void processProperties(KrollDict d)
{
boolean nativeViewNull = false;
if (nativeView == null) {
nativeViewNull = true;
Log.d(TAG, "Nativeview is null", Log.DEBUG_MODE);
}
if (d.containsKey(TiC.PROPERTY_LAYOUT)) {
String layout = TiConvert.toString(d, TiC.PROPERTY_LAYOUT);
if (nativeView instanceof TiCompositeLayout) {
((TiCompositeLayout)nativeView).setLayoutArrangement(layout);
}
}
if (TiConvert.fillLayout(d, layoutParams) && !nativeViewNull) {
nativeView.requestLayout();
}
if (d.containsKey(TiC.PROPERTY_HORIZONTAL_WRAP)) {
if (nativeView instanceof TiCompositeLayout) {
((TiCompositeLayout) nativeView).setEnableHorizontalWrap(TiConvert.toBoolean(d, TiC.PROPERTY_HORIZONTAL_WRAP));
}
}
Integer bgColor = null;
// Default background processing.
// Prefer image to color.
if (hasImage(d) || hasColorState(d) || hasGradient(d)) {
handleBackgroundImage(d);
} else if (d.containsKey(TiC.PROPERTY_BACKGROUND_COLOR) && !nativeViewNull) {
bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR);
// Set the background color on the view directly only
// if there is no border. If a border is present we must
// use the TiBackgroundDrawable.
if (hasBorder(d)) {
if (background == null) {
applyCustomBackground(false);
}
background.setBackgroundColor(bgColor);
} else {
nativeView.setBackgroundColor(bgColor);
}
}
if (d.containsKey(TiC.PROPERTY_VISIBLE) && !nativeViewNull) {
nativeView.setVisibility(TiConvert.toBoolean(d, TiC.PROPERTY_VISIBLE) ? View.VISIBLE : View.INVISIBLE);
}
if (d.containsKey(TiC.PROPERTY_ENABLED) && !nativeViewNull) {
nativeView.setEnabled(TiConvert.toBoolean(d, TiC.PROPERTY_ENABLED));
}
initializeBorder(d, bgColor);
if (d.containsKey(TiC.PROPERTY_OPACITY) && !nativeViewNull) {
setOpacity(TiConvert.toFloat(d, TiC.PROPERTY_OPACITY, 1f));
}
if (d.containsKey(TiC.PROPERTY_TRANSFORM)) {
Ti2DMatrix matrix = (Ti2DMatrix) d.get(TiC.PROPERTY_TRANSFORM);
if (matrix != null) {
applyTransform(matrix);
}
}
if (d.containsKey(TiC.PROPERTY_KEEP_SCREEN_ON) && !nativeViewNull) {
nativeView.setKeepScreenOn(TiConvert.toBoolean(d, TiC.PROPERTY_KEEP_SCREEN_ON));
}
if (d.containsKey(TiC.PROPERTY_ACCESSIBILITY_HINT) || d.containsKey(TiC.PROPERTY_ACCESSIBILITY_LABEL)
|| d.containsKey(TiC.PROPERTY_ACCESSIBILITY_VALUE) || d.containsKey(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)) {
applyAccessibilityProperties();
}
}
// TODO dead code? @Override
public void propertiesChanged(List<KrollPropertyChange> changes, KrollProxy proxy)
{
for (KrollPropertyChange change : changes) {
propertyChanged(change.getName(), change.getOldValue(), change.getNewValue(), proxy);
}
}
private void applyCustomBackground()
{
applyCustomBackground(true);
}
private void applyCustomBackground(boolean reuseCurrentDrawable)
{
if (nativeView != null) {
if (background == null) {
background = new TiBackgroundDrawable();
Drawable currentDrawable = nativeView.getBackground();
if (currentDrawable != null) {
if (reuseCurrentDrawable) {
background.setBackgroundDrawable(currentDrawable);
} else {
nativeView.setBackgroundDrawable(null);
currentDrawable.setCallback(null);
if (currentDrawable instanceof TiBackgroundDrawable) {
((TiBackgroundDrawable) currentDrawable).releaseDelegate();
}
}
}
}
nativeView.setBackgroundDrawable(background);
}
}
public void onFocusChange(final View v, boolean hasFocus)
{
if (hasFocus) {
TiMessenger.postOnMain(new Runnable() {
public void run() {
TiUIHelper.requestSoftInputChange(proxy, v);
}
});
proxy.fireEvent(TiC.EVENT_FOCUS, getFocusEventObject(hasFocus));
} else {
proxy.fireEvent(TiC.EVENT_BLUR, getFocusEventObject(hasFocus));
}
}
protected KrollDict getFocusEventObject(boolean hasFocus)
{
return null;
}
protected InputMethodManager getIMM()
{
InputMethodManager imm = null;
imm = (InputMethodManager) TiApplication.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE);
return imm;
}
/**
* Focuses the view.
*/
public void focus()
{
if (nativeView != null) {
nativeView.requestFocus();
}
}
/**
* Blurs the view.
*/
public void blur()
{
if (nativeView != null) {
TiUIHelper.showSoftKeyboard(nativeView, false);
nativeView.clearFocus();
}
}
public void release()
{
Log.d(TAG, "Releasing: " + this, Log.DEBUG_MODE);
View nv = getNativeView();
if (nv != null) {
if (nv instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) nv;
Log.d(TAG, "Group has: " + vg.getChildCount(), Log.DEBUG_MODE);
if (!(vg instanceof AdapterView<?>)) {
vg.removeAllViews();
}
}
Drawable d = nv.getBackground();
if (d != null) {
nv.setBackgroundDrawable(null);
d.setCallback(null);
if (d instanceof TiBackgroundDrawable) {
((TiBackgroundDrawable)d).releaseDelegate();
}
d = null;
}
nativeView = null;
borderView = null;
if (proxy != null) {
proxy.setModelListener(null);
}
}
}
/**
* Shows the view, changing the view's visibility to View.VISIBLE.
*/
public void show()
{
if (borderView != null) {
borderView.setVisibility(View.VISIBLE);
}
if (nativeView != null) {
nativeView.setVisibility(View.VISIBLE);
} else {
Log.w(TAG, "Attempt to show null native control", Log.DEBUG_MODE);
}
}
/**
* Hides the view, changing the view's visibility to View.INVISIBLE.
*/
public void hide()
{
if (borderView != null) {
borderView.setVisibility(View.INVISIBLE);
}
if (nativeView != null) {
nativeView.setVisibility(View.INVISIBLE);
} else {
Log.w(TAG, "Attempt to hide null native control", Log.DEBUG_MODE);
}
}
private String resolveImageUrl(String path) {
return path.length() > 0 ? proxy.resolveUrl(null, path) : null;
}
private void handleBackgroundImage(KrollDict d)
{
String bg = d.getString(TiC.PROPERTY_BACKGROUND_IMAGE);
String bgSelected = d.optString(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE, bg);
String bgFocused = d.optString(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE, bg);
String bgDisabled = d.optString(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE, bg);
String bgColor = d.getString(TiC.PROPERTY_BACKGROUND_COLOR);
String bgSelectedColor = d.optString(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR, bgColor);
String bgFocusedColor = d.optString(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR, bgColor);
String bgDisabledColor = d.optString(TiC.PROPERTY_BACKGROUND_DISABLED_COLOR, bgColor);
if (bg != null) {
bg = resolveImageUrl(bg);
}
if (bgSelected != null) {
bgSelected = resolveImageUrl(bgSelected);
}
if (bgFocused != null) {
bgFocused = resolveImageUrl(bgFocused);
}
if (bgDisabled != null) {
bgDisabled = resolveImageUrl(bgDisabled);
}
TiGradientDrawable gradientDrawable = null;
KrollDict gradientProperties = d.getKrollDict(TiC.PROPERTY_BACKGROUND_GRADIENT);
if (gradientProperties != null) {
try {
gradientDrawable = new TiGradientDrawable(nativeView, gradientProperties);
if (gradientDrawable.getGradientType() == GradientType.RADIAL_GRADIENT) {
// TODO: Remove this once we support radial gradients.
Log.w(TAG, "Android does not support radial gradients.");
gradientDrawable = null;
}
}
catch (IllegalArgumentException e) {
gradientDrawable = null;
}
}
if (bg != null || bgSelected != null || bgFocused != null || bgDisabled != null ||
bgColor != null || bgSelectedColor != null || bgFocusedColor != null || bgDisabledColor != null || gradientDrawable != null)
{
if (background == null) {
applyCustomBackground(false);
}
Drawable bgDrawable = TiUIHelper.buildBackgroundDrawable(
bg,
d.getBoolean(TiC.PROPERTY_BACKGROUND_REPEAT),
bgColor,
bgSelected,
bgSelectedColor,
bgDisabled,
bgDisabledColor,
bgFocused,
bgFocusedColor,
gradientDrawable);
background.setBackgroundDrawable(bgDrawable);
}
}
private void initializeBorder(KrollDict d, Integer bgColor)
{
if (hasBorder(d)) {
if(nativeView != null) {
if (borderView == null) {
Activity currentActivity = proxy.getActivity();
if (currentActivity == null) {
currentActivity = TiApplication.getAppCurrentActivity();
}
borderView = new TiBorderWrapperView(currentActivity);
// Create new layout params for the child view since we just want the
// wrapper to control the layout
LayoutParams params = new LayoutParams();
params.height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
params.width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
borderView.addView(nativeView, params);
}
if (d.containsKey(TiC.PROPERTY_BORDER_RADIUS)) {
float radius = TiConvert.toFloat(d, TiC.PROPERTY_BORDER_RADIUS, 0f);
if (radius > 0f && HONEYCOMB_OR_GREATER) {
disableHWAcceleration();
}
borderView.setRadius(radius);
}
if (d.containsKey(TiC.PROPERTY_BORDER_COLOR) || d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) {
if (d.containsKey(TiC.PROPERTY_BORDER_COLOR)) {
borderView.setColor(TiConvert.toColor(d, TiC.PROPERTY_BORDER_COLOR));
} else {
if (bgColor != null) {
borderView.setColor(bgColor);
}
}
if (d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) {
borderView.setBorderWidth(TiConvert.toFloat(d, TiC.PROPERTY_BORDER_WIDTH, 0f));
}
}
}
}
}
private void handleBorderProperty(String property, Object value)
{
if (TiC.PROPERTY_BORDER_COLOR.equals(property)) {
borderView.setColor(TiConvert.toColor(value.toString()));
} else if (TiC.PROPERTY_BORDER_RADIUS.equals(property)) {
float radius = TiConvert.toFloat(value, 0f);
if (radius > 0f && HONEYCOMB_OR_GREATER) {
disableHWAcceleration();
}
borderView.setRadius(radius);
} else if (TiC.PROPERTY_BORDER_WIDTH.equals(property)) {
borderView.setBorderWidth(TiConvert.toFloat(value, 0f));
}
}
private static HashMap<Integer, String> motionEvents = new HashMap<Integer,String>();
static
{
motionEvents.put(MotionEvent.ACTION_DOWN, TiC.EVENT_TOUCH_START);
motionEvents.put(MotionEvent.ACTION_UP, TiC.EVENT_TOUCH_END);
motionEvents.put(MotionEvent.ACTION_MOVE, TiC.EVENT_TOUCH_MOVE);
motionEvents.put(MotionEvent.ACTION_CANCEL, TiC.EVENT_TOUCH_CANCEL);
}
protected KrollDict dictFromEvent(MotionEvent e)
{
KrollDict data = new KrollDict();
data.put(TiC.EVENT_PROPERTY_X, (double)e.getX());
data.put(TiC.EVENT_PROPERTY_Y, (double)e.getY());
data.put(TiC.EVENT_PROPERTY_SOURCE, proxy);
return data;
}
private KrollDict dictFromEvent(KrollDict dictToCopy){
KrollDict data = new KrollDict();
if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_X)){
data.put(TiC.EVENT_PROPERTY_X, dictToCopy.get(TiC.EVENT_PROPERTY_X));
} else {
data.put(TiC.EVENT_PROPERTY_X, (double)0);
}
if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_Y)){
data.put(TiC.EVENT_PROPERTY_Y, dictToCopy.get(TiC.EVENT_PROPERTY_Y));
} else {
data.put(TiC.EVENT_PROPERTY_Y, (double)0);
}
data.put(TiC.EVENT_PROPERTY_SOURCE, proxy);
return data;
}
protected boolean allowRegisterForTouch()
{
return true;
}
/**
* @module.api
*/
protected boolean allowRegisterForKeyPress()
{
return true;
}
public View getOuterView()
{
if (borderView == null) {
return nativeView;
}
return borderView;
}
public void registerForTouch()
{
if (allowRegisterForTouch()) {
registerForTouch(getNativeView());
}
}
protected void registerTouchEvents(final View touchable)
{
touchView = new WeakReference<View>(touchable);
final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(touchable.getContext(),
new SimpleOnScaleGestureListener()
{
// protect from divide by zero errors
long minTimeDelta = 1;
float minStartSpan = 1.0f;
float startSpan;
@Override
public boolean onScale(ScaleGestureDetector sgd)
{
if (proxy.hierarchyHasListener(TiC.EVENT_PINCH)) {
float timeDelta = sgd.getTimeDelta() == 0 ? minTimeDelta : sgd.getTimeDelta();
// Suppress scale events (and allow for possible two-finger tap events)
// until we've moved at least a few pixels. Without this check, two-finger
// taps are very hard to register on some older devices.
if (!didScale) {
if (Math.abs(sgd.getCurrentSpan() - startSpan) > SCALE_THRESHOLD) {
didScale = true;
}
}
if (didScale) {
KrollDict data = new KrollDict();
data.put(TiC.EVENT_PROPERTY_SCALE, sgd.getCurrentSpan() / startSpan);
data.put(TiC.EVENT_PROPERTY_VELOCITY, (sgd.getScaleFactor() - 1.0f) / timeDelta * 1000);
data.put(TiC.EVENT_PROPERTY_SOURCE, proxy);
return proxy.fireEvent(TiC.EVENT_PINCH, data);
}
}
return false;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector sgd)
{
startSpan = sgd.getCurrentSpan() == 0 ? minStartSpan : sgd.getCurrentSpan();
return true;
}
});
final GestureDetector detector = new GestureDetector(touchable.getContext(), new SimpleOnGestureListener()
{
@Override
public boolean onDoubleTap(MotionEvent e)
{
if (proxy.hierarchyHasListener(TiC.EVENT_DOUBLE_TAP) || proxy.hierarchyHasListener(TiC.EVENT_DOUBLE_CLICK)) {
boolean handledTap = proxy.fireEvent(TiC.EVENT_DOUBLE_TAP, dictFromEvent(e));
boolean handledClick = proxy.fireEvent(TiC.EVENT_DOUBLE_CLICK, dictFromEvent(e));
return handledTap || handledClick;
}
return false;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e)
{
Log.d(TAG, "TAP, TAP, TAP on " + proxy, Log.DEBUG_MODE);
if (proxy.hierarchyHasListener(TiC.EVENT_SINGLE_TAP)) {
return proxy.fireEvent(TiC.EVENT_SINGLE_TAP, dictFromEvent(e));
// Moved click handling to the onTouch listener, because a single tap is not the
// same as a click. A single tap is a quick tap only, whereas clicks can be held
// before lifting.
// boolean handledClick = proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(event));
// Note: this return value is irrelevant in our case. We "want" to use it
// in onTouch below, when we call detector.onTouchEvent(event); But, in fact,
// onSingleTapConfirmed is *not* called in the course of onTouchEvent. It's
// called via Handler in GestureDetector. <-- See its Java source.
// return handledTap;// || handledClick;
}
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
Log.d(TAG, "SWIPE on " + proxy, Log.DEBUG_MODE);
if (proxy.hierarchyHasListener(TiC.EVENT_SWIPE)) {
KrollDict data = dictFromEvent(e2);
if (Math.abs(velocityX) > Math.abs(velocityY)) {
data.put(TiC.EVENT_PROPERTY_DIRECTION, velocityX > 0 ? "right" : "left");
} else {
data.put(TiC.EVENT_PROPERTY_DIRECTION, velocityY > 0 ? "down" : "up");
}
return proxy.fireEvent(TiC.EVENT_SWIPE, data);
}
return false;
}
@Override
public void onLongPress(MotionEvent e)
{
Log.d(TAG, "LONGPRESS on " + proxy, Log.DEBUG_MODE);
if (proxy.hierarchyHasListener(TiC.EVENT_LONGPRESS)) {
proxy.fireEvent(TiC.EVENT_LONGPRESS, dictFromEvent(e));
}
}
});
touchable.setOnTouchListener(new OnTouchListener()
{
int pointersDown = 0;
public boolean onTouch(View view, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_UP) {
lastUpEvent.put(TiC.EVENT_PROPERTY_X, (double) event.getX());
lastUpEvent.put(TiC.EVENT_PROPERTY_Y, (double) event.getY());
}
scaleDetector.onTouchEvent(event);
if (scaleDetector.isInProgress()) {
pointersDown = 0;
return true;
}
boolean handled = detector.onTouchEvent(event);
if (handled) {
pointersDown = 0;
return true;
}
if (event.getActionMasked() == MotionEvent.ACTION_POINTER_UP) {
if (didScale) {
didScale = false;
pointersDown = 0;
} else {
pointersDown++;
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (pointersDown == 1) {
proxy.fireEvent(TiC.EVENT_TWOFINGERTAP, dictFromEvent(event));
pointersDown = 0;
return true;
}
pointersDown = 0;
}
String motionEvent = motionEvents.get(event.getAction());
if (motionEvent != null) {
if (proxy.hierarchyHasListener(motionEvent)) {
proxy.fireEvent(motionEvent, dictFromEvent(event));
}
}
// Inside View.java, dispatchTouchEvent() does not call onTouchEvent() if this listener returns true. As
// a result, click and other motion events do not occur on the native Android side. To prevent this, we
// always return false and let Android generate click and other motion events.
return false;
}
});
}
protected void registerForTouch(final View touchable)
{
if (touchable == null) {
return;
}
registerTouchEvents(touchable);
// Previously, we used the single tap handling above to fire our click event. It doesn't
// work: a single tap is not the same as a click. A click can be held for a while before
// lifting the finger; a single-tap is only generated from a quick tap (which will also cause
// a click.) We wanted to do it in single-tap handling presumably because the singletap
// listener gets a MotionEvent, which gives us the information we want to provide to our
// users in our click event, whereas Android's standard OnClickListener does _not_ contain
// that info. However, an "up" seems to always occur before the click listener gets invoked,
// so we store the last up event's x,y coordinates (see onTouch above) and use them here.
// Note: AdapterView throws an exception if you try to put a click listener on it.
doSetClickable(touchable);
}
public void registerForKeyPress()
{
if (allowRegisterForKeyPress()) {
registerForKeyPress(getNativeView());
}
}
protected void registerForKeyPress(final View v)
{
if (v == null) {
return;
}
Object focusable = proxy.getProperty(TiC.PROPERTY_FOCUSABLE);
if (focusable != null) {
registerForKeyPress(v, TiConvert.toBoolean(focusable));
}
}
protected void registerForKeyPress(final View v, boolean focusable)
{
if (v == null) {
return;
}
v.setFocusable(focusable);
// The listener for the "keypressed" event is only triggered when the view has focus. So we only register the
// "keypressed" event when the view is focusable.
if (focusable) {
registerForKeyPressEvents(v);
} else {
v.setOnKeyListener(null);
}
}
/**
* Registers a callback to be invoked when a hardware key is pressed in this view.
*
* @param v The view to have the key listener to attach to.
*/
protected void registerForKeyPressEvents(final View v)
{
if (v == null) {
return;
}
v.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View view, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_UP) {
KrollDict data = new KrollDict();
data.put(TiC.EVENT_PROPERTY_KEYCODE, keyCode);
proxy.fireEvent(TiC.EVENT_KEY_PRESSED, data);
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
if (proxy.hasListeners(TiC.EVENT_CLICK)) {
proxy.fireEvent(TiC.EVENT_CLICK, null);
return true;
}
}
}
return false;
}
});
}
/**
* Sets the nativeView's opacity.
* @param opacity the opacity to set.
*/
public void setOpacity(float opacity)
{
if (opacity < 0 || opacity > 1) {
Log.w(TAG, "Ignoring invalid value for opacity: " + opacity);
return;
}
if (borderView != null) {
borderView.setBorderAlpha(Math.round(opacity * 255));
}
setOpacity(nativeView, opacity);
}
/**
* Sets the view's opacity.
* @param view the view object.
* @param opacity the opacity to set.
*/
protected void setOpacity(View view, float opacity)
{
if (view != null) {
TiUIHelper.setDrawableOpacity(view.getBackground(), opacity);
if (opacity == 1) {
clearOpacity(view);
}
view.invalidate();
}
}
public void clearOpacity(View view)
{
Drawable d = view.getBackground();
if (d != null) {
d.clearColorFilter();
}
}
public KrollDict toImage()
{
return TiUIHelper.viewToImage(proxy.getProperties(), getNativeView());
}
private View getTouchView()
{
if (nativeView != null) {
return nativeView;
} else {
if (touchView != null) {
return touchView.get();
}
}
return null;
}
private void doSetClickable(View view, boolean clickable)
{
if (view == null) {
return;
}
if (!clickable) {
view.setOnClickListener(null); // This will set clickable to true in the view, so make sure it stays here so the next line turns it off.
view.setClickable(false);
view.setOnLongClickListener(null);
view.setLongClickable(false);
} else if ( ! (view instanceof AdapterView) ){
// n.b.: AdapterView throws if click listener set.
// n.b.: setting onclicklistener automatically sets clickable to true.
setOnClickListener(view);
setOnLongClickListener(view);
}
}
private void doSetClickable(boolean clickable)
{
doSetClickable(getTouchView(), clickable);
}
/*
* Used just to setup the click listener if applicable.
*/
private void doSetClickable(View view)
{
if (view == null) {
return;
}
doSetClickable(view, view.isClickable());
}
/**
* Can be overriden by inheriting views for special click handling. For example,
* the Facebook module's login button view needs special click handling.
*/
protected void setOnClickListener(View view)
{
view.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(lastUpEvent));
}
});
}
protected void setOnLongClickListener(View view)
{
view.setOnLongClickListener(new OnLongClickListener()
{
public boolean onLongClick(View view)
{
return proxy.fireEvent(TiC.EVENT_LONGCLICK, null);
}
});
}
private void disableHWAcceleration()
{
if (nativeView == null) {
return;
}
Log.d(TAG, "Disabling hardware acceleration for instance of " + nativeView.getClass().getSimpleName(),
Log.DEBUG_MODE);
if (mSetLayerTypeMethod == null) {
try {
Class<? extends View> c = nativeView.getClass();
mSetLayerTypeMethod = c.getMethod("setLayerType", int.class, Paint.class);
} catch (SecurityException e) {
Log.e(TAG, "SecurityException trying to get View.setLayerType to disable hardware acceleration.", e,
Log.DEBUG_MODE);
} catch (NoSuchMethodException e) {
Log.e(TAG, "NoSuchMethodException trying to get View.setLayerType to disable hardware acceleration.", e,
Log.DEBUG_MODE);
}
}
if (mSetLayerTypeMethod == null) {
return;
}
try {
mSetLayerTypeMethod.invoke(nativeView, LAYER_TYPE_SOFTWARE, null);
} catch (IllegalArgumentException e) {
Log.e(TAG, e.getMessage(), e);
} catch (IllegalAccessException e) {
Log.e(TAG, e.getMessage(), e);
} catch (InvocationTargetException e) {
Log.e(TAG, e.getMessage(), e);
}
}
/**
* Retrieve the saved animated scale values, which we store here since Android provides no property
* for looking them up.
*/
public Pair<Float, Float> getAnimatedScaleValues()
{
return animatedScaleValues;
}
/**
* Store the animated x and y scale values (i.e., the scale after an animation)
* since Android provides no property for looking them up.
*/
public void setAnimatedScaleValues(Pair<Float, Float> newValues)
{
animatedScaleValues = newValues;
}
/**
* Set the animated rotation degrees, since Android provides no property for looking it up.
*/
public void setAnimatedRotationDegrees(float degrees)
{
animatedRotationDegrees = degrees;
}
/**
* Retrieve the animated rotation degrees, which we store here since Android provides no property
* for looking it up.
*/
public float getAnimatedRotationDegrees()
{
return animatedRotationDegrees;
}
/**
* Set the animated alpha values, since Android provides no property for looking it up.
*/
public void setAnimatedAlpha(float alpha)
{
animatedAlpha = alpha;
}
/**
* Retrieve the animated alpha value, which we store here since Android provides no property
* for looking it up.
*/
public float getAnimatedAlpha()
{
return animatedAlpha;
}
/**
* "Forget" the values we save after scale and rotation and alpha animations.
*/
private void resetPostAnimationValues()
{
animatedRotationDegrees = 0f; // i.e., no rotation.
animatedScaleValues = Pair.create(Float.valueOf(1f), Float.valueOf(1f)); // 1 means no scaling
animatedAlpha = Float.MIN_VALUE; // we use min val to signal no val.
}
/**
* Our view proxy supports three properties to match iOS regarding
* the text that is read aloud (or otherwise communicated) by the
* assistive technology: accessibilityLabel, accessibilityHint
* and accessibilityValue.
*
* We combine these to create the single Android property contentDescription.
* (e.g., View.setContentDescription(...));
*/
private void composeContentDescription()
{
if (nativeView == null || proxy == null) {
return;
}
final String punctuationPattern = "^.*\\p{Punct}\\s*$";
StringBuilder buffer = new StringBuilder();
KrollDict properties = proxy.getProperties();
String label, hint, value;
label = TiConvert.toString(properties.get(TiC.PROPERTY_ACCESSIBILITY_LABEL));
hint = TiConvert.toString(properties.get(TiC.PROPERTY_ACCESSIBILITY_HINT));
value = TiConvert.toString(properties.get(TiC.PROPERTY_ACCESSIBILITY_VALUE));
if (!TextUtils.isEmpty(label)) {
buffer.append(label);
if (!label.matches(punctuationPattern)) {
buffer.append(".");
}
}
if (!TextUtils.isEmpty(value)) {
if (buffer.length() > 0) {
buffer.append(" ");
}
buffer.append(value);
if (!value.matches(punctuationPattern)) {
buffer.append(".");
}
}
if (!TextUtils.isEmpty(hint)) {
if (buffer.length() > 0) {
buffer.append(" ");
}
buffer.append(hint);
if (!hint.matches(punctuationPattern)) {
buffer.append(".");
}
}
nativeView.setContentDescription(buffer.toString());
}
private void applyAccessibilityProperties()
{
if (nativeView != null) {
composeContentDescription();
applyAccessibilityHidden();
}
}
private void applyAccessibilityHidden()
{
if (nativeView == null || proxy == null) {
return;
}
applyAccessibilityHidden(proxy.getProperty(TiC.PROPERTY_ACCESSIBILITY_HIDDEN));
}
private void applyAccessibilityHidden(Object hiddenPropertyValue)
{
if (nativeView == null) {
return;
}
int importanceMode = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
if (hiddenPropertyValue != null && TiConvert.toBoolean(hiddenPropertyValue)) {
importanceMode = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO;
}
ViewCompat.setImportantForAccessibility(nativeView, importanceMode);
}
}
|
package org.xnio.channels;
import static java.lang.Thread.currentThread;
import static java.util.Arrays.copyOf;
import static java.util.concurrent.locks.LockSupport.park;
import static java.util.concurrent.locks.LockSupport.parkNanos;
import static java.util.concurrent.locks.LockSupport.unpark;
import java.io.IOException;
import java.nio.channels.Channel;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.IoUtils;
import org.xnio.Option;
import org.xnio.XnioExecutor;
import org.xnio.XnioWorker;
import static org.xnio.Bits.*;
/**
* An abstract wrapped channel.
*
* @param <C> the channel type implemented by this class
* @param <W> the channel type being wrapped by this class
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
@SuppressWarnings("unused")
public abstract class TranslatingSuspendableChannel<C extends SuspendableChannel, W extends SuspendableChannel> implements SuspendableChannel, WrappedChannel<W> {
/**
* The wrapped channel.
*/
protected final W channel;
private final ChannelListener.SimpleSetter<C> readSetter = new ChannelListener.SimpleSetter<C>();
private final ChannelListener.SimpleSetter<C> writeSetter = new ChannelListener.SimpleSetter<C>();
private final ChannelListener.SimpleSetter<C> closeSetter = new ChannelListener.SimpleSetter<C>();
private volatile int state;
private volatile Thread[] readWaiters = NOT_WAITING;
private volatile Thread[] writeWaiters = NOT_WAITING;
private static final Thread[] NOT_WAITING = new Thread[0];
private static final AtomicIntegerFieldUpdater<TranslatingSuspendableChannel> stateUpdater = AtomicIntegerFieldUpdater.newUpdater(TranslatingSuspendableChannel.class, "state");
private static final AtomicReferenceFieldUpdater<TranslatingSuspendableChannel, Thread[]> readWaitersUpdater = AtomicReferenceFieldUpdater.newUpdater(TranslatingSuspendableChannel.class, Thread[].class, "readWaiters");
private static final AtomicReferenceFieldUpdater<TranslatingSuspendableChannel, Thread[]> writeWaitersUpdater = AtomicReferenceFieldUpdater.newUpdater(TranslatingSuspendableChannel.class, Thread[].class, "writeWaiters");
// read-side
private static final int READ_REQUESTED = 1 << 0x00; // user wants to be notified on read
private static final int READ_REQUIRES_WRITE = 1 << 0x01; // channel cannot be read due to pending write
private static final int READ_READY = 1 << 0x02; // channel is always ready to be read
private static final int READ_SHUT_DOWN = 1 << 0x03; // user shut down reads
private static final int READ_REQUIRES_EXT = intBitMask(0x0B, 0x0F); // channel cannot be read until external event completes, up to 32 events
private static final int READ_SINGLE_EXT = 1 << 0x0B; // one external event count value
private static final int READ_FLAGS = intBitMask(0x00, 0x0F);
// write-side
private static final int WRITE_REQUESTED = 1 << 0x10;
private static final int WRITE_REQUIRES_READ = 1 << 0x11;
private static final int WRITE_READY = 1 << 0x12;
private static final int WRITE_SHUT_DOWN = 1 << 0x13; // user requested shut down of writes
private static final int WRITE_COMPLETE = 1 << 0x14; // flush acknowledged full write shutdown
private static final int WRITE_REQUIRES_EXT = intBitMask(0x1B, 0x1F); // up to 32 events
private static final int WRITE_SINGLE_EXT = 1 << 0x1B;
private static final int WRITE_FLAGS = intBitMask(0x10, 0x1F);
private final ChannelListener<Channel> readListener = new ChannelListener<Channel>() {
public void handleEvent(final Channel channel) {
handleReadable();
}
public String toString() {
return "Read listener for " + TranslatingSuspendableChannel.this;
}
};
private final ChannelListener<Channel> writeListener = new ChannelListener<Channel>() {
public void handleEvent(final Channel channel) {
handleWritable();
}
public String toString() {
return "Write listener for " + TranslatingSuspendableChannel.this;
}
};
private final ChannelListener<Channel> closeListener = new ChannelListener<Channel>() {
public void handleEvent(final Channel channel) {
IoUtils.safeClose(TranslatingSuspendableChannel.this);
}
public String toString() {
return "Close listener for " + TranslatingSuspendableChannel.this;
}
};
/**
* Construct a new instance.
*
* @param channel the channel being wrapped
*/
protected TranslatingSuspendableChannel(final W channel) {
if (channel == null) {
throw new IllegalArgumentException("channel is null");
}
this.channel = channel;
channel.getReadSetter().set(readListener);
channel.getWriteSetter().set(writeListener);
channel.getCloseSetter().set(closeListener);
}
/**
* Called when the underlying channel is readable.
*/
protected void handleReadable() {
int oldState;
oldState = clearFlags(WRITE_REQUIRES_READ);
if (allAreSet(oldState, WRITE_REQUIRES_READ)) {
unparkWriteWaiters();
if (allAreSet(oldState, WRITE_REQUESTED)) {
channel.wakeupWrites();
}
}
if (allAreClear(oldState, READ_READY) && anyAreSet(oldState, READ_REQUIRES_WRITE | READ_REQUIRES_EXT)) {
channel.suspendReads();
oldState = state;
if (anyAreSet(oldState, READ_READY) || allAreClear(oldState, READ_REQUIRES_WRITE | READ_REQUIRES_EXT)) {
// undo
channel.resumeReads();
} else {
return;
}
}
do {
if (anyAreSet(oldState, READ_SHUT_DOWN)) {
channel.suspendReads();
return;
}
if (allAreClear(oldState, READ_REQUESTED)) {
channel.suspendReads();
oldState = state;
if (allAreSet(oldState, READ_REQUESTED)) {
// undo
channel.resumeReads();
} else {
return;
}
}
unparkReadWaiters();
final ChannelListener<? super C> listener = readSetter.get();
if (listener == null) {
// damage control
oldState = clearFlag(READ_REQUESTED | WRITE_REQUIRES_READ) & ~READ_REQUESTED;
} else {
ChannelListeners.<C>invokeChannelListener(thisTyped(), listener);
oldState = clearFlags(WRITE_REQUIRES_READ);
}
if (allAreSet(oldState, WRITE_REQUIRES_READ)) {
unparkWriteWaiters();
// race is OK
channel.wakeupWrites();
}
} while (allAreSet(oldState, READ_READY));
}
/**
* Called when the underlying channel is writable.
*/
protected void handleWritable() {
int oldState;
oldState = clearFlags(READ_REQUIRES_WRITE);
if (allAreSet(oldState, READ_REQUIRES_WRITE)) {
unparkReadWaiters();
if (allAreSet(oldState, READ_REQUESTED)) {
channel.wakeupReads();
}
}
if (allAreClear(oldState, WRITE_READY) && anyAreSet(oldState, WRITE_REQUIRES_READ | WRITE_REQUIRES_EXT)) {
channel.suspendWrites();
oldState = state;
if (anyAreSet(oldState, WRITE_READY) || allAreClear(oldState, WRITE_REQUIRES_READ | WRITE_REQUIRES_EXT)) {
// undo
channel.resumeWrites();
} else {
return;
}
}
do {
if (anyAreSet(oldState, WRITE_COMPLETE)) {
channel.suspendWrites();
return;
}
if (allAreClear(oldState, WRITE_REQUESTED)) {
channel.suspendWrites();
oldState = state;
if (allAreSet(oldState, WRITE_REQUESTED)) {
// undo
channel.resumeWrites();
} else {
return;
}
}
unparkWriteWaiters();
final ChannelListener<? super C> listener = writeSetter.get();
if (listener == null) {
// damage control
oldState = clearFlags(WRITE_REQUESTED | READ_REQUIRES_WRITE) & ~WRITE_REQUESTED;
} else {
ChannelListeners.<C>invokeChannelListener(thisTyped(), listener);
oldState = clearFlags(READ_REQUIRES_WRITE);
}
if (allAreSet(oldState, READ_REQUIRES_WRITE)) {
unparkReadWaiters();
// race is OK
channel.wakeupReads();
}
} while (allAreSet(oldState, WRITE_READY));
}
/**
* Called when the underlying channel is closed.
*
*/
protected void handleClosed() {
ChannelListeners.<C>invokeChannelListener(thisTyped(), closeSetter.get());
}
/**
* Indicate that the channel is definitely immediately readable, regardless of the underlying channel state.
*/
protected void setReadReady() {
int oldState = setFlags(READ_READY);
if (allAreSet(oldState, READ_READY)) {
// idempotent
return;
}
if (allAreSet(oldState, READ_REQUESTED) && anyAreSet(oldState, READ_REQUIRES_EXT | READ_REQUIRES_WRITE)) {
// wakeup is required to proceed
channel.wakeupReads();
}
}
/**
* Indicate that the channel is no longer definitely immediately readable.
*/
protected void clearReadReady() {
int oldState = clearFlags(READ_READY);
if (allAreClear(oldState, READ_READY)) {
// idempotent
return;
}
if (!allAreClear(oldState, READ_REQUESTED) && !anyAreSet(oldState, READ_REQUIRES_EXT | READ_REQUIRES_WRITE)) {
// we can read again when the underlying channel is ready
channel.resumeReads();
}
}
/**
* Indicate that the channel will not be readable until the write handler is called.
*/
protected void setReadRequiresWrite() {
int oldState = setFlags(READ_REQUIRES_WRITE);
if (allAreSet(oldState, READ_REQUIRES_WRITE)) {
// not the first caller
return;
}
if (allAreClear(oldState, READ_READY | READ_REQUIRES_EXT)) {
// read cannot proceed until write does
channel.resumeWrites();
}
}
/**
* Indicate if the channel is not readable until the write handler is called.
*/
protected boolean readRequiresWrite() {
return allAreSet(state, READ_REQUIRES_WRITE);
}
/**
* Indicate that the channel no longer requires writability for reads to proceed.
*/
protected void clearReadRequiresWrite() {
int oldState = clearFlags(READ_REQUIRES_WRITE);
if (allAreClear(oldState, READ_REQUIRES_WRITE)) {
// idempotent
return;
}
if (allAreClear(oldState, READ_REQUIRES_EXT) && allAreSet(oldState, READ_REQUESTED)) {
if (allAreSet(oldState, READ_READY)) {
channel.wakeupReads();
} else {
channel.resumeReads();
}
}
}
/**
* Indicate that read requires an external task to complete.
*
* @return {@code true} if the flag was set, {@code false} if too many tasks are already outstanding
*/
protected boolean tryAddReadRequiresExternal() {
int oldState = addFlag(READ_REQUIRES_EXT, READ_SINGLE_EXT);
return (oldState & READ_REQUIRES_EXT) != READ_REQUIRES_EXT;
}
/**
* Indicate that one external read task was completed. This method should be called once for every time
* that {@link #tryAddReadRequiresExternal()} returned {@code true}.
*/
protected void removeReadRequiresExternal() {
clearFlag(READ_SINGLE_EXT);
}
/**
* Set the channel read shut down flag.
*
* @return {@code true} if the channel has fully closed due to this call, {@code false} otherwise
*/
protected boolean setReadShutDown() {
return (setFlags(READ_SHUT_DOWN) & (READ_SHUT_DOWN | WRITE_SHUT_DOWN)) == WRITE_SHUT_DOWN;
}
/**
* Indicate that the channel is definitely immediately writable, regardless of the underlying channel state.
*/
protected void setWriteReady() {
int oldState = setFlags(WRITE_READY);
if (allAreSet(oldState, WRITE_READY)) {
// idempotent
return;
}
if (allAreSet(oldState, WRITE_REQUESTED) && anyAreSet(oldState, WRITE_REQUIRES_EXT | WRITE_REQUIRES_READ)) {
// wakeup is required to proceed
channel.wakeupWrites();
}
}
/**
* Indicate that the channel is no longer definitely immediately writable.
*/
protected void clearWriteReady() {
int oldState = clearFlags(WRITE_READY);
if (allAreClear(oldState, WRITE_READY)) {
// idempotent
return;
}
if (!allAreClear(oldState, WRITE_REQUESTED) && ! anyAreSet(oldState, WRITE_REQUIRES_EXT | WRITE_REQUIRES_READ)) {
// we can write again when the underlying channel is ready
channel.resumeWrites();
}
}
/**
* Indicate that the channel will not be writable until the read handler is called.
*/
protected void setWriteRequiresRead() {
int oldState = setFlags(WRITE_REQUIRES_READ);
if (allAreSet(oldState, WRITE_REQUIRES_READ)) {
// not the first caller
return;
}
if (allAreClear(oldState, WRITE_READY | WRITE_REQUIRES_EXT)) {
// write cannot proceed until read does
channel.resumeReads();
}
}
/**
* Indicate if the channel is not writable until the read handler is called.
*/
protected boolean writeRequiresRead() {
return allAreSet(state, WRITE_REQUIRES_READ);
}
/**
* Indicate that the channel no longer requires writability for writes to proceed.
*/
protected void clearWriteRequiresRead() {
int oldState = clearFlags(WRITE_REQUIRES_READ);
if (allAreClear(oldState, WRITE_REQUIRES_READ)) {
// idempotent
return;
}
if (allAreClear(oldState, WRITE_REQUIRES_EXT) && allAreSet(oldState, WRITE_REQUESTED)) {
if (allAreSet(oldState, WRITE_READY)) {
channel.wakeupWrites();
} else {
channel.resumeWrites();
}
}
}
/**
* Indicate that write requires an external task to complete.
*
* @return {@code true} if the flag was set, {@code false} if too many tasks are already outstanding
*/
protected boolean tryAddWriteRequiresExternal() {
int oldState = addFlag(WRITE_REQUIRES_EXT, WRITE_SINGLE_EXT);
return (oldState & WRITE_REQUIRES_EXT) != WRITE_REQUIRES_EXT;
}
/**
* Indicate that one external write task was completed. This method should be called once for every time
* that {@link #tryAddWriteRequiresExternal()} returned {@code true}.
*/
protected void removeWriteRequiresExternal() {
clearFlag(WRITE_SINGLE_EXT);
}
/**
* Set the channel write shut down flag.
*
* @return {@code true} if the channel has fully closed due to this call, {@code false} otherwise
*/
protected boolean setWriteShutDown() {
return (setFlags(WRITE_SHUT_DOWN) & (WRITE_SHUT_DOWN | READ_SHUT_DOWN)) == READ_SHUT_DOWN;
}
/**
* Set both the channel read and write shut down flags.
*
* @return {@code true} if the channel has fully closed (for the first time) due to this call, {@code false} otherwise
*/
protected boolean setClosed() {
return (setFlags(READ_SHUT_DOWN | WRITE_SHUT_DOWN) & (READ_SHUT_DOWN | WRITE_SHUT_DOWN)) != (READ_SHUT_DOWN | WRITE_SHUT_DOWN);
}
/**
* Get this channel, cast to the implemented channel type.
*
* @return {@code this}
*/
@SuppressWarnings("unchecked")
protected final C thisTyped() {
return (C) this;
}
/** {@inheritDoc} */
public ChannelListener.Setter<C> getCloseSetter() {
return closeSetter;
}
/** {@inheritDoc} */
public ChannelListener.Setter<C> getReadSetter() {
return readSetter;
}
/** {@inheritDoc} */
public ChannelListener.Setter<C> getWriteSetter() {
return writeSetter;
}
/** {@inheritDoc} */
public void suspendReads() {
clearFlags(READ_REQUESTED);
// let the read/write handler actually suspend, to avoid awkward race conditions
}
/** {@inheritDoc} */
public void resumeReads() {
final int oldState = setFlags(READ_REQUESTED);
if (anyAreSet(oldState, READ_REQUESTED | READ_SHUT_DOWN)) {
// idempotent or shut down, either way
return;
}
if (allAreSet(oldState, READ_READY)) {
// reads are known to be ready so trigger listener right away
channel.wakeupReads();
return;
}
if (allAreClear(oldState, READ_REQUIRES_EXT)) {
if (allAreSet(oldState, READ_REQUIRES_WRITE)) {
channel.resumeWrites();
} else {
channel.resumeReads();
}
}
}
public boolean isReadResumed() {
return allAreSet(state, READ_REQUESTED);
}
/** {@inheritDoc} */
public void wakeupReads() {
final int oldState = setFlags(READ_REQUESTED);
if (anyAreSet(oldState, READ_SHUT_DOWN)) {
return;
}
channel.wakeupReads();
}
/** {@inheritDoc} */
public void suspendWrites() {
clearFlags(WRITE_REQUESTED);
// let the read/write handler actually suspend, to avoid awkward race conditions
}
/** {@inheritDoc} */
public void resumeWrites() {
final int oldState = setFlags(WRITE_REQUESTED);
if (anyAreSet(oldState, WRITE_REQUESTED | WRITE_COMPLETE)) {
// idempotent or shut down, either way
return;
}
if (allAreSet(oldState, WRITE_READY)) {
// reads are known to be ready so trigger listener right away
channel.wakeupWrites();
return;
}
if (allAreClear(oldState, WRITE_REQUIRES_EXT)) {
if (allAreSet(oldState, WRITE_REQUIRES_READ)) {
channel.resumeReads();
} else {
channel.resumeWrites();
}
}
}
public boolean isWriteResumed() {
return allAreSet(state, WRITE_REQUESTED);
}
/** {@inheritDoc} */
public void wakeupWrites() {
final int oldState = setFlags(WRITE_REQUESTED);
if (anyAreSet(oldState, WRITE_COMPLETE)) {
return;
}
channel.wakeupWrites();
}
/** {@inheritDoc} */
public boolean supportsOption(final Option<?> option) {
return channel.supportsOption(option);
}
/** {@inheritDoc} */
public <T> T getOption(final Option<T> option) throws IOException {
return channel.getOption(option);
}
/** {@inheritDoc} */
public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException {
return channel.setOption(option, value);
}
/**
* Perform channel flush. To change the action taken to flush, subclasses should override {@link #flushAction(boolean)}.
*
* @return {@code true} if the flush completed, or {@code false} if the operation would block
* @throws IOException if an error occurs
*/
public final boolean flush() throws IOException {
int oldState, newState;
oldState = stateUpdater.get(this);
if (allAreSet(oldState, WRITE_COMPLETE)) {
return channel.flush();
}
final boolean shutDown = allAreSet(oldState, WRITE_SHUT_DOWN);
if (! flushAction(shutDown)) {
return false;
}
if (! shutDown) {
return true;
}
newState = oldState | WRITE_COMPLETE;
while (! stateUpdater.compareAndSet(this, oldState, newState)) {
oldState = stateUpdater.get(this);
if (allAreSet(oldState, WRITE_COMPLETE)) {
return channel.flush();
}
newState = oldState | WRITE_COMPLETE;
}
final boolean readShutDown = allAreSet(oldState, READ_SHUT_DOWN);
try {
shutdownWritesComplete(readShutDown);
} finally {
if (readShutDown) ChannelListeners.<C>invokeChannelListener(thisTyped(), closeSetter.get());
}
return channel.flush();
}
/**
* The action to perform when the channel is flushed. By default, this method delegates to the underlying channel.
* If the {@code shutDown} parameter is set, and this method returns {@code true}, the underlying channel will be
* shut down and this method will never be called again (future calls to {@link #flush()} will flush the underlying
* channel until it returns {@code true}).
*
* @param shutDown {@code true} if the channel's write side has been shut down, {@code false} otherwise
* @return {@code true} if the flush succeeded, {@code false} if it would block
* @throws IOException if an error occurs
*/
protected boolean flushAction(final boolean shutDown) throws IOException {
return channel.flush();
}
/**
* Notification that the channel has successfully flushed after having shut down writes. The underlying
* channel may not yet be fully flushed at this time.
*
* @param readShutDown {@code true} if the read side was already shut down, {@code false} otherwise
* @throws IOException if an error occurs
*/
protected void shutdownWritesComplete(final boolean readShutDown) throws IOException {
}
/**
* Perform the read shutdown action if it hasn't been performed already.
*
* @throws IOException if an I/O error occurs
*/
public void shutdownReads() throws IOException {
int old = setFlags(READ_SHUT_DOWN);
if (allAreClear(old, READ_SHUT_DOWN)) {
final boolean writeComplete = allAreSet(old, WRITE_COMPLETE);
try {
shutdownReadsAction(writeComplete);
} finally {
if (writeComplete) {
ChannelListeners.<C>invokeChannelListener(thisTyped(), closeSetter.get());
}
}
}
}
/**
* The action to perform when reads are shut down. By default, this method delegates to the underlying channel.
*
* @throws IOException if an error occurs
* @param writeComplete
*/
protected void shutdownReadsAction(final boolean writeComplete) throws IOException {
channel.shutdownReads();
}
/**
* Determine whether the channel is shut down for reads.
*
* @return whether the channel is shut down for reads
*/
protected boolean isReadShutDown() {
return allAreSet(state, READ_SHUT_DOWN);
}
/**
* Perform the write shutdown action if it hasn't been performed already.
*
* @throws IOException if an I/O error occurs
*/
public void shutdownWrites() throws IOException {
int old = setFlags(WRITE_SHUT_DOWN);
if (allAreClear(old, WRITE_SHUT_DOWN)) {
shutdownWritesAction();
}
}
/**
* The action to perform when writes are requested to be shut down. By default, this method delegates to the
* underlying channel.
*
* @throws IOException if an error occurs
*/
protected void shutdownWritesAction() throws IOException {
channel.shutdownWrites();
}
/**
* Determine whether the channel is shut down for writes.
*
* @return whether the channel is shut down for writes
*/
protected boolean isWriteShutDown() {
return allAreSet(state, WRITE_SHUT_DOWN);
}
protected boolean isWriteComplete() {
return allAreSet(state, WRITE_COMPLETE);
}
/** {@inheritDoc} */
public void awaitReadable() throws IOException {
int oldState = state;
if (anyAreSet(oldState, READ_READY | READ_SHUT_DOWN)) {
return;
}
if (addReadWaiter()) {
if (allAreSet(oldState, READ_REQUIRES_WRITE)) {
channel.resumeWrites();
} else {
channel.resumeReads();
}
park(this);
}
return;
}
/** {@inheritDoc} */
public void awaitReadable(final long time, final TimeUnit timeUnit) throws IOException {
int oldState = state;
if (anyAreSet(oldState, READ_READY | READ_SHUT_DOWN)) {
return;
}
if (addReadWaiter()) {
if (allAreSet(oldState, READ_REQUIRES_WRITE)) {
channel.resumeWrites();
} else {
channel.resumeReads();
}
parkNanos(this, timeUnit.toNanos(time));
}
return;
}
public XnioExecutor getReadThread() {
return channel.getReadThread();
}
/** {@inheritDoc} */
public void awaitWritable() throws IOException {
int oldState = state;
if (anyAreSet(oldState, WRITE_READY | WRITE_SHUT_DOWN)) {
return;
}
if (addWriteWaiter()) {
if (allAreSet(oldState, WRITE_REQUIRES_READ)) {
channel.resumeReads();
} else {
channel.resumeWrites();
}
park(this);
}
return;
}
/** {@inheritDoc} */
public void awaitWritable(final long time, final TimeUnit timeUnit) throws IOException {
int oldState = state;
if (anyAreSet(oldState, WRITE_READY | WRITE_SHUT_DOWN)) {
return;
}
if (addWriteWaiter()) {
if (allAreSet(oldState, WRITE_REQUIRES_READ)) {
channel.resumeReads();
} else {
channel.resumeWrites();
}
parkNanos(this, timeUnit.toNanos(time));
}
return;
}
public XnioExecutor getWriteThread() {
return channel.getWriteThread();
}
/**
* Close this channel. This method is idempotent.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
int old = setFlags(READ_SHUT_DOWN | WRITE_SHUT_DOWN | WRITE_COMPLETE);
final boolean readShutDown = allAreSet(old, READ_SHUT_DOWN), writeShutDown = allAreSet(old, WRITE_COMPLETE);
if (! (readShutDown && writeShutDown)) try {
closeAction(readShutDown, writeShutDown);
} finally {
ChannelListeners.<C>invokeChannelListener(thisTyped(), closeSetter.get());
}
}
/**
* The action to perform when the channel is closed via the {@link #close()} method. By default, the underlying
* channel is closed.
*
* @param readShutDown if reads were previously shut down
* @param writeShutDown if writes were previously shut down
* @throws IOException if an error occurs
*/
protected void closeAction(final boolean readShutDown, final boolean writeShutDown) throws IOException {
channel.close();
}
/** {@inheritDoc} */
public boolean isOpen() {
return ! allAreSet(state, READ_SHUT_DOWN | WRITE_COMPLETE);
}
/** {@inheritDoc} */
public W getChannel() {
return channel;
}
/** {@inheritDoc} */
public XnioWorker getWorker() {
return channel.getWorker();
}
/** {@inheritDoc} */
public String toString() {
return getClass().getName() + " around " + channel;
}
// state operations
private int setFlags(int flags) {
int oldState;
do {
oldState = state;
if ((oldState & flags) == flags) {
return oldState;
}
} while (! stateUpdater.compareAndSet(this, oldState, oldState | flags));
return oldState;
}
private int clearFlags(int flags) {
int oldState;
do {
oldState = state;
if ((oldState & flags) == 0) {
return oldState;
}
} while (! stateUpdater.compareAndSet(this, oldState, oldState & ~flags));
return oldState;
}
private int addFlag(final int mask, final int count) {
int oldState;
do {
oldState = state;
if ((oldState & mask) == mask) {
return oldState;
}
} while (! stateUpdater.compareAndSet(this, oldState, oldState + count));
return oldState;
}
private int clearFlag(final int count) {
return stateUpdater.getAndAdd(this, -count);
}
private boolean addReadWaiter() {
Thread[] oldWaiters, newWaiters;
do {
oldWaiters = readWaiters;
if (oldWaiters == NOT_WAITING) {
return false;
} else if (oldWaiters == null) {
newWaiters = new Thread[] { currentThread() };
} else {
final int oldLength = oldWaiters.length;
for (int i = 0; i < oldLength; i++) {
if (oldWaiters[i] == currentThread()) {
return true;
}
}
newWaiters = copyOf(oldWaiters, oldLength + 1);
newWaiters[oldLength] = currentThread();
}
} while (! readWaitersUpdater.compareAndSet(this, oldWaiters, newWaiters));
return true;
}
private boolean addWriteWaiter() {
Thread[] oldWaiters, newWaiters;
do {
oldWaiters = writeWaiters;
if (oldWaiters == NOT_WAITING) {
return false;
} else if (oldWaiters == null) {
newWaiters = new Thread[] { currentThread() };
} else {
final int oldLength = oldWaiters.length;
for (int i = 0; i < oldLength; i++) {
if (oldWaiters[i] == currentThread()) {
return true;
}
}
newWaiters = copyOf(oldWaiters, oldLength + 1);
newWaiters[oldLength] = currentThread();
}
} while (! writeWaitersUpdater.compareAndSet(this, oldWaiters, newWaiters));
return true;
}
private void unparkReadWaiters() {
final Thread[] waiters = readWaitersUpdater.getAndSet(this, NOT_WAITING);
for (Thread waiter : waiters) {
unpark(waiter);
}
}
private void unparkWriteWaiters() {
final Thread[] waiters = writeWaitersUpdater.getAndSet(this, NOT_WAITING);
for (Thread waiter : waiters) {
unpark(waiter);
}
}
}
|
package edu.berkeley.cs.amplab.carat.android;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.BackStackEntry;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.flurry.android.FlurryAgent;
import edu.berkeley.cs.amplab.carat.android.fragments.AboutFragment;
import edu.berkeley.cs.amplab.carat.android.fragments.BugsOrHogsFragment;
import edu.berkeley.cs.amplab.carat.android.fragments.CaratSettingsFragment;
import edu.berkeley.cs.amplab.carat.android.fragments.EnableInternetDialogFragment;
import edu.berkeley.cs.amplab.carat.android.fragments.MyDeviceFragment;
import edu.berkeley.cs.amplab.carat.android.fragments.SuggestionsFragment;
import edu.berkeley.cs.amplab.carat.android.fragments.SummaryFragment;
import edu.berkeley.cs.amplab.carat.android.sampling.SamplingLibrary;
import edu.berkeley.cs.amplab.carat.android.subscreens.WebViewFragment;
import edu.berkeley.cs.amplab.carat.android.utils.JsonParser;
import edu.berkeley.cs.amplab.carat.android.utils.Tracker;
/**
* Carat Android App Main Activity. Is loaded right after CaratApplication.
* Holds the Tabs that comprise the UI. Place code related to tab handling and
* global Activity code here.
*
* @author Eemil Lagerspetz
*
*/
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitle;
private String[] mDrawerItems;
// Log tag
// private static final String TAG = "MainActivity";
public static final String ACTION_BUGS = "bugs",
ACTION_HOGS = "hogs";
// Key File
private static final String FLURRY_KEYFILE = "flurry.properties";
private String fullVersion = null;
private Tracker tracker = null;
/**
* Dynamic way of dealing with a list of fragments that you need to keep references for.
*/
private Fragment[] frags = new Fragment[CaratApplication.getTitles().length];
private Bundle mArgs;
// public boolean updateSummaryFragment;
// counts (general Carat statistics shown in the summary fragment)
public int mWellbehaved = Constants.VALUE_NOT_AVAILABLE,
mHogs = Constants.VALUE_NOT_AVAILABLE,
mBugs = Constants.VALUE_NOT_AVAILABLE ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CaratApplication.setMain(this);
tracker = Tracker.getInstance(this);
// track user clicks (taps)
tracker.trackUser("caratstarted", getTitle());
if (!CaratApplication.isInternetAvailable()) {
EnableInternetDialogFragment dialog = new EnableInternetDialogFragment();
dialog.show(getSupportFragmentManager(), "dialog");
}
/*
* Activity.getWindow.requestFeature() should get invoked only before
* setContentView(), otherwise it will cause an app crash The progress
* bar doesn't get displayed when there is no update in progress
*/
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
// Log.d(TAG, "about to set the layout");
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
setTitleNormal();
// read and load the preferences specified in our xml preference file
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
// Log.d(TAG, "about to initialize fragments");
preInittializeFragments();
// Log.d(TAG, "done with fragment initialization");
/*
* Before using the field "fullVersion", first invoke setTitleNormal()
* or setFullVersion() to set this field
*/
mDrawerItems = getResources().getStringArray(R.array.drawer_items);
List<Item> items = new ArrayList<Item>();
// items.add(new NavDrawerListHeader("Main"));
items.add(new ListItem(mDrawerItems[0]));
items.add(new ListItem(mDrawerItems[1]));
items.add(new ListItem(mDrawerItems[2]));
items.add(new ListItem(mDrawerItems[3]));
items.add(new ListItem(mDrawerItems[4]));
items.add(new NavDrawerListHeader(""));
items.add(new ListItem(mDrawerItems[5]));
items.add(new ListItem(mDrawerItems[6]));
TextArrayAdapter adapter = new TextArrayAdapter(this, items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(adapter);
// mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
//getSupportActionBar().setTitle(mTitle);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitle);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Enable ActionBar app icon to behave as action to toggle navigation drawer
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
if (savedInstanceState == null) {
selectItem(0);
}
setTitleNormal();
// Uncomment the following to enable listening on local port 8080:
/*
* try {
* HelloServer h = new HelloServer();
* } catch (IOException e) {
* e.printStackTrace();
* }
*/
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
// To remove the lag in closing the drawer, don't do a fragment transaction
// while the drawer is getting closed.
// First close the drawer (takes about 300ms (transition/animation time)),
// wait for it to get closed completely, then start replacing the fragment .
// How to modify the navigation drawer closing transition time:
// consider menu item headers (additional menu items) when selecting an item
// TODO: use a dynamic approach
final int newPosition = (position <= 4) ? position : position - 1;
mDrawerLayout.closeDrawer(mDrawerList);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
selectItem(newPosition);
}
}, 300); // wait 300ms before calling selectItem()
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
replaceFragment(frags[position], mDrawerItems[position], true);
mDrawerList.setItemChecked(position, true);
}
/**
*
* @param index 0-based index of the navigation drawer entries (e.g. 3 for bugs fragment)
* @return the tag of the fragment corresponding to the index
*/
public String getFragmentTag(int index) {
return mDrawerItems[index];
}
/**
* Avoid displaying a white screen when the back button is pressed in the summary fragment.
* When we are in the summary fragment, since there is only one fragment in the backstack,
* the fragment manager will fail to pop another fragment from the backstack,
* so only the framelayout (the parent/host widget for fragments (in our activity's layout)) is shown.
* We need to check the number of fragments present in the backstack, and act accordingly
*/
@Override
public void onBackPressed() {
FragmentManager manager = getSupportFragmentManager();
// If we will pop a top level screen, show drawer indicator again
int stackTop = manager.getBackStackEntryCount()-1;
if (manager != null && stackTop >= 0) {
// The implementation sets entry count to 0 if the stack is null.
BackStackEntry entry = manager.getBackStackEntryAt(stackTop);
String name = entry.getName();
String[] titles = CaratApplication.getTitles();
boolean found = false;
for (String t : titles) {
if (!found)
found = t.equals(name);
}
if (found) {
// Restore menu
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
}
if (stackTop >= 0 ) {
// If there are back-stack entries, replace the fragment (go to the fragment)
manager.popBackStack();
}else
finish();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
/*
* FIXME: Don't save anything for now.
* This fixes some crashes with the backstack, but needs to be fixed in the long run.
*
* What we should do here is:
* 1. Save which Fragment, and which subscreen the user is looking at
* 2. Save the data shown by that fragment
* 3. Then in onCreate, read those fields and set them after initializing the app normally
*/
//super.onSaveInstanceState(outState);
}
@Override
public void setTitle(CharSequence title) {
getSupportActionBar().setTitle(title);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggle
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
// In case we are at a sublevel, enable going back by clicking title.
if (item.getItemId() == android.R.id.home && !mDrawerToggle.isDrawerIndicatorEnabled()){
onBackPressed();
return true;
}
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
public void setTitleNormal() {
setFullVersion();
if (CaratApplication.getStorage() != null) {
long s = CaratApplication.getStorage().getSamplesReported();
Log.d("setTitleNormal", "number of samples reported=" + String.valueOf(s));
if (s > 0) {
mTitle = fullVersion + " - "+ s + " " + getString(R.string.samplesreported);
} else {
mTitle = fullVersion;
}
}
setTitle(mTitle);
}
private void setFullVersion() {
fullVersion = getString(R.string.app_name) + " " + getString(R.string.version_name);
}
public String getFullVersion() {
return fullVersion;
}
public void setTitleUpdating(String what) {
setTitle(getString(R.string.updating) + " " + what);
// this is quick hack to update SummaryFragment.
if (what.equals(getString(R.string.finishing)))
refreshSummaryFragment();
}
public void setTitleUpdatingFailed(String what) {
setTitle(getString(R.string.didntget) + " " + what);
}
/**
* Used in the system settings fragment and the summary fragment
* @param intentString
* @param thing
*/
public void safeStart(String intentString, String thing) {
Intent intent = null;
try {
intent = new Intent(intentString);
startActivity(intent);
} catch (Throwable th) {
// Log.e(TAG, "Could not start activity: " + intent, th);
if (thing != null) {
Toast t = Toast.makeText(this, getString(R.string.opening) + thing + getString(R.string.notsupported),
Toast.LENGTH_SHORT);
t.show();
}
}
}
@Override
protected void onStart() {
super.onStart();
String secretKey = null;
Properties properties = new Properties();
try {
InputStream raw = MainActivity.this.getAssets().open(FLURRY_KEYFILE);
if (raw != null) {
properties.load(raw);
if (properties.containsKey("secretkey"))
secretKey = properties.getProperty("secretkey", "secretkey");
// Log.d(TAG, "Set Flurry secret key.");
} else {
// Log.e(TAG, "Could not open Flurry key file!");
}
} catch (IOException e) {
// Log.e(TAG, "Could not open Flurry key file: " + e.toString());
}
if (secretKey != null) {
FlurryAgent.onStartSession(getApplicationContext(), secretKey);
}
/* To perform an action when our defaultSharedPreferences changes, we can do it in this listener
* when you uncomment this, remember to uncomment the unregistering code in the onStop() method of this activity (right below)
*/
// PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);
}
@Override
protected void onStop() {
super.onStop();
FlurryAgent.onEndSession(getApplicationContext());
// PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);
}
@Override
protected void onResume() {
// Log.i(TAG, "Resumed. Refreshing UI");
tracker.trackUser("caratresumed", getTitle());
// if statistics data for the summary fragment is not already fetched,
// and the device has an Internet connection, fetch statistics and then refresh the summary fragment
if ( (! isStatsDataAvailable()) && CaratApplication.isInternetAvailable()) {
getStatsFromServer();
}
/**
* This may take minutes, so refresh summary frag here again.
*/
new Thread() {
public void run() {
((CaratApplication) getApplication()).refreshUi();
// This should only run if we are on that tab, so onResume of SummaryFragment should be enough.
//refreshSummaryFragment();
}}.start();
super.onResume();
}
public Fragment getVisibleFragment(){
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
return fragment;
}
return null;
}
@Override
protected void onPause() {
// Log.i(TAG, "Paused");
tracker.trackUser("caratpaused", getTitle());
SamplingLibrary.resetRunningProcessInfo();
super.onPause();
}
@Override
public void finish() {
// Log.d(TAG, "Finishing up");
tracker.trackUser("caratstopped", getTitle());
super.finish();
}
/**
* must be called in onCreate() method of the activity, before calling selectItem() method
* [before attaching the navigation drawer listener]
* pre-initialize all fragments before committing a replace fragment transaction
* may help for better smoothness when user selects a navigation drawer item
*/
private void preInittializeFragments() {
getStatsFromServer();
// after fetching the data needed by the summary fragment, initialize it
int idx = 0;
frags[idx] = new SummaryFragment();
idx++;
frags[idx] = new SuggestionsFragment();
idx++;
frags[idx] = new MyDeviceFragment();
idx++;
frags[idx] = new BugsOrHogsFragment();
mArgs = new Bundle();
mArgs.putBoolean("isBugs", true);
frags[idx].setArguments(mArgs);
idx++;
frags[idx] = new BugsOrHogsFragment();
mArgs = new Bundle();
mArgs.putBoolean("isBugs", false);
frags[idx].setArguments(mArgs);
idx++;
frags[idx] = new CaratSettingsFragment();
idx++;
frags[idx] = new AboutFragment();
}
/**
* Before initializing the summary fragment, we need to fetch the the data it needs from our server,
* in an asyncTask in a new thread
*/
@SuppressLint("NewApi")
private void getStatsFromServer() {
PrefetchData prefetchData = new PrefetchData();
// run this asyncTask in a new thread [from the thread pool] (run in parallel to other asyncTasks)
// (do not wait for them to finish, it takes a long time)
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
prefetchData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
prefetchData.execute();
}
/*
* shows the fragment using a fragment transaction (replaces the FrameLayout
* (a placeholder in the main activity's layout file) with the passed-in fragment)
*
* @param fragment the fragment that should be shown
* @param tag a name for the fragment to be shown in the
* fragment (task) stack
*/
public void replaceFragment(Fragment fragment, String tag, boolean showDrawerIndicator) {
// use a fragment tag, so that later on we can find the currently displayed fragment
final String FRAGMENT_TAG = tag;
// replace the fragment, using a fragment transaction
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (!isDestroyed()) {
// Crash fix.
transaction.replace(R.id.content_frame, fragment, FRAGMENT_TAG)
.addToBackStack(FRAGMENT_TAG).commitAllowingStateLoss();
mDrawerToggle.setDrawerIndicatorEnabled(showDrawerIndicator);
}
}
/**
* used by other classes
* @param fileName
*/
public void showHTMLFile(String fileName, String title, boolean showDrawerIndicator) {
WebViewFragment fragment = WebViewFragment.getInstance(fileName);
replaceFragment(fragment, title, showDrawerIndicator);
}
public boolean isStatsDataAvailable() {
if (isStatsDataLoaded()) {
// Log.i(TAG, "isStatsDataAvailable(), mWellbehaved=" + mWellbehaved + ", mHogs=" + mHogs + ", mBugs=" + mBugs);
return true;
} else {
return isStatsDataStoredInPref();
}
}
private boolean isStatsDataLoaded() {
// don't check for zero, check for something unlikely, e.g. -1 (use a constant for that value, use it consistently)
return mWellbehaved != Constants.VALUE_NOT_AVAILABLE && mHogs != Constants.VALUE_NOT_AVAILABLE && mBugs != Constants.VALUE_NOT_AVAILABLE;
}
private boolean isStatsDataStoredInPref() {
// TODO: consider a data freshness timeout (e.g. two weeks)
int wellbehaved = CaratApplication.mPrefs.getInt(Constants.STATS_WELLBEHAVED_COUNT_PREFERENCE_KEY, Constants.VALUE_NOT_AVAILABLE);
int hogs = CaratApplication.mPrefs.getInt(Constants.STATS_HOGS_COUNT_PREFERENCE_KEY, Constants.VALUE_NOT_AVAILABLE);
int bugs = CaratApplication.mPrefs.getInt(Constants.STATS_BUGS_COUNT_PREFERENCE_KEY, Constants.VALUE_NOT_AVAILABLE);
if (wellbehaved != Constants.VALUE_NOT_AVAILABLE && hogs != Constants.VALUE_NOT_AVAILABLE && bugs != Constants.VALUE_NOT_AVAILABLE) {
// Log.i(TAG, "isStatsDataAvailable(), wellbehaved (fetched from the pref)=" + wellbehaved);
mWellbehaved = wellbehaved;
mHogs = hogs;
mBugs = bugs;
return true;
} else {
return false;
}
}
public void GoToWifiScreen() {
safeStart(android.provider.Settings.ACTION_WIFI_SETTINGS, getString(R.string.wifisettings));
}
public void refreshSummaryFragment() {
if (frags.length > 0)
((SummaryFragment) frags[0]).scheduleRefresh();
}
public Fragment getMydeviceFragment() {
return frags[2];
}
public Fragment getHogsFragment() {
return frags[4];
}
public void setHogsFragment(Fragment hogsFragment) {
frags[4] = hogsFragment;
}
public Fragment getBugsFragment() {
return frags[3];
}
public void setBugsFragment(Fragment bugsFragment) {
frags[3] = bugsFragment;
}
/**
* A listener that is triggered when a value changes in our defualtSharedPreferences.
* Can be used to do an immediate action whenever one of our items in that hashtable (defualtSharedPreferences) changes.
* Should be registered (in our main activity's onStart()) and unregistered (in onStop())
*/
// private OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Toast.makeText(CaratApplication.getMainActivity(), String.valueOf(sharedPreferences.getBoolean(key, false)), Toast.LENGTH_SHORT).show();
public class PrefetchData extends AsyncTask<Void, Void, Void> {
String serverResponseJson = null;
private final String TAG = "PrefetchData";
@Override
protected Void doInBackground(Void... arg0) {
// Log.d(TAG, "started doInBackground() method of the asyncTask");
JsonParser jsonParser = new JsonParser();
try {
if (CaratApplication.isInternetAvailable()) {
serverResponseJson = jsonParser
.getJSONFromUrl("http://carat.cs.helsinki.fi/statistics-data/stats.json");
}
} catch (Exception e) {
}
if (serverResponseJson != null && serverResponseJson != "") {
try {
JSONArray jsonArray = new JSONObject(serverResponseJson).getJSONArray("android-apps");
// Using Java reflections to set fields by passing their name to a method
try {
setIntFieldsFromJson(jsonArray, 0, "mWellbehaved");
setIntFieldsFromJson(jsonArray, 1, "mHogs");
setIntFieldsFromJson(jsonArray, 2, "mBugs");
if (CaratApplication.mPrefs != null) {
saveStatsToPref();
} else {
// Log.e(TAG, "The shared preference is null (not loaded yet. "
// + "Check CaratApplication's new thread for loading the sharedPref)");
}
// Log.i(TAG, "received JSON: " + "mBugs: " + mWellbehaved
// + ", mHogs: " + mHogs + ", mBugs: " + mBugs);
} catch (IllegalArgumentException e) {
Log.e(TAG, "IllegalArgumentException in setFieldsFromJson()");
} catch (IllegalAccessException e) {
Log.e(TAG, "IllegalAccessException in setFieldsFromJson()");
}
} catch (JSONException e) {
// Log.e(TAG, e.getStackTrace().toString());
}
} else {
// Log.d(TAG, "server response JSON is null.");
}
return null;
}
@SuppressLint("NewApi")
private void saveStatsToPref() {
SharedPreferences.Editor editor = CaratApplication.mPrefs.edit();
// the returned values (from setIntFieldsFromJson()
// might be -1 (Constants.VALUE_NOT_AVAILABLE). So
// when we are reading the following pref values, we
// should check that condition )
editor.putInt(Constants.STATS_WELLBEHAVED_COUNT_PREFERENCE_KEY, mWellbehaved);
editor.putInt(Constants.STATS_HOGS_COUNT_PREFERENCE_KEY, mHogs);
editor.putInt(Constants.STATS_BUGS_COUNT_PREFERENCE_KEY, mBugs);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
editor.apply(); // async (runs in parallel
// in a new shared thread (off the UI thread)
} else {
editor.commit();
}
}
@Override
protected void onPostExecute(Void result) {
// Log.d(TAG, "started the onPostExecute() of the asyncTask");
super.onPostExecute(result);
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
// sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
// Log.d(TAG, "asyncTask.onPstExecute(). mWellbehaved=" + mWellbehaved);
refreshSummaryFragment();
}
/**
* Using Java reflections to set fields by passing their name to a method
* @param jsonArray the json array from which we want to extract different json objects
* @param objIdx the index of the object in the json array
* @param fieldName the name of the field in the current NESTED class (PrefetchData)
*/
private void setIntFieldsFromJson(JSONArray jsonArray, int objIdx, String fieldName)
throws JSONException, IllegalArgumentException, IllegalAccessException {
// Class<? extends PrefetchData> currentClass = this.getClass();
Field field = null;
int res = Constants.VALUE_NOT_AVAILABLE;
try {
// important: getField() can only get PUBLIC fields.
// For private fields, use another method: getDeclaredField(fieldName)
field = /*currentClass.*/ CaratApplication.getMainActivity().getClass().getField(fieldName);
} catch(NoSuchFieldException e) {
// Log.e(TAG, "NoSuchFieldException when trying to get a reference to the field: " + fieldName);
}
if (field != null) {
JSONObject jsonObject = null;
if (jsonArray != null ) {
jsonObject = jsonArray.getJSONObject(objIdx);
if (jsonObject != null && jsonObject.getString("value") != null && jsonObject.getString("value") != "") {
res = Integer.parseInt(jsonObject.getString("value"));
field.set(CaratApplication.getMainActivity()/*this*/, res);
} else {
// Log.e(TAG, "json object (server response) is null: jsonArray(" + objIdx + ")=null (or ='')");
}
}
}
// if an exception occurs, the value of the field would be -1 (Constants.VALUE_NOT_AVAILABLE)
}
}
/**
* Handle physical menu button (e.g. Samsung devices).
*/
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
if (drawerOpen) {
mDrawerLayout.closeDrawers();
} else {
// FIXME: Gravity.Start is not available in API Level 8, so hack below.
int grav = Gravity.TOP|Gravity.LEFT;
if (isRTL())
grav = Gravity.TOP|Gravity.RIGHT;
mDrawerLayout.openDrawer(grav);
}
return true;
} else {
return super.onKeyUp(keyCode, event);
}
}
private static boolean isRTL() {
return isRTL(Locale.getDefault());
}
private static boolean isRTL(Locale locale) {
final int directionality = Character.getDirectionality(locale.getDisplayName().charAt(0));
return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT ||
directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
}
}
|
package edu.umd.cs.findbugs;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import javax.annotation.Nonnull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;
/**
* A DetectorFactory is responsible for creating instances of Detector objects
* and for maintaining meta-information about the detector class.
*
* @author David Hovemeyer
* @see Detector
*/
public class DetectorFactory {
private static final boolean DEBUG_JAVA_VERSION = SystemProperties.getBoolean("findbugs.debug.javaversion");
// Backwards-compatibility: if the Detector has a setAnalysisContext()
// method, call it, passing the current AnalysisContext. We do this
// because some released versions of FindBugs had a Detector
// interface which specified this method (and ensured it was called
// before the Detector was used to analyze any code).
private static final boolean SUPPORT_OLD_DETECTOR_INTERFACE = SystemProperties
.getBoolean("findbugs.support.old.detector.interface");
private static final Class<?>[] constructorArgTypes = new Class<?>[] { BugReporter.class };
static class ReflectionDetectorCreator {
private final Class<?> detectorClass;
private Method setAnalysisContext;
ReflectionDetectorCreator(Class<?> detectorClass) {
this.detectorClass = detectorClass;
if (SUPPORT_OLD_DETECTOR_INTERFACE)
try {
setAnalysisContext = detectorClass.getDeclaredMethod("setAnalysisContext",
new Class[] { AnalysisContext.class });
} catch (NoSuchMethodException e) {
// Ignore
}
}
@Override
public String toString() {
return detectorClass.getSimpleName();
}
public Detector createDetector(BugReporter bugReporter) {
try {
Constructor<?> constructor = detectorClass.getConstructor(constructorArgTypes);
Detector detector = (Detector) constructor.newInstance(new Object[] { bugReporter });
if (setAnalysisContext != null) {
setAnalysisContext.invoke(detector, new Object[] { AnalysisContext.currentAnalysisContext() });
}
return detector;
} catch (Exception e) {
throw new RuntimeException("Could not instantiate " + detectorClass.getName() + " as Detector", e);
}
}
public Detector2 createDetector2(BugReporter bugReporter) {
if (Detector2.class.isAssignableFrom(detectorClass)) {
try {
Constructor<?> constructor = detectorClass.getConstructor(constructorArgTypes);
return (Detector2) constructor.newInstance(new Object[] { bugReporter });
} catch (Exception e) {
throw new RuntimeException("Could not instantiate " + detectorClass.getName() + " as Detector2", e);
}
}
if (Detector.class.isAssignableFrom(detectorClass)) {
if (NonReportingDetector.class.isAssignableFrom(detectorClass))
return new NonReportingDetectorToDetector2Adapter(createDetector(bugReporter));
return new DetectorToDetector2Adapter(createDetector(bugReporter));
}
throw new RuntimeException("Class " + detectorClass.getName() + " is not a detector class");
}
public Class<?> getDetectorClass() {
return detectorClass;
}
}
private final @Nonnull Plugin plugin;
private final ReflectionDetectorCreator detectorCreator;
private final @Nonnull @DottedClassName String className;
private int positionSpecifiedInPluginDescriptor;
private final boolean defEnabled;
private final String speed;
private final String reports;
private final String requireJRE;
private String detailHTML;
private int priorityAdjustment;
private boolean enabledButNonReporting;
private boolean hidden;
/**
* Constructor.
*
* @param plugin
* the Plugin the Detector is part of
* @param className
* TODO
* @param detectorClass
* the Class object of the Detector
* @param enabled
* true if the Detector is enabled by default, false if disabled
* @param speed
* a string describing roughly how expensive the analysis
* performed by the detector is; suggested values are "fast",
* "moderate", and "slow"
* @param reports
* comma separated list of bug pattern codes reported by the
* detector; empty if unknown
* @param requireJRE
* string describing JRE version required to run the the
* detector: e.g., "1.5"
*/
public DetectorFactory(@Nonnull Plugin plugin, @Nonnull String className,
Class<?> detectorClass, boolean enabled, String speed,
String reports, String requireJRE) {
this.plugin = plugin;
this.className = className;
this.detectorCreator = FindBugs.isNoAnalysis() ? null : new ReflectionDetectorCreator(detectorClass);
this.defEnabled = enabled;
this.speed = speed;
this.reports = reports;
this.requireJRE = requireJRE;
this.priorityAdjustment = 0;
this.hidden = false;
}
@Override
public String toString() {
return getShortName();
}
/**
* Set the overall position in which this detector was specified in the
* plugin descriptor.
*
* @param positionSpecifiedInPluginDescriptor
* position in plugin descriptor
*/
public void setPositionSpecifiedInPluginDescriptor(int positionSpecifiedInPluginDescriptor) {
this.positionSpecifiedInPluginDescriptor = positionSpecifiedInPluginDescriptor;
}
/**
* Get the overall position in which this detector was specified in the
* plugin descriptor.
*
* @return position in plugin descriptor
*/
public int getPositionSpecifiedInPluginDescriptor() {
return positionSpecifiedInPluginDescriptor;
}
/**
* Get the Plugin that this Detector is part of.
*
* @return the Plugin this Detector is part of
*/
public Plugin getPlugin() {
return plugin;
}
/**
* Determine whether the detector class is a subtype of the given class (or
* interface).
*
* @param otherClass
* a class or interface
* @return true if the detector class is a subtype of the given class or
* interface
*/
public boolean isDetectorClassSubtypeOf(Class<?> otherClass) {
if (FindBugs.isNoAnalysis())
throw new IllegalStateException("No analysis specified");
return otherClass.isAssignableFrom(detectorCreator.getDetectorClass());
}
/**
* Return whether or not this DetectorFactory produces detectors which
* report warnings.
*
* @return true if the created Detectors report warnings, false if not
*/
public boolean isReportingDetector() {
return !isDetectorClassSubtypeOf(TrainingDetector.class) && !isDetectorClassSubtypeOf(NonReportingDetector.class);
}
/**
* Check to see if we are running on a recent-enough JRE for this detector
* to be enabled.
*
* @return true if the current JRE is recent enough to run the Detector,
* false if it is too old
*/
public boolean isEnabledForCurrentJRE() {
if (requireJRE.equals(""))
return true;
try {
JavaVersion requiredVersion = new JavaVersion(requireJRE);
JavaVersion runtimeVersion = JavaVersion.getRuntimeVersion();
if (DEBUG_JAVA_VERSION) {
System.out.println("Checking JRE version for " + getShortName() + " (requires " + requiredVersion
+ ", running on " + runtimeVersion + ")");
}
boolean enabledForCurrentJRE = runtimeVersion.isSameOrNewerThan(requiredVersion);
if (DEBUG_JAVA_VERSION) {
System.out.println("\t==> " + enabledForCurrentJRE);
}
return enabledForCurrentJRE;
} catch (JavaVersionException e) {
if (DEBUG_JAVA_VERSION) {
System.out.println("Couldn't check Java version: " + e.toString());
e.printStackTrace(System.out);
}
return false;
}
}
/**
* Set visibility of the factory (to GUI dialogs to configure detectors).
* Invisible detectors are those that are needed behind the scenes, but
* shouldn't be explicitly enabled or disabled by the user.
*
* @param hidden
* true if this factory should be hidden, false if not
*/
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
/**
* Get visibility of the factory (to GUI dialogs to configure detectors).
*/
public boolean isHidden() {
return hidden;
}
/**
* Is this factory enabled by default
*/
public boolean isDefaultEnabled() {
return defEnabled;
}
/**
* Set the priority adjustment for the detector produced by this factory.
*
* @param priorityAdjustment
* the priority adjustment
*/
public void setPriorityAdjustment(int priorityAdjustment) {
this.priorityAdjustment = priorityAdjustment;
}
public void setEnabledButNonReporting(boolean notReporting) {
this.enabledButNonReporting = notReporting;
}
/**
* Get the priority adjustment for the detector produced by this factory.
*
* @return the priority adjustment
*/
public int getPriorityAdjustment() {
if (enabledButNonReporting)
return 100;
return priorityAdjustment;
}
/**
* Get the speed of the Detector produced by this factory.
*/
@Deprecated
public String getSpeed() {
return speed;
}
/**
* Get list of bug pattern codes reported by the detector: empty if unknown.
*/
public String getReportedBugPatternCodes() {
return reports;
}
/**
* Get set of all BugPatterns this detector reports. An empty set means that
* we don't know what kind of bug patterns might be reported.
*/
public Set<BugPattern> getReportedBugPatterns() {
Set<BugPattern> result = new TreeSet<BugPattern>();
StringTokenizer tok = new StringTokenizer(reports, ",");
while (tok.hasMoreTokens()) {
String type = tok.nextToken();
BugPattern bugPattern = DetectorFactoryCollection.instance().lookupBugPattern(type);
if (bugPattern != null)
result.add(bugPattern);
}
return result;
}
/**
* Get an HTML document describing the Detector.
*/
public String getDetailHTML() {
return detailHTML;
}
/**
* Set the HTML document describing the Detector.
*/
public void setDetailHTML(String detailHTML) {
this.detailHTML = detailHTML;
}
/**
* Create a Detector instance. This method is only guaranteed to work for
* old-style detectors using the BCEL bytecode framework.
*
* @param bugReporter
* the BugReporter to be used to report bugs
* @return the Detector
* @deprecated Use createDetector2 in new code
*/
@Deprecated
public Detector create(BugReporter bugReporter) {
if (FindBugs.isNoAnalysis())
throw new IllegalStateException("No analysis specified");
return detectorCreator.createDetector(bugReporter);
}
/**
* Create a Detector2 instance.
*
* @param bugReporter
* the BugReporter to be used to report bugs
* @return the Detector2
*/
public Detector2 createDetector2(BugReporter bugReporter) {
if (FindBugs.isNoAnalysis())
throw new IllegalStateException("No analysis specified");
return detectorCreator.createDetector2(bugReporter);
}
/**
* Get the short name of the Detector. This is the name of the detector
* class without the package qualification.
*/
public String getShortName() {
int endOfPkg = className.lastIndexOf('.');
if (endOfPkg >= 0)
return className.substring(endOfPkg + 1);
return className;
}
/**
* Get the full name of the detector. This is the name of the detector
* class, with package qualification.
*/
public @Nonnull @DottedClassName
String getFullName() {
return className;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + className.hashCode();
result = prime * result + plugin.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DetectorFactory)) {
return false;
}
DetectorFactory other = (DetectorFactory) obj;
if (!className.equals(other.className)) {
return false;
}
if (!plugin.equals(other.plugin)) {
return false;
}
return true;
}
}
|
// $Revision: 1.9 $
package edu.umd.cs.findbugs.graph;
/**
* GraphEdge interface; represents an edge in a graph.
*/
public interface GraphEdge
<
ActualEdgeType extends GraphEdge<ActualEdgeType, VertexType>,
VertexType extends GraphVertex<VertexType>
>
extends Comparable<ActualEdgeType> {
/**
* Get the source vertex.
*/
public VertexType getSource();
/**
* Get the target vertex.
*/
public VertexType getTarget();
/**
* Get the integer label.
*/
public int getLabel();
/**
* Set the integer label.
*/
public void setLabel(int label);
}
// vim:ts=4
|
package edu.umd.cs.findbugs.gui2;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPInputStream;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.FontUIResource;
import javax.swing.plaf.basic.BasicTreeUI;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.text.JTextComponent;
import javax.swing.text.TextAction;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import edu.umd.cs.findbugs.BugAnnotation;
import edu.umd.cs.findbugs.BugCollection;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.ClassAnnotation;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.FindBugsDisplayFeatures;
import edu.umd.cs.findbugs.I18N;
import edu.umd.cs.findbugs.MethodAnnotation;
import edu.umd.cs.findbugs.PackageMemberAnnotation;
import edu.umd.cs.findbugs.Project;
import edu.umd.cs.findbugs.SortedBugCollection;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.SuppressionMatcher;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.SourceFinder;
import edu.umd.cs.findbugs.filter.Filter;
import edu.umd.cs.findbugs.filter.LastVersionMatcher;
import edu.umd.cs.findbugs.filter.Matcher;
import edu.umd.cs.findbugs.gui.ConsoleLogger;
import edu.umd.cs.findbugs.gui.LogSync;
import edu.umd.cs.findbugs.gui.Logger;
import edu.umd.cs.findbugs.gui2.BugTreeModel.BranchOperationException;
import edu.umd.cs.findbugs.gui2.BugTreeModel.TreeModification;
import edu.umd.cs.findbugs.sourceViewer.NavigableTextPane;
@SuppressWarnings("serial")
/*
* This is where it all happens... seriously... all of it...
* All the menus are set up, all the listeners, all the frames, dockable window functionality
* There is no one style used, no one naming convention, its all just kinda here. This is another one of those
* classes where no one knows quite why it works.
*/
/**
* The MainFrame is just that, the main application window where just about everything happens.
*/
public class MainFrame extends FBFrame implements LogSync
{
static JButton newButton(String key, String name) {
JButton b = new JButton();
edu.umd.cs.findbugs.L10N.localiseButton(b, key, name, false);
return b;
}
static JMenuItem newJMenuItem(String key, String string, int vkF) {
JMenuItem m = new JMenuItem();
edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, false);
m.setMnemonic(vkF);
return m;
}
static JMenuItem newJMenuItem(String key, String string) {
JMenuItem m = new JMenuItem();
edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, true);
return m;
}
static JMenu newJMenu(String key, String string) {
JMenu m = new JMenu();
edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, true);
return m;
}
JTree tree;
private BasicTreeUI treeUI;
boolean userInputEnabled;
static boolean isMacLookAndFeel() {
return UIManager.getLookAndFeel().getClass().getName().startsWith("apple");
}
static final String DEFAULT_SOURCE_CODE_MSG = edu.umd.cs.findbugs.L10N.getLocalString("msg.nosource_txt", "No available source");
static final int COMMENTS_TAB_STRUT_SIZE = 5;
static final int COMMENTS_MARGIN = 5;
static final int SEARCH_TEXT_FIELD_SIZE = 32;
static final String TITLE_START_TXT = "FindBugs: ";
private JTextField sourceSearchTextField = new JTextField(SEARCH_TEXT_FIELD_SIZE);
private JButton findButton = newButton("button.find", "Find");
private JButton findNextButton = newButton("button.findNext", "Find Next");
private JButton findPreviousButton = newButton("button.findPrev", "Find Previous");
public static final boolean DEBUG = SystemProperties.getBoolean("gui2.debug");
static final boolean MAC_OS_X = SystemProperties.getProperty("os.name").toLowerCase().startsWith("mac os x");
final static String WINDOW_MODIFIED = "windowModified";
NavigableTextPane sourceCodeTextPane = new NavigableTextPane();
private JScrollPane sourceCodeScrollPane;
final CommentsArea comments;
private SorterTableColumnModel sorter;
private JTableHeader tableheader;
private JLabel statusBarLabel = new JLabel();
private JPanel summaryTopPanel;
private final HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
private final JEditorPane summaryHtmlArea = new JEditorPane();
private JScrollPane summaryHtmlScrollPane = new JScrollPane(summaryHtmlArea);
final private FindBugsLayoutManagerFactory findBugsLayoutManagerFactory;
final private FindBugsLayoutManager guiLayout;
/* To change this value must use setProjectChanged(boolean b).
* This is because saveProjectItemMenu is dependent on it for when
* saveProjectMenuItem should be enabled.
*/
boolean projectChanged = false;
final private JMenuItem reconfigMenuItem = newJMenuItem("menu.reconfig", "Reconfigure...", KeyEvent.VK_F);
private JMenuItem redoAnalysis;
BugLeafNode currentSelectedBugLeaf;
BugAspects currentSelectedBugAspects;
private JPopupMenu bugPopupMenu;
private JPopupMenu branchPopupMenu;
private static MainFrame instance;
private RecentMenu recentMenuCache;
private JMenu recentMenu;
private JMenuItem preferencesMenuItem;
private Project curProject = new Project();
private JScrollPane treeScrollPane;
SourceFinder sourceFinder;
private Object lock = new Object();
private boolean newProject = false;
private Class osxAdapter;
private Method osxPrefsEnableMethod;
private Logger logger = new ConsoleLogger(this);
SourceCodeDisplay displayer = new SourceCodeDisplay(this);
private SaveType saveType = SaveType.NOT_KNOWN;
FBFileChooser saveOpenFileChooser;
@CheckForNull private File saveFile = null;
enum SaveReturn {SAVE_SUCCESSFUL, SAVE_IO_EXCEPTION, SAVE_ERROR};
JMenuItem saveMenuItem = newJMenuItem("menu.save_item", "Save", KeyEvent.VK_S);
static void makeInstance(FindBugsLayoutManagerFactory factory) {
if (instance != null) throw new IllegalStateException();
instance=new MainFrame(factory);
instance.initializeGUI();
}
/**
* @param string
* @param vkF
* @return
*/
static MainFrame getInstance() {
if (instance==null) throw new IllegalStateException();
return instance;
}
private void initializeGUI() {
SwingUtilities.invokeLater(new InitializeGUI());
}
private MainFrame(FindBugsLayoutManagerFactory factory)
{
this.findBugsLayoutManagerFactory = factory;
this.guiLayout = factory.getInstance(this);
this.comments = new CommentsArea(this);
FindBugsDisplayFeatures.setAbridgedMessages(true);
}
/**
* Show About
*/
void about() {
AboutDialog dialog = new AboutDialog(this, logger, true);
dialog.setSize(600, 554);
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
}
/**
* Show Preferences
*/
void preferences() {
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
PreferencesFrame.getInstance().setLocationRelativeTo(MainFrame.this);
PreferencesFrame.getInstance().setVisible(true);
}
/**
* enable/disable preferences menu
*/
void enablePreferences(boolean b) {
preferencesMenuItem.setEnabled(b);
if (MAC_OS_X) {
if (osxPrefsEnableMethod != null) {
Object args[] = {Boolean.valueOf(b)};
try {
osxPrefsEnableMethod.invoke(osxAdapter, args);
}
catch (Exception e) {
System.err.println("Exception while enabling Preferences menu: " + e);
}
}
}
}
/**
* This method is called when the application is closing. This is either by
* the exit menuItem or by clicking on the window's system menu.
*/
void callOnClose(){
comments.saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
if(projectChanged){
int value = JOptionPane.showConfirmDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("msg.you_are_closing_txt", "You are closing") + " " +
edu.umd.cs.findbugs.L10N.getLocalString("msg.without_saving_txt", "without saving. Do you want to save?"),
edu.umd.cs.findbugs.L10N.getLocalString("msg.confirm_save_txt", "Do you want to save?"), JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(value == JOptionPane.CANCEL_OPTION || value == JOptionPane.CLOSED_OPTION)
return ;
else if(value == JOptionPane.YES_OPTION){
if(saveFile == null){
if(!saveAs())
return;
}
else
save();
}
}
GUISaveState.getInstance().setPreviousComments(comments.prevCommentsList);
guiLayout.saveState();
GUISaveState.getInstance().setFrameBounds( getBounds() );
GUISaveState.getInstance().save();
System.exit(0);
}
/*
* A lot of if(false) here is for switching from special cases based on localSaveType
* to depending on the SaveType.forFile(f) method. Can delete when sure works.
*/
JMenuItem createRecentItem(final File f, final SaveType localSaveType)
{
if (DEBUG) System.out.println("createRecentItem("+f+", "+localSaveType +")");
String name = f.getName();
final JMenuItem item=new JMenuItem(name);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
setCursor(new Cursor(Cursor.WAIT_CURSOR));
if (!f.exists())
{
JOptionPane.showMessageDialog(null,edu.umd.cs.findbugs.L10N.getLocalString("msg.proj_not_found", "This project can no longer be found"));
GUISaveState.getInstance().fileNotFound(f);
return;
}
GUISaveState.getInstance().fileReused(f);//Move to front in GUISaveState, so it will be last thing to be removed from the list
MainFrame.this.recentMenuCache.addRecentFile(f);
if (!f.exists())
throw new IllegalStateException ("User used a recent projects menu item that didn't exist.");
//Moved this outside of the thread, and above the line saveFile=f.getParentFile()
//Since if this save goes on in the thread below, there is no way to stop the save from
//overwriting the files we are about to load.
if (curProject != null && projectChanged)
{
int response = JOptionPane.showConfirmDialog(MainFrame.this,
edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_current_changes", "The current project has been changed, Save current changes?")
,edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_changes", "Save Changes?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.YES_OPTION)
{
if(saveFile != null)
save();
else
saveAs();
}
else if (response == JOptionPane.CANCEL_OPTION)
return;
//IF no, do nothing.
}
SaveType st = SaveType.forFile(f);
boolean result = true;
switch(st){
case PROJECT:
openProject(f);
break;
case XML_ANALYSIS:
result = openAnalysis(f, st);
break;
case FBP_FILE:
result = openFBPFile(f);
break;
case FBA_FILE:
result = openFBAFile(f);
break;
default:
error("Wrong file type in recent menu item.");
}
if(!result){
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"There was an error in opening the file", "Recent Menu Opening Error",
JOptionPane.WARNING_MESSAGE);
}
}
finally
{
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
setSaveType(localSaveType);
}
}
});
item.setFont(item.getFont().deriveFont(Driver.getFontSize()));
return item;
}
BugCollection bugCollection;
@SwingThread
void setProjectAndBugCollection(Project project, @CheckForNull BugCollection bugCollection) {
Filter suppressionMatcher = project.getSuppressionFilter();
if (suppressionMatcher != null) {
suppressionMatcher.softAdd(LastVersionMatcher.DEAD_BUG_MATCHER);
}
// setRebuilding(false);
if (bugCollection == null) {
showTreeCard();
} else {
curProject = project;
this.bugCollection = bugCollection;
displayer.clearCache();
BugTreeModel model = (BugTreeModel) getTree().getModel();
setSourceFinder(new SourceFinder());
getSourceFinder().setSourceBaseList(project.getSourceDirList());
BugSet bs = new BugSet(bugCollection);
model.getOffListenerList();
model.changeSet(bs);
if (bs.size() == 0 && bs.sizeUnfiltered() > 0) {
warnUserOfFilters();
}
updateStatusBar();
}
PreferencesFrame.getInstance().updateFilterPanel();
setProjectChanged(false);
reconfigMenuItem.setEnabled(true);
newProject();
clearSourcePane();
clearSummaryTab();
/* This is here due to a threading issue. It can only be called after
* curProject has been changed. Since this method is called by both open methods
* it is put here.*/
changeTitle();
}
void updateProjectAndBugCollection(Project project, BugCollection bugCollection, BugTreeModel previousModel) {
setRebuilding(false);
if (bugCollection != null)
{
displayer.clearCache();
BugSet bs = new BugSet(bugCollection);
//Dont clear data, the data's correct, just get the tree off the listener lists.
((BugTreeModel) tree.getModel()).getOffListenerList();
((BugTreeModel)tree.getModel()).changeSet(bs);
//curProject=BugLoader.getLoadedProject();
setProjectChanged(true);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
/**
* Changes the title based on curProject and saveFile.
*
*/
public void changeTitle(){
String name = curProject.getProjectName();
if(name == null && saveFile != null)
name = saveFile.getAbsolutePath();
if(name == null)
name = Project.UNNAMED_PROJECT;
MainFrame.this.setTitle(TITLE_START_TXT + name);
}
/**
* Creates popup menu for bugs on tree.
* @return
*/
private JPopupMenu createBugPopupMenu() {
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem filterMenuItem = newJMenuItem("menu.filterBugsLikeThis", "Filter bugs like this");
filterMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
new NewFilterFromBug(currentSelectedBugLeaf.getBug());
setProjectChanged(true);
MainFrame.getInstance().getTree().setSelectionRow(0);//Selects the top of the Jtree so the CommentsArea syncs up.
}
});
popupMenu.add(filterMenuItem);
JMenu changeDesignationMenu = newJMenu("menu.changeDesignation", "Change bug designation");
int i = 0;
int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9};
for(String key : I18N.instance().getUserDesignationKeys(true)) {
String name = I18N.instance().getUserDesignation(key);
comments.addDesignationItem(changeDesignationMenu, name, keyEvents[i++]);
}
popupMenu.add(changeDesignationMenu);
return popupMenu;
}
/**
* Creates the branch pop up menu that ask if the user wants
* to hide all the bugs in that branch.
* @return
*/
private JPopupMenu createBranchPopUpMenu(){
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem filterMenuItem = newJMenuItem("menu.filterTheseBugs", "Filter these bugs");
filterMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
//TODO This code does a smarter version of filtering that is only possible for branches, and does so correctly
//However, it is still somewhat of a hack, because if we ever add more tree listeners than simply the bugtreemodel,
//They will not be called by this code. Using FilterActivity to notify all listeners will however destroy any
//benefit of using the smarter deletion method.
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
int startCount;
TreePath path=MainFrame.getInstance().getTree().getSelectionPath();
TreePath deletePath=path;
startCount=((BugAspects)(path.getLastPathComponent())).getCount();
int count=((BugAspects)(path.getParentPath().getLastPathComponent())).getCount();
while(count==startCount)
{
deletePath=deletePath.getParentPath();
if (deletePath.getParentPath()==null)//We are at the top of the tree, don't let this be removed, rebuild tree from root.
{
Matcher m = currentSelectedBugAspects.getMatcher();
Filter suppressionFilter = MainFrame.getInstance().getProject().getSuppressionFilter();
suppressionFilter.addChild(m);
PreferencesFrame.getInstance().updateFilterPanel();
FilterActivity.notifyListeners(FilterListener.Action.FILTERING, null);
return;
}
count=((BugAspects)(deletePath.getParentPath().getLastPathComponent())).getCount();
}
/*
deletePath should now be a path to the highest
ancestor branch with the same number of elements
as the branch to be deleted
in other words, the branch that we actually have
to remove in order to correctly remove the selected branch.
*/
BugTreeModel model=MainFrame.getInstance().getBugTreeModel();
TreeModelEvent event=new TreeModelEvent(this,deletePath.getParentPath(),
new int[]{model.getIndexOfChild(deletePath.getParentPath().getLastPathComponent(),deletePath.getLastPathComponent())},
new Object[]{deletePath.getLastPathComponent()});
Matcher m = currentSelectedBugAspects.getMatcher();
Filter suppressionFilter = MainFrame.getInstance().getProject().getSuppressionFilter();
suppressionFilter.addChild(m);
PreferencesFrame.getInstance().updateFilterPanel();
model.sendEvent(event, TreeModification.REMOVE);
// FilterActivity.notifyListeners(FilterListener.Action.FILTERING, null);
setProjectChanged(true);
MainFrame.getInstance().getTree().setSelectionRow(0);//Selects the top of the Jtree so the CommentsArea syncs up.
}
});
popupMenu.add(filterMenuItem);
JMenu changeDesignationMenu = newJMenu("menu.changeDesignation", "Change bug designation");
int i = 0;
int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9};
for(String key : I18N.instance().getUserDesignationKeys(true)) {
String name = I18N.instance().getUserDesignation(key);
addDesignationItem(changeDesignationMenu, name, keyEvents[i++]);
}
popupMenu.add(changeDesignationMenu);
return popupMenu;
}
/**
* Creates the MainFrame's menu bar.
* @return the menu bar for the MainFrame
*/
protected JMenuBar createMainMenuBar() {
JMenuBar menuBar = new JMenuBar();
//Create JMenus for menuBar.
JMenu fileMenu = newJMenu("menu.file_menu", "File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenu editMenu = newJMenu("menu.edit_menu", "Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
//Edit fileMenu JMenu object.
JMenuItem newProjectMenuItem = newJMenuItem("menu.new_item", "New Project", KeyEvent.VK_N);
JMenuItem openMenuItem = newJMenuItem("menu.open_item", "Open...", KeyEvent.VK_O);
recentMenu = newJMenu("menu.recent", "Recent");
recentMenuCache=new RecentMenu(recentMenu);
JMenuItem saveAsMenuItem = newJMenuItem("menu.saveas_item", "Save As...", KeyEvent.VK_A);;
redoAnalysis = newJMenuItem("menu.rerunAnalysis", "Redo Analysis", KeyEvent.VK_R);
JMenuItem exitMenuItem = null;
if (!MAC_OS_X) {
exitMenuItem = newJMenuItem("menu.exit", "Exit", KeyEvent.VK_X);
exitMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
callOnClose();
}
});
}
JMenu windowMenu = guiLayout.createWindowMenu();
attachAcceleratorKey(newProjectMenuItem, KeyEvent.VK_N);
newProjectMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
newProjectMenu();
}
});
reconfigMenuItem.setEnabled(false);
attachAcceleratorKey(reconfigMenuItem, KeyEvent.VK_F);
reconfigMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
new NewProjectWizard(curProject);
}
});
JMenuItem mergeMenuItem = newJMenuItem("menu.mergeAnalysis", "Merge Analysis...");
mergeMenuItem.setEnabled(true);
mergeMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
mergeAnalysis();
}
});
redoAnalysis.setEnabled(false);
attachAcceleratorKey(redoAnalysis, KeyEvent.VK_R);
redoAnalysis.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
redoAnalysis();
}
});
openMenuItem.setEnabled(true);
attachAcceleratorKey(openMenuItem, KeyEvent.VK_O);
openMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
open();
}
});
saveAsMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
saveAs();
}
});
saveMenuItem.setEnabled(false);
attachAcceleratorKey(saveMenuItem, KeyEvent.VK_S);
saveMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
save();
}
});
fileMenu.add(newProjectMenuItem);
fileMenu.add(reconfigMenuItem);
fileMenu.addSeparator();
fileMenu.add(openMenuItem);
fileMenu.add(recentMenu);
fileMenu.addSeparator();
fileMenu.add(saveAsMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(redoAnalysis);
// fileMenu.add(mergeMenuItem);
//TODO: This serves no purpose but to test something
if(false){
JMenuItem temp = new JMenuItem("Temp");
temp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
System.out.println("Current Project Name: " + curProject.getProjectName());
}
});
fileMenu.add(temp);
}
if (exitMenuItem != null) {
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
}
menuBar.add(fileMenu);
//Edit editMenu Menu object.
JMenuItem cutMenuItem = new JMenuItem(new CutAction());
JMenuItem copyMenuItem = new JMenuItem(new CopyAction());
JMenuItem pasteMenuItem = new JMenuItem(new PasteAction());
preferencesMenuItem = newJMenuItem("menu.preferences_menu", "Filters/Suppressions...");
JMenuItem sortMenuItem = newJMenuItem("menu.sortConfiguration", "Sort Configuration...");
JMenuItem goToLineMenuItem = newJMenuItem("menu.gotoLine", "Go to line...");
attachAcceleratorKey(cutMenuItem, KeyEvent.VK_X);
attachAcceleratorKey(copyMenuItem, KeyEvent.VK_C);
attachAcceleratorKey(pasteMenuItem, KeyEvent.VK_V);
preferencesMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
preferences();
}
});
sortMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
SorterDialog.getInstance().setLocationRelativeTo(MainFrame.this);
SorterDialog.getInstance().setVisible(true);
}
});
attachAcceleratorKey(goToLineMenuItem, KeyEvent.VK_L);
goToLineMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
guiLayout.makeSourceVisible();
try{
int num = Integer.parseInt(JOptionPane.showInputDialog(MainFrame.this, "", edu.umd.cs.findbugs.L10N.getLocalString("dlg.go_to_line_lbl", "Go To Line") + ":", JOptionPane.QUESTION_MESSAGE));
displayer.showLine(num);
}
catch(NumberFormatException e){}
}});
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
editMenu.addSeparator();
editMenu.add(goToLineMenuItem);
editMenu.addSeparator();
//editMenu.add(selectAllMenuItem);
// editMenu.addSeparator();
if (!MAC_OS_X) {
// Preferences goes in Findbugs menu and is handled by OSXAdapter
editMenu.add(preferencesMenuItem);
}
editMenu.add(sortMenuItem);
menuBar.add(editMenu);
if (windowMenu != null)
menuBar.add(windowMenu);
final ActionMap map = tree.getActionMap();
JMenu navMenu = newJMenu("menu.navigation", "Navigation");
addNavItem(map, navMenu, "menu.expand", "Expand", "expand", KeyEvent.VK_RIGHT );
addNavItem(map, navMenu, "menu.collapse", "Collapse", "collapse", KeyEvent.VK_LEFT);
addNavItem(map, navMenu, "menu.up", "Up", "selectPrevious", KeyEvent.VK_UP );
addNavItem(map, navMenu, "menu.down", "Down", "selectNext", KeyEvent.VK_DOWN);
menuBar.add(navMenu);
JMenu designationMenu = newJMenu("menu.designation", "Designation");
int i = 0;
int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9};
for(String key : I18N.instance().getUserDesignationKeys(true)) {
String name = I18N.instance().getUserDesignation(key);
addDesignationItem(designationMenu, name, keyEvents[i++]);
}
menuBar.add(designationMenu);
if (!MAC_OS_X) {
// On Mac, 'About' appears under Findbugs menu, so no need for it here
JMenu helpMenu = newJMenu("menu.help_menu", "Help");
JMenuItem aboutItem = newJMenuItem("menu.about_item", "About FindBugs");
helpMenu.add(aboutItem);
aboutItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
about();
}
});
menuBar.add(helpMenu);
}
return menuBar;
}
/**
* @param map
* @param navMenu
*/
private void addNavItem(final ActionMap map, JMenu navMenu, String menuNameKey, String menuNameDefault, String actionName, int keyEvent) {
JMenuItem toggleItem = newJMenuItem(menuNameKey, menuNameDefault);
toggleItem.addActionListener(treeActionAdapter(map, actionName));
attachAcceleratorKey(toggleItem, keyEvent);
navMenu.add(toggleItem);
}
ActionListener treeActionAdapter(ActionMap map, String actionName) {
final Action selectPrevious = map.get(actionName);
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.setSource(tree);
selectPrevious.actionPerformed(e);
}};
}
static void attachAcceleratorKey(JMenuItem item, int keystroke) {
attachAcceleratorKey(item, keystroke, 0);
}
static void attachAcceleratorKey(JMenuItem item, int keystroke,
int additionalMask) {
// As far as I know, Mac is the only platform on which it is normal
// practice to use accelerator masks such as Shift and Alt, so
// if we're not running on Mac, just ignore them
if (!MAC_OS_X && additionalMask != 0) {
return;
}
item.setAccelerator(KeyStroke.getKeyStroke(keystroke, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | additionalMask));
}
void newProject(){
clearSourcePane();
redoAnalysis.setEnabled(true);
if(newProject){
setProjectChanged(true);
// setTitle(TITLE_START_TXT + Project.UNNAMED_PROJECT);
saveFile = null;
saveMenuItem.setEnabled(false);
reconfigMenuItem.setEnabled(true);
newProject=false;
}
}
/**
* This method is for when the user wants to open a file.
*/
private void open(){
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
if (projectChanged)
{
int response = JOptionPane.showConfirmDialog(MainFrame.this,
edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_current_changes", "The current project has been changed, Save current changes?")
,edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_changes", "Save Changes?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.YES_OPTION)
{
if (saveFile!=null)
save();
else
saveAs();
}
else if (response == JOptionPane.CANCEL_OPTION)
return;
//IF no, do nothing.
}
boolean loading = true;
SaveType fileType = SaveType.NOT_KNOWN;
tryAgain: while (loading)
{
int value=saveOpenFileChooser.showOpenDialog(MainFrame.this);
if(value!=JFileChooser.APPROVE_OPTION) return;
loading = false;
fileType = convertFilterToType(saveOpenFileChooser.getFileFilter());
final File f = saveOpenFileChooser.getSelectedFile();
if(!fileType.isValid(f)){
JOptionPane.showMessageDialog(saveOpenFileChooser,
"That file is not compatible with the choosen file type", "Invalid File",
JOptionPane.WARNING_MESSAGE);
loading = true;
continue;
}
switch (fileType) {
case PROJECT:
File xmlFile = OriginalGUI2ProjectFile.fileContainingXMLData(f);
if (!xmlFile.exists())
{
JOptionPane.showMessageDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.no_xml_data_lbl", "This directory does not contain saved bug XML data, please choose a different directory."));
loading=true;
continue tryAgain;
}
openProject(f);
break;
case XML_ANALYSIS:
if(!f.getName().endsWith(".xml")){
JOptionPane.showMessageDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.not_xml_data_lbl", "This is not a saved bug XML data file."));
loading=true;
continue tryAgain;
}
if(!openAnalysis(f, fileType)){
//TODO: Deal if something happens when loading analysis
JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis.");
loading=true;
continue tryAgain;
}
break;
case FBP_FILE:
if(!openFBPFile(f)){
//TODO: Deal if something happens when loading analysis
JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis.");
loading=true;
continue tryAgain;
}
break;
case FBA_FILE:
if(!openFBAFile(f)){
//TODO: Deal if something happens when loading analysis
JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis.");
loading=true;
continue tryAgain;
}
break;
}
}
}
/**
* Method called to open FBA file.
* @param f
* @return
*/
private boolean openFBAFile(File f) {
return openAnalysis(f, SaveType.FBA_FILE);
}
/**
* Method called to open FBP file.
* @param f
* @return
*/
private boolean openFBPFile(File f) {
if (!f.exists() || !f.canRead()) {
return false;
}
prepareForFileLoad(f, SaveType.FBP_FILE);
loadProjectFromFile(f);
return true;
}
private boolean saveAs(){
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
saveOpenFileChooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.saveas_ttl", "Save as..."));
if (curProject==null)
{
JOptionPane.showMessageDialog(MainFrame.this,edu.umd.cs.findbugs.L10N.getLocalString("dlg.no_proj_save_lbl", "There is no project to save"));
return false;
}
boolean retry = true;
SaveType fileType = SaveType.NOT_KNOWN;
boolean alreadyExists = true;
File f = null;
while(retry){
retry = false;
int value=saveOpenFileChooser.showSaveDialog(MainFrame.this);
if (value!=JFileChooser.APPROVE_OPTION) return false;
fileType = convertFilterToType(saveOpenFileChooser.getFileFilter());
if(fileType == SaveType.NOT_KNOWN){
Debug.println("Error! fileType == SaveType.NOT_KNOWN");
//This should never happen b/c saveOpenFileChooser can only display filters
//given it.
retry = true;
continue;
}
f = saveOpenFileChooser.getSelectedFile();
f = convertFile(f, fileType);
if(!fileType.isValid(f)){
JOptionPane.showMessageDialog(saveOpenFileChooser,
"That file is not compatible with the chosen file type", "Invalid File",
JOptionPane.WARNING_MESSAGE);
retry = true;
continue;
}
alreadyExists = fileAlreadyExists(f, fileType);
if(alreadyExists){
int response = -1;
switch(fileType){
case XML_ANALYSIS:
response = JOptionPane.showConfirmDialog(saveOpenFileChooser,
edu.umd.cs.findbugs.L10N.getLocalString("dlg.analysis_exists_lbl", "This analysis already exists.\nReplace it?"),
edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
break;
case PROJECT:
response = JOptionPane.showConfirmDialog(saveOpenFileChooser,
edu.umd.cs.findbugs.L10N.getLocalString("dlg.proj_already_exists_lbl", "This project already exists.\nDo you want to replace it?"),
edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
break;
case FBP_FILE:
response = JOptionPane.showConfirmDialog(saveOpenFileChooser,
edu.umd.cs.findbugs.L10N.getLocalString("FB Project File already exists", "This FB project file already exists.\nDo you want to replace it?"),
edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
break;
case FBA_FILE:
response = JOptionPane.showConfirmDialog(saveOpenFileChooser,
edu.umd.cs.findbugs.L10N.getLocalString("FB Analysis File already exists", "This FB analysis file already exists.\nDo you want to replace it?"),
edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
break;
}
if(response == JOptionPane.OK_OPTION)
retry = false;
if(response == JOptionPane.CANCEL_OPTION){
retry = true;
continue;
}
}
SaveReturn successful = SaveReturn.SAVE_ERROR;
switch(fileType){
case PROJECT:
successful = saveProject(f);
break;
case XML_ANALYSIS:
successful = saveAnalysis(f);
break;
case FBA_FILE:
successful = saveFBAFile(f);
break;
case FBP_FILE:
successful = saveFBPFile(f);
break;
}
if (successful != SaveReturn.SAVE_SUCCESSFUL)
{
JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.saving_error_lbl", "An error occurred in saving."));
return false;
}
}
// saveProjectMenuItem.setEnabled(false);
saveMenuItem.setEnabled(false);
setSaveType(fileType);
saveFile = f;
File xmlFile;
if (getSaveType()==SaveType.PROJECT)
xmlFile=new File(f.getAbsolutePath() + File.separator + f.getName() + ".xml");
else
xmlFile=f;
addFileToRecent(xmlFile, getSaveType());
return true;
}
/*
* Returns SaveType equivalent depending on what kind of FileFilter passed.
*/
private SaveType convertFilterToType(FileFilter f){
if (f instanceof FindBugsFileFilter)
return ((FindBugsFileFilter)f).getSaveType();
return SaveType.NOT_KNOWN;
}
/*
* Depending on File and SaveType determines if f already exists. Returns false if not
* exist, true otherwise. For a project calls
* OriginalGUI2ProjectFile.fileContainingXMLData(f).exists
*/
private boolean fileAlreadyExists(File f, SaveType fileType){
if(fileType == SaveType.PROJECT){
/*File xmlFile=new File(f.getAbsolutePath() + File.separator + f.getName() + ".xml");
File fasFile=new File(f.getAbsolutePath() + File.separator + f.getName() + ".fas");
return xmlFile.exists() || fasFile.exists();*/
return (OriginalGUI2ProjectFile.fileContainingXMLData(f).exists());
}
return f.exists();
}
/*
* If f is not of type FileType will convert file so it is.
*/
private File convertFile(File f, SaveType fileType){
//WARNING: This assumes the filefilter for project is working so f can only be a directory.
if(fileType == SaveType.PROJECT)
return f;
//Checks that it has the correct file extension, makes a new file if it doesn't.
if(!f.getName().endsWith(fileType.getFileExtension()))
f = new File(f.getAbsolutePath() + fileType.getFileExtension());
return f;
}
private void save(){
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
SaveReturn result = SaveReturn.SAVE_ERROR;
switch(getSaveType()){
case PROJECT:
result = saveProject(saveFile);
break;
case XML_ANALYSIS:
result = saveAnalysis(saveFile);
break;
case FBA_FILE:
result = saveFBAFile(saveFile);
break;
case FBP_FILE:
result = saveFBPFile(saveFile);
break;
}
if(result != SaveReturn.SAVE_SUCCESSFUL){
JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString(
"dlg.saving_error_lbl", "An error occurred in saving."));
}
}
/**
* @param saveFile2
* @return
*/
private SaveReturn saveFBAFile(File saveFile2) {
return saveAnalysis(saveFile2);
}
/**
* @param saveFile2
* @return
*/
private SaveReturn saveFBPFile(File saveFile2) {
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
try {
curProject.writeXML(saveFile2);
} catch (IOException e) {
AnalysisContext.logError("Couldn't save FBP file to " + saveFile2, e);
return SaveReturn.SAVE_IO_EXCEPTION;
}
setProjectChanged(false);
return SaveReturn.SAVE_SUCCESSFUL;
}
static final String TREECARD = "Tree";
static final String WAITCARD = "Wait";
public void showWaitCard() {
showCard(WAITCARD, new Cursor(Cursor.WAIT_CURSOR));
}
public void showTreeCard() {
showCard(TREECARD, new Cursor(Cursor.DEFAULT_CURSOR));
}
private void showCard(final String c, final Cursor cursor) {
if (SwingUtilities.isEventDispatchThread()) {
setCursor(cursor);
CardLayout layout = (CardLayout) cardPanel.getLayout();
layout.show(cardPanel, c);
} else
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setCursor(cursor);
CardLayout layout = (CardLayout) cardPanel.getLayout();
layout.show(cardPanel, c);
}
});
}
JPanel waitPanel, cardPanel;
/**
*
* @return
*/
JPanel bugListPanel()
{
cardPanel = new JPanel(new CardLayout());
JPanel topPanel = new JPanel();
waitPanel = new JPanel();
waitPanel.add(new JLabel("Please wait..."));
cardPanel.add(topPanel, TREECARD);
cardPanel.add(waitPanel, WAITCARD);
topPanel.setMinimumSize(new Dimension(200,200));
tableheader = new JTableHeader();
//Listener put here for when user double clicks on sorting
//column header SorterDialog appears.
tableheader.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
Debug.println("tableheader.getReorderingAllowed() = " + tableheader.getReorderingAllowed());
if (!tableheader.getReorderingAllowed())
return;
if (e.getClickCount()==2)
SorterDialog.getInstance().setVisible(true);
}
@Override
public void mouseReleased(MouseEvent arg0) {
if (!tableheader.getReorderingAllowed())
return;
BugTreeModel bt=(BugTreeModel) (MainFrame.this.getTree().getModel());
bt.checkSorter();
}
});
sorter = GUISaveState.getInstance().getStarterTable();
tableheader.setColumnModel(sorter);
tableheader.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.reorder_message", "Drag to reorder tree folder and sort order"));
tree = new JTree();
treeUI = (BasicTreeUI) tree.getUI();
tree.setLargeModel(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setCellRenderer(new BugRenderer());
tree.setRowHeight((int)(Driver.getFontSize() + 7));
if (false) {
System.out.println("Left indent had been " + treeUI.getLeftChildIndent());
System.out.println("Right indent had been " + treeUI.getRightChildIndent());
treeUI.setLeftChildIndent(30 );
treeUI.setRightChildIndent(30 );
}
tree.setModel(new BugTreeModel(tree, sorter, new BugSet(new ArrayList<BugLeafNode>())));
setupTreeListeners();
curProject= new Project();
treeScrollPane = new JScrollPane(tree);
topPanel.setLayout(new BorderLayout());
//New code to fix problem in Windows
JTable t = new JTable(new DefaultTableModel(0, Sortables.values().length));
t.setTableHeader(tableheader);
JScrollPane sp = new JScrollPane(t);
//This sets the height of the scrollpane so it is dependent on the fontsize.
int num = (int) (Driver.getFontSize()*1.2);
sp.setPreferredSize(new Dimension(0, 10+num));
//End of new code.
//Changed code.
topPanel.add(sp, BorderLayout.NORTH);
//topPanel.add(tableheader, BorderLayout.NORTH);
//End of changed code.
topPanel.add(treeScrollPane, BorderLayout.CENTER);
return cardPanel;
}
public void newTree(final JTree newTree, final BugTreeModel newModel)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
tree = newTree;
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setLargeModel(true);
tree.setCellRenderer(new BugRenderer());
showTreeCard();
Container container = treeScrollPane.getParent();
container.remove(treeScrollPane);
treeScrollPane = new JScrollPane(newTree);
container.add(treeScrollPane, BorderLayout.CENTER);
setFontSizeHelper(container.getComponents(), Driver.getFontSize());
tree.setRowHeight((int)(Driver.getFontSize() + 7));
MainFrame.getInstance().getContentPane().validate();
MainFrame.getInstance().getContentPane().repaint();
setupTreeListeners();
newModel.openPreviouslySelected(((BugTreeModel)(tree.getModel())).getOldSelectedBugs());
MainFrame.this.getSorter().addColumnModelListener(newModel);
FilterActivity.addFilterListener(newModel.bugTreeFilterListener);
MainFrame.this.setSorting(true);
}
});
}
private void setupTreeListeners()
{
tree.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(TreeSelectionEvent selectionEvent) {
TreePath path = selectionEvent.getNewLeadSelectionPath();
if (path != null)
{
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
Object lastPathComponent = path.getLastPathComponent();
if (lastPathComponent instanceof BugLeafNode)
{
boolean beforeProjectChanged = projectChanged;
currentSelectedBugLeaf = (BugLeafNode)lastPathComponent;
currentSelectedBugAspects = null;
syncBugInformation();
setProjectChanged(beforeProjectChanged);
}
else
{
boolean beforeProjectChanged = projectChanged;
updateDesignationDisplay();
currentSelectedBugLeaf = null;
currentSelectedBugAspects = (BugAspects)lastPathComponent;
syncBugInformation();
setProjectChanged(beforeProjectChanged);
}
}
// Debug.println("Tree selection count:" + tree.getSelectionCount());
if (tree.getSelectionCount() !=1)
{
Debug.println("Tree selection count not equal to 1, disabling comments tab" + selectionEvent);
MainFrame.this.setUserCommentInputEnable(false);
}
}
});
tree.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if(path == null)
return;
if ((e.getButton() == MouseEvent.BUTTON3) ||
(e.getButton() == MouseEvent.BUTTON1 && e.isControlDown())){
if (tree.getModel().isLeaf(path.getLastPathComponent())){
tree.setSelectionPath(path);
bugPopupMenu.show(tree, e.getX(), e.getY());
}
else{
tree.setSelectionPath(path);
if (!(path.getParentPath()==null))//If the path's parent path is null, the root was selected, dont allow them to filter out the root.
branchPopupMenu.show(tree, e.getX(), e.getY());
}
}
}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
});
}
void syncBugInformation (){
boolean prevProjectChanged = projectChanged;
if (currentSelectedBugLeaf != null) {
BugInstance bug = currentSelectedBugLeaf.getBug();
displayer.displaySource(bug, bug.getPrimarySourceLineAnnotation());
comments.updateCommentsFromLeafInformation(currentSelectedBugLeaf);
updateDesignationDisplay();
comments.updateCommentsFromLeafInformation(currentSelectedBugLeaf);
updateSummaryTab(currentSelectedBugLeaf);
} else if (currentSelectedBugAspects != null) {
updateDesignationDisplay();
comments.updateCommentsFromNonLeafInformation(currentSelectedBugAspects);
displayer.displaySource(null, null);
clearSummaryTab();
} else {
displayer.displaySource(null, null);
clearSummaryTab();
}
setProjectChanged(prevProjectChanged);
}
/**
* Clears the source code text pane.
*
*/
void clearSourcePane(){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
setSourceTabTitle("Source");
sourceCodeTextPane.setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT);
}
});
}
/**
* @param b
*/
private void setUserCommentInputEnable(boolean b) {
comments.setUserCommentInputEnable(b);
}
/**
* Creates the status bar of the GUI.
* @return
*/
JPanel statusBar()
{
JPanel statusBar = new JPanel();
// statusBar.setBackground(Color.WHITE);
statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
statusBar.setLayout(new BorderLayout());
statusBar.add(statusBarLabel,BorderLayout.WEST);
JLabel logoLabel = new JLabel();
ImageIcon logoIcon = new ImageIcon(MainFrame.class.getResource("logo_umd.png"));
logoLabel.setIcon(logoIcon);
statusBar.add(logoLabel, BorderLayout.EAST);
return statusBar;
}
void updateStatusBar()
{
int countFilteredBugs = BugSet.countFilteredBugs();
if (countFilteredBugs == 0)
statusBarLabel.setText(" http://findbugs.sourceforge.net/");
else if (countFilteredBugs == 1)
statusBarLabel.setText(" 1 " + edu.umd.cs.findbugs.L10N.getLocalString("statusbar.bug_hidden", "bug hidden"));
else
statusBarLabel.setText(" " + countFilteredBugs + " " + edu.umd.cs.findbugs.L10N.getLocalString("statusbar.bugs_hidden", "bugs hidden"));
}
private void updateSummaryTab(BugLeafNode node)
{
final BugInstance bug = node.getBug();
final ArrayList<BugAnnotation> primaryAnnotations = new ArrayList<BugAnnotation>();
boolean classIncluded = false;
//This ensures the order of the primary annotations of the bug
if(bug.getPrimarySourceLineAnnotation() != null)
primaryAnnotations.add(bug.getPrimarySourceLineAnnotation());
if(bug.getPrimaryMethod() != null)
primaryAnnotations.add(bug.getPrimaryMethod());
if(bug.getPrimaryField() != null)
primaryAnnotations.add(bug.getPrimaryField());
/*
* This makes the primary class annotation appear only when
* the visible field and method primary annotations don't have
* the same class.
*/
if(bug.getPrimaryClass() != null){
FieldAnnotation primeField = bug.getPrimaryField();
MethodAnnotation primeMethod = bug.getPrimaryMethod();
ClassAnnotation primeClass = bug.getPrimaryClass();
String fieldClass = "";
String methodClass = "";
if(primeField != null)
fieldClass = primeField.getClassName();
if(primeMethod != null)
methodClass = primeMethod.getClassName();
if((primaryAnnotations.size() < 2) || (!(primeClass.getClassName().equals(fieldClass) ||
primeClass.getClassName().equals(methodClass)))){
primaryAnnotations.add(primeClass);
classIncluded = true;
}
}
final boolean classIncluded2 = classIncluded;
SwingUtilities.invokeLater(new Runnable(){
public void run(){
summaryTopPanel.removeAll();
summaryTopPanel.add(bugSummaryComponent(bug.getMessageWithoutPrefix(), bug));
for(BugAnnotation b : primaryAnnotations)
summaryTopPanel.add(bugSummaryComponent(b, bug));
if(!classIncluded2 && bug.getPrimaryClass() != null)
primaryAnnotations.add(bug.getPrimaryClass());
for(Iterator<BugAnnotation> i = bug.annotationIterator(); i.hasNext();){
BugAnnotation b = i.next();
boolean cont = true;
for(BugAnnotation p : primaryAnnotations)
if(p == b)
cont = false;
if(cont)
summaryTopPanel.add(bugSummaryComponent(b, bug));
}
summaryHtmlArea.setText(bug.getBugPattern().getDetailHTML());
summaryTopPanel.add(Box.createVerticalGlue());
summaryTopPanel.revalidate();
SwingUtilities.invokeLater(new Runnable(){
public void run(){
summaryHtmlScrollPane.getVerticalScrollBar().setValue(summaryHtmlScrollPane.getVerticalScrollBar().getMinimum());
}
});
}
});
}
private void clearSummaryTab()
{
summaryHtmlArea.setText("");
summaryTopPanel.removeAll();
summaryTopPanel.revalidate();
}
/**
* Creates initial summary tab and sets everything up.
* @return
*/
JSplitPane summaryTab()
{
int fontSize = (int) Driver.getFontSize();
summaryTopPanel = new JPanel();
summaryTopPanel.setLayout(new GridLayout(0,1));
summaryTopPanel.setBorder(BorderFactory.createEmptyBorder(2,4,2,4));
summaryTopPanel.setMinimumSize(new Dimension(fontSize * 50, fontSize*5));
JPanel summaryTopOuter = new JPanel(new BorderLayout());
summaryTopOuter.add(summaryTopPanel, BorderLayout.NORTH);
summaryHtmlArea.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.longer_description", "This gives a longer description of the detected bug pattern"));
summaryHtmlArea.setContentType("text/html");
summaryHtmlArea.setEditable(false);
summaryHtmlArea.addHyperlinkListener(new javax.swing.event.HyperlinkListener() {
public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {
AboutDialog.editorPaneHyperlinkUpdate(evt);
}
});
setStyleSheets();
//JPanel temp = new JPanel(new BorderLayout());
//temp.add(summaryTopPanel, BorderLayout.CENTER);
JScrollPane summaryScrollPane = new JScrollPane(summaryTopOuter);
summaryScrollPane.getVerticalScrollBar().setUnitIncrement( (int)Driver.getFontSize() );
JSplitPane splitP = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false,
summaryScrollPane, summaryHtmlScrollPane);
splitP.setDividerLocation(GUISaveState.getInstance().getSplitSummary());
splitP.setOneTouchExpandable(true);
return splitP;
}
/**
* Creates bug summary component. If obj is a string will create a JLabel
* with that string as it's text and return it. If obj is an annotation
* will return a JLabel with the annotation's toString(). If that
* annotation is a SourceLineAnnotation or has a SourceLineAnnotation
* connected to it and the source file is available will attach
* a listener to the label.
* @param obj
* @param bug TODO
* @return
*/
private Component bugSummaryComponent(Object obj, BugInstance bug){
JLabel label = new JLabel();
label.setFont(label.getFont().deriveFont(Driver.getFontSize()));
label.setFont(label.getFont().deriveFont(Font.PLAIN));
label.setForeground(Color.BLACK);
if(obj instanceof String){
String str = (String) obj;
label.setText(str);
}
else{
BugAnnotation value = (BugAnnotation) obj;
if(value == null)
return new JLabel(edu.umd.cs.findbugs.L10N.getLocalString("summary.null", "null"));
if(value instanceof SourceLineAnnotation){
final SourceLineAnnotation note = (SourceLineAnnotation) value;
if(sourceCodeExist(note)){
String srcStr = "";
int start = note.getStartLine();
int end = note.getEndLine();
if(start < 0 && end < 0)
srcStr = edu.umd.cs.findbugs.L10N.getLocalString("summary.source_code", "source code.");
else if(start == end)
srcStr = " [" + edu.umd.cs.findbugs.L10N.getLocalString("summary.line", "Line") + " " + start + "]";
else if(start < end)
srcStr = " [" + edu.umd.cs.findbugs.L10N.getLocalString("summary.lines", "Lines") + " " + start + " - " + end + "]";
label.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.click_to_go_to", "Click to go to") + " " + srcStr);
label.addMouseListener(new BugSummaryMouseListener(bug, label, note));
}
label.setText(note.toString());
}
else if(value instanceof PackageMemberAnnotation){
PackageMemberAnnotation note = (PackageMemberAnnotation) value;
final SourceLineAnnotation noteSrc = note.getSourceLines();
String srcStr = "";
if(sourceCodeExist(noteSrc) && noteSrc != null){
int start = noteSrc.getStartLine();
int end = noteSrc.getEndLine();
if(start < 0 && end < 0)
srcStr = edu.umd.cs.findbugs.L10N.getLocalString("summary.source_code", "source code.");
else if(start == end)
srcStr = " [" + edu.umd.cs.findbugs.L10N.getLocalString("summary.line", "Line") + " " + start + "]";
else if(start < end)
srcStr = " [" + edu.umd.cs.findbugs.L10N.getLocalString("summary.lines", "Lines") + " " + start + " - " + end + "]";
if(!srcStr.equals("")){
label.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.click_to_go_to", "Click to go to") + " " + srcStr);
label.addMouseListener(new BugSummaryMouseListener(bug, label, noteSrc));
}
}
if(!srcStr.equals(edu.umd.cs.findbugs.L10N.getLocalString("summary.source_code", "source code.")))
label.setText(note.toString() + srcStr);
else
label.setText(note.toString());
}
else{
label.setText(((BugAnnotation) value).toString());
}
}
return label;
}
/**
* @author pugh
*/
private final class InitializeGUI implements Runnable {
public void run()
{
setTitle("FindBugs");
guiLayout.initialize();
bugPopupMenu = createBugPopupMenu();
branchPopupMenu = createBranchPopUpMenu();
comments.loadPrevCommentsList(GUISaveState.getInstance().getPreviousComments().toArray(new String[GUISaveState.getInstance().getPreviousComments().size()]));
updateStatusBar();
setBounds(GUISaveState.getInstance().getFrameBounds());
Toolkit.getDefaultToolkit().setDynamicLayout(true);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
setJMenuBar(createMainMenuBar());
setVisible(true);
//Initializes save and open filechooser. - Kristin
saveOpenFileChooser = new FBFileChooser();
saveOpenFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
saveOpenFileChooser.setAcceptAllFileFilterUsed(false);
saveOpenFileChooser.addChoosableFileFilter(FindBugsProjectFileFilter.INSTANCE);
saveOpenFileChooser.addChoosableFileFilter(FindBugsAnalysisFileFilter.INSTANCE);
saveOpenFileChooser.addChoosableFileFilter(FindBugsFBPFileFilter.INSTANCE);
saveOpenFileChooser.addChoosableFileFilter(FindBugsFBAFileFilter.INSTANCE);
saveOpenFileChooser.setFileFilter(FindBugsAnalysisFileFilter.INSTANCE);
//Sets the size of the tooltip to match the rest of the GUI. - Kristin
JToolTip tempToolTip = tableheader.createToolTip();
UIManager.put( "ToolTip.font", new FontUIResource(tempToolTip.getFont().deriveFont(Driver.getFontSize())));
if (MAC_OS_X)
{
try {
osxAdapter = Class.forName("edu.umd.cs.findbugs.gui2.OSXAdapter");
Class[] defArgs = {MainFrame.class};
Method registerMethod = osxAdapter.getDeclaredMethod("registerMacOSXApplication", defArgs);
if (registerMethod != null) {
registerMethod.invoke(osxAdapter, MainFrame.this);
}
defArgs[0] = boolean.class;
osxPrefsEnableMethod = osxAdapter.getDeclaredMethod("enablePrefs", defArgs);
enablePreferences(true);
} catch (NoClassDefFoundError e) {
// This will be thrown first if the OSXAdapter is loaded on a system without the EAWT
// because OSXAdapter extends ApplicationAdapter in its def
System.err.println("This version of Mac OS X does not support the Apple EAWT. Application Menu handling has been disabled (" + e + ")");
} catch (ClassNotFoundException e) {
// This shouldn't be reached; if there's a problem with the OSXAdapter we should get the
// above NoClassDefFoundError first.
System.err.println("This version of Mac OS X does not support the Apple EAWT. Application Menu handling has been disabled (" + e + ")");
} catch (Exception e) {
System.err.println("Exception while loading the OSXAdapter: " + e);
e.printStackTrace();
if (DEBUG) {
e.printStackTrace();
}
}
}
String loadFromURL = SystemProperties.getProperty("findbugs.loadBugsFromURL");
if (loadFromURL != null) {
InputStream in;
try {
in = new URL(loadFromURL).openConnection().getInputStream();
if (loadFromURL.endsWith(".gz"))
in = new GZIPInputStream(in);
BugTreeModel.pleaseWait(edu.umd.cs.findbugs.L10N.getLocalString("msg.loading_bugs_over_network_txt", "Loading bugs over network..."));
loadAnalysisFromInputStream(in);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(MainFrame.this, "Error loading " +e1.getMessage());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(MainFrame.this, "Error loading " +e1.getMessage());
}
}
addComponentListener(new ComponentAdapter(){
@Override
public void componentResized(ComponentEvent e){
comments.resized();
}
});
addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
if(comments.hasFocus())
setProjectChanged(true);
callOnClose();
}
});
Driver.removeSplashScreen();
}
}
/**
* Listens for when cursor is over the label and when it is clicked.
* When the cursor is over the label will make the label text blue
* and the cursor the hand cursor. When clicked will take the
* user to the source code tab and to the lines of code connected
* to the SourceLineAnnotation.
* @author Kristin Stephens
*
*/
private class BugSummaryMouseListener extends MouseAdapter{
private BugInstance bugInstance;
private JLabel label;
private SourceLineAnnotation note;
BugSummaryMouseListener(@NonNull BugInstance bugInstance, @NonNull JLabel label, @NonNull SourceLineAnnotation note){
this.bugInstance = bugInstance;
this.label = label;
this.note = note;
}
@Override
public void mouseClicked(MouseEvent e) {
displayer.displaySource(bugInstance, note);
}
@Override
public void mouseEntered(MouseEvent e){
label.setForeground(Color.blue);
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e){
label.setForeground(Color.black);
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
/**
* Checks if source code file exists/is available
* @param note
* @return
*/
private boolean sourceCodeExist(SourceLineAnnotation note){
try{
sourceFinder.findSourceFile(note);
}catch(FileNotFoundException e){
return false;
}catch(IOException e){
return false;
}
return true;
}
private void setStyleSheets() {
StyleSheet styleSheet = new StyleSheet();
styleSheet.addRule("body {font-size: " + Driver.getFontSize() +"pt}");
styleSheet.addRule("H1 {color: red; font-size: 120%; font-weight: bold;}");
styleSheet.addRule("code {font-family: courier; font-size: " + Driver.getFontSize() +"pt}");
htmlEditorKit.setStyleSheet(styleSheet);
summaryHtmlArea.setEditorKit(htmlEditorKit);
}
JPanel createCommentsInputPanel() {
return comments.createCommentsInputPanel();
}
/**
* Creates the source code panel, but does not put anything in it.
* @param text
* @return
*/
JPanel createSourceCodePanel()
{
Font sourceFont = new Font("Monospaced", Font.PLAIN, (int)Driver.getFontSize());
sourceCodeTextPane.setFont(sourceFont);
sourceCodeTextPane.setEditable(false);
sourceCodeTextPane.getCaret().setSelectionVisible(true);
sourceCodeTextPane.setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT);
sourceCodeScrollPane = new JScrollPane(sourceCodeTextPane);
sourceCodeScrollPane.getVerticalScrollBar().setUnitIncrement(20);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(sourceCodeScrollPane, BorderLayout.CENTER);
panel.revalidate();
if (DEBUG) System.out.println("Created source code panel");
return panel;
}
JPanel createSourceSearchPanel()
{
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
JPanel thePanel = new JPanel();
thePanel.setLayout(gridbag);
c.gridx = 0;
c.gridy = 0;
c.weightx = 1.0;
c.insets = new Insets(0, 5, 0, 5);
c.fill = GridBagConstraints.HORIZONTAL;
gridbag.setConstraints(sourceSearchTextField, c);
thePanel.add(sourceSearchTextField);
//add the buttons
findButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
searchSource(0);
}
});
c.gridx = 1;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
gridbag.setConstraints(findButton, c);
thePanel.add(findButton);
findNextButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
searchSource(1);
}
});
c.gridx = 2;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
gridbag.setConstraints(findNextButton, c);
thePanel.add(findNextButton);
findPreviousButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
searchSource(2);
}
});
c.gridx = 3;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
gridbag.setConstraints(findPreviousButton, c);
thePanel.add(findPreviousButton);
return thePanel;
}
void searchSource(int type)
{
int targetLineNum = -1;
String targetString = sourceSearchTextField.getText();
switch(type)
{
case 0: targetLineNum = displayer.find(targetString);
break;
case 1: targetLineNum = displayer.findNext(targetString);
break;
case 2: targetLineNum = displayer.findPrevious(targetString);
break;
}
if(targetLineNum != -1)
displayer.foundItem(targetLineNum);
}
/**
* Sets the title of the source tabs for either docking or non-docking
* versions.
* @param title
*/
void setSourceTabTitle(String title){
guiLayout.setSourceTitle(title);
}
/**
* Returns the SorterTableColumnModel of the MainFrame.
* @return
*/
SorterTableColumnModel getSorter()
{
return sorter;
}
/*
* This is overridden for changing the font size
*/
@Override
public void addNotify(){
super.addNotify();
float size = Driver.getFontSize();
getJMenuBar().setFont(getJMenuBar().getFont().deriveFont(size));
for(int i = 0; i < getJMenuBar().getMenuCount(); i++){
for(int j = 0; j < getJMenuBar().getMenu(i).getMenuComponentCount(); j++){
Component temp = getJMenuBar().getMenu(i).getMenuComponent(j);
temp.setFont(temp.getFont().deriveFont(size));
}
}
bugPopupMenu.setFont(bugPopupMenu.getFont().deriveFont(size));
setFontSizeHelper(bugPopupMenu.getComponents(), size);
branchPopupMenu.setFont(branchPopupMenu.getFont().deriveFont(size));
setFontSizeHelper(branchPopupMenu.getComponents(), size);
}
public JTree getTree()
{
return tree;
}
public BugTreeModel getBugTreeModel() {
return (BugTreeModel)getTree().getModel();
}
static class CutAction extends TextAction {
public CutAction() {
super(edu.umd.cs.findbugs.L10N.getLocalString("txt.cut", "Cut"));
}
public void actionPerformed( ActionEvent evt ) {
JTextComponent text = getTextComponent( evt );
if(text == null)
return;
text.cut();
}
}
static class CopyAction extends TextAction {
public CopyAction() {
super(edu.umd.cs.findbugs.L10N.getLocalString("txt.copy", "Copy"));
}
public void actionPerformed( ActionEvent evt ) {
JTextComponent text = getTextComponent( evt );
if(text == null)
return;
text.copy();
}
}
static class PasteAction extends TextAction {
public PasteAction() {
super(edu.umd.cs.findbugs.L10N.getLocalString("txt.paste", "Paste"));
}
public void actionPerformed( ActionEvent evt ) {
JTextComponent text = getTextComponent( evt );
if(text == null)
return;
text.paste();
}
}
public Project getProject() {
return curProject;
}
public void setProject(Project p) {
curProject=p;
}
public SourceFinder getSourceFinder()
{
return sourceFinder;
}
public void setSourceFinder(SourceFinder sf)
{
sourceFinder=sf;
}
@SwingThread
public void setRebuilding(boolean b)
{
tableheader.setReorderingAllowed(!b);
enablePreferences(!b);
if (b) {
SorterDialog.getInstance().freeze();
showWaitCard();
}
else {
SorterDialog.getInstance().thaw();
showTreeCard();
}
recentMenu.setEnabled(!b);
}
public void setSorting(boolean b) {
tableheader.setReorderingAllowed(b);
}
private void setSaveMenu() {
saveMenuItem.setEnabled(projectChanged && saveFile != null && getSaveType() != SaveType.FBP_FILE && saveFile.exists());
}
/**
* Called when something in the project is changed and the change needs to be saved.
* This method should be called instead of using projectChanged = b.
*/
public void setProjectChanged(boolean b){
if(curProject == null)
return;
if(projectChanged == b)
return;
projectChanged = b;
setSaveMenu();
// if(projectDirectory != null && projectDirectory.exists())
// saveProjectMenuItem.setEnabled(b);
getRootPane().putClientProperty(WINDOW_MODIFIED, Boolean.valueOf(b));
}
public boolean getProjectChanged(){
return projectChanged;
}
/*
* DO NOT use the projectDirectory variable to figure out the current project directory in this function
* use the passed in value, as that variable may or may not have been set to the passed in value at this point.
*/
private SaveReturn saveProject(File dir)
{
if (curProject == null) {
curProject = new Project();
JOptionPane.showMessageDialog(MainFrame.this, "Null project; this is unexpected. "
+" Creating a new Project so the bugs can be saved, but please report this error.");
}
dir.mkdir();
//updateDesignationDisplay(); - Don't think we need this anymore - Kristin
File f = new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".xml");
File filtersAndSuppressions=new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".fas");
BugSaver.saveBugs(f,bugCollection,curProject);
try {
filtersAndSuppressions.createNewFile();
ProjectSettings.getInstance().save(new FileOutputStream(filtersAndSuppressions));
} catch (IOException e) {
Debug.println(e);
return SaveReturn.SAVE_IO_EXCEPTION;
}
setProjectChanged(false);
return SaveReturn.SAVE_SUCCESSFUL;
}
/**
* @param currentSelectedBugLeaf2
* @param currentSelectedBugAspects2
*/
private void saveComments(BugLeafNode theNode, BugAspects theAspects) {
comments.saveComments(theNode, theAspects);
}
void saveComments() {
comments.saveComments();
}
/**
* Returns the color of the source code pane's background.
* @return the color of the source code pane's background
*/
public Color getSourceColor(){
return sourceCodeTextPane.getBackground();
}
/**
* Show an error dialog.
*/
public void error(String message) {
JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE);
}
/**
* Write a message to the console window.
*
* @param message the message to write
*/
public void writeToLog(String message) {
if (DEBUG)
System.out.println(message);
// consoleMessageArea.append(message);
// consoleMessageArea.append("\n");
}
/**
* Save current analysis as file passed in. Return SAVE_SUCCESSFUL if save successful.
*/
/*
* Method doesn't do much. This method is more if need to do other things in the future for
* saving analysis. And to keep saving naming convention.
*/
private SaveReturn saveAnalysis(File f){
BugSaver.saveBugs(f, bugCollection, curProject);
setProjectChanged(false);
return SaveReturn.SAVE_SUCCESSFUL;
}
/**
* Opens the analysis. Also clears the source and summary panes. Makes comments enabled false.
* Sets the saveType and adds the file to the recent menu.
* @param f
* @return
*/
private boolean openAnalysis(File f, SaveType saveType){
if (!f.exists() || !f.canRead()) {
throw new IllegalArgumentException("Can't read " + f);
}
prepareForFileLoad(f, saveType);
try {
FileInputStream in = new FileInputStream(f);
loadAnalysisFromInputStream(in);
return true;
} catch (IOException e) {
return false;
}
}
private void prepareForFileLoad(File f, SaveType saveType) {
setRebuilding(true);
//This creates a new filters and suppressions so don't use the previoues one.
ProjectSettings.newInstance();
clearSourcePane();
clearSummaryTab();
comments.setUserCommentInputEnable(false);
reconfigMenuItem.setEnabled(true);
setProjectChanged(false);
this.setSaveType(saveType);
saveFile = f;
addFileToRecent(f, saveType);
}
/**
* @param file
* @return
*/
private void loadAnalysisFromInputStream(final InputStream in) {
Runnable runnable = new Runnable(){
public void run()
{
final Project project = new Project();
final SortedBugCollection bc=BugLoader.loadBugs(MainFrame.this, project, in);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (bc == null)
setProjectAndBugCollection(new Project(), new SortedBugCollection());
else setProjectAndBugCollection(project, bc);
}});
}
};
if (EventQueue.isDispatchThread())
new Thread(runnable).start();
else runnable.run();
return;
}
/**
* @param file
* @return
*/
private void loadProjectFromFile(final File f) {
Runnable runnable = new Runnable(){
public void run()
{
final Project project = BugLoader.loadProject(MainFrame.this, f);
final BugCollection bc = project == null ? null : BugLoader.doAnalysis(project);
updateProjectAndBugCollection(project, bc, null);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (project == null)
setProjectAndBugCollection(new Project(), new SortedBugCollection());
else setProjectAndBugCollection(project,bc);
}});
}
};
if (EventQueue.isDispatchThread())
new Thread(runnable).start();
else runnable.run();
return;
}
/**
* Redo the analysis
*/
private void redoAnalysis() {
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
showWaitCard();
new Thread()
{
@Override
public void run()
{
updateDesignationDisplay();
BugCollection bc=BugLoader.redoAnalysisKeepComments(curProject);
updateProjectAndBugCollection(curProject, bc, null);
}
}.start();
}
private void mergeAnalysis() {
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
showWaitCard();
Project p = new Project();
BugCollection bc=BugLoader.combineBugHistories(p);
setProjectAndBugCollection(p, bc);
}
/**
* This takes a directory and opens it as a project.
* @param dir
*/
private void openProject(final File dir){
File xmlFile= new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".xml");
File fasFile=new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".fas");
if (!fasFile.exists())
{
JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString(
"dlg.filter_settings_not_found_lbl", "Filter settings not found, using default settings."));
ProjectSettings.newInstance();
}
else
{
try
{
ProjectSettings.loadInstance(new FileInputStream(fasFile));
} catch (FileNotFoundException e)
{
//Impossible.
if (MainFrame.DEBUG) System.err.println(".fas file not found, using default settings");
ProjectSettings.newInstance();
}
}
final File extraFinalReferenceToXmlFile=xmlFile;
new Thread(new Runnable(){
public void run()
{
BugTreeModel.pleaseWait();
MainFrame.this.setRebuilding(true);
Project project = new Project();
SortedBugCollection bc=BugLoader.loadBugs(MainFrame.this, project, extraFinalReferenceToXmlFile);
setProjectAndBugCollection(project, bc);
}
}).start();
// addFileToRecent(xmlFile, SaveType.PROJECT);
addFileToRecent(dir, SaveType.PROJECT);
clearSourcePane();
clearSummaryTab();
comments.setUserCommentInputEnable(false);
setProjectChanged(false);
setSaveType(SaveType.PROJECT);
saveFile = dir;
changeTitle();
}
/**
* This checks if the xmlFile is in the GUISaveState. If not adds it. Then adds the file
* to the recentMenuCache.
* @param xmlFile
*/
/*
* If the file already existed, its already in the preferences, as well as
* the recent projects menu items, only add it if they change the name,
* otherwise everything we're storing is still accurate since all we're
* storing is the location of the file.
*/
private void addFileToRecent(File xmlFile, SaveType st){
ArrayList<File> xmlFiles=GUISaveState.getInstance().getRecentFiles();
if (!xmlFiles.contains(xmlFile))
{
GUISaveState.getInstance().addRecentFile(xmlFile);
}
MainFrame.this.recentMenuCache.addRecentFile(xmlFile);
}
private void newProjectMenu() {
comments.saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
new NewProjectWizard();
newProject = true;
}
void updateDesignationDisplay() {
comments.updateDesignationComboBox();
}
void addDesignationItem(JMenu menu, final String menuName, int keyEvent) {
comments.addDesignationItem(menu, menuName, keyEvent);
}
void warnUserOfFilters()
{
JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.everything_is_filtered",
"All bugs in this project appear to be filtered out. \nYou may wish to check your filter settings in the preferences menu."),
"Warning",JOptionPane.WARNING_MESSAGE);
}
/**
* @param saveType The saveType to set.
*/
void setSaveType(SaveType saveType) {
if (DEBUG && this.saveType != saveType)
System.out.println("Changing save type from " + this.saveType + " to " + saveType);
this.saveType = saveType;
}
/**
* @return Returns the saveType.
*/
SaveType getSaveType() {
return saveType;
}
}
|
package com.android.grabqqpwd;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import java.util.List;
/**
* Description: #TODO
*
* @author zzp(zhao_zepeng@hotmail.com)
* @since 2016-01-08
*/
public class BackgroundDetectService extends Service implements View.OnClickListener{
WindowManager windowManager;
RelativeLayoutWithKeyDetect v;
Button btn_sure;
Button btn_cancel;
EditText et_account;
EditText et_pwd;
CheckBox cb_showpwd;
boolean isRunning = true;
@Override
public void onCreate() {
super.onCreate();
final MyHandler myHandler = new MyHandler();
new Thread(new Runnable() {
@Override
public void run() {
while (isRunning){
L.e("running");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ActivityManager activityManager = (ActivityManager)
getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> list =
activityManager.getRunningAppProcesses();
if (list.get(0).processName.equals("com.tencent.mobileqq")){
myHandler.sendEmptyMessage(1);
}
}
}
}).start();
}
private class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
if (v==null || !v.isAttachedToWindow())
showWindow();
}
}
private void showWindow(){
windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.MATCH_PARENT;
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.format = PixelFormat.TRANSPARENT;
params.gravity = Gravity.CENTER;
params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
LayoutInflater inflater = LayoutInflater.from(this);
v = (RelativeLayoutWithKeyDetect) inflater.inflate(R.layout.window, null);
v.setCallback(new RelativeLayoutWithKeyDetect.IKeyCodeBackCallback() {
@Override
public void backCallback() {
if (v!=null && v.isAttachedToWindow())
L.e("remove view ");
windowManager.removeViewImmediate(v);
}
});
btn_sure = (Button) v.findViewById(R.id.btn_sure);
btn_cancel = (Button) v.findViewById(R.id.btn_cancel);
et_account = (EditText) v.findViewById(R.id.et_account);
et_pwd = (EditText) v.findViewById(R.id.et_pwd);
cb_showpwd = (CheckBox) v.findViewById(R.id.cb_showpwd);
cb_showpwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
et_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else {
et_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
et_pwd.setSelection(TextUtils.isEmpty(et_pwd.getText()) ?
0 : et_pwd.getText().length());
}
});
//useless
// v.setOnKeyListener(new View.OnKeyListener() {
// @Override
// public boolean onKey(View v, int keyCode, KeyEvent event) {
// Log.e("zhao", keyCode+"");
// if (keyCode == KeyEvent.KEYCODE_BACK) {
// windowManager.removeViewImmediate(v);
// return true;
// return false;
v.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
Rect temp = new Rect();
view.getGlobalVisibleRect(temp);
L.e("remove view ");
if (temp.contains((int)(event.getX()), (int)(event.getY()))){
windowManager.removeViewImmediate(v);
return true;
}
return false;
}
});
btn_sure.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
L.e("add view ");
windowManager.addView(v, params);
}
@Override
public void onDestroy() {
super.onDestroy();
isRunning = false;
L.e("remove view ");
if (v!=null && v.hasWindowFocus())
windowManager.removeView(v);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onClick(View view) {
if (view == btn_cancel){
if (v!=null && v.hasWindowFocus())
windowManager.removeViewImmediate(v);
}else{
if (TextUtils.isEmpty(et_account.getText())){
et_account.setError("");
return;
}
if (TextUtils.isEmpty(et_pwd.getText())){
et_pwd.setError("");
return;
}
//TODO
L.e("remove view ");
if (v!=null && v.hasWindowFocus())
windowManager.removeViewImmediate(v);
}
}
}
|
package edu.umd.cs.findbugs.gui2;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import edu.umd.cs.findbugs.AppVersion;
import edu.umd.cs.findbugs.BugCollection;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugPattern;
import edu.umd.cs.findbugs.BugRanker;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.I18N;
import edu.umd.cs.findbugs.ProjectPackagePrefixes;
import edu.umd.cs.findbugs.gui2.BugAspects.SortableValue;
import edu.umd.cs.findbugs.util.ClassName;
/**
* A useful enum for dealing with all the types of filterable and sortable data in BugInstances
* This is the preferred way for getting the information out of a BugInstance and formatting it for display
* It also has the comparators for the different types of data
*
* @author Reuven
*/
public enum Sortables implements Comparator<SortableValue>
{
FIRST_SEEN(edu.umd.cs.findbugs.L10N.getLocalString("sort.first_seen", "First Seen"))
{
@Override
public String getFrom(BugInstance bug)
{
long firstSeen = getFirstSeen(bug);
return Long.toString(firstSeen);
}
/**
* @param bug
* @return
*/
private long getFirstSeen(BugInstance bug) {
BugCollection bugCollection = MainFrame.getInstance().bugCollection;
long firstSeen = bugCollection.getCloud().getFirstSeen(bug);
return firstSeen;
}
@Override
public String formatValue(String value)
{
long when = Long.parseLong(value);
return DateFormat.getDateTimeInstance().format(when);
}
@Override
public int compare(SortableValue one, SortableValue two)
{
// Numerical (zero is first)
return Integer.valueOf(one.value).compareTo(Integer.valueOf(two.value));
}
},
FIRSTVERSION(edu.umd.cs.findbugs.L10N.getLocalString("sort.first_version", "First Version"))
{
@Override
public String getFrom(BugInstance bug)
{
return Long.toString(bug.getFirstVersion());
}
@Override
public String formatValue(String value)
{
int seqNum = Integer.parseInt(value);
BugCollection bugCollection = MainFrame.getInstance().bugCollection;
if (bugCollection == null) return "
AppVersion appVersion = bugCollection.getAppVersionFromSequenceNumber(seqNum);
String appendItem = "";
if(appVersion != null)
{
String timestamp = new Timestamp(appVersion.getTimestamp()).toString();
appendItem = appVersion.getReleaseName() + " (" + timestamp.substring(0, timestamp.indexOf(' ')) + ")";
}
if(appendItem == "")
appendItem = "#" +seqNum;
return appendItem;
}
@Override
public int compare(SortableValue one, SortableValue two)
{
// Numerical (zero is first)
return Integer.valueOf(one.value).compareTo(Integer.valueOf(two.value));
}
@Override
public boolean isAvailable(MainFrame mainframe) {
BugCollection bugCollection = mainframe.bugCollection;
return bugCollection.getCurrentAppVersion().getSequenceNumber() > 0;
}
},
LASTVERSION(edu.umd.cs.findbugs.L10N.getLocalString("sort.last_version", "Last Version"))
{
@Override
public String getFrom(BugInstance bug)
{
return Long.toString(bug.getLastVersion());
}
@Override
public String formatValue(String value)
{
//System.out.println("Formatting last version value");
if(value.equals("-1"))
return "";
int seqNum = Integer.parseInt(value);
BugCollection bugCollection = MainFrame.getInstance().bugCollection;
if (bugCollection == null) return "
AppVersion appVersion = bugCollection.getAppVersionFromSequenceNumber(seqNum);
String appendItem = "";
if(appVersion != null)
{
String timestamp = new Timestamp(appVersion.getTimestamp()).toString();
appendItem = appVersion.getReleaseName() + " (" + timestamp.substring(0, timestamp.indexOf(' ')) + ")";
}
if(appendItem == "")
appendItem = "#" + seqNum;
return appendItem;
}
@Override
public int compare(SortableValue one, SortableValue two)
{
if (one.value.equals(two.value)) return 0;
// Numerical (except that -1 is last)
int first = Integer.valueOf(one.value);
int second = Integer.valueOf(two.value);
if (first == second) return 0;
if (first < 0) return 1;
if (second < 0) return -1;
if (first < second) return -1;
return 1;
}
@Override
public boolean isAvailable(MainFrame mainframe) {
BugCollection bugCollection = mainframe.bugCollection;
return bugCollection.getCurrentAppVersion().getSequenceNumber() > 0;
}
},
PRIORITY(edu.umd.cs.findbugs.L10N.getLocalString("sort.priority", "Priority"))
{
@Override
public String getFrom(BugInstance bug)
{
return String.valueOf(bug.getPriority());
}
@Override
public String formatValue(String value)
{
if (value.equals(String.valueOf(Detector.HIGH_PRIORITY)))
return edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_high", "High");
if (value.equals(String.valueOf(Detector.NORMAL_PRIORITY)))
return edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_normal", "Normal");
if (value.equals(String.valueOf(Detector.LOW_PRIORITY)))
return edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_low", "Low");
if (value.equals(String.valueOf(Detector.EXP_PRIORITY)))
return edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_experimental", "Experimental");
return edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_ignore", "Ignore"); // This probably shouldn't ever happen, but what the hell, let's be complete
}
@Override
public int compare(SortableValue one, SortableValue two)
{
// Numerical
return Integer.valueOf(one.value).compareTo(Integer.valueOf(two.value));
}
},
CLASS(edu.umd.cs.findbugs.L10N.getLocalString("sort.class", "Class"))
{
@Override
public String getFrom(BugInstance bug)
{
return bug.getPrimarySourceLineAnnotation().getClassName();
}
@Override
public int compare(SortableValue one, SortableValue two)
{
// If both have dollar signs and are of the same outer class, compare the numbers after the dollar signs.
try
{
if (one.value.contains("$") && two.value.contains("$")
&& one.value.substring(0, one.value.lastIndexOf("$")).equals(two.value.substring(0, two.value.lastIndexOf("$"))))
return Integer.valueOf(one.value.substring(one.value.lastIndexOf("$"))).compareTo(Integer.valueOf(two.value.substring(two.value.lastIndexOf("$"))));
}
catch (NumberFormatException e) {} // Somebody's playing silly buggers with dollar signs, just do it lexicographically
// Otherwise, lexicographicalify it
return one.value.compareTo(two.value);
}
},
PACKAGE(edu.umd.cs.findbugs.L10N.getLocalString("sort.package", "Package"))
{
@Override
public String getFrom(BugInstance bug)
{
return bug.getPrimarySourceLineAnnotation().getPackageName();
}
@Override
public String formatValue(String value)
{
if (value.equals(""))
return "(Default)";
return value;
}
},
PACKAGE_PREFIX(edu.umd.cs.findbugs.L10N.getLocalString("sort.package_prefix", "Package prefix")) {
@Override
public String getFrom(BugInstance bug)
{
int count = GUISaveState.getInstance().getPackagePrefixSegments();
if (count < 1)
count = 1;
String packageName = bug.getPrimarySourceLineAnnotation().getPackageName();
return ClassName.extractPackagePrefix(packageName, count);
}
@Override
public String formatValue(String value)
{
return value + "...";
}
},
CATEGORY(edu.umd.cs.findbugs.L10N.getLocalString("sort.category", "Category"))
{
@Override
public String getFrom(BugInstance bug)
{
BugPattern bugPattern = bug.getBugPattern();
if (bugPattern == null) {
return "?";
}
return bugPattern.getCategory();
}
@Override
public String formatValue(String value)
{
return I18N.instance().getBugCategoryDescription(value);
}
@Override
public int compare(SortableValue one, SortableValue two)
{
String catOne = one.value;
String catTwo = two.value;
int compare = catOne.compareTo(catTwo);
if (compare == 0)
return 0;
if (catOne.equals("CORRECTNESS"))
return -1;
if (catTwo.equals("CORRECTNESS"))
return 1;
return compare;
}
},
DESIGNATION(edu.umd.cs.findbugs.L10N.getLocalString("sort.designation", "Designation"))
{
@Override
public String getFrom(BugInstance bug)
{
return bug.getUserDesignationKey();
}
/**
* value is the key of the designations.
* @param value
* @return
*/
@Override
public String formatValue(String value)
{
return I18N.instance().getUserDesignation(value);
}
@Override
public String[] getAllSorted()
{//FIXME I think we always want user to see all possible designations, not just the ones he has set in his project, Agreement? -Dan
List<String> sortedDesignations=I18N.instance().getUserDesignationKeys(true);
return sortedDesignations.toArray(new String[sortedDesignations.size()]);
}
},
BUGCODE(edu.umd.cs.findbugs.L10N.getLocalString("sort.bug_kind", "Bug Kind"))
{
@Override
public String getFrom(BugInstance bug)
{
BugPattern bugPattern = bug.getBugPattern();
if (bugPattern == null) return null;
return bugPattern.getAbbrev();
}
@Override
public String formatValue(String value)
{
return I18N.instance().getBugTypeDescription(value);
}
@Override
public int compare(SortableValue one, SortableValue two)
{
return formatValue(one.value).compareTo(formatValue(two.value));
}
},
TYPE(edu.umd.cs.findbugs.L10N.getLocalString("sort.bug_pattern", "Bug Pattern"))
{
@Override
public String getFrom(BugInstance bug)
{
if((bug.getBugPattern()) == null)
return "?";
else return bug.getBugPattern().getType();
}
@Override
public String formatValue(String value)
{
return I18N.instance().getShortMessageWithoutCode(value);
}
},
BUG_RANK(edu.umd.cs.findbugs.L10N.getLocalString("sort.bug_bugrank", "Bug Rank"))
{
String [] values;
{ values = new String[40];
for(int i = 0; i < values.length; i++)
values[i] = String.format("%2d", i);
}
@Override
public String getFrom(BugInstance bug)
{
if((bug.getBugPattern()) == null)
return "??";
int rank = BugRanker.findRank(bug);
return values[rank];
}
@Override
public String formatValue(String value)
{
return value;
}
},
PROJECT(edu.umd.cs.findbugs.L10N.getLocalString("sort.bug_project", "Project")) {
@Override
public String getFrom(BugInstance bug) {
ProjectPackagePrefixes p = MainFrame.getInstance().projectPackagePrefixes;
Collection<String> projects = p.getProjects(bug.getPrimaryClass().getClassName());
if (projects.size() == 0)
return "unclassified";
String result = projects.toString();
return result.substring(1, result.length() -1);
}
@Override
public boolean isAvailable(MainFrame mf) {
return mf.projectPackagePrefixes.size() > 0;
}
},
DIVIDER(" ")
{
@Override
public String getFrom(BugInstance bug)
{
throw new UnsupportedOperationException();
}
@Override
public String[] getAll()
{
throw new UnsupportedOperationException();
}
@Override
public String formatValue(String value)
{
throw new UnsupportedOperationException();
}
@Override
public int compare(SortableValue one, SortableValue two)
{
throw new UnsupportedOperationException();
}
};
String prettyName;
Sortables(String prettyName)
{
this.prettyName = prettyName;
}
@Override
public String toString()
{
return prettyName;
}
public abstract String getFrom(BugInstance bug);
public String[] getAll()
{
return getAll(BugSet.getMainBugSet());
}
public String[] getAll(BugSet set)
{
return set.getAll(this);
}
public String formatValue(String value)
{
return value;
}
public int compare(SortableValue one, SortableValue two)
{
// Lexicographical by default
return one.value.compareTo(two.value);
}
public String[] getAllSorted()
{
return getAllSorted(BugSet.getMainBugSet());
}
public String[] getAllSorted(BugSet set)
{
String[] values = getAll(set);
SortableValue[] pairs = new SortableValue[values.length];
for (int i = 0; i < values.length; i++)
pairs[i] = new SortableValue(this, values[i]);
Arrays.sort(pairs, this);
for (int i = 0; i < values.length; i++)
values[i] = pairs[i].value;
return values;
}
private SortableStringComparator comparator = new SortableStringComparator(this);
public SortableStringComparator getComparator() {
return comparator;
}
public Comparator<BugLeafNode> getBugLeafNodeComparator()
{
final Sortables key = this;
return new Comparator<BugLeafNode>()
{
public int compare(BugLeafNode one, BugLeafNode two)
{
return key.compare(new SortableValue(key, key.getFrom(one.getBug())), new SortableValue(key, key.getFrom(two.getBug())));
}
};
}
public boolean isAvailable(MainFrame frame) {
return true;
}
public static Sortables getSortableByPrettyName(String name)
{
for (Sortables s: values())
{
if (s.prettyName.equals(name))
return s;
}
return null;
}
}
|
package com.example.android.sunshine.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] forecastArray = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Weds - Cloudy - 72/63",
"Thurs - Asteroids - 75/65",
"Fri - Heavy Rain - 65/56",
"Sat - HELP TRAPPED IN WEATHERSTATION - 60/51",
"Sun - Sunny - 80/68"
};
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(forecastArray));
//ArrayAdapter will take data from a source
mForecastAdapter =
new ArrayAdapter<String>(
// the current context
getActivity(),
//ID of list item layout
R.layout.list_item_forecast,
// ID of the textview to populate
R.id.list_item_forecast_textview,
//data
weekForecast
);
ListView listView = (ListView) rootView.findViewById(
R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
}
}
|
package com.example.star.zhihudaily.base;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class BaseActivity extends AppCompatActivity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package net.minecraft.src.forge;
import net.minecraft.src.Block;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityMinecart;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.IInventory;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Item;
import net.minecraft.src.EnumStatus;
import net.minecraft.src.ModLoader;
import net.minecraft.src.World;
import java.util.*;
public class ForgeHooks {
// TODO: move all app-side hooks from MinecraftForge
// List Handling Hooks
public static void onTakenFromCrafting(EntityPlayer player, ItemStack ist,
IInventory craftMatrix) {
for (ICraftingHandler handler : craftingHandlers) {
handler.onTakenFromCrafting(player,ist,craftMatrix);
}
}
static LinkedList<ICraftingHandler> craftingHandlers = new LinkedList<ICraftingHandler>();
public static void onDestroyCurrentItem(EntityPlayer player, ItemStack orig) {
for (IDestroyToolHandler handler : destroyToolHandlers) {
handler.onDestroyCurrentItem(player,orig);
}
}
static LinkedList<IDestroyToolHandler> destroyToolHandlers = new LinkedList<IDestroyToolHandler>();
public static boolean onUseBonemeal(World world,
int bid, int i, int j, int k) {
for(IBonemealHandler handler : bonemealHandlers) {
if(handler.onUseBonemeal(world,bid,i,j,k))
return true;
}
return false;
}
static LinkedList<IBonemealHandler> bonemealHandlers = new LinkedList<IBonemealHandler>();
public static boolean onUseHoe(ItemStack hoe, EntityPlayer player,
World world, int i, int j, int k) {
for(IHoeHandler handler : hoeHandlers) {
if(handler.onUseHoe(hoe,player,world,i,j,k))
return true;
}
return false;
}
static LinkedList<IHoeHandler> hoeHandlers = new LinkedList<IHoeHandler>();
public static EnumStatus sleepInBedAt(EntityPlayer player, int i, int j, int k) {
for (ISleepHandler handler : sleepHandlers) {
EnumStatus status = handler.sleepInBedAt(player, i, j, k);
if (status != null)
return status;
}
return null;
}
static LinkedList<ISleepHandler> sleepHandlers = new LinkedList<ISleepHandler>();
public static void onMinecartUpdate(EntityMinecart minecart, int x, int y, int z)
{
for (IMinecartHandler handler : minecartHandlers)
{
handler.onMinecartUpdate(minecart, x, y, z);
}
}
public static void onMinecartEntityCollision(EntityMinecart minecart, Entity entity)
{
for (IMinecartHandler handler : minecartHandlers)
{
handler.onMinecartEntityCollision(minecart, entity);
}
}
public static boolean onMinecartInteract(EntityMinecart minecart, EntityPlayer player)
{
boolean canceled = true;
for (IMinecartHandler handler : minecartHandlers)
{
boolean tmp = handler.onMinecartInteract(minecart, player, canceled);
canceled = canceled && tmp;
}
return canceled;
}
static LinkedList<IMinecartHandler> minecartHandlers = new LinkedList<IMinecartHandler>();
// Plant Management
static class ProbableItem {
public ProbableItem(int item, int md, int q, int st, int e) {
wstart=st; wend=e;
itemid=item; meta=md;
qty=q;
}
int wstart, wend;
int itemid, meta;
int qty;
}
static ProbableItem getRandomItem(List<ProbableItem> list, int prop) {
int n=Collections.binarySearch(list,prop,new Comparator(){
public int compare(Object o1, Object o2) {
ProbableItem pi=(ProbableItem)o1;
Integer i1=(Integer)o2;
if(i1<pi.wstart) return 1;
if(i1>=pi.wend) return -1;
return 0;
}
});
if(n<0) return null;
return list.get(n);
}
static List<ProbableItem> plantGrassList;
static int plantGrassWeight;
static List<ProbableItem> seedGrassList;
static int seedGrassWeight;
static {
plantGrassList=new ArrayList<ProbableItem>();
plantGrassList.add(new ProbableItem(
Block.plantYellow.blockID,0,1,0,20));
plantGrassList.add(new ProbableItem(
Block.plantRed.blockID,0,1,20,30));
plantGrassWeight=30;
seedGrassList=new ArrayList<ProbableItem>();
seedGrassList.add(new ProbableItem(
Item.seeds.shiftedIndex,0,1,0,10));
seedGrassWeight=10;
}
public static void plantGrassPlant(World world, int i, int j, int k) {
int n=world.rand.nextInt(plantGrassWeight);
ProbableItem pi=getRandomItem(plantGrassList,n);
if(pi==null) return;
world.setBlockAndMetadataWithNotify(i,j,k,pi.itemid,pi.meta);
}
public static void addPlantGrass(int item, int md, int prop) {
plantGrassList.add(new ProbableItem(
item,md,1,plantGrassWeight,plantGrassWeight+prop));
plantGrassWeight+=prop;
}
public static ItemStack getGrassSeed(World world) {
int n=world.rand.nextInt(seedGrassWeight);
ProbableItem pi=getRandomItem(seedGrassList,n);
if(pi==null) return null;
return new ItemStack(pi.itemid,pi.qty,pi.meta);
}
public static void addGrassSeed(int item, int md, int qty, int prop) {
seedGrassList.add(new ProbableItem(
item,md,qty,seedGrassWeight,seedGrassWeight+prop));
seedGrassWeight+=prop;
}
// Tool Path
public static boolean canHarvestBlock(Block bl,
EntityPlayer player, int md) {
if(bl.blockMaterial.getIsHarvestable())
return true;
ItemStack itemstack = player.inventory.getCurrentItem();
if(itemstack == null) return false;
List tc=(List)toolClasses.get(itemstack.itemID);
if(tc==null) return itemstack.canHarvestBlock(bl);
Object[] ta=tc.toArray();
String cls=(String)ta[0]; int hvl=(Integer)ta[1];
Integer bhl=(Integer)toolHarvestLevels.get(Arrays.asList(
bl.blockID,md,cls));
if(bhl==null) return itemstack.canHarvestBlock(bl);
if(bhl>hvl) return false;
return true;
}
public static float blockStrength(Block bl,
EntityPlayer player, int md) {
float bh=bl.getHardness(md);
if(bh < 0.0F) return 0.0F;
if(!canHarvestBlock(bl,player,md)) {
return 1.0F / bh / 100F;
} else {
return player.getCurrentPlayerStrVsBlock(bl,md) /
bh / 30F;
}
}
public static boolean isToolEffective(ItemStack ist, Block bl, int md) {
List tc = (List)toolClasses.get(ist.itemID);
if (tc == null)
{
return false;
}
Object[] ta = tc.toArray();
String cls = (String)ta[0];
return toolEffectiveness.contains(Arrays.asList(bl.blockID, md, cls));
}
static void initTools() {
if(toolInit)
{
return;
}
toolInit = true;
MinecraftForge.setToolClass(Item.pickaxeWood, "pickaxe", 0);
MinecraftForge.setToolClass(Item.pickaxeStone, "pickaxe", 1);
MinecraftForge.setToolClass(Item.pickaxeSteel, "pickaxe", 2);
MinecraftForge.setToolClass(Item.pickaxeGold, "pickaxe", 0);
MinecraftForge.setToolClass(Item.pickaxeDiamond, "pickaxe", 3);
MinecraftForge.setToolClass(Item.axeWood, "axe", 0);
MinecraftForge.setToolClass(Item.axeStone, "axe", 1);
MinecraftForge.setToolClass(Item.axeSteel, "axe", 2);
MinecraftForge.setToolClass(Item.axeGold, "axe", 0);
MinecraftForge.setToolClass(Item.axeDiamond, "axe", 3);
MinecraftForge.setToolClass(Item.shovelWood, "shovel", 0);
MinecraftForge.setToolClass(Item.shovelStone, "shovel", 1);
MinecraftForge.setToolClass(Item.shovelSteel, "shovel", 2);
MinecraftForge.setToolClass(Item.shovelGold, "shovel", 0);
MinecraftForge.setToolClass(Item.shovelDiamond, "shovel", 3);
MinecraftForge.setBlockHarvestLevel(Block.obsidian, "pickaxe", 3);
MinecraftForge.setBlockHarvestLevel(Block.oreDiamond, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.blockDiamond, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.oreGold, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.blockGold, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.oreIron, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.blockSteel, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.oreLapis, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.blockLapis, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.oreRedstone, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.oreRedstoneGlowing, "pickaxe", 2);
MinecraftForge.removeBlockEffectiveness(Block.oreRedstone, "pickaxe");
MinecraftForge.removeBlockEffectiveness(Block.obsidian, "pickaxe");
MinecraftForge.removeBlockEffectiveness(Block.oreRedstoneGlowing, "pickaxe");
Block[] pickeff = {
Block.cobblestone, Block.stairDouble,
Block.stairSingle, Block.stone,
Block.sandStone, Block.cobblestoneMossy,
Block.oreCoal, Block.ice,
Block.netherrack, Block.oreLapis,
Block.blockLapis
};
for (Block bl : pickeff)
{
MinecraftForge.setBlockHarvestLevel(bl, "pickaxe", 0);
}
Block[] spadeEff = {
Block.grass, Block.dirt,
Block.sand, Block.gravel,
Block.snow, Block.blockSnow,
Block.blockClay, Block.tilledField,
Block.slowSand, Block.mycelium
};
for (Block bl : spadeEff)
{
MinecraftForge.setBlockHarvestLevel(bl, "shovel", 0);
}
Block[] axeEff = {
Block.planks, Block.bookShelf,
Block.wood, Block.chest,
Block.stairDouble, Block.stairSingle,
Block.pumpkin, Block.pumpkinLantern
};
for (Block bl : axeEff)
{
MinecraftForge.setBlockHarvestLevel(bl, "axe", 0);
}
}
public static final int majorVersion=1;
public static final int minorVersion=2;
public static final int revisionVersion=5;
static {
System.out.printf("MinecraftForge V%d.%d.%d Initialized\n", majorVersion, minorVersion, revisionVersion);
ModLoader.getLogger().info(String.format("MinecraftForge V%d.%d.%d Initialized\n", majorVersion, minorVersion, revisionVersion));
}
static boolean toolInit=false;
static HashMap toolClasses=new HashMap();
static HashMap toolHarvestLevels=new HashMap();
static HashSet toolEffectiveness=new HashSet();
}
|
package com.firstcode.xiaolu.coolweather;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
package com.gh4a.adapter.timeline;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.gh4a.R;
import com.gh4a.adapter.RootAdapter;
import com.gh4a.loader.TimelineItem;
import com.gh4a.utils.HttpImageGetter;
import com.gh4a.utils.IntentUtils;
import org.eclipse.egit.github.core.Comment;
import java.util.Collection;
public class TimelineItemAdapter extends
RootAdapter<TimelineItem, TimelineItemAdapter.TimelineItemViewHolder> {
private static final int VIEW_TYPE_COMMENT = CUSTOM_VIEW_TYPE_START + 1;
private static final int VIEW_TYPE_EVENT = CUSTOM_VIEW_TYPE_START + 2;
private static final int VIEW_TYPE_REVIEW = CUSTOM_VIEW_TYPE_START + 3;
private static final int VIEW_TYPE_DIFF = CUSTOM_VIEW_TYPE_START + 4;
private static final int VIEW_TYPE_REPLY = CUSTOM_VIEW_TYPE_START + 5;
private final HttpImageGetter mImageGetter;
private final String mRepoOwner;
private final String mRepoName;
private final int mIssueNumber;
private final boolean mIsPullRequest;
private final OnCommentAction mActionCallback;
private boolean mDontClearCacheOnClear;
private boolean mLocked;
public interface OnCommentAction {
void editComment(Comment comment);
void deleteComment(Comment comment);
void quoteText(CharSequence text);
void replyToComment(long replyToId, String text);
String getShareSubject(Comment comment);
}
private CommentViewHolder.Callback mCallback = new CommentViewHolder.Callback() {
@Override
public boolean canQuote(Comment comment) {
return !mLocked;
}
@Override
public void quoteText(CharSequence text) {
mActionCallback.quoteText(text);
}
@Override
public boolean onMenItemClick(TimelineItem.TimelineComment comment, MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.edit:
mActionCallback.editComment(comment.comment);
return true;
case R.id.delete:
mActionCallback.deleteComment(comment.comment);
return true;
case R.id.share:
IntentUtils.share(mContext, mActionCallback.getShareSubject(comment.comment),
comment.comment.getHtmlUrl());
return true;
case R.id.view_in_file:
Intent intent = comment.makeDiffIntent(mContext);
if (intent != null) {
mContext.startActivity(intent);
}
return true;
}
return false;
}
};
private ReplyViewHolder.Callback mReplyCallback = new ReplyViewHolder.Callback() {
@Override
public void reply(long replyToId, String text) {
mActionCallback.replyToComment(replyToId, text);
}
};
public TimelineItemAdapter(Context context, String repoOwner, String repoName, int issueNumber,
boolean isPullRequest, OnCommentAction callback) {
super(context);
mImageGetter = new HttpImageGetter(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
mIssueNumber = issueNumber;
mIsPullRequest = isPullRequest;
mActionCallback = callback;
}
public void setLocked(boolean locked) {
mLocked = locked;
notifyDataSetChanged();
}
public void destroy() {
mImageGetter.destroy();
}
public void pause() {
mImageGetter.pause();
}
public void resume() {
mImageGetter.resume();
}
public void suppressCacheClearOnNextClear() {
mDontClearCacheOnClear = true;
}
@Override
public void clear() {
super.clear();
if (!mDontClearCacheOnClear) {
mImageGetter.clearHtmlCache();
}
}
@Override
public void addAll(Collection<TimelineItem> objects) {
mDontClearCacheOnClear = false;
super.addAll(objects);
}
@Override
public TimelineItemViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent,
int viewType) {
View view;
TimelineItemViewHolder holder;
switch (viewType) {
case VIEW_TYPE_COMMENT:
view = inflater.inflate(R.layout.row_timeline_comment, parent, false);
holder = new CommentViewHolder(view, mImageGetter, mRepoOwner, mCallback);
break;
case VIEW_TYPE_EVENT:
view = inflater.inflate(R.layout.row_timeline_event, parent, false);
holder = new EventViewHolder(view, mIsPullRequest);
break;
case VIEW_TYPE_REVIEW:
view = inflater.inflate(R.layout.row_timeline_review, parent, false);
holder = new ReviewViewHolder(view, mRepoOwner, mRepoName, mIssueNumber,
mIsPullRequest);
break;
case VIEW_TYPE_DIFF:
view = inflater.inflate(R.layout.row_timeline_diff, parent, false);
holder = new DiffViewHolder(view, mRepoOwner, mRepoName, mIssueNumber);
break;
case VIEW_TYPE_REPLY:
view = inflater.inflate(R.layout.row_timeline_reply, parent, false);
holder = new ReplyViewHolder(view, mReplyCallback);
break;
default:
throw new IllegalArgumentException("viewType: Unknown timeline item type.");
}
return holder;
}
@Override
protected int getItemViewType(TimelineItem item) {
if (item instanceof TimelineItem.TimelineComment) {
return VIEW_TYPE_COMMENT;
}
if (item instanceof TimelineItem.TimelineEvent) {
return VIEW_TYPE_EVENT;
}
if (item instanceof TimelineItem.TimelineReview) {
return VIEW_TYPE_REVIEW;
}
if (item instanceof TimelineItem.Diff) {
return VIEW_TYPE_DIFF;
}
if (item instanceof TimelineItem.Reply) {
return VIEW_TYPE_REPLY;
}
return super.getItemViewType(item);
}
@Override
public void onBindViewHolder(TimelineItemViewHolder holder, TimelineItem item) {
switch (getItemViewType(item)) {
case VIEW_TYPE_COMMENT:
((CommentViewHolder) holder).bind((TimelineItem.TimelineComment) item);
break;
case VIEW_TYPE_EVENT:
((EventViewHolder) holder).bind((TimelineItem.TimelineEvent) item);
break;
case VIEW_TYPE_REVIEW:
((ReviewViewHolder) holder).bind((TimelineItem.TimelineReview) item);
break;
case VIEW_TYPE_DIFF:
((DiffViewHolder) holder).bind((TimelineItem.Diff) item);
break;
case VIEW_TYPE_REPLY:
((ReplyViewHolder) holder).bind((TimelineItem.Reply) item);
break;
}
}
public static abstract class TimelineItemViewHolder<TItem extends TimelineItem> extends
RecyclerView.ViewHolder {
protected final Context mContext;
public TimelineItemViewHolder(View itemView) {
super(itemView);
mContext = itemView.getContext();
}
public abstract void bind(TItem item);
}
}
|
package com.github.skittlesdev.kubrick;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.*;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import com.github.skittlesdev.kubrick.asyncs.SearchMediaTask;
import com.github.skittlesdev.kubrick.interfaces.SearchListener;
import com.github.skittlesdev.kubrick.ui.menus.DrawerMenu;
import com.github.skittlesdev.kubrick.ui.menus.ToolbarMenu;
import info.movito.themoviedbapi.TmdbSearch;
import info.movito.themoviedbapi.model.MovieDb;
import info.movito.themoviedbapi.model.Multi;
import info.movito.themoviedbapi.model.core.IdElement;
import info.movito.themoviedbapi.model.tv.TvSeries;
import android.support.v7.widget.Toolbar;
import java.util.LinkedList;
import java.util.List;
public class SearchActivity extends AppCompatActivity implements SearchListener, View.OnClickListener, AdapterView.OnItemClickListener {
private TmdbSearch.MultiListResultsPage results;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
this.setSupportActionBar((Toolbar) this.findViewById(R.id.toolBar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
new DrawerMenu(this, (DrawerLayout) findViewById(R.id.homeDrawerLayout), (RecyclerView) findViewById(R.id.homeRecyclerView)).draw();
this.setActionListener();
ImageButton submitButton = (ImageButton) findViewById(R.id.searchButton);
submitButton.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_home, menu);
new ToolbarMenu(this).filterItems(menu);
return true;
}
public void executeSearchTask(TextView searchInput, SearchActivity searchActivity) {
SearchMediaTask searchTask = new SearchMediaTask(searchActivity);
searchTask.execute(searchInput.getText().toString());
}
private void setActionListener() {
final EditText searchInput = (EditText) findViewById(R.id.search);
searchInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 2){
Context context = ((ContextWrapper) searchInput.getContext()).getBaseContext();
SearchActivity searchActivity =(SearchActivity) context;
TextView tv = new TextView(context);
tv.setText(s);
searchActivity.executeSearchTask(tv, searchActivity);
}
}
});
searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView searchInput, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
Context context = searchInput.getContext();
if (context instanceof SearchActivity) {
SearchActivity searchActivity = (SearchActivity) context;
searchActivity.executeSearchTask(searchInput, searchActivity);
handled = true;
}
}
return handled;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
new ToolbarMenu(this).itemSelected(item);
return super.onOptionsItemSelected(item);
}
/*@Override
public void onSearchResults(MovieResultsPage results) {
this.results = results;
List<String> titles = new LinkedList<>();
for(MovieDb item: results.getResults()) {
titles.add(item.getTitle());
}
ArrayAdapter<String> items = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, titles);
ListView view = (ListView) findViewById(R.id.results);
view.setAdapter(items);
view.setOnItemClickListener(this);
}*/
@Override
public void onSearchResults(TmdbSearch.MultiListResultsPage results) {
this.results = results;
List<String> titles = new LinkedList<>();
for (Multi item: results.getResults()) {
if (item.getMediaType() == Multi.MediaType.MOVIE) {
titles.add(((MovieDb) item).getTitle());
}
if (item.getMediaType() == Multi.MediaType.TV_SERIES) {
titles.add(((TvSeries) item).getName());
}
}
ArrayAdapter<String> items = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, titles);
ListView view = (ListView) findViewById(R.id.results);
view.setAdapter(items);
view.setOnItemClickListener(this);
}
@Override
public void onClick(View view) {
this.executeSearchTask((EditText) findViewById(R.id.search), this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Multi item = this.results.getResults().get(position);
if (item.getMediaType() == Multi.MediaType.MOVIE) {
int movieId = ((IdElement) item).getId();
Intent intent = new Intent(this, MediaActivity.class);
intent.putExtra("MEDIA_ID", movieId);
intent.putExtra("MEDIA_TYPE", "movie");
startActivity(intent);
}
if (item.getMediaType() == Multi.MediaType.TV_SERIES) {
int seriesId = ((IdElement) item).getId();
Intent intent = new Intent(this, MediaActivity.class);
intent.putExtra("MEDIA_ID", seriesId);
intent.putExtra("MEDIA_TYPE", "tv");
startActivity(intent);
}
}
}
|
package com.manoj.dlt.features;
import android.content.Context;
import com.google.firebase.database.DatabaseReference;
import com.manoj.dlt.Constants;
import com.manoj.dlt.DbConstants;
import com.manoj.dlt.events.DeepLinkFireEvent;
import com.manoj.dlt.interfaces.IDeepLinkHistory;
import com.manoj.dlt.models.DeepLinkInfo;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DeepLinkHistoryFeature implements IDeepLinkHistory
{
private static DeepLinkHistoryFeature _instance;
private FileSystem _fileSystem;
private Context _context;
private DeepLinkHistoryFeature(Context context)
{
_fileSystem = new FileSystem(context, Constants.DEEP_LINK_HISTORY_KEY);
EventBus.getDefault().register(this);
_context = context;
}
public static DeepLinkHistoryFeature getInstance(Context context)
{
if(_instance == null)
{
_instance = new DeepLinkHistoryFeature(context);
}
return _instance;
}
@Override
public List<DeepLinkInfo> getAllLinksSearchedInfo()
{
//TODO: read from firebase
List<DeepLinkInfo> deepLinks = new ArrayList<DeepLinkInfo>();
for (String deepLinkInfoJson : _fileSystem.values())
{
deepLinks.add(DeepLinkInfo.fromJson(deepLinkInfoJson));
}
Collections.sort(deepLinks);
return deepLinks;
}
@Override
public List<String> getAllLinksSearched()
{
return _fileSystem.keyList();
}
@Override
public void addLinkToHistory(final DeepLinkInfo deepLinkInfo)
{
DatabaseReference baseUserReference = ProfileFeature.getInstance(_context).getCurrentUserFirebaseBaseRef();
DatabaseReference linkReference = baseUserReference.child(DbConstants.USER_HISTORY).child(deepLinkInfo.getId());
Map<String, Object> infoMap = new HashMap<String, Object>(){{
put(DbConstants.DL_ACTIVITY_LABEL, deepLinkInfo.getActivityLabel());
put(DbConstants.DL_DEEP_LINK, deepLinkInfo.getDeepLink());
put(DbConstants.DL_PACKAGE_NAME, deepLinkInfo.getPackageName());
put(DbConstants.DL_UPDATED_TIME, deepLinkInfo.getUpdatedTime());
}};
linkReference.setValue(infoMap);
//TODO: remove this legacy code
_fileSystem.write(deepLinkInfo.getId(), DeepLinkInfo.toJson(deepLinkInfo));
}
@Override
public void removeLinkFromHistory(String deepLinkId)
{
_fileSystem.clear(deepLinkId);
}
@Override
public void clearAllHistory()
{
_fileSystem.clearAll();
}
@Subscribe(sticky = true, priority = 1)
public void onEvent(DeepLinkFireEvent deepLinkFireEvent)
{
addLinkToHistory(deepLinkFireEvent.getDeepLinkInfo());
}
}
|
package com.studio4plus.homerplayer.model;
import android.content.Context;
import android.os.Environment;
import android.util.Base64;
import com.studio4plus.homerplayer.util.DirectoryFilter;
import com.studio4plus.homerplayer.util.FilesystemUtil;
import com.studio4plus.homerplayer.util.OrFilter;
import java.io.File;
import java.io.FileFilter;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
public class FileScanner {
static final String SAMPLE_BOOK_FILE_NAME = ".sample";
private static final String[] SUPPORTED_SUFFIXES = {".mp3", ".m4a", ".ogg"};
private final String audioBooksDirectoryPath;
private final Context context;
@Inject
public FileScanner(
@Named("AUDIOBOOKS_DIRECTORY") String audioBooksDirectoryPath,
Context context) {
this.audioBooksDirectoryPath = audioBooksDirectoryPath;
this.context = context;
}
public List<FileSet> scanAudioBooksDirectories() {
List<FileSet> fileSets = new ArrayList<>();
List<File> dirsToScan = FilesystemUtil.listRootDirs(context);
File defaultStorage = Environment.getExternalStorageDirectory();
if (!containsByValue(dirsToScan, defaultStorage))
dirsToScan.add(defaultStorage);
for (File rootDir : dirsToScan) {
File audioBooksDir = new File(rootDir, audioBooksDirectoryPath);
scanAndAppendBooks(audioBooksDir, fileSets);
}
return fileSets;
}
/**
* Provide the default directory for audio books.
*
* The directory is in the devices external storage. Other than that there is nothing
* special about it (e.g. it may be on an removable storage).
*/
public File getDefaultAudioBooksDirectory() {
File externalStorage = Environment.getExternalStorageDirectory();
return new File(externalStorage, audioBooksDirectoryPath);
}
private void scanAndAppendBooks(File audioBooksDir, List<FileSet> fileSets) {
if (audioBooksDir.exists() && audioBooksDir.isDirectory() && audioBooksDir.canRead()) {
File[] audioBookDirs = audioBooksDir.listFiles(new DirectoryFilter());
for (File directory : audioBookDirs) {
FileSet fileSet = createFileSet(directory);
if (fileSet != null && !fileSets.contains(fileSet))
fileSets.add(fileSet);
}
}
}
private FileSet createFileSet(File bookDirectory) {
File[] allFiles = getAllAudioFiles(bookDirectory);
int bookDirectoryPathLength = bookDirectory.getAbsolutePath().length();
ByteBuffer bufferLong = ByteBuffer.allocate(Long.SIZE);
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
for (File file : allFiles) {
String path = file.getAbsolutePath();
String relativePath = path.substring(bookDirectoryPathLength);
// TODO: what if the same book is in two directories?
bufferLong.putLong(0, file.length());
digest.update(relativePath.getBytes());
digest.update(bufferLong);
}
String id = Base64.encodeToString(digest.digest(), Base64.NO_PADDING | Base64.NO_WRAP);
if (allFiles.length > 0) {
File sampleIndicator = new File(bookDirectory, SAMPLE_BOOK_FILE_NAME);
boolean isDemoSample = sampleIndicator.exists();
return new FileSet(id, bookDirectory, allFiles, isDemoSample);
} else {
return null;
}
} catch (NoSuchAlgorithmException e) {
// Never happens.
e.printStackTrace();
throw new RuntimeException("MD5 not available");
}
}
private File[] getAllAudioFiles(File directory) {
List<File> files = new ArrayList<>();
FileFilter audioFiles = new FileFilter() {
@Override
public boolean accept(File pathname) {
return isAudioFile(pathname);
}
};
FileFilter filesAndDirectoriesFilter = new OrFilter(audioFiles, new DirectoryFilter());
addFilesRecursive(directory, filesAndDirectoriesFilter, files);
return files.toArray(new File[files.size()]);
}
private void addFilesRecursive(File directory, FileFilter filter, List<File> allFiles) {
File[] files = directory.listFiles(filter);
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
return lhs.getName().compareToIgnoreCase(rhs.getName());
}
});
for (File file : files) {
if (file.isDirectory()) {
addFilesRecursive(file, filter, allFiles);
} else {
allFiles.add(file);
}
}
}
private <Type> boolean containsByValue(List<Type> items, Type needle) {
for (Type item : items)
if (item.equals(needle))
return true;
return false;
}
private static boolean isAudioFile(File file) {
String lowerCaseFileName = file.getName().toLowerCase();
for (String suffix : SUPPORTED_SUFFIXES)
if (lowerCaseFileName.endsWith(suffix))
return true;
return false;
}
}
|
package com.apps.adrcotfas.goodtime.BL;
import android.os.SystemClock;
import java.util.concurrent.TimeUnit;
import static androidx.preference.PreferenceManager.getDefaultSharedPreferences;
public class PreferenceHelper {
private final static String FIRST_RUN = "pref_first_run";
public final static String PROFILE = "pref_profile";
public final static String WORK_DURATION = "pref_work_duration";
public final static String BREAK_DURATION = "pref_break_duration";
public final static String ENABLE_LONG_BREAK = "pref_enable_long_break";
public final static String LONG_BREAK_DURATION = "pref_long_break_duration";
public final static String SESSIONS_BEFORE_LONG_BREAK = "pref_sessions_before_long_break";
public final static String ENABLE_RINGTONE = "pref_enable_ringtone";
public final static String INSISTENT_RINGTONE = "pref_ringtone_insistent";
public final static String RINGTONE_WORK = "pref_ringtone";
public final static String RINGTONE_BREAK = "pref_ringtone_break";
public final static String ENABLE_VIBRATE = "pref_vibrate";
public final static String ENABLE_FULLSCREEN = "pref_fullscreen";
public final static String DISABLE_SOUND_AND_VIBRATION = "pref_disable_sound_and_vibration";
public final static String DISABLE_WIFI = "pref_disable_wifi";
public final static String ENABLE_SCREEN_ON = "pref_keep_screen_on";
public final static String ENABLE_CONTINUOUS_MODE = "pref_continuous_mode";
public final static String THEME = "pref_theme";
public final static String DISABLE_BATTERY_OPTIMIZATION = "pref_disable_battery_optimization";
public final static String WORK_STREAK = "pref_WORK_STREAK";
public final static String LAST_WORK_FINISHED_AT = "pref_last_work_finished_at";
private static final String ADDED_60_SECONDS_STATE = "pref_added_60_seconds_State";
private static final String CURRENT_SESSION_LABEL = "pref_current_session_label";
private static final String INTRO_SNACKBAR_STEP = "pref_intro_snackbar_step";
public static long getSessionDuration(SessionType sessionType) {
final long duration;
switch (sessionType) {
case WORK:
duration = getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getInt(WORK_DURATION, 25);
break;
case BREAK:
duration = getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getInt(BREAK_DURATION, 5);
break;
case LONG_BREAK:
duration = getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getInt(LONG_BREAK_DURATION, 15);
break;
default:
duration = 42;
break;
}
return duration;
}
public static boolean isLongBreakEnabled() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getBoolean(ENABLE_LONG_BREAK, false);
}
public static int getSessionsBeforeLongBreak() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getInt(SESSIONS_BEFORE_LONG_BREAK, 4);
}
public static boolean isRingtoneEnabled() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getBoolean(ENABLE_RINGTONE, true);
}
public static boolean isRingtoneInsistent() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getBoolean(INSISTENT_RINGTONE, false);
}
public static String getNotificationSound() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getString(RINGTONE_WORK, "");
}
public static String getNotificationSoundBreak() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getString(RINGTONE_BREAK, "");
}
public static boolean isVibrationEnabled() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getBoolean(ENABLE_VIBRATE, true);
}
public static boolean isFullscreenEnabled() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getBoolean(ENABLE_FULLSCREEN, false);
}
public static boolean isSoundAndVibrationDisabled() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getBoolean(DISABLE_SOUND_AND_VIBRATION, false);
}
public static boolean isWiFiDisabled() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getBoolean(DISABLE_WIFI, false);
}
public static boolean isScreenOnEnabled() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getBoolean(ENABLE_SCREEN_ON, false);
}
public static boolean isContinuousModeEnabled() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getBoolean(ENABLE_CONTINUOUS_MODE, false);
}
public static int getTheme() {
return getDefaultSharedPreferences(GoodtimeApplication.getInstance())
.getInt(THEME, 0);
}
/**
* Increments the current completed work session streak but only if it's completed
* in a reasonable time frame comparing with the last completed work session,
* else it considers this session the first completed one in the streak.
*/
public static void incrementCurrentStreak() {
// Add an extra 10 minutes to a work and break sessions duration
// If the user did not complete another session in this time frame, just increment from 0.
final long maxDifference = TimeUnit.MINUTES.toMillis(PreferenceHelper.getSessionDuration(SessionType.WORK)
+ PreferenceHelper.getSessionDuration(SessionType.BREAK)
+ 10);
final long currentMillis = SystemClock.elapsedRealtime();
final boolean increment = lastWorkFinishedAt() == 0
|| currentMillis - lastWorkFinishedAt() < maxDifference;
GoodtimeApplication.getSharedPreferences().edit()
.putInt(WORK_STREAK, increment ? getCurrentStreak() + 1 : 1).apply();
GoodtimeApplication.getSharedPreferences().edit()
.putLong(LAST_WORK_FINISHED_AT, increment ? currentMillis: 0).apply();
}
public static int getCurrentStreak() {
return GoodtimeApplication.getSharedPreferences().getInt(WORK_STREAK, 0);
}
public static long lastWorkFinishedAt() {
return GoodtimeApplication.getSharedPreferences().getLong(LAST_WORK_FINISHED_AT, 0);
}
public static void resetCurrentStreak() {
GoodtimeApplication.getSharedPreferences().edit()
.putInt(WORK_STREAK, 0).apply();
GoodtimeApplication.getSharedPreferences().edit()
.putLong(LAST_WORK_FINISHED_AT, 0).apply();
}
public static boolean itsTimeForLongBreak() {
return getCurrentStreak() >= getSessionsBeforeLongBreak();
}
/**
* Persists the state of a session prolonged by the "Add 60 seconds" action.
* It should be set to true when a session is started from an inactive state with the
* "add 60 seconds" action.
* It should be set to false when a session is stopped by a "stop" event and when a session is finished.
* @param enable specifies the new state.
*/
public static void toggleAdded60SecondsState(boolean enable) {
GoodtimeApplication.getSharedPreferences().edit()
.putBoolean(ADDED_60_SECONDS_STATE, enable).apply();
}
/**
* This is used to identify when not to increase the current finished session streak.
* @return the state of the "added 60 seconds" state.
*/
public static boolean isInAdded60SecondsState() {
return GoodtimeApplication.getSharedPreferences().getBoolean(ADDED_60_SECONDS_STATE, false);
}
public static String getCurrentSessionLabel() {
return GoodtimeApplication.getSharedPreferences().getString(CURRENT_SESSION_LABEL, null);
}
public static void setCurrentSessionLabel(String label) {
GoodtimeApplication.getSharedPreferences().edit()
.putString(CURRENT_SESSION_LABEL, label).apply();
}
public static boolean isFirstRun() {
return GoodtimeApplication.getSharedPreferences().getBoolean(FIRST_RUN, true);
}
public static void consumeFirstRun() {
GoodtimeApplication.getSharedPreferences().edit()
.putBoolean(FIRST_RUN, true).apply();
}
public static int getLastIntroStep() {
return GoodtimeApplication.getSharedPreferences().getInt(INTRO_SNACKBAR_STEP, 0);
}
public static void setLastIntroStep(int step) {
GoodtimeApplication.getSharedPreferences().edit()
.putInt(INTRO_SNACKBAR_STEP, step).apply();
}
}
|
package com.uwics.uwidiscover.activities;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.uwics.uwidiscover.R;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class LiveActivity extends AppCompatActivity {
private final static Calendar CURRENT_DAY = Calendar.getInstance();
private final static Calendar DAY_ONE = new GregorianCalendar(2016, 1, 17);
private final static Calendar DAY_TWO = new GregorianCalendar(2016, 1, 18);
private final static Calendar DAY_THREE = new GregorianCalendar(2016, 1, 19);
private final static int DAY_ONE_DAY_OF_YEAR = DAY_ONE.get(Calendar.DAY_OF_YEAR);
private final static int DAY_TWO_DAY_OF_YEAR = DAY_TWO.get(Calendar.DAY_OF_YEAR);
private final static int DAY_THREE_DAY_OF_YEAR = DAY_THREE.get(Calendar.DAY_OF_YEAR);
private final static int DAY_ONE_YEAR = DAY_ONE.get(Calendar.YEAR);
private final static int DAY_TWO_YEAR = DAY_TWO.get(Calendar.YEAR);
private final static int DAY_THREE_YEAR = DAY_THREE.get(Calendar.YEAR);
private WebView mWebView;
private ProgressBar progressBar;
private Spinner streamChannelSpinner;
private TextView noStreamTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
if (getActionBar() != null) {
getActionBar().setTitle("Live");
getActionBar().setDisplayHomeAsUpEnabled(true);
}
mWebView = (WebView) findViewById(R.id.webview);
streamChannelSpinner = (Spinner) findViewById(R.id.channel_selector_spinner);
noStreamTextView = (TextView) findViewById(R.id.text_no_stream_available);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setMax(100);
setUpChannelSpinner();
setUpWebView();
}
private void setUpChannelSpinner() {
ArrayAdapter<String> streamChannelOptionsAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.array_stream_channels));
streamChannelOptionsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
streamChannelSpinner.setAdapter(streamChannelOptionsAdapter);
streamChannelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int channelIndex = parent.getSelectedItemPosition();
// TODO: Put delay to show that stream has changed
showStream(channelIndex);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
@SuppressWarnings("StatementWithEmptyBody")
private void showStream(int channelIndex) {
// TODO: Gonna probably run this through an Async after testing
// TODO: Do some check to show unavailable stream if user is on screen and the stream ends
// int i = currResearchDay();
int i = researchDayIndex();
if (i != 0) {
String streamUrl = validLinkToStreamForTime(i, channelIndex);
if (streamUrl != null) {
noStreamTextView.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
mWebView.loadUrl(streamUrl);
} else {
mWebView.setVisibility(View.GONE);
noStreamTextView.setVisibility(View.VISIBLE);
}
} else {
mWebView.setVisibility(View.GONE);
noStreamTextView.setVisibility(View.VISIBLE);
}
}
private int currResearchDay() {
// if (isResearchDay(DAY_ONE)) {
// return 1;
// } else if (isResearchDay(DAY_TWO)) {
// return 2;
// } else if (isResearchDay(DAY_THREE)) {
// return 3;
// } else {
// return 0;
return researchDayIndex();
}
private int researchDayIndex() {
if ((CURRENT_DAY.get(Calendar.YEAR) == DAY_ONE_YEAR) && (CURRENT_DAY.get(Calendar.DAY_OF_YEAR) == DAY_ONE_DAY_OF_YEAR)) {
return 1;
} else if ((CURRENT_DAY.get(Calendar.YEAR) == DAY_TWO_YEAR) && (CURRENT_DAY.get(Calendar.DAY_OF_YEAR) == DAY_TWO_DAY_OF_YEAR)) {
return 2;
} else if ((CURRENT_DAY.get(Calendar.YEAR) == DAY_THREE_YEAR) && (CURRENT_DAY.get(Calendar.DAY_OF_YEAR) == DAY_THREE_DAY_OF_YEAR)) {
return 3;
} else return 0;
}
private boolean isResearchDay(Calendar rDay) {
// TODO: DAY_OF_YEAR being incremented/decremented by 1 when it gets here after initial run. Figure out why
return (CURRENT_DAY.get(Calendar.YEAR) == rDay.get(Calendar.YEAR))
&& (CURRENT_DAY.get(Calendar.DAY_OF_YEAR) == rDay.get(Calendar.DAY_OF_YEAR));
}
/* D1
9 - 12 : C1 - S1
10:30 - 3 : C2 - S2
12 - ?? : C1 - S3
2 - 7 : C3 - S4
5:16 - 9 : C2 - S5
D2
11 - 1:30 : C1 - S1
12 - 3 : C2 - S2
1:30 - 4 : C1 - S3
1:30 - 5 : C3 - S4
2:30 - 5:30 : C4 - S5
4 - 9 : C1 - S6
4 - 9 : C2 - S7
D3
(9:30 (10 - 12) 12:30) : C1 - S1
(11:45 (12 - 12:45) 1) : C2 - S2
3 - ?? : C1 - S3 */
@Nullable
private String validLinkToStreamForTime(int rDayIndex, int cStream) {
if (rDayIndex == 1) {
if (cStream == 0) {
if (CURRENT_DAY.after(tempDay(rDayIndex, 9, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 12, 0))) {
return getString(R.string.string_d1_s1_c1);
} else if (CURRENT_DAY.after(tempDay(rDayIndex, 12, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 13, 0))) {
// TODO: Verify this time
return getString(R.string.string_d1_s3_c1);
}
} else if (cStream == 1) {
if (CURRENT_DAY.after(tempDay(rDayIndex, 10, 30)) && CURRENT_DAY.before(tempDay(rDayIndex, 21, 0))) {
return getString(R.string.string_d1_s2_c2);
} else if (CURRENT_DAY.after(tempDay(rDayIndex, 17, 16)) && CURRENT_DAY.before(tempDay(rDayIndex, 9, 0))) {
return getString(R.string.string_d1_s5_c2);
}
} else if (cStream == 2) {
if (CURRENT_DAY.after(tempDay(rDayIndex, 14, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 19, 0))) {
return getString(R.string.string_d1_s4_c3);
}
} else if (cStream == 3) {
return null;
}
} else if (rDayIndex == 2) {
if (cStream == 0) {
if (CURRENT_DAY.after(tempDay(rDayIndex, 11, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 13, 30))) {
return getString(R.string.string_d2_s1_c1);
} else if (CURRENT_DAY.after(tempDay(rDayIndex, 13, 30)) && CURRENT_DAY.before(tempDay(rDayIndex, 16, 0))) {
return getString(R.string.string_d2_s3_c1);
} else if (CURRENT_DAY.after(tempDay(rDayIndex, 16, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 21, 0))) {
return getString(R.string.string_d2_s6_c1);
}
} else if (cStream == 1) {
if (CURRENT_DAY.after(tempDay(rDayIndex, 21, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 21, 0))) {
return getString(R.string.string_d2_s2_c2);
} else if (CURRENT_DAY.after(tempDay(rDayIndex, 16, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 21, 0))) {
return getString(R.string.string_d2_s7_c2);
}
} else if (cStream == 2) {
if (CURRENT_DAY.after(tempDay(rDayIndex, 13, 30)) && CURRENT_DAY.before(tempDay(rDayIndex, 17, 0))) {
return getString(R.string.string_d2_s4_c3);
}
} else if (cStream == 3) {
if (CURRENT_DAY.after(tempDay(rDayIndex, 14, 30)) && CURRENT_DAY.before(tempDay(rDayIndex, 17, 30))) {
return getString(R.string.string_d2_s5_c4);
}
}
} else if (rDayIndex == 3) {
if (cStream == 0) {
if (CURRENT_DAY.after(tempDay(rDayIndex, 10, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 12, 0))) {
// TODO: Verify this time
return getString(R.string.string_d3_s1_c1);
} else if (CURRENT_DAY.after(tempDay(rDayIndex, 15, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 17, 0))) {
// TODO: Verify this time
return getString(R.string.string_d3_s3_c1);
}
} else if (cStream == 1) {
if (CURRENT_DAY.after(tempDay(rDayIndex, 12, 0)) && CURRENT_DAY.before(tempDay(rDayIndex, 12, 45))) {
// TODO: Verify this time
return getString(R.string.string_d3_s2_c2);
}
} else if (cStream == 2) {
return null;
} else if (cStream == 3) {
return null;
}
}
return null;
}
@Nullable
private Calendar tempDay(int cal, int hourOfDay, int min) {
Calendar temp;
switch (cal) {
case 1:
temp = DAY_ONE;
temp.set(Calendar.HOUR_OF_DAY, hourOfDay);
temp.set(Calendar.MINUTE, min);
return temp;
case 2:
temp = DAY_TWO;
temp.set(Calendar.HOUR_OF_DAY, hourOfDay);
temp.set(Calendar.MINUTE, min);
return temp;
case 3:
temp = DAY_THREE;
temp.set(Calendar.HOUR_OF_DAY, hourOfDay);
temp.set(Calendar.MINUTE, min);
return temp;
default:
return null;
}
}
@SuppressLint("SetJavaScriptEnabled")
private void setUpWebView() {
mWebView.setWebViewClient(new WebClient());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class WebClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
progressBar.setProgress(100);
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
}
|
package com.example.aventador.protectalarm;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.comthings.gollum.api.gollumandroidlib.GollumDongle;
import com.comthings.gollum.api.gollumandroidlib.callback.GollumCallbackGetBoolean;
import com.example.aventador.protectalarm.callbacks.DongleCallbacks;
import com.example.aventador.protectalarm.events.Action;
import com.example.aventador.protectalarm.events.ActionEvent;
import com.example.aventador.protectalarm.events.State;
import com.example.aventador.protectalarm.events.StateEvent;
import com.example.aventador.protectalarm.process.Pandwarf;
import com.example.aventador.protectalarm.tools.Logger;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import no.nordicsemi.android.nrftoolbox.scanner.ExtendedBluetoothDevice;
import no.nordicsemi.android.nrftoolbox.scanner.ScannerListener;
import static android.view.View.GONE;
import static com.example.aventador.protectalarm.tools.Tools.isValidAddressMac;
/**
* A placeholder fragment containing a simple view.
*/
/**
* HomeFragment allows the user to select the pandwarf mac address to connect
*/
public class HomeFragment extends Fragment {
private static final String TAG = "HomeFragment";
private Button connectionButton;
private AtomicBoolean scanIsRunning;
private AtomicBoolean connexionInProgress;
private ProgressBar scanProgressbar;
private ListView listView;
private TextView pandwarfConnectedTextView;
public HomeFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View bodyView = inflater.inflate(R.layout.fragment_home, container, false);
scanProgressbar = (ProgressBar) bodyView.findViewById(R.id.scan_progressbar);
scanProgressbar.setIndeterminate(true);
scanProgressbar.setVisibility(GONE);
pandwarfConnectedTextView = (TextView) bodyView.findViewById(R.id.pandwarf_connected_text_view);
listView = (ListView) bodyView.findViewById(R.id.pandwarf_list_view);
listView.setAdapter(new ListAdapterCustom(getContext(), 0, new ArrayList<ExtendedBluetoothDevice>()));
scanIsRunning = new AtomicBoolean(false);
connexionInProgress = new AtomicBoolean(false);
connectionButton = (Button) bodyView.findViewById(R.id.connection_button);
resetFragment();
return bodyView;
}
@Override
@Subscribe
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Override
@CallSuper
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
public void connect(ExtendedBluetoothDevice extendedBluetoothDevice) {
if (!Pandwarf.getInstance().isConnected() && connexionInProgress.compareAndSet(false, true)) {
GollumDongle.getInstance(getActivity()).openDevice(extendedBluetoothDevice, true, false, new DongleCallbacks());
}
}
public void disconnect() {
killAllProcess(new GollumCallbackGetBoolean() {
@Override
public void done(boolean b) {
resetFragment();
Pandwarf.getInstance().close(getActivity());
EventBus.getDefault().postSticky(new StateEvent(State.DISCONNECTED, ""));
}
});
}
/**
* Reset the progress bar and connectionButton.
* stop the scan process.
*/
private void stopScan() {
if (scanIsRunning.compareAndSet(true, false)) {
resetFragment();
GollumDongle.getInstance(getActivity()).stopSearchDevice();
}
}
/**
* Search all pandwarf in the environment.
* Start scan process.
*/
private void startScan() {
if (BluetoothAdapter.getDefaultAdapter().getState() != BluetoothAdapter.STATE_ON) {
Toast toast = Toast.makeText(getContext(), "Bluetooth must be started", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
return;
}
scanProgressbar.setVisibility(View.VISIBLE);
connectionButton.setText(getString(R.string.stop_scan_pandwarf));
connectionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopScan();
}
});
if (!scanIsRunning.compareAndSet(false, true)) {
Logger.e(TAG, "scan is already running");
return;
}
Logger.d(TAG, "start search: ");
GollumDongle.getInstance(getActivity()).searchDevice(new ScannerListener() {
@Override
public void onSignalNewDevice(ExtendedBluetoothDevice extendedBluetoothDevice) {
Logger.d(TAG, "onSignalNewDevice: " + extendedBluetoothDevice.getAddress());
ListAdapterCustom listAdapterCustom = ((ListAdapterCustom) listView.getAdapter());
listAdapterCustom.add(extendedBluetoothDevice);
listAdapterCustom.notifyDataSetChanged();
}
@Override
public void onSignalUpdateDevice(ExtendedBluetoothDevice extendedBluetoothDevice) {
}
@Override
public void onSignalEndScan(Exception e) {
}
});
}
/**
* Reset the progress bar and connectionButton.
*/
public void resetFragment() {
connectionButton.setText(getString(R.string.start_scan_pandwarf));
scanProgressbar.setVisibility(View.GONE);
connectionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startScan();
}
});
}
/**
* Kill all process, scan, threshold discovery, protection, jamming, fast protection analyzer
* /!\ Duplicated in Main2Activity /!\
*/
public void killAllProcess(final GollumCallbackGetBoolean killDone) {
Pandwarf.getInstance().stopFastProtectionAnalyzer(getActivity(), new GollumCallbackGetBoolean() {
@Override
public void done(boolean b) {
Pandwarf.getInstance().stopDiscovery(getActivity(), new GollumCallbackGetBoolean() {
@Override
public void done(boolean b) {
Pandwarf.getInstance().stopGuardian(getActivity(), new GollumCallbackGetBoolean() {
@Override
public void done(boolean b) {
Pandwarf.getInstance().stopJamming(getActivity(), true, new GollumCallbackGetBoolean() {
@Override
public void done(boolean b) {
killDone.done(true);
Pandwarf.getInstance().close(getActivity());
}
});
}
});
}
});
}
});
}
/**
* Used by EventBus
* Called when a Publisher send a action to be executed.
* @param actionEvent
*/
@Subscribe
public void onMessageEvent(ActionEvent actionEvent) {
}
/**
* Used by EventBus
* Called when a Publisher send a state.
* @param stateEvent
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(StateEvent stateEvent) {
Logger.d(TAG, "onMessageEvent: State Event: " + stateEvent.getState());
switch (stateEvent.getState()) {
case CONNECTED: {
Logger.d(TAG, "CONNECTED");
scanProgressbar.setVisibility(GONE);
connexionInProgress.set(false);
pandwarfConnectedTextView.setText("Pandwarf: " + GollumDongle.getInstance(getActivity()).getCurrentBleDeviceMacAddress());
stopScan();
connectionButton.setText(getString(R.string.disconnect_pandwarf));
connectionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
disconnect();
}
});
break;
}
case DISCONNECTED: {
Logger.d(TAG, "DISCONNECTED");
pandwarfConnectedTextView.setText("Pandwarf:");
resetFragment();
break;
}
}
}
private class ListAdapterCustom extends ArrayAdapter<ExtendedBluetoothDevice> {
private List<ExtendedBluetoothDevice> extendedBluetoothDevices;
public ListAdapterCustom(@NonNull Context context, int resource) {
super(context, resource);
}
public ListAdapterCustom(@NonNull Context context, int resource, int textViewResourceId) {
super(context, resource, textViewResourceId);
extendedBluetoothDevices = new ArrayList<>();
}
public ListAdapterCustom(@NonNull Context context, int resource, @NonNull ExtendedBluetoothDevice[] objects) {
super(context, resource, objects);
extendedBluetoothDevices = Arrays.asList(objects);
}
public ListAdapterCustom(@NonNull Context context, int resource, int textViewResourceId, @NonNull ExtendedBluetoothDevice[] objects) {
super(context, resource, textViewResourceId, objects);
extendedBluetoothDevices = Arrays.asList(objects);
}
public ListAdapterCustom(@NonNull Context context, int resource, @NonNull List<ExtendedBluetoothDevice> objects) {
super(context, resource, objects);
extendedBluetoothDevices = objects;
}
public ListAdapterCustom(@NonNull Context context, int resource, int textViewResourceId, @NonNull List<ExtendedBluetoothDevice> objects) {
super(context, resource, textViewResourceId, objects);
extendedBluetoothDevices = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.row_connection_listview, parent, false);;
} else {
view = convertView;
}
final ExtendedBluetoothDevice extendedBluetoothDevice = getItem(position);
if (extendedBluetoothDevice == null) {
return view;
}
TextView bleAddressTextView = (TextView) view.findViewById(R.id.ble_address_text_view);
bleAddressTextView.setText("Pandwarf: " + extendedBluetoothDevice.getAddress().toUpperCase());
bleAddressTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
connect(extendedBluetoothDevice);
}
});
return view;
}
}
}
|
package com.walletudo.ui.statistics;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.github.clans.fab.FloatingActionMenu;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.walletudo.R;
import com.walletudo.Walletudo;
import com.walletudo.model.Tag;
import com.walletudo.service.StatisticService;
import com.walletudo.ui.view.AmountView;
import com.walletudo.ui.view.PeriodView;
import com.walletudo.ui.view.TagView;
import org.joda.time.LocalDate;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class StatisticFragment extends Fragment {
private static final int FAB_MENU_COUNT = 3;
@InjectView(R.id.summaryView)
CardView summaryView;
@InjectView(R.id.balance)
AmountView balance;
@InjectView(R.id.period)
PeriodView period;
@InjectView(R.id.viewPager)
ViewPager viewPager;
@InjectView(R.id.emptyProfitList)
TextView emptyProfitList;
@InjectView(R.id.profitList)
ListView profitList;
@InjectView(R.id.emptyLostList)
TextView emptyLostList;
@InjectView(R.id.lostList)
ListView lostList;
@InjectView(R.id.fab)
FloatingActionMenu fab;
@Inject
StatisticService statisticService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((Walletudo) getActivity().getApplication()).component().inject(this);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = View.inflate(getActivity(), R.layout.fragment_statistics, null);
ButterKnife.inject(this, view);
setupViews();
onFabWeekPeriodClick();
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.toolbar_tabs);
tabLayout.setVisibility(View.VISIBLE);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViews() {
profitList.setEmptyView(emptyProfitList);
lostList.setEmptyView(emptyLostList);
viewPager.setAdapter(new PagerAdapter() {
@Override
public Object instantiateItem(ViewGroup container, int position) {
switch (position) {
case 0:
return getActivity().findViewById(R.id.profitView);
case 1:
return getActivity().findViewById(R.id.lostView);
}
return null;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.statisticsProfitLabel);
case 1:
return getString(R.string.statisticsLostLabel);
}
return "";
}
@Override
public int getCount() {
return 2;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
});
}
@OnClick(R.id.fab_week)
public void onFabWeekPeriodClick() {
LocalDate now = LocalDate.now();
setupStatisticFromPeriod(now.dayOfWeek().withMinimumValue(), now.dayOfWeek().withMaximumValue());
fab.close(true);
}
@OnClick(R.id.fab_month)
public void onFabMonthPeriodClick() {
LocalDate now = LocalDate.now();
setupStatisticFromPeriod(now.dayOfMonth().withMinimumValue(), now.dayOfMonth().withMaximumValue());
fab.close(true);
}
@OnClick(R.id.fab_custom)
public void onFabCustomPeriodClick() {
Toast.makeText(getActivity(), getActivity().getString(R.string.statisticCustomPeriodNotAvailable), Toast.LENGTH_SHORT).show();
}
private void setupStatisticFromPeriod(LocalDate from, LocalDate to) {
StatisticService.Statistics statistics = statisticService.getStatistics(from.toDate(), to.toDate());
balance.setAmount(statistics.getBalance());
period.setPeriod(from.toDate(), to.plusDays(1).toDate());
profitList.setAdapter(new StatisticEntryAdapter(getActivity(), statistics.getProfit()));
handlePaddingOnProfitAndLostList();
List<Map.Entry<Tag, Double>> lost = Lists.transform(statistics.getLost(), new Function<Map.Entry<Tag, Double>, Map.Entry<Tag, Double>>() {
@Override
public Map.Entry<Tag, Double> apply(@Nullable Map.Entry<Tag, Double> input) {
return Maps.immutableEntry(input.getKey(), -input.getValue());
}
});
lostList.setAdapter(new StatisticEntryAdapter(getActivity(), lost));
}
private void handlePaddingOnProfitAndLostList() {
summaryView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int listTopPadding = summaryView.getHeight() + ((ViewGroup.MarginLayoutParams) summaryView.getLayoutParams()).topMargin;
profitList.setPadding(0, listTopPadding, 0, profitList.getPaddingBottom());
lostList.setPadding(0, listTopPadding, 0, lostList.getPaddingBottom());
summaryView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
fab.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int listBottomPadding = (fab.getHeight() / (FAB_MENU_COUNT + 1)) + ((ViewGroup.MarginLayoutParams) fab.getLayoutParams()).bottomMargin;
profitList.setPadding(0, profitList.getPaddingTop(), 0, listBottomPadding);
lostList.setPadding(0, profitList.getPaddingTop(), 0, listBottomPadding);
summaryView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
public static class StatisticEntryAdapter extends BaseAdapter {
private List<Map.Entry<Tag, Double>> profit;
private Context context;
public StatisticEntryAdapter(Context context, List<Map.Entry<Tag, Double>> profit) {
this.context = context;
this.profit = profit;
}
@Override
public int getCount() {
return profit.size();
}
@Override
public Map.Entry<Tag, Double> getItem(int position) {
return profit.get(position);
}
@Override
public long getItemId(int position) {
return getItem(position).getKey().getId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_statistics_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Map.Entry<Tag, Double> item = getItem(position);
holder.tag.setText(item.getKey().getName());
holder.tag.setTagColor(item.getKey().getColor());
holder.amount.setAmount(item.getValue());
return convertView;
}
static class ViewHolder {
@InjectView(R.id.tag)
TagView tag;
@InjectView(R.id.amount)
AmountView amount;
ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
}
}
|
package com.example.musedroid.musedroid;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FirebaseHandler extends AppCompatActivity {
public static boolean flag = false;
public static FirebaseDatabase database = FirebaseDatabase.getInstance();
public static DatabaseReference mDatabase = database.getReference();
public static MuseumAdapter museumAdapter = new MuseumAdapter(new ArrayList<Museum>());
private static boolean signalFull;
private static List<AdapterFullListener> adapterFullListeners = new ArrayList<>();
//Create named childEventListener to keep the reference for when you want to mDatabase.removeEventListener(listener)
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//It is important for the adapter to works to use museumAdapter.notifyDataSetChanged(); after
//firebase add all museum inside the list , triggers adapter to see the data changes\
final Museum museum = dataSnapshot.getValue(Museum.class);
assert museum != null;
museum.key = dataSnapshot.getKey();
museumAdapter.add(museum);
museumAdapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
public static boolean getSignalFull() {
return signalFull;
}
public static void setSignalFull(boolean bool) {
signalFull = bool;
for (AdapterFullListener adapterFullListener : adapterFullListeners) {
adapterFullListener.OnAdapterFull();
}
}
public static void addAdapterFullListener(AdapterFullListener adapterFullListener) {
adapterFullListeners.add(adapterFullListener);
}
public void getMuseums(final MuseumAdapter adapter, final ProgressBar progressBar, final String appLanguage, final View view) {
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (flag) {
progressBar.setVisibility(view.GONE);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabase.child("museums").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//It is important for the adapter to works to use museumAdapter.notifyDataSetChanged(); after
//firebase add all museum inside the list , triggers adapter to see the data changes
if (!flag) {
flag = true;
}
final Museum museum = dataSnapshot.getValue(Museum.class);
assert museum != null;
museum.key = dataSnapshot.getKey();
//Get all Museum Exhibit based on language of the app
mDatabase.child("museumFields").orderByChild("museum").equalTo(museum.key).addChildEventListener(new ChildEventListener() {
String userLanguage = appLanguage;
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
MuseumFields museumFields = dataSnapshot.getValue(MuseumFields.class);
assert museumFields != null;
if (museumFields.museum.equals(museum.key) && museumFields.language.equals(userLanguage.toLowerCase())) {
museum.description = museumFields.description;
museum.name = museumFields.name;
museum.shortDescription = museumFields.shortDescription;
adapter.add(museum);
adapter.notifyDataSetChanged();
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// String museumName = (String) dataSnapshot.child("name")
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
//adapter.remove((String) dataSnapshot.child("name").getValue());
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void getMuseumsForGeofence() {
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Fire the adapterFull event!
if (museumAdapter.getItemCount() != 0) {
setSignalFull(true);
mDatabase.removeEventListener(this);
mDatabase.removeEventListener(childEventListener);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabase.child("museums").addChildEventListener(childEventListener);
}
public void userFavorite(String userId, Museum museum, boolean isfav) {
Map<String, Object> museumValues = museum.toMap();
Map<String, Object> childUpdates = new HashMap<>();
if (isfav) {
childUpdates.put("/user-favorites/" + userId + "/" + museum.key, museumValues);
mDatabase.updateChildren(childUpdates);
} else {
mDatabase.child("user-favorites").child(userId).child(museum.key).removeValue();
}
}
}
|
package app.iamin.iamin.ui;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.squareup.otto.Subscribe;
import java.util.regex.Pattern;
import app.iamin.iamin.BusProvider;
import app.iamin.iamin.model.Need;
import app.iamin.iamin.util.LocationUtils;
import app.iamin.iamin.R;
import app.iamin.iamin.RegisterTask;
import app.iamin.iamin.event.LocationEvent;
import app.iamin.iamin.service.LocationService;
import app.iamin.iamin.util.TimeUtils;
import app.iamin.iamin.util.UiUtils;
public class DetailActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener {
private boolean isAttending = false; // TODO: set value based on registration !
private LinearLayout btnBarLayout;
private Button submitButton;
private Button cancelButton;
private Button calendarButton;
private TextView typeTextView;
private TextView addressTextView;
private TextView dateTextView;
private TextView submitInfoTextView;
private TextView webTextView;
private TextView countTextView;
private ImageView typeImageView;
private SupportMapFragment mMapFragment;
private Need need;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
need = new Need().fromIntent(getIntent());
if (savedInstanceState != null) {
// Restore value from saved state
isAttending = savedInstanceState.getBoolean("isAttending");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(need.getCategoryPlural() + " - " + need.getAddress().getAddressLine(0));
toolbar.setNavigationIcon(R.drawable.ic_action_back);
toolbar.setNavigationOnClickListener(this);
typeTextView = (TextView) findViewById(R.id.type);
typeImageView = (ImageView) findViewById(R.id.type_icon);
typeImageView.setImageResource(need.getCategoryIcon());
addressTextView = (TextView) findViewById(R.id.address);
addressTextView.setText(need.getAddress().getAddressLine(0));
dateTextView = (TextView) findViewById(R.id.date);
dateTextView.setText(
TimeUtils.formatHumanFriendlyShortDate(this, need.getStart()) + " " +
TimeUtils.formatTimeOfDay(need.getStart()) + " - " +
TimeUtils.formatTimeOfDay(need.getEnd()) + " Uhr" + " (" +
TimeUtils.getDuration(need.getStart(), need.getEnd()) + ")");
webTextView = (TextView) findViewById(R.id.web);
webTextView.setText("www.google.at");
webTextView.setOnClickListener(this);
submitInfoTextView = (TextView) findViewById(R.id.info);
submitInfoTextView.setText("Danke! Bitte komm um " + TimeUtils.formatTimeOfDay(need.getStart()) + "!");
btnBarLayout = (LinearLayout) findViewById(R.id.btnBar);
calendarButton = (Button) findViewById(R.id.calendar);
calendarButton.setOnClickListener(this);
cancelButton = (Button) findViewById(R.id.cancel);
cancelButton.setOnClickListener(this);
submitButton = (Button) findViewById(R.id.submit);
submitButton.setOnClickListener(this);
countTextView = (TextView) findViewById(R.id.count);
setUiMode(isAttending);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if (mMapFragment == null) {
GoogleMapOptions options = new GoogleMapOptions().liteMode(true)
.camera(CameraPosition.fromLatLngZoom(need.getLocation(), 13));
mMapFragment = SupportMapFragment.newInstance(options);
mMapFragment.getMapAsync(DetailActivity.this);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.map, mMapFragment);
ft.commit();
}
}
private void setUiMode(boolean isAttending) {
if (isAttending) {
countTextView.setText("" + (need.getCount() - 1)); // TODO: cheat ! ;-)
submitButton.setEnabled(true);
submitInfoTextView.setVisibility(View.VISIBLE);
btnBarLayout.setVisibility(View.VISIBLE);
submitButton.setText("Weitersagen!");
typeTextView.setText((need.getCount() - 1) == 1 ? need.getCategorySingular() : need.getCategoryPlural());
} else {
countTextView.setText("" + (need.getCount())); // TODO: cheat ! ;-)
submitInfoTextView.setVisibility(View.GONE);
btnBarLayout.setVisibility(View.GONE);
submitButton.setText("I'm In!");
typeTextView.setText((need.getCount()) == 1 ? need.getCategorySingular() : need.getCategoryPlural());
}
}
@Override
protected void onResume() {
super.onResume();
BusProvider.getInstance().register(this);
LocationService.requestLocation(this);
// TODO: also update need (data) when user comes back
}
@Override
public void onPause() {
super.onPause();
BusProvider.getInstance().unregister(this);
}
@Subscribe
public void onLocationUpdate(LocationEvent event) {
LatLng userLocation = event.getLocation();
if (userLocation != null) {
String distance = LocationUtils.formatDistanceBetween(need.getLocation(), userLocation);
addressTextView.setText(need.getAddress().getAddressLine(0) + " (" + distance + ")");
} else {
addressTextView.setText(need.getAddress().getAddressLine(0));
}
}
@Override
public void onMapReady(GoogleMap map) {
map.getUiSettings().setMapToolbarEnabled(false);
map.addMarker(new MarkerOptions()
.title(need.getAddress().getAddressLine(0))
.position(need.getLocation()));
}
public void onRegisterSuccess() {
isAttending = true;
setUiMode(isAttending);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default: // Back button hack
finish();
break;
case R.id.submit:
if (submitInfoTextView.getVisibility() != View.VISIBLE) {
onActionSubmit();
} else {
UiUtils.fireShareIntent(DetailActivity.this, need);
}
break;
case R.id.cancel:
onActionCancel();
break;
case R.id.calendar:
UiUtils.fireCalendarIntent(DetailActivity.this, need);
break;
case R.id.web:
UiUtils.fireWebIntent(DetailActivity.this, need);
break;
}
}
private void onActionSubmit() {
submitButton.setText("Registriere...");
submitButton.setEnabled(false);
String email = null;
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(this).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
email = account.name;
break;
}
}
Log.d("onActionSubmit", email);
//TODO: If email is null ask user for email or phone number
new RegisterTask(this, getIntent().getExtras().getInt("id"), email).execute();
}
private void onActionCancel() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Wir brauchen dich! Willst du wirklich absagen?");
builder.setPositiveButton("Natürlich nicht!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do nothing
}
});
builder.setNegativeButton("Ja...", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
isAttending = false;
setUiMode(isAttending);
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current state
savedInstanceState.putBoolean("isAttending", isAttending);
super.onSaveInstanceState(savedInstanceState);
}
}
|
package edu.usc.parknpay.authentication;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import edu.usc.parknpay.R;
import edu.usc.parknpay.database.User;
import edu.usc.parknpay.owner.OwnerMainActivity;
import edu.usc.parknpay.seeker.SeekerMainActivity;
public class LoginActivity extends AppCompatActivity {
private EditText editEmail, editPassword;
ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authentication_login);
// Get references to UI views
editEmail = (EditText) findViewById(R.id.edit_email);
editPassword = (EditText) findViewById(R.id.edit_password);
progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Please wait logging in...");
progress.setCancelable(false);
}
@Override
protected void onNewIntent(Intent intent)
{
progress.dismiss();
}
/** Called when the user clicks the authentication_login button. */
public void authenticateUser(View view) {
// Communicate with Firebase to authenticate the user.
String email = editEmail.getText().toString();
String password = editPassword.getText().toString();
// Verify input
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
Toast.makeText(LoginActivity.this, "Please enter your email and/or password", Toast.LENGTH_SHORT).show();
return;
}
progress.show();
// Authenticate user through database
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
// Get the newly generated user
String userId = task.getResult().getUser().getUid();
FirebaseDatabase.getInstance().getReference().child("Users").child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// Create user
User user = snapshot.getValue(User.class);
User.createUser(user);
// If authentication is successful, proceed to default (owner/seeker) main view.
if (User.getInstance().getIsCurrentlySeeker()) {
User.getInstance().setIsCurrentlySeeker(false);
Intent seekerIntent = new Intent(LoginActivity.this, SeekerMainActivity.class);
startActivity(seekerIntent);
} else {
User.getInstance().setIsCurrentlySeeker(true);
Intent ownerIntent = new Intent(LoginActivity.this, OwnerMainActivity.class);
startActivity(ownerIntent);
progress.dismiss();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Toast.makeText(LoginActivity.this, "Failed to authenticate user", Toast.LENGTH_SHORT).show();
}
}
});
progress.dismiss();
}
/** Called when the user selects the authentication_registration option. */
public void displayRegistrationScreen(View view) {
Intent intent = new Intent(this, RegistrationActivity.class);
startActivity(intent);
}
// TESTING
public void SeekerTestLogin(View view){
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
progress.show();
firebaseAuth.signInWithEmailAndPassword("s@s.com", "sssssss").addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
// Get the newly generated user
String userId = task.getResult().getUser().getUid();
FirebaseDatabase.getInstance().getReference().child("Users").child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// Create user
User user = snapshot.getValue(User.class);
User.createUser(user);
(User.getInstance()).setIsCurrentlySeeker(true);
// If authentication is successful, proceed to default (owner/seeker) main view.
//if (User.getInstance().isSeeker()) {
Intent seekerIntent = new Intent(LoginActivity.this, SeekerMainActivity.class);
startActivity(seekerIntent);
progress.dismiss();
//} else {
// Intent ownerIntent = new Intent(LoginActivity.this, OwnerMainActivity.class);
// startActivity(ownerIntent);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Toast.makeText(LoginActivity.this, "Failed to authenticate user", Toast.LENGTH_SHORT).show();
}
}
});
}
public void HostTestLogin(View view){
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
progress.show();
firebaseAuth.signInWithEmailAndPassword("h@h.com", "hhhhhhh").addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
// Get the newly generated user
String userId = task.getResult().getUser().getUid();
FirebaseDatabase.getInstance().getReference().child("Users").child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// Create user
User user = snapshot.getValue(User.class);
User.createUser(user);
User.getInstance().setIsCurrentlySeeker(false);
// If authentication is successful, proceed to default (owner/seeker) main view.
//if (User.getInstance().isSeeker()) {
// Intent seekerIntent = new Intent(LoginActivity.this, SeekerMainActivity.class);
// startActivity(seekerIntent);
//} else {
Intent ownerIntent = new Intent(LoginActivity.this, OwnerMainActivity.class);
startActivity(ownerIntent);
progress.dismiss();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Toast.makeText(LoginActivity.this, "Failed to authenticate user", Toast.LENGTH_SHORT).show();
}
}
});
}
}
|
package com.expidev.gcmapp.model;
import java.io.Serializable;
import java.util.List;
public class Ministry implements Serializable
{
private static final long serialVersionUID = 0L;
private String ministryId;
private String name;
private String ministryCode;
private String parentId;
private boolean hasSlm;
private boolean hasLlm;
private boolean hasDs;
private boolean hasGcm;
private List<Ministry> subMinistries;
public String getMinistryId()
{
return ministryId;
}
public void setMinistryId(String ministryId)
{
this.ministryId = ministryId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getMinistryCode()
{
return ministryCode;
}
public void setMinistryCode(String ministryCode)
{
this.ministryCode = ministryCode;
}
public String getParentId()
{
return parentId;
}
public void setParentId(String parentId)
{
this.parentId = parentId;
}
public boolean hasSlm()
{
return hasSlm;
}
public void setHasSlm(boolean hasSlm)
{
this.hasSlm = hasSlm;
}
public boolean hasLlm()
{
return hasLlm;
}
public void setHasLlm(boolean hasLlm)
{
this.hasLlm = hasLlm;
}
public boolean hasDs()
{
return hasDs;
}
public void setHasDs(boolean hasDs)
{
this.hasDs = hasDs;
}
public boolean hasGcm()
{
return hasGcm;
}
public void setHasGcm(boolean hasGcm)
{
this.hasGcm = hasGcm;
}
public List<Ministry> getSubMinistries()
{
return subMinistries;
}
public void setSubMinistries(List<Ministry> subMinistries)
{
this.subMinistries = subMinistries;
}
@Override
public String toString()
{
return name;
}
}
|
package com.infoeducatie.app.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.infoeducatie.app.R;
import com.infoeducatie.app.client.entities.Project;
import com.infoeducatie.app.client.entities.ProjectCategory;
import com.infoeducatie.app.helpers.AsyncTaskHelper;
import com.infoeducatie.app.helpers.UIMessageHelper;
import com.infoeducatie.app.recyclerviews.smallprojects.SmallProjectAdapter;
import com.infoeducatie.app.service.management.ProjectsManagement;
/**
* A simple {@link Fragment} subclass.
*/
public class ProjectsFragment extends Fragment {
/* all the projects */
private Project[] mAllProjects = new Project[0];
/* the projects displayed in the adapter */
private Project[] mDisplayProjects = new Project[0];
private SmallProjectAdapter mAdapter;
private RecyclerView mRecycler;
private SmallProjectAdapter.SmallProjectItemListener smallProjectItemListener;
public void setSmallProjectItemListener(SmallProjectAdapter.SmallProjectItemListener smallProjectItemListener) {
this.smallProjectItemListener = smallProjectItemListener;
}
public ProjectsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_projects, container, false);
/* initialize the recycler view */
mRecycler = (RecyclerView) view.findViewById(R.id.fragment_projects_recycler);
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new SmallProjectAdapter();
mAdapter.setSmallProjectItemListener(smallProjectItemListener);
mAdapter.setProjects(mDisplayProjects);
mRecycler.setAdapter(mAdapter);
refreshProjects();
return view;
}
public void filterProjects(ProjectCategory projectCategory) {
mDisplayProjects = ProjectsManagement.filterProjects(mAllProjects, projectCategory);
mAdapter.setProjects(mDisplayProjects);
}
public void refreshProjects() {
AsyncTaskHelper.create(new AsyncTaskHelper.AsyncMethods<Project[]>() {
@Override
public Project[] doInBackground() {
return ProjectsManagement.getAllProjects();
}
@Override
public void onDone(Project[] value, long ms) {
gotProjects(value);
}
});
}
private void gotProjects(Project[] projects) {
if (projects == null) {
UIMessageHelper.showNetworkErrorMessage(getActivity());
return;
}
mAllProjects = projects;
mDisplayProjects = projects;
mAdapter.setProjects(mAllProjects);
}
}
|
package com.nnys.bikeable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.GeoApiContext;
import com.google.maps.model.DirectionsRoute;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.maps.model.ElevationResult;
import com.jjoe64.graphview.GraphView;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
public class CentralActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback {
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
protected GoogleApiClient mGoogleApiClient;
protected GeoApiContext context;
protected DirectionsManager directionsManager = null;
private PlaceAutocompleteAdapter from_adapter;
private PlaceAutocompleteAdapter to_adapter;
private AutocompletePrediction to_prediction = null, from_prediction= null;
private Button searchBtn, clearBtn, showGraphBtn, bikePathButton;
private DirectionsRoute[] routes;
private ArrayList<com.google.maps.model.LatLng> points = new ArrayList<>();
private GoogleMap mMap;
private AutoCompleteTextView to, from;
private PopupWindow graphPopupWindow;
private LayoutInflater layoutInflater;
private int GRAPH_X_INTERVAL = 20;
private int MAX_GRAPH_SAMPLES = 400;
private IriaBikePath iriaBikePath = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to enable getting data from Tel Aviv muni website
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Construct a GoogleApiClient for the {@link Places#GEO_DATA_API} using AutoManage
// functionality, which automatically sets up the API client to handle Activity lifecycle
// events. If your activity does not extend FragmentActivity, make sure to call connect()
// and disconnect() explicitly.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0 /* clientId */, this)
.addApi(Places.GEO_DATA_API)
.build();
setContentView(R.layout.central_activity_layout);
from = (AutoCompleteTextView) findViewById(R.id.from);
to = (AutoCompleteTextView) findViewById(R.id.to);
from.setText("");
to.setText("");
from_adapter = new PlaceAutocompleteAdapter(this, mGoogleApiClient, BOUNDS_GREATER_SYDNEY,
null);
from.setAdapter(from_adapter);
to_adapter = new PlaceAutocompleteAdapter(this, mGoogleApiClient, BOUNDS_GREATER_SYDNEY,
null);
to.setAdapter(to_adapter);
final MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
from.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
from_prediction = (AutocompletePrediction) parent.getItemAtPosition(position);
}
});
to.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
to_prediction = (AutocompletePrediction) parent.getItemAtPosition(position);
}
});
context = new GeoApiContext().setApiKey(getString(R.string.api_key_server));
searchBtn = (Button) findViewById(R.id.res_button);
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (from_prediction == null || to_prediction == null)
return;
if (directionsManager != null) {
directionsManager.clearDirectionFromMap();
}
directionsManager = new DirectionsManager(context, from_prediction, to_prediction);
directionsManager.drawAllRoutes(mMap);
directionsManager.drawRouteMarkers(mMap);
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(directionsManager.getDirectionBounds(), getResources()
.getInteger(R.integer.bound_padding)));
}
});
clearBtn = (Button) findViewById(R.id.clear_button);
clearBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (directionsManager != null) {
directionsManager.clearDirectionFromMap();
directionsManager = null;
}
to_prediction = null;
from_prediction= null;
from.setText("");
to.setText("");
}
});
showGraphBtn = (Button) findViewById(R.id.show_graph_button);
showGraphBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (directionsManager == null || directionsManager.getSelectedRouteIndex() == -1) {
return;
}
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.graph_popup,null);
GraphView graph = (GraphView) container.findViewById(R.id.altitude_graph);
PathElevationGraphDrawer graphDrawer = new PathElevationGraphDrawer(graph);
for (int i = 0; i < directionsManager.getNumRoutes(); i ++ ) {
PathElevationQuerier querier = new PathElevationQuerier(directionsManager.getEnodedPoylineByIndex(i));
long distance = directionsManager.getRouteDistanceByIndex(i);
int numOfSamples = querier.calcNumOfSamplesForXmetersIntervals(distance, GRAPH_X_INTERVAL, MAX_GRAPH_SAMPLES);
ElevationResult[] results = querier.getElevationSamples(numOfSamples);
graphDrawer.addSeries(results);
if ( results == null )
return;
}
graphDrawer.colorSeriosByIndex(directionsManager.getSelectedRouteIndex());
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
graphPopupWindow = new PopupWindow(container, width,300, true);
graphPopupWindow.showAtLocation(findViewById(R.id.centralLayout), Gravity.BOTTOM, 0, 0);
container.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
graphPopupWindow.dismiss();
return false;
}
});
}
});
bikePathButton = (Button) findViewById(R.id.bike_button);
bikePathButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (iriaBikePath == null){
try {
iriaBikePath = new IriaBikePath(mMap);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
if (iriaBikePath.isBikePathShown) {
iriaBikePath.removeBikePathFromMap();
}
else {
iriaBikePath.showBikePathOnMap();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Called when the Activity could not connect to Google Play services and the auto manager
* could resolve the error automatically.
* In this case the API is not available and notify the user.
*
* @param connectionResult can be inspected to determine the cause of the failure
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// TODO(Developer): Check error code and notify the user of error state and resolution.
Toast.makeText(this,
"Could not connect to Google API Client: Error " + connectionResult.getErrorCode(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng tau = new LatLng(32.113523, 34.804399);
mMap.addMarker(new MarkerOptions()
.title("Tel-Aviv University")
.position(tau)
);
mMap.moveCamera(CameraUpdateFactory.newLatLng(tau));
mMap.moveCamera(CameraUpdateFactory.zoomTo(15f));
mMap.setOnMapClickListener((new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng clickLatLng) {
Log.i("inside listener begin", "inside listener begin2");
if (directionsManager != null) {
MapUtils.selectClickedRoute(directionsManager, clickLatLng);
}
}
}
));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
return true;
}
});
/*double[][] arr2 = {{32.141237, 34.800872}, {32.141489, 34.800135}, {32.141641, 34.799725}, {32.141962, 34.798795},
{32.142071, 34.798485}, {32.142149, 34.798263}, {32.142359, 34.797588}, {32.142451, 34.797285}};
ArrayList<com.google.android.gms.maps.model.LatLng> points = new ArrayList<>();
for (int i = 0; i < 8; i++){
points.add(new LatLng(arr2[i][0], arr2[i][1]));
}
PolylineOptions line = new PolylineOptions();
com.google.android.gms.maps.model.LatLng currPoint;
for (com.google.android.gms.maps.model.LatLng point : points) {
currPoint = new com.google.android.gms.maps.model.LatLng(point.latitude, point.longitude);
line.add(currPoint);
}
mMap.addPolyline(line);*/
}
}
|
package home.climax708.librecarpool;
import android.annotation.SuppressLint;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;
import java.util.Calendar;
public class HitchRideActivity extends AppCompatActivity
implements ServerConnection.OnRidesRetrievedListener,
RidesAdapter.ViewHolder.OnRideCardClickListener {
public final static String ARG_HOUR_OF_DAY = "ARG_HOD";
public final static String ARG_MINUTE = "ARG_MINUTE";
public static final String ARG_GAPI_CONNECTED = "ARG_GAPI_CONNECTED";
private String[] departureIDs = {
"ChIJxRQE9XRQAhURAgSWZPXXP8s",
"ChIJ7YhnMzlwAhUR5sh_Q-vld3g"
};
private View mFilterOptionsLayout;
private Button mFilterOptionsButton;
private EditText mDestinationEditText;
private GoogleApiClient mGoogleApiClient;
private TextView mDepartureTimeTextView;
private TextView mResultsTextView;
private RideTime mRideTime;
private Place mRideDestination = null;
private String mRideOriginID;
private int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
private ServerConnection mServerConnection;
private RidesAdapter mRidesAdapter;
private Spinner mOriginSpinner;
public void clearFields(View view) {
if (mRideTime == null)
mRideTime = new RideTime(0, 0);
else {
mRideTime.setHour(0);
mRideTime.setMinute(0);
}
if (mDepartureTimeTextView != null)
mDepartureTimeTextView.setText(mRideTime.toString());
mRideDestination = null;
if (mDestinationEditText != null)
mDestinationEditText.setText("");
mRideOriginID = null;
if (mOriginSpinner != null)
mOriginSpinner.setSelection(0, true);
}
public void filterRides(View view) {
toggleExpandedFilterOptionsLayout(false);
Ride filterRide;
if (mRideDestination == null) {
filterRide = new Ride(null, mRideTime, mRideOriginID, null, "", null);
} else {
filterRide = new Ride(null, mRideTime, mRideOriginID, null, mRideDestination, null);
}
updateRidesView(filterRide);
}
public void contactViaMessage(View view, Ride ride) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + ride.getDriverPhoneNumber()));
String smsBody = getString(R.string.ride_request_sms_body,
ride.getDestinationPlace().getName(),
ride.getDeparturePlace().getName(),
ride.getRideTime().getHour(), ride.getRideTime().getMinute());
intent.putExtra("sms_body", smsBody);
intent.putExtra(Intent.EXTRA_TEXT, smsBody);
startActivity(Intent.createChooser(intent, ""));
}
public void contactViaCall(View view, Ride ride) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + ride.getDriverPhoneNumber()));
startActivity(intent);
}
public void expandLayout(View view) {
toggleExpandedFilterOptionsLayout(true);
if (mDestinationEditText.getText().length() == 0) {
if (mGoogleApiClient.isConnected()) {
try {
Intent intent = Utils.buildPlaceAutocompleteIntent(HitchRideActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
mDestinationEditText.requestFocus();
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
} else {
mDestinationEditText.requestFocus();
// Force the keyboard to show.
Utils.forceToggleKeyboardForView(HitchRideActivity.this, mDestinationEditText, true);
}
}
}
public void collapseLayout(View view) {
toggleExpandedFilterOptionsLayout(false);
// Force the keyboard to hide.
Utils.forceToggleKeyboardForView(HitchRideActivity.this, mDestinationEditText, false);
}
public void showTimePickerDialog(View v) {
TimePickerFragment timePickerFragment = new TimePickerFragment();
if (mRideTime != null) {
Bundle bundle = new Bundle();
bundle.putInt(ARG_HOUR_OF_DAY, mRideTime.getHour());
bundle.putInt(ARG_MINUTE, mRideTime.getMinute());
timePickerFragment.setArguments(bundle);
}
timePickerFragment.setOnTimeListener(new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mRideTime = new RideTime(hourOfDay, minute);
mDepartureTimeTextView.setText(mRideTime.toString());
}
});
timePickerFragment.show(getSupportFragmentManager(), "timePicker");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hitch_ride);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setupActionBar(toolbar);
mFilterOptionsLayout = findViewById(R.id.ride_filter_layout);
mFilterOptionsButton = (Button) findViewById(R.id.ride_filter_toggle_button);
mDestinationEditText = (EditText) findViewById(R.id.hitch_destination_edittext);
mDestinationEditText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mGoogleApiClient.isConnected()) {
try {
mDestinationEditText.requestFocus();
Intent intent = Utils.buildPlaceAutocompleteIntent(HitchRideActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
}
return false;
}
});
FloatingActionButton offerRideFAB = (FloatingActionButton) findViewById(R.id.offerFAB);
setupOfferFAB(offerRideFAB);
mDepartureTimeTextView = (TextView) findViewById(R.id.hitch_departure_time_textview);
final Calendar calendar = Calendar.getInstance();
mRideTime = new RideTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));
mDepartureTimeTextView.setText(mRideTime.toString());
mResultsTextView = (TextView) findViewById(R.id.resultsTextView);
mOriginSpinner = (Spinner) findViewById(R.id.hitch_origin_spinner);
setupOriginSpinner(mOriginSpinner);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, new GoogleApiConnectionFailListener())
.build();
mServerConnection = new ServerConnection();
RecyclerView ridesRecyclerView = (RecyclerView) findViewById(R.id.rides_recycler_view);
mRidesAdapter = new RidesAdapter(new Ride[0], this);
if (ridesRecyclerView != null) {
ridesRecyclerView.setAdapter(mRidesAdapter);
}
setupRidesRecyclerView(ridesRecyclerView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_hitch_ride, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// TODO: Launch settings activity.
break;
// TODO: Implement "about" menu item.
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mFilterOptionsLayout.getVisibility() == View.VISIBLE) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
toggleExpandedFilterOptionsLayout(false);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onStart() {
super.onStart();
// Refresh rides when application is (re)started.
// Make sure it takes filter rides into consideration (if any).
if (mRideOriginID != null || mRideDestination != null)
updateRidesView(new Ride(null, mRideTime, mRideOriginID, null, mRideDestination, null));
else
updateRidesView();
}
@Override
public void onStop() {
super.onStop();
mServerConnection.cancelTask();
}
@Override
public void onRidesRetrievingStarted() {
ProgressBar progressBar = (ProgressBar) findViewById(R.id.ridesProgressBar);
if (progressBar != null) {
progressBar.setVisibility(View.VISIBLE);
}
mResultsTextView.setVisibility(View.GONE);
}
@Override
public void onRidesRetrieved(Ride[] rides) {
if (rides.length == 0) {
// Display empty results text.
onRidesRetrievalEnd(getString(R.string.no_rides_found));
} else {
onRidesRetrievalEnd(null);
mRidesAdapter.addItems(rides);
}
}
@Override
public void onRidesRetrievingFailed(Exception exception) {
// Clear current rides
mRidesAdapter.clear();
// Display error text.
onRidesRetrievalEnd(getString(R.string.rides_retrieval_error));
}
/**
* Handles rides retrieval task ending - whether successful or not.
* Cleans up after retrieval has started.
* @param results Result TextView to display
*/
private void onRidesRetrievalEnd(@Nullable String results) {
ProgressBar progressBar = (ProgressBar) findViewById(R.id.ridesProgressBar);
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
if (results != null) {
mResultsTextView.setText(results);
mResultsTextView.setVisibility(View.VISIBLE);
}
}
@Override
public void onRideCardClick(View v, int position) {
final Ride clickedRide = mRidesAdapter.getRide(position);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
final View dialogLayout = getLayoutInflater().inflate(
R.layout.dialog_ride_info_layout, null);
AlertDialog rideDialog = dialogBuilder.setTitle(R.string.ride_dialog_info_title)
.setView(dialogLayout)
.setIcon(R.mipmap.ic_time_to_leave_black_24dp)
.setNeutralButton(R.string.dialog_button_dismiss, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
int primaryColor = Utils.getThemeAttributeColor(HitchRideActivity.this,
Utils.ColorType.PRIMARY);
final TextView destinationTextView = (TextView) dialogLayout.findViewById(
R.id.ride_info_destination_text_view);
if (destinationTextView != null) {
SpannableStringBuilder destinationName = new SpannableStringBuilder(
clickedRide.getDestinationPlace().getName());
destinationName.setSpan(new ForegroundColorSpan(primaryColor), 0, destinationName.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
SpannableStringBuilder departure = new SpannableStringBuilder(
clickedRide.getDeparturePlace().getName());
departure.setSpan(new ForegroundColorSpan(primaryColor), 0, departure.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// We don't care about locale for this specific string because it only displays time in 24 hour format.
@SuppressLint("DefaultLocale") SpannableStringBuilder departureTime = new SpannableStringBuilder(
String.format("%d:%02d", clickedRide.getRideTime().getHour(),
clickedRide.getRideTime().getMinute()));
departureTime.setSpan(new ForegroundColorSpan(primaryColor), 0, departureTime.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
destinationTextView.setText(
Utils.getSpannedString(
getString(R.string.ride_dialog_info_destination),
destinationName,
departure,
departureTime));
}
final TextView throughTextView = (TextView) dialogLayout.findViewById(
R.id.ride_info_through_text_view);
if (throughTextView != null) {
String passingThrough = clickedRide.getPassingThrough();
if (passingThrough != null && !passingThrough.isEmpty()) {
throughTextView.setVisibility(View.VISIBLE);
SpannableStringBuilder passingThroughPlaceName = new SpannableStringBuilder(
passingThrough);
passingThroughPlaceName.setSpan(new ForegroundColorSpan(primaryColor), 0,
passingThroughPlaceName.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
throughTextView.setText(Utils.getSpannedString(
getString(R.string.ride_dialog_info_through),
passingThroughPlaceName));
}
}
String rideComments = clickedRide.getComments();
if (rideComments != null && !rideComments.isEmpty()) {
final TextView commentsTextView = (TextView) dialogLayout.findViewById(
R.id.ride_info_comments_text_view);
if (commentsTextView != null && !rideComments.isEmpty()) {
commentsTextView.setVisibility(View.VISIBLE);
SpannableStringBuilder comments = new SpannableStringBuilder(rideComments);
comments.setSpan(new ForegroundColorSpan(primaryColor), 0, comments.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
commentsTextView.setText(Utils.getSpannedString(
getString(R.string.ride_dialog_info_comments), comments));
}
}
final TextView callTextView = (TextView) dialogLayout.findViewById(
R.id.ride_dialog_call_textView);
if (callTextView != null) {
callTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
contactViaCall(v, clickedRide);
}
});
Drawable topDrawable = callTextView.getCompoundDrawables()[1];
if (topDrawable != null) {
topDrawable.setColorFilter(
ContextCompat.getColor(
HitchRideActivity.this, android.R.color.holo_green_dark),
PorterDuff.Mode.SRC_ATOP);
}
}
final TextView smsTextView = (TextView) dialogLayout.findViewById(
R.id.ride_dialog_sms_textView);
if (smsTextView != null) {
smsTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
contactViaMessage(v, clickedRide);
}
});
Drawable topDrawable = smsTextView.getCompoundDrawables()[1];
if (topDrawable != null) {
topDrawable.setColorFilter(
ContextCompat.getColor(
HitchRideActivity.this, android.R.color.holo_orange_light),
PorterDuff.Mode.SRC_ATOP);
}
}
rideDialog.show();
rideDialog.getButton(DialogInterface.BUTTON_NEUTRAL).setTextColor(
Utils.getThemeAttributeColor(HitchRideActivity.this, Utils.ColorType.ACCENT));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
mRideDestination = place;
mDestinationEditText.setText(place.getName());
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
} else if (resultCode == RESULT_CANCELED) {
}
findViewById(R.id.coordinator_layout).requestFocus();
// Force the keyboard to hide.
Utils.forceToggleKeyboardForView(HitchRideActivity.this, mDestinationEditText, false);
}
}
private void setupRidesRecyclerView(RecyclerView recyclerView) {
recyclerView.addItemDecoration(new VerticalSpaceItemDecoration(
(int) getResources().getDimension(R.dimen.ride_list_divider_height)));
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
private void updateRidesView() {
updateRidesView(null);
}
private void updateRidesView(Ride... rides) {
mRidesAdapter.clear();
if (mGoogleApiClient != null) {
mServerConnection.getRides(mGoogleApiClient, this, rides);
}
}
private class GoogleApiConnectionFailListener
implements GoogleApiClient.OnConnectionFailedListener {
@Override
public void onConnectionFailed(ConnectionResult result) {
Toast.makeText(HitchRideActivity.this,
"Connection to GoogleApiClient failed with result=" + result,
Toast.LENGTH_SHORT).show();
}
}
private void setupActionBar(Toolbar toolbar) {
setSupportActionBar(toolbar);
}
private void setupOfferFAB(FloatingActionButton offerRideFAB) {
offerRideFAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HitchRideActivity.this, OfferRideActivity.class);
intent.putExtra(ARG_GAPI_CONNECTED, mGoogleApiClient.isConnected());
startActivity(intent);
}
});
}
private void setupOriginSpinner(Spinner originSpinner) {
originSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View v, int position, long id) {
if (position > 0 ) {
mRideOriginID = departureIDs[position - 1];
} else {
mRideOriginID = null;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
ArrayAdapter<CharSequence> originsAdapter = ArrayAdapter.createFromResource(this,
R.array.origins, android.R.layout.simple_spinner_item);
originsAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
originSpinner.setAdapter(originsAdapter);
}
private void toggleExpandedFilterOptionsLayout(boolean toggle) {
int EXPAND_COLLAPSE_DURATION = 350;
if (toggle) {
Utils.collapseView(mFilterOptionsButton, EXPAND_COLLAPSE_DURATION);
Utils.expandView(mFilterOptionsLayout, EXPAND_COLLAPSE_DURATION);
} else {
Utils.collapseView(mFilterOptionsLayout, EXPAND_COLLAPSE_DURATION);
Utils.expandView(mFilterOptionsButton, EXPAND_COLLAPSE_DURATION);
}
}
}
|
package com.kickstarter.ui.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.kickstarter.KsrApplication;
import com.kickstarter.R;
import com.kickstarter.libs.BaseActivity;
import com.kickstarter.libs.RequiresPresenter;
import com.kickstarter.libs.RxUtils;
import com.kickstarter.models.Project;
import com.kickstarter.presenters.DiscoveryPresenter;
import com.kickstarter.services.ApiResponses.InternalBuildEnvelope;
import com.kickstarter.ui.adapters.ProjectListAdapter;
import com.kickstarter.ui.containers.ApplicationContainer;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Subscription;
import rx.subjects.PublishSubject;
@RequiresPresenter(DiscoveryPresenter.class)
public class DiscoveryActivity extends BaseActivity<DiscoveryPresenter> {
ProjectListAdapter adapter;
LinearLayoutManager layoutManager;
final ArrayList<Project> projects = new ArrayList<>();
final PublishSubject<Integer> visibleItem = PublishSubject.create();
final PublishSubject<Integer> itemCount = PublishSubject.create();
Subscription pageSubscription;
@Inject ApplicationContainer applicationContainer;
@InjectView(R.id.recyclerView) RecyclerView recyclerView;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((KsrApplication) getApplication()).component().inject(this);
final ViewGroup container = applicationContainer.bind(this);
final LayoutInflater layoutInflater = getLayoutInflater();
layoutInflater.inflate(R.layout.discovery_layout, container);
ButterKnife.inject(this, container);
layoutManager = new LinearLayoutManager(this);
adapter = new ProjectListAdapter(projects, presenter);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
pageSubscription = RxUtils.combineLatestPair(visibleItem, itemCount)
.distinctUntilChanged()
.filter(itemAndCount -> itemAndCount.first == itemAndCount.second - 2)
.subscribe(itemAndCount -> presenter.takeNextPage());
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
final int visibleItemCount = layoutManager.getChildCount();
final int totalItemCount = layoutManager.getItemCount();
final int pastVisibleItems = layoutManager.findFirstVisibleItemPosition();
visibleItem.onNext(visibleItemCount + pastVisibleItems);
itemCount.onNext(totalItemCount);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
recyclerView.clearOnScrollListeners();
pageSubscription.unsubscribe();
}
public void onItemsNext(final List<Project> newProjects) {
for (Project newProject: newProjects){
if (! projects.contains(newProject)) {
projects.add(newProject);
}
}
adapter.notifyDataSetChanged();
}
public void clearItems() {
projects.clear();
adapter.notifyDataSetChanged();
}
public void startProjectDetailActivity(final Project project) {
final Intent intent = new Intent(this, ProjectDetailActivity.class)
.putExtra(getString(R.string.intent_project), project);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out_slide_out_left);
}
public void showBuildAlert(final InternalBuildEnvelope envelope) {
new AlertDialog.Builder(this)
.setTitle("Upgrade app")
.setMessage("A newer build is available. Download upgrade?")
.setPositiveButton(android.R.string.yes, (dialog, which) -> {
Intent intent = new Intent(this, DownloadBetaActivity.class)
.putExtra(getString(R.string.intent_internal_build_envelope), envelope);
startActivity(intent);
})
.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
|
package com.muzima.view.patients;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.Menu;
import com.muzima.MuzimaApplication;
import com.muzima.R;
import com.muzima.adapters.patients.PatientAdapterHelper;
import com.muzima.api.model.Patient;
import com.muzima.api.model.SmartCardRecord;
import com.muzima.api.model.User;
import com.muzima.api.service.SmartCardRecordService;
import com.muzima.controller.EncounterController;
import com.muzima.controller.FormController;
import com.muzima.controller.NotificationController;
import com.muzima.controller.ObservationController;
import com.muzima.controller.PatientController;
import com.muzima.controller.SmartCardController;
import com.muzima.model.shr.kenyaemr.KenyaEmrShrModel;
import com.muzima.service.JSONInputOutputToDisk;
import com.muzima.utils.Constants;
import com.muzima.utils.smartcard.KenyaEmrShrMapper;
import com.muzima.utils.smartcard.SmartCardIntentIntegrator;
import com.muzima.utils.smartcard.SmartCardIntentResult;
import com.muzima.view.BaseActivity;
import com.muzima.view.SHRObservationsDataActivity;
import com.muzima.view.encounters.EncountersActivity;
import com.muzima.view.forms.PatientFormsActivity;
import com.muzima.view.notifications.PatientNotificationActivity;
import com.muzima.view.observations.ObservationsActivity;
import org.apache.lucene.util.fst.BytesRefFSTEnum;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import static com.muzima.utils.DateUtils.getFormattedDate;
import static com.muzima.utils.smartcard.SmartCardIntentIntegrator.SMARTCARD_READ_REQUEST_CODE;
import static com.muzima.utils.smartcard.SmartCardIntentIntegrator.SMARTCARD_WRITE_REQUEST_CODE;
public class PatientSummaryActivity extends BaseActivity {
private static final String TAG = "PatientSummaryActivity";
public static final String PATIENT = "patient";
private AlertDialog writeShrDataOptionDialog;
private BackgroundQueryTask mBackgroundQueryTask;
private Patient patient;
private ImageView imageView;
private Boolean isRegisteredOnShr;
private TextView searchDialogTextView;
private Button yesOptionShrSearchButton;
private Button noOptionShrSearchButton;
private SmartCardRecord smartCardRecord;
private SmartCardRecordService smartCardRecordService;
private SmartCardController smartCardController;
private MuzimaApplication muzimaApplication;
private PatientController patientController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_summary);
Bundle intentExtras = getIntent().getExtras();
if (intentExtras != null) {
patient = (Patient) intentExtras.getSerializable(PATIENT);
isRegisteredOnShr = intentExtras.getBoolean("isRegisteredOnShr");
}
try {
setupPatientMetadata();
notifyOfIdChange();
} catch (PatientController.PatientLoadException e) {
Toast.makeText(this, R.string.error_patient_fetch, Toast.LENGTH_SHORT).show();
finish();
}
muzimaApplication = (MuzimaApplication) getApplicationContext();
patientController = muzimaApplication.getPatientController();
try {
smartCardRecordService = muzimaApplication.getMuzimaContext().getSmartCardRecordService();
smartCardController = new SmartCardController(smartCardRecordService);
} catch (IOException e) {
e.printStackTrace();
}
imageView = (ImageView) findViewById(R.id.sync_status_imageview);
if (isRegisteredOnShr) {
prepareWriteToCardOptionDialog(getApplicationContext());
} else {
prepareNonShrWriteToCardOptionDialog(getApplicationContext());
}
}
private void notifyOfIdChange() {
final JSONInputOutputToDisk jsonInputOutputToDisk = new JSONInputOutputToDisk(getApplication());
List list = null;
try {
list = jsonInputOutputToDisk.readList();
} catch (IOException e) {
Log.e(TAG, "Exception thrown when reading to phone disk", e);
}
if (list.size() == 0) {
return;
}
final String patientIdentifier = patient.getIdentifier();
if (list.contains(patientIdentifier)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true)
.setIcon(getResources().getDrawable(R.drawable.ic_warning))
.setTitle("Notice")
.setMessage(getString(R.string.info_client_identifier_change))
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
patient.removeIdentifier(Constants.LOCAL_PATIENT);
try {
jsonInputOutputToDisk.remove(patientIdentifier);
} catch (IOException e) {
Log.e(TAG, "Error occurred while saving patient which has local identifier removed!", e);
}
}
}).create().show();
}
}
@Override
protected void onResume() {
super.onResume();
executeBackgroundTask();
}
@Override
protected void onStop() {
if (mBackgroundQueryTask != null) {
mBackgroundQueryTask.cancel(true);
}
super.onStop();
}
private void setupPatientMetadata() throws PatientController.PatientLoadException {
TextView patientName = (TextView) findViewById(R.id.patientName);
patientName.setText(PatientAdapterHelper.getPatientFormattedName(patient));
ImageView genderIcon = (ImageView) findViewById(R.id.genderImg);
int genderDrawable = patient.getGender().equalsIgnoreCase("M") ? R.drawable.ic_male : R.drawable.ic_female;
genderIcon.setImageDrawable(getResources().getDrawable(genderDrawable));
TextView dob = (TextView) findViewById(R.id.dob);
dob.setText("DOB: " + getFormattedDate(patient.getBirthdate()));
TextView patientIdentifier = (TextView) findViewById(R.id.patientIdentifier);
patientIdentifier.setText(patient.getIdentifier());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.client_summary, menu);
MenuItem shrCardMenuItem = menu.getItem(0);
if (isRegisteredOnShr) {
shrCardMenuItem.setIcon(R.drawable.ic_action_shr_card);
} else {
shrCardMenuItem.setVisible(true);
shrCardMenuItem.setIcon(R.drawable.ic_action_no_shr_card);
}
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.shr_client_summary:
//todo write card workspace.
if (isRegisteredOnShr) {
Log.e("TAG", "is Patient shr");
prepareWriteToCardOptionDialog(getApplicationContext());
writeShrDataOptionDialog.show();
} else {
Log.e("TAG", "is Patient not shr");
prepareNonShrWriteToCardOptionDialog(getApplicationContext());
writeShrDataOptionDialog.show();
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void invokeShrApplication() {
SmartCardController smartCardController = ((MuzimaApplication) getApplicationContext()).getSmartCardController();
SmartCardRecord smartCardRecord = null;
try {
smartCardRecord = smartCardController.getSmartCardRecordByPersonUuid(patient.getUuid());
} catch (SmartCardController.SmartCardRecordFetchException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true)
.setMessage("Could not obtain smartcard record for writing to card. " + e.getMessage())
.show();
Log.e(TAG, "Could not obtain smartcard record for writing to card", e);
}
if (smartCardRecord != null) {
SmartCardIntentIntegrator shrIntegrator = new SmartCardIntentIntegrator(this);
try {
shrIntegrator.initiateCardWrite(smartCardRecord.getPlainPayload());
} catch (IOException e) {
Log.e(TAG, "Could not write to card", e);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true)
.setMessage("Could not write to card. " + e.getMessage())
.show();
}
Toast.makeText(getApplicationContext(), "Opening Card Reader", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent dataIntent) {
switch (requestCode) {
case SMARTCARD_READ_REQUEST_CODE:
SmartCardIntentResult cardReadIntentResult = null;
try {
cardReadIntentResult = SmartCardIntentIntegrator.parseActivityResult(requestCode, resultCode, dataIntent);
if (cardReadIntentResult.isSuccessResult()) {
Toast.makeText(this, "Successfully written to card. ", Toast.LENGTH_LONG).show();
} else {
StringBuilder stringBuilder = new StringBuilder();
List<String> errors = cardReadIntentResult.getErrors();
if (errors != null && errors.size() > 0) {
for (String error : errors) {
stringBuilder.append(error);
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true)
.setMessage("Could not write to card. " + errors)
.show();
}
} catch (Exception e) {
Log.e(TAG, "Could not get result", e);
}
break;
case SMARTCARD_WRITE_REQUEST_CODE:
SmartCardIntentResult cardWriteIntentResult = null;
try {
cardWriteIntentResult = SmartCardIntentIntegrator.parseActivityResult(requestCode, resultCode, dataIntent);
List<String> writeErrors = cardWriteIntentResult.getErrors();
if (writeErrors == null) {
Snackbar.make(findViewById(R.id.shr_client_summary_view), "Smart card data write was successful.", Snackbar.LENGTH_LONG)
.show();
} else if (writeErrors != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Snackbar.make(findViewById(R.id.shr_client_summary_view), "Smart card data write failed." + writeErrors.get(0), Snackbar.LENGTH_LONG)
.setActionTextColor(getResources().getColor(android.R.color.holo_red_dark, null))
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View v) {
invokeShrApplication();
}
})
.show();
} else {
Snackbar.make(findViewById(R.id.shr_client_summary_view), "Smart card data write failed." + writeErrors.get(0), Snackbar.LENGTH_LONG)
.setActionTextColor(getResources().getColor(android.R.color.holo_red_dark))
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View v) {
invokeShrApplication();
}
})
.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
writeShrDataOptionDialog.dismiss();
writeShrDataOptionDialog.cancel();
break;
}
}
public void showForms(View v) {
Intent intent = new Intent(this, PatientFormsActivity.class);
intent.putExtra(PATIENT, patient);
startActivity(intent);
}
public void showNotifications(View v) {
Intent intent = new Intent(this, PatientNotificationActivity.class);
intent.putExtra(PATIENT, patient);
startActivity(intent);
}
public void showObservations(View v) {
Intent intent = new Intent(this, ObservationsActivity.class);
intent.putExtra(PATIENT, patient);
startActivity(intent);
}
public void showEncounters(View v) {
Intent intent = new Intent(this, EncountersActivity.class);
intent.putExtra(PATIENT, patient);
startActivity(intent);
}
public void showSHRObservations(View v) {
Intent intent = new Intent(PatientSummaryActivity.this, SHRObservationsDataActivity.class);
intent.putExtra(PATIENT, patient);
startActivity(intent);
}
public void switchSyncStatus(View view) {
imageView.setImageResource(R.drawable.ic_action_shr_synced);
}
private static class PatientSummaryActivityMetadata {
int recommendedForms;
int incompleteForms;
int completeForms;
int newNotifications;
int totalNotifications;
int observations;
int encounters;
}
public class BackgroundQueryTask extends AsyncTask<Void, Void, PatientSummaryActivityMetadata> {
@Override
protected PatientSummaryActivityMetadata doInBackground(Void... voids) {
MuzimaApplication muzimaApplication = (MuzimaApplication) getApplication();
PatientSummaryActivityMetadata patientSummaryActivityMetadata = new PatientSummaryActivityMetadata();
FormController formController = muzimaApplication.getFormController();
NotificationController notificationController = muzimaApplication.getNotificationController();
ObservationController observationController = muzimaApplication.getObservationController();
EncounterController encounterController = muzimaApplication.getEncounterController();
try {
patientSummaryActivityMetadata.recommendedForms = formController.getRecommendedFormsCount();
patientSummaryActivityMetadata.completeForms = formController.getCompleteFormsCountForPatient(patient.getUuid());
patientSummaryActivityMetadata.incompleteForms = formController.getIncompleteFormsCountForPatient(patient.getUuid());
patientSummaryActivityMetadata.observations = observationController.getObservationsCountByPatient(patient.getUuid());
patientSummaryActivityMetadata.encounters = encounterController.getEncountersCountByPatient(patient.getUuid());
User authenticatedUser = ((MuzimaApplication) getApplicationContext()).getAuthenticatedUser();
if (authenticatedUser != null) {
patientSummaryActivityMetadata.newNotifications =
notificationController.getNotificationsCountForPatient(patient.getUuid(), authenticatedUser.getPerson().getUuid(),
Constants.NotificationStatusConstants.NOTIFICATION_UNREAD);
patientSummaryActivityMetadata.totalNotifications =
notificationController.getNotificationsCountForPatient(patient.getUuid(), authenticatedUser.getPerson().getUuid(), null);
} else {
patientSummaryActivityMetadata.newNotifications = 0;
patientSummaryActivityMetadata.totalNotifications = 0;
}
} catch (FormController.FormFetchException e) {
Log.w(TAG, "FormFetchException occurred while fetching metadata in MainActivityBackgroundTask", e);
} catch (NotificationController.NotificationFetchException e) {
Log.w(TAG, "NotificationFetchException occurred while fetching metadata in MainActivityBackgroundTask", e);
} catch (IOException e) {
e.printStackTrace();
}
return patientSummaryActivityMetadata;
}
@Override
protected void onPostExecute(PatientSummaryActivityMetadata patientSummaryActivityMetadata) {
TextView formsDescription = (TextView) findViewById(R.id.formDescription);
formsDescription.setText(getString(R.string.hint_client_summary_forms, patientSummaryActivityMetadata.incompleteForms,
patientSummaryActivityMetadata.completeForms,
patientSummaryActivityMetadata.recommendedForms));
TextView notificationsDescription = (TextView) findViewById(R.id.notificationDescription);
notificationsDescription.setText(getString(R.string.hint_client_summary_notifications, patientSummaryActivityMetadata.newNotifications,
patientSummaryActivityMetadata.totalNotifications));
TextView observationDescription = (TextView) findViewById(R.id.observationDescription);
observationDescription.setText(getString(R.string.hint_client_summary_observations, patientSummaryActivityMetadata.observations));
TextView encounterDescription = (TextView) findViewById(R.id.encounterDescription);
encounterDescription.setText(getString(R.string.hint_client_summary_encounters, patientSummaryActivityMetadata.encounters));
}
}
private void executeBackgroundTask() {
mBackgroundQueryTask = new BackgroundQueryTask();
mBackgroundQueryTask.execute();
}
public void prepareWriteToCardOptionDialog(Context context) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = layoutInflater.inflate(R.layout.write_to_card_option_dialog_layout, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(PatientSummaryActivity.this);
writeShrDataOptionDialog = alertBuilder
.setView(dialogView)
.create();
writeShrDataOptionDialog.setCancelable(true);
searchDialogTextView = (TextView) dialogView.findViewById(R.id.patent_dialog_message_textview);
yesOptionShrSearchButton = (Button) dialogView.findViewById(R.id.yes_shr_search_dialog);
noOptionShrSearchButton = (Button) dialogView.findViewById(R.id.no_shr_search_dialog);
searchDialogTextView.setText("Do you want to write shr to card ?");
yesOptionShrSearchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
invokeShrApplication();
}
});
noOptionShrSearchButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
writeShrDataOptionDialog.cancel();
writeShrDataOptionDialog.dismiss();
}
});
}
public void prepareNonShrWriteToCardOptionDialog(Context context) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = layoutInflater.inflate(R.layout.write_to_card_option_dialog_layout, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(PatientSummaryActivity.this);
writeShrDataOptionDialog = alertBuilder
.setView(dialogView)
.create();
writeShrDataOptionDialog.setCancelable(true);
searchDialogTextView = (TextView) dialogView.findViewById(R.id.patent_dialog_message_textview);
yesOptionShrSearchButton = (Button) dialogView.findViewById(R.id.yes_shr_search_dialog);
noOptionShrSearchButton = (Button) dialogView.findViewById(R.id.no_shr_search_dialog);
searchDialogTextView.setText("Client does not have an shr. Do you want to create new shr and write to card ?");
yesOptionShrSearchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
registerNewShrRecord();
}
});
noOptionShrSearchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchDialogTextView.setText("");
writeShrDataOptionDialog.cancel();
writeShrDataOptionDialog.dismiss();
}
});
}
public void registerNewShrRecord() {
try {
KenyaEmrShrModel kenyaEmrShrModel = KenyaEmrShrMapper.createInitialSHRModelForPatient(muzimaApplication, patient);
String jsonShrModel = KenyaEmrShrMapper.createJsonFromSHRModel(kenyaEmrShrModel);
if (jsonShrModel != null) {
SmartCardRecord smartCardRecord = new SmartCardRecord();
smartCardRecord.setPlainPayload(jsonShrModel);
smartCardRecord.setPersonUuid(patient.getUuid());
smartCardRecord.setUuid(UUID.randomUUID().toString());
smartCardRecord.setType(Constants.Shr.KenyaEmr.SMART_CARD_RECORD_TYPE);
smartCardController.saveSmartCardRecord(smartCardRecord);
Toast.makeText(getApplicationContext(), "SHR has been Recorded.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(PatientSummaryActivity.this, PatientSummaryActivity.class);
/**
* todo check if this patient is registered in shr
* before opening PatientSummary activity
*/
intent.putExtra("isRegisteredOnShr", true);
intent.putExtra(PatientSummaryActivity.PATIENT, patient);
startActivity(intent);
} else {
Snackbar.make(findViewById(R.id.shr_client_summary_view), "", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View v) {
registerNewShrRecord();
}
});
}
} catch (KenyaEmrShrMapper.ShrParseException e) {
Log.e(TAG, "Error", e);
} catch (SmartCardController.SmartCardRecordSaveException e) {
e.printStackTrace();
}
}
}
|
package com.tasomaniac.openwith;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.tasomaniac.openwith.data.prefs.BooleanPreference;
import com.tasomaniac.openwith.data.prefs.TutorialShown;
import com.tasomaniac.openwith.data.prefs.UsageAccess;
import javax.inject.Singleton;
import java.io.File;
import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
@Module
final class AppModule {
private static final int DISK_CACHE_SIZE = 5 * 1024 * 1024;
@Provides
static SharedPreferences provideSharedPreferences(Application app) {
return PreferenceManager.getDefaultSharedPreferences(app);
}
@Provides
static ActivityManager provideActivityManager(Application app) {
return (ActivityManager) app.getSystemService(Context.ACTIVITY_SERVICE);
}
@Provides
@Singleton
static IconLoader provideIconLoader(Application app, ActivityManager am) {
int iconDpi = am.getLauncherLargeIconDensity();
return new IconLoader(app.getPackageManager(), iconDpi);
}
@Provides
@Singleton
@TutorialShown
static BooleanPreference provideTutorialShown(SharedPreferences prefs) {
return new BooleanPreference(prefs, "pref_tutorial_shown");
}
@Provides
@Singleton
@UsageAccess
static BooleanPreference provideUsageAccess(SharedPreferences prefs) {
return new BooleanPreference(prefs, "usage_access");
}
@Provides
@Singleton
static OkHttpClient provideOkHttpClient(Application app) {
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
return new OkHttpClient.Builder()
.cache(cache)
.build();
}
}
|
package me.devsaki.hentoid.adapters;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.documentfile.provider.DocumentFile;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.vectordrawable.graphics.drawable.Animatable2Compat;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.github.penfeizhou.animation.apng.APNGDrawable;
import com.github.penfeizhou.animation.io.FilterReader;
import com.github.penfeizhou.animation.io.Reader;
import com.github.penfeizhou.animation.io.StreamReader;
import com.github.penfeizhou.animation.loader.Loader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;
import me.devsaki.hentoid.HentoidApp;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.util.FileHelper;
import me.devsaki.hentoid.util.Helper;
import me.devsaki.hentoid.util.ImageLoaderThreadExecutor;
import me.devsaki.hentoid.util.Preferences;
import me.devsaki.hentoid.views.ssiv.CustomSubsamplingScaleImageView;
import me.devsaki.hentoid.views.ssiv.ImageSource;
import timber.log.Timber;
public final class ImagePagerAdapter extends ListAdapter<ImageFile, ImagePagerAdapter.ImageViewHolder> {
private static final int TYPE_OTHER = 0; // PNGs and JPEGs -> use CustomSubsamplingScaleImageView
private static final int TYPE_GIF = 1; // Static and animated GIFs -> use native Glide
private static final int TYPE_APNG = 2; // Animated PNGs -> use APNG4Android library
private static final int PX_600_DP = Helper.dpToPixel(HentoidApp.getInstance(), 600);
private static final Executor executor = new ImageLoaderThreadExecutor();
private final RequestOptions glideRequestOptions = new RequestOptions().centerInside();
private View.OnTouchListener itemTouchListener;
private RecyclerView recyclerView;
// To preload images before they appear on screen with CustomSubsamplingScaleImageView
private int maxBitmapWidth = -1;
private int maxBitmapHeight = -1;
// Cached prefs
private int separatingBarsHeight;
private int viewerOrientation;
public ImagePagerAdapter() {
super(DIFF_CALLBACK);
refreshPrefs();
}
public void refreshPrefs() {
int separatingBarsPrefs = Preferences.getViewerSeparatingBars();
switch (separatingBarsPrefs) {
case Preferences.Constant.PREF_VIEWER_SEPARATING_BARS_SMALL:
separatingBarsHeight = 4;
break;
case Preferences.Constant.PREF_VIEWER_SEPARATING_BARS_MEDIUM:
separatingBarsHeight = 16;
break;
case Preferences.Constant.PREF_VIEWER_SEPARATING_BARS_LARGE:
separatingBarsHeight = 64;
break;
default:
separatingBarsHeight = 0;
}
viewerOrientation = Preferences.getViewerOrientation();
}
public void setRecyclerView(RecyclerView v) {
recyclerView = v;
}
public void setItemTouchListener(View.OnTouchListener itemTouchListener) {
this.itemTouchListener = itemTouchListener;
}
public boolean isFavouritePresent() {
for (ImageFile img : getCurrentList())
if (img.isFavourite()) return true;
return false;
}
@Override
public int getItemViewType(int position) {
ImageFile img = getImageAt(position);
if (null == img) return TYPE_OTHER;
String extension = FileHelper.getExtension(img.getAbsolutePath());
if ("gif".equalsIgnoreCase(extension) || img.getMimeType().contains("gif")) {
return TYPE_GIF;
}
if ("apng".equalsIgnoreCase(extension) || img.getMimeType().contains("apng")) {
return TYPE_APNG;
}
return TYPE_OTHER;
}
@NonNull
@Override
public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view;
if (TYPE_GIF == viewType || TYPE_APNG == viewType) {
view = inflater.inflate(R.layout.item_viewer_image_simple, viewGroup, false);
} else if (Preferences.Constant.PREF_VIEWER_ORIENTATION_VERTICAL == viewerOrientation) {
view = inflater.inflate(R.layout.item_viewer_image_subsampling, viewGroup, false);
((CustomSubsamplingScaleImageView) view).setIgnoreTouchEvents(true);
} else {
view = inflater.inflate(R.layout.item_viewer_image_subsampling, viewGroup, false);
}
return new ImageViewHolder(view, viewType);
}
@Override
public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) { // TODO make all that method less ugly
if (Preferences.Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL == viewerOrientation
&& TYPE_OTHER == holder.imgType) {
CustomSubsamplingScaleImageView ssView = (CustomSubsamplingScaleImageView) holder.imgView;
ssView.setPreloadDimensions(recyclerView.getWidth(), recyclerView.getHeight());
if (!Preferences.isViewerZoomTransitions()) ssView.setDoubleTapZoomDuration(10);
}
int layoutStyle = (Preferences.Constant.PREF_VIEWER_ORIENTATION_VERTICAL == viewerOrientation) ? ViewGroup.LayoutParams.WRAP_CONTENT : ViewGroup.LayoutParams.MATCH_PARENT;
ViewGroup.LayoutParams layoutParams = holder.imgView.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.height = layoutStyle;
holder.imgView.setLayoutParams(layoutParams);
ImageFile img = getImageAt(position);
if (img != null) holder.setImage(img);
}
@Override
public void onViewRecycled(@NonNull ImageViewHolder holder) {
// Set the holder back to its original constraints while in vertical mode
// (not doing this will cause super high memory usage by trying to load _all_ images)
if (Preferences.Constant.PREF_VIEWER_ORIENTATION_VERTICAL == viewerOrientation)
holder.imgView.setMinimumHeight(PX_600_DP);
super.onViewRecycled(holder);
}
@Nullable
public ImageFile getImageAt(int position) {
return (position >= 0 && position < getItemCount()) ? getItem(position) : null;
}
public void resetScaleAtPosition(int position) {
if (recyclerView != null) {
ImageViewHolder holder = (ImageViewHolder) recyclerView.findViewHolderForAdapterPosition(position);
if (holder != null) holder.resetScale();
}
}
public void setMaxDimensions(int maxWidth, int maxHeight) {
maxBitmapWidth = maxWidth;
maxBitmapHeight = maxHeight;
}
private static final DiffUtil.ItemCallback<ImageFile> DIFF_CALLBACK =
new DiffUtil.ItemCallback<ImageFile>() {
@Override
public boolean areItemsTheSame(
@NonNull ImageFile oldAttr, @NonNull ImageFile newAttr) {
return oldAttr.getId() == newAttr.getId();
}
@Override
public boolean areContentsTheSame(
@NonNull ImageFile oldAttr, @NonNull ImageFile newAttr) {
return oldAttr.getOrder().equals(newAttr.getOrder()) && oldAttr.getStatus().equals(newAttr.getStatus());
}
};
final class ImageViewHolder extends RecyclerView.ViewHolder implements CustomSubsamplingScaleImageView.OnImageEventListener, RequestListener<Drawable> {
private final int imgType;
private final View imgView;
private ImageFile img;
private ImageViewHolder(@NonNull View itemView, int imageType) {
super(itemView);
imgType = imageType;
imgView = itemView;
if (TYPE_OTHER == imgType) {
((CustomSubsamplingScaleImageView) imgView).setExecutor(executor);
imgView.setOnTouchListener(itemTouchListener);
}
}
void setImage(ImageFile img) {
this.img = img;
String uri = img.getAbsolutePath();
Timber.i(">>>>IMG %s %s", imgType, uri);
if (TYPE_GIF == imgType) {
ImageView view = (ImageView) imgView;
Glide.with(imgView)
.load(uri)
.apply(glideRequestOptions)
.listener(this)
.into(view);
} else if (TYPE_APNG == imgType) {
ImageView view = (ImageView) imgView;
APNGDrawable apngDrawable = new APNGDrawable(new ImgLoader(uri));
apngDrawable.registerAnimationCallback(animationCallback);
view.setImageDrawable(apngDrawable);
} else {
CustomSubsamplingScaleImageView ssView = (CustomSubsamplingScaleImageView) imgView;
ssView.recycle();
ssView.setMinimumScaleType(getScaleType());
ssView.setOnImageEventListener(this);
if (maxBitmapWidth > 0) ssView.setMaxTileSize(maxBitmapWidth, maxBitmapHeight);
ssView.setImage(ImageSource.uri(uri));
}
}
private int getScaleType() {
if (Preferences.Constant.PREF_VIEWER_DISPLAY_FILL == Preferences.getViewerResizeMode()) {
return CustomSubsamplingScaleImageView.SCALE_TYPE_START;
} else {
return CustomSubsamplingScaleImageView.SCALE_TYPE_CENTER_INSIDE;
}
}
void resetScale() {
if (TYPE_GIF != imgType && TYPE_APNG != imgType) {
CustomSubsamplingScaleImageView ssView = (CustomSubsamplingScaleImageView) imgView;
if (ssView.isImageLoaded() && ssView.isReady() && ssView.isLaidOut())
ssView.resetScaleAndCenter();
}
}
private void adjustHeight(int imgHeight) {
int targetHeight = imgHeight + separatingBarsHeight;
imgView.setMinimumHeight(targetHeight);
}
// == SUBSAMPLINGSCALEVIEW CALLBACKS
@Override
public void onReady() {
if (Preferences.Constant.PREF_VIEWER_ORIENTATION_VERTICAL == viewerOrientation) {
CustomSubsamplingScaleImageView scaleView = (CustomSubsamplingScaleImageView) imgView;
adjustHeight((int) (scaleView.getScale() * scaleView.getSHeight()));
}
}
@Override
public void onImageLoaded() {
// Nothing special
}
@Override
public void onPreviewLoadError(Exception e) {
// Nothing special
}
@Override
public void onImageLoadError(Exception e) {
Timber.i(">>>>IMG %s reloaded with Glide", img.getAbsolutePath());
// Manually force mime-type as GIF to fall back to Glide
img.setMimeType("image/gif");
// Reload adapter
notifyItemChanged(getLayoutPosition());
}
@Override
public void onTileLoadError(Exception e) {
// Nothing special
}
@Override
public void onPreviewReleased() {
// Nothing special
}
// == GLIDE CALLBACKS
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
if (Preferences.Constant.PREF_VIEWER_ORIENTATION_VERTICAL == viewerOrientation)
adjustHeight(resource.getIntrinsicHeight());
return false;
}
// == APNG4Android ANIMATION CALLBACK
private final Animatable2Compat.AnimationCallback animationCallback = new Animatable2Compat.AnimationCallback() {
@Override
public void onAnimationStart(Drawable drawable) {
if (Preferences.Constant.PREF_VIEWER_ORIENTATION_VERTICAL == viewerOrientation)
adjustHeight(drawable.getIntrinsicHeight());
}
};
}
/**
* Custom image loaders for APNG4Android to work with files located in SAF area
*/
static class ImgLoader implements Loader {
private String path;
ImgLoader(String path) {
this.path = path;
}
@Override
public synchronized Reader obtain() throws IOException {
DocumentFile file = FileHelper.getDocumentFile(new File(path), false); // Helper to get a DocumentFile out of the given File
if (null == file || !file.exists()) return null; // Not triggered
return new ImgReader(file.getUri());
}
}
static class ImgReader extends FilterReader {
private Uri uri;
private static InputStream getInputStream(Uri uri) throws IOException {
return HentoidApp.getInstance().getContentResolver().openInputStream(uri);
}
ImgReader(Uri uri) throws IOException {
super(new StreamReader(getInputStream(uri)));
this.uri = uri;
}
@Override
public void reset() throws IOException {
reader.close();
reader = new StreamReader(getInputStream(uri));
}
}
}
|
package com.mxn.soul.specialalbum;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
public class DiscoverContainerView extends RelativeLayout implements
SlidingCard.OnPageChangeListener {
private Activity activity;
private List<PhotoContent> dataList = new ArrayList<>();
private ContainerInterface containerInterface;
private int count = 0;
//ViewPagerListView
// private ViewPager mPager;
// private ListView listView;
// public void setPagerAndListView(ViewPager mPager, ListView listView) {
// this.mPager = mPager;
// this.listView = listView;
public DiscoverContainerView(Context context) {
super(context);
}
public DiscoverContainerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void addToView(View child) {
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
addView(child, 0, layoutParams);
}
public void initCardView(final Activity activity, List<PhotoContent> dataList) {
this.activity = activity;
this.dataList = dataList;
if (dataList != null && dataList.size() > 0) {
for (int i = 0; i < 3; i++) {
PhotoContent userVo = dataList.get(i);
if (userVo != null) {
SlidingCard mSlidingCard = new SlidingCard(this.activity);
mSlidingCard.setContent(R.layout.sliding_card_item);
mSlidingCard.setUserVo(userVo);
View contentView = mSlidingCard.getContentView();
if (i == 1) {
contentView.setRotation(4);
}
if (i == 2) {
contentView.setRotation(-3);
}
// postInvalidate();
mSlidingCard.setListIndex(i);
mSlidingCard.setCurrentItem(1, false);
mSlidingCard.setOnPageChangeListener(this);
addToView(mSlidingCard);
}
}
}
}
public SlidingCard getCurrentView() {
if (getChildCount() > 0) {
return (SlidingCard) getChildAt(getChildCount() - 1);
}
return null;
}
public SlidingCard getNextView() {
if (getChildCount() - 1 > 0) {
return (SlidingCard) getChildAt(getChildCount() - 2);
}
return null;
}
@Override
public void onPageScrolled(SlidingCard v, int position,
float positionOffset, int positionOffsetPixels) {
if (positionOffset == 0f) {
positionOffset = 1f;
}
SlidingCard slidingCard = getNextView();
if (slidingCard != null) {
if (Math.abs(positionOffsetPixels) != 0) {
View contentView = slidingCard.getContentView();
LayoutParams params = new LayoutParams(
contentView.getLayoutParams());
params.topMargin = (int) ((1 - Math.abs(positionOffset)) *
getResources()
.getDimensionPixelSize(R.dimen.card_item_margin));
params.leftMargin = (int) ((2 - Math.abs(positionOffset)) *
getResources()
.getDimensionPixelSize(R.dimen.card_item_margin));
params.rightMargin = (int) ((2 - Math.abs(positionOffset)) *
getResources()
.getDimensionPixelSize(R.dimen.card_item_margin));
contentView.setLayoutParams(params);
contentView.setRotation(0);
postInvalidate();
}
}
}
@Override
public void onPageSelectedAfterAnimation(SlidingCard v, int prevPosition,
int curPosition) {
if (activity != null) {
removeViewAt(getChildCount() - 1);
//UserVo userVo = dataList.get(curPosition);
if (containerInterface != null) {
dataList.remove(0);
containerInterface.onFeelOperat(count);
}
PhotoContent userVo = dataList.get(curPosition);
if (userVo != null) {
SlidingCard mSlidingCard = new SlidingCard(activity);
mSlidingCard.setContent(R.layout.sliding_card_item);
mSlidingCard.setUserVo(userVo);
View contentView = mSlidingCard.getContentView();
setRotation(contentView);
mSlidingCard.setCurrentItem(1, false);
mSlidingCard.setOnPageChangeListener(this);
addToView(mSlidingCard);
}
// if (containerInterface != null) {
// dataList.remove(0);
// containerInterface.onFeelOperat(count);
Log.e("test", "onPageSelectedAfterAnimation:" + curPosition + ","
+ getChildCount());
}
}
@Override
public void onPageSelected(SlidingCard v, int prevPosition, int curPosition) {
Log.e("test", "onPageSelected:" + curPosition);
}
@Override
public void onPageScrollStateChanged(SlidingCard v, int state) {
Log.e("test", "state change:" + state);
}
public List<PhotoContent> getDataList() {
return dataList;
}
public void setDataList(List<PhotoContent> dataList) {
this.dataList = dataList;
}
public interface ContainerInterface {
void onFeelOperat(int count);
}
public void setContainerInterface(ContainerInterface containerInterface) {
this.containerInterface = containerInterface;
}
public void addNew(PhotoContent u) {
dataList.add(u);
}
private void setRotation(View v) {
if (count % 3 == 1) {
v.setRotation(4);
} else if (count % 3 == 2) {
v.setRotation(-3);
}
postInvalidate();
count++;
}
//ViewPagerListView
// @Override
// public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
// mPager.requestDisallowInterceptTouchEvent(true);
// listView.requestDisallowInterceptTouchEvent(true);
// return super.dispatchTouchEvent(ev);
// @Override
// public boolean onInterceptTouchEvent(MotionEvent ev) {
// mPager.requestDisallowInterceptTouchEvent(true);
// listView.requestDisallowInterceptTouchEvent(true);
// return super.onInterceptTouchEvent(ev);
// @Override
// public boolean onTouchEvent(@NonNull MotionEvent event) {
// mPager.requestDisallowInterceptTouchEvent(true);
// listView.requestDisallowInterceptTouchEvent(true);
// return super.onTouchEvent(event);
}
|
package com.zfdang.zsmth_android;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import com.zfdang.SMTHApplication;
import com.zfdang.devicemodeltomarketingname.DeviceMarketingName;
/**
* Usage:
* String username = Settings.getInstance().getUsername();
* Settings.getInstance().setUsername("mozilla");
*/
/*
how to add a new setting:
1. create private String setting_key
2. create private local variable
3. init the variable in initSetting()
4. implement get and set methods to access the setting
*/
public class Settings {
private static final String USERNAME_KEY = "username";
private String mUsername;
public String getUsername() {
return mUsername;
}
public void setUsername(String mUsername) {
if(this.mUsername == null || !this.mUsername.equals(mUsername)){
this.mUsername = mUsername;
mEditor.putString(USERNAME_KEY, this.mUsername);
mEditor.commit();
}
}
private static final String PASSWORD_KEY = "password";
private String mPassword;
public String getPassword() {
return mPassword;
}
public void setPassword(String mPassword) {
if(this.mPassword == null || !this.mPassword.equals(mPassword)){
this.mPassword = mPassword;
mEditor.putString(PASSWORD_KEY, this.mPassword);
mEditor.commit();
}
}
private static final String AUTO_LOGIN = "auto_login";
private boolean bAutoLogin;
public boolean isAutoLogin() {
return bAutoLogin;
}
public void setAutoLogin(boolean mAutoLogin) {
if(this.bAutoLogin != mAutoLogin) {
this.bAutoLogin = mAutoLogin;
mEditor.putBoolean(AUTO_LOGIN, this.bAutoLogin);
mEditor.commit();
}
}
private static final String LAST_LOGIN_SUCCESS = "last_login_success";
private boolean bLastLoginSuccess;
public boolean isLastLoginSuccess() {
return bLastLoginSuccess;
}
public void setLastLoginSuccess(boolean bLastLoginSuccess) {
if(this.bLastLoginSuccess != bLastLoginSuccess) {
this.bLastLoginSuccess = bLastLoginSuccess;
mEditor.putBoolean(LAST_LOGIN_SUCCESS, this.bLastLoginSuccess);
mEditor.commit();
}
}
// after user init login action, set online = true;
// after user init logout action, set online = false;
// this value will impact autoLogin behaviour of service
private static final String USER_ONLINE = "user_online";
private boolean bUserOnline;
public boolean isUserOnline() {
return bUserOnline;
}
public void setUserOnline(boolean bUserOnline) {
if(this.bUserOnline != bUserOnline) {
this.bUserOnline = bUserOnline;
mEditor.putBoolean(USER_ONLINE, this.bUserOnline);
mEditor.commit();
}
}
private static final String DEVICE_SIGNATURE = "device_signature";
private String mSignature;
public String getSignature() {
if(mSignature!= null && mSignature.length() > 0) {
return mSignature;
} else {
return "Android";
}
}
public void setSignature(String signature) {
if(this.mSignature == null || !this.mSignature.equals(signature)){
this.mSignature = signature;
mEditor.putString(DEVICE_SIGNATURE, this.mSignature);
mEditor.commit();
}
}
private static final String SHOW_STICKY_TOPIC = "show_sticky_topic";
private boolean mShowSticky;
public boolean isShowSticky() {
return mShowSticky;
}
public void setShowSticky(boolean mShowSticky) {
if(this.mShowSticky != mShowSticky) {
this.mShowSticky = mShowSticky;
mEditor.putBoolean(SHOW_STICKY_TOPIC, this.mShowSticky);
mEditor.commit();
}
}
public void toggleShowSticky() {
this.mShowSticky = !this.mShowSticky;
mEditor.putBoolean(SHOW_STICKY_TOPIC, this.mShowSticky);
mEditor.commit();
}
private static final String FORWARD_TAEGET = "forward_target";
private String mTarget;
public String getTarget() {
return mTarget;
}
public void setTarget(String target) {
if(this.mTarget == null || !this.mTarget.equals(target)){
this.mTarget = target;
mEditor.putString(FORWARD_TAEGET, this.mTarget);
mEditor.commit();
}
}
// load original image in post list, or load resized image
// FS image viewer will always load original image
private static final String LOAD_ORIGINAL_IMAGE = "LOAD_ORIGINAL_IMAGE";
private boolean bLoadOriginalImage;
public boolean isLoadOriginalImage() {
return bLoadOriginalImage;
}
public void setLoadOriginalImage(boolean bLoadOriginalImage) {
if(this.bLoadOriginalImage != bLoadOriginalImage) {
this.bLoadOriginalImage = bLoadOriginalImage;
mEditor.putBoolean(LOAD_ORIGINAL_IMAGE, this.bLoadOriginalImage);
mEditor.commit();
}
}
private static final String NIGHT_MODE = "NIGHT_MODE";
private boolean bNightMode;
public boolean isNightMode() {
return bNightMode;
}
public void setNightMode(boolean bNightMode) {
if(this.bNightMode != bNightMode) {
this.bNightMode = bNightMode;
mEditor.putBoolean(NIGHT_MODE, this.bNightMode);
mEditor.commit();
}
}
private static final String LAST_LAUNCH_VERSION = "LAST_LAUNCH_VERSION";
private int iLastVersion;
public boolean isFirstRun() {
PackageManager pm = SMTHApplication.getAppContext().getPackageManager();
int currentVersion = 0;
try {
PackageInfo pi = pm.getPackageInfo(SMTHApplication.getAppContext().getPackageName(), 0);
currentVersion = pi.versionCode;
} catch (PackageManager.NameNotFoundException e) {
Log.e("Setting", "isFirstRun: " + Log.getStackTraceString(e));
}
if(currentVersion == iLastVersion) {
return false;
} else {
this.iLastVersion = currentVersion;
mEditor.putInt(LAST_LAUNCH_VERSION, this.iLastVersion);
mEditor.commit();
return true;
}
}
private static final String NOTIFICATION_MAIL = "NOTIFICATION_MAIL";
private boolean bNotificationMail;
public boolean isNotificationMail() {
return bNotificationMail;
}
public void setNotificationMail(boolean bNotificationMail) {
if(this.bNotificationMail != bNotificationMail) {
this.bNotificationMail = bNotificationMail;
mEditor.putBoolean(NOTIFICATION_MAIL, this.bNotificationMail);
mEditor.commit();
}
}
private static final String NOTIFICATION_AT = "NOTIFICATION_AT";
private boolean bNotificationAt;
public boolean isNotificationAt() {
return bNotificationAt;
}
public void setNotificationAt(boolean bNotificationAt) {
if(this.bNotificationAt != bNotificationAt) {
this.bNotificationAt = bNotificationAt;
mEditor.putBoolean(NOTIFICATION_AT, this.bNotificationAt);
mEditor.commit();
}
}
private static final String NOTIFICATION_LIKE = "NOTIFICATION_LIKE";
private boolean bNotificationLike;
public boolean isNotificationLike() {
return bNotificationLike;
}
public void setNotificationLike(boolean bNotificationLike) {
if(this.bNotificationLike != bNotificationLike) {
this.bNotificationLike = bNotificationLike;
mEditor.putBoolean(NOTIFICATION_LIKE, this.bNotificationLike);
mEditor.commit();
}
}
private static final String NOTIFICATION_REPLY = "NOTIFICATION_REPLY";
private boolean bNotificationReply;
public boolean isNotificationReply() {
return bNotificationReply;
}
public void setNotificationReply(boolean bNotificationReply) {
if(this.bNotificationReply != bNotificationReply) {
this.bNotificationReply = bNotificationReply;
mEditor.putBoolean(NOTIFICATION_REPLY, this.bNotificationReply);
mEditor.commit();
}
}
private final String Preference_Name = "ZSMTH_Config";
private SharedPreferences mPreference;
private SharedPreferences.Editor mEditor;
// Singleton
private static Settings ourInstance = new Settings();
public static Settings getInstance() {
return ourInstance;
}
private Settings() {
initSettings();
}
// load all settings from SharedPreference
private void initSettings(){
// this
mPreference = SMTHApplication.getAppContext().getSharedPreferences(Preference_Name, Activity.MODE_PRIVATE);
mEditor = mPreference.edit();
// load all values from preference to variables
mShowSticky = mPreference.getBoolean(SHOW_STICKY_TOPIC, false);
mUsername = mPreference.getString(USERNAME_KEY, "");
mPassword = mPreference.getString(PASSWORD_KEY, "");
bAutoLogin = mPreference.getBoolean(AUTO_LOGIN, true);
bLastLoginSuccess = mPreference.getBoolean(LAST_LOGIN_SUCCESS, false);
mSignature = mPreference.getString(DEVICE_SIGNATURE, "");
if(mSignature.length() == 0) {
String marketingName = DeviceMarketingName.getInstance(SMTHApplication.getAppContext())
.getDeviceMarketingName(false);
setSignature(marketingName);
}
mTarget = mPreference.getString(FORWARD_TAEGET, "");
bUserOnline = mPreference.getBoolean(USER_ONLINE, false);
bLoadOriginalImage = mPreference.getBoolean(LOAD_ORIGINAL_IMAGE, true);
bNightMode = mPreference.getBoolean(NIGHT_MODE, true);
iLastVersion = mPreference.getInt(LAST_LAUNCH_VERSION, 0);
bNotificationMail = mPreference.getBoolean(NOTIFICATION_MAIL, true);
bNotificationAt = mPreference.getBoolean(NOTIFICATION_AT, true);
bNotificationLike = mPreference.getBoolean(NOTIFICATION_LIKE, true);
bNotificationReply = mPreference.getBoolean(NOTIFICATION_REPLY, true);
}
}
|
package org.msf.records.ui.chart;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.msf.records.App;
import org.msf.records.R;
import org.msf.records.data.app.AppModel;
import org.msf.records.data.app.AppPatient;
import org.msf.records.events.CrudEventBus;
import org.msf.records.inject.Qualifiers;
import org.msf.records.location.LocationManager;
import org.msf.records.location.LocationTree;
import org.msf.records.location.LocationTree.LocationSubtree;
import org.msf.records.model.Concept;
import org.msf.records.mvcmodels.PatientModel;
import org.msf.records.net.OpenMrsChartServer;
import org.msf.records.prefs.BooleanPreference;
import org.msf.records.sync.LocalizedChartHelper;
import org.msf.records.sync.LocalizedChartHelper.LocalizedObservation;
import org.msf.records.sync.SyncManager;
import org.msf.records.ui.BaseActivity;
import org.msf.records.ui.OdkActivityLauncher;
import org.msf.records.ui.chart.PatientChartController.ObservationsProvider;
import org.msf.records.ui.chart.PatientChartController.OdkResultSender;
import org.msf.records.utils.EventBusWrapper;
import org.msf.records.widget.DataGridView;
import org.msf.records.widget.VitalView;
import org.odk.collect.android.model.PrepopulatableFields;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Provider;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
/**
* Activity displaying a patient's vitals and charts.
*/
public final class PatientChartActivity extends BaseActivity {
private static final String TAG = PatientChartActivity.class.getSimpleName();
private static final String KEY_CONTROLLER_STATE = "controllerState";
private static final String PATIENT_UUIDS_BUNDLE_KEY = "PATIENT_UUIDS_ARRAY";
public static final String PATIENT_UUID_KEY = "PATIENT_UUID";
public static final String PATIENT_NAME_KEY = "PATIENT_NAME";
public static final String PATIENT_ID_KEY = "PATIENT_ID";
private PatientChartController mController;
private final MyUi mMyUi = new MyUi();
// TODO(dxchen): Refactor.
private boolean mIsFetchingXform = false;
@Inject AppModel mModel;
@Inject EventBus mEventBus;
@Inject Provider<CrudEventBus> mCrudEventBusProvider;
@Inject PatientModel mPatientModel;
@Inject LocationManager mLocationManager;
@Inject @Qualifiers.XformUpdateClientCache BooleanPreference mUpdateClientCache;
@Inject SyncManager mSyncManager;
@Nullable private View mChartView;
@InjectView(R.id.patient_chart_root) ViewGroup mRootView;
@InjectView(R.id.patient_chart_general_condition_parent) ViewGroup mGeneralConditionContainer;
@InjectView(R.id.patient_chart_temperature_parent) ViewGroup mTemperature;
@InjectView(R.id.patient_chart_vital_temperature) TextView mTemperatureTextView;
@InjectView(R.id.vital_responsiveness) VitalView mResponsiveness;
@InjectView(R.id.vital_mobility) VitalView mMobility;
@InjectView(R.id.vital_diet) VitalView mDiet;
@InjectView(R.id.vital_food_drink) VitalView mHydration;
@InjectView(R.id.patient_chart_vital_pcr) TextView mVitalPcr;
@InjectView(R.id.patient_chart_vital_general_condition) TextView mGeneralCondition;
@InjectView(R.id.patient_chart_vital_special) TextView mVitalSpecial;
@InjectView(R.id.patient_chart_id) TextView mPatientIdView;
@InjectView(R.id.patient_chart_fullname) TextView mPatientFullNameView;
@InjectView(R.id.patient_chart_gender) TextView mPatientGenderView;
@InjectView(R.id.patient_chart_location) TextView mPatientLocationView;
@InjectView(R.id.patient_chart_age) TextView mPatientAgeView;
@InjectView(R.id.patient_chart_days) TextView mPatientAdmissionDateView;
@InjectView(R.id.patient_chart_last_observation_date_time) TextView mLastObservationTimeView;
@InjectView(R.id.patient_chart_last_observation_label) TextView mLastObservationLabel;
public PatientChartController getController() {
return mController;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_patient_chart);
OdkResultSender odkResultSender = new OdkResultSender() {
@Override
public void sendOdkResultToServer(String patientUuid, int resultCode, Intent data) {
OdkActivityLauncher.sendOdkResultToServer(PatientChartActivity.this, patientUuid,
mUpdateClientCache.get(), resultCode, data);
}
};
ObservationsProvider observationsProvider = new ObservationsProvider() {
@Override
public Map<String, LocalizedObservation> getMostRecentObservations(
String patientUuid) {
return LocalizedChartHelper.getMostRecentObservations(getContentResolver(), patientUuid);
}
@Override
public List<LocalizedObservation> getObservations(String patientUuid) {
return LocalizedChartHelper.getObservations(getContentResolver(), patientUuid);
}
};
String patientName = getIntent().getStringExtra(PATIENT_NAME_KEY);
String patientId = getIntent().getStringExtra(PATIENT_ID_KEY);
String patientUuid = getIntent().getStringExtra(PATIENT_UUID_KEY);
@Nullable Bundle controllerState = null;
if (savedInstanceState != null) {
controllerState = savedInstanceState.getBundle(KEY_CONTROLLER_STATE);
}
ButterKnife.inject(this);
App.getInstance().inject(this);
mController = new PatientChartController(
mModel,
new OpenMrsChartServer(App.getConnectionDetails()),
new EventBusWrapper(mEventBus),
mCrudEventBusProvider.get(),
mMyUi,
odkResultSender,
observationsProvider,
controllerState,
mPatientModel,
mSyncManager);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
mController.setPatient(patientUuid, patientName, patientId);
if (patientName != null && patientId != null) {
setTitle(patientName + " (" + patientId + ")");
}
}
@Override
protected void onStart() {
super.onStart();
mController.init();
}
@Override
protected void onStop() {
mController.suspend();
super.onStop();
}
@Override
public void onExtendOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.overview, menu);
menu.findItem(R.id.action_relocate_patient).setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
mController.showAssignLocationDialog(
PatientChartActivity.this, mLocationManager);
return true;
}
}
);
menu.findItem(R.id.action_update_chart).setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
mController.onAddObservationPressed();
return true;
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mIsFetchingXform = false;
mController.onXFormResult(requestCode, resultCode, data);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// Go back rather than reloading the activity, so that the patient list retains its
// filter state.
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle(KEY_CONTROLLER_STATE, mController.getState());
}
@OnClick({
R.id.patient_chart_general_condition_parent,
R.id.patient_chart_temperature_parent}) void onVitalsPressed(View v) {
mController.onAddObservationPressed("Vital signs");
}
@OnClick({
R.id.vital_responsiveness,
R.id.vital_mobility,
R.id.vital_diet,
R.id.vital_food_drink})
void onSignsAndSymptomsPressed(View v) {
mController.onAddObservationPressed("Symptoms the patient reports (first set)");
}
/** Updates a {@link VitalView} to display a new observation value. */
private void showObservation(VitalView view, @Nullable LocalizedObservation observation) {
if (observation != null) {
view.setValue(observation.localizedValue);
} else {
view.setValue("-");
}
}
private final class MyUi implements PatientChartController.Ui {
@Override
public void setTitle(String title) {
PatientChartActivity.this.setTitle(title);
}
@Override
public void setLatestEncounter(long encounterTimeMilli) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(encounterTimeMilli);
SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd MMM yyyy HH:mm");
//dateFormatter.setTimeZone( calendar.getTimeZone() );
if (calendar.getTime().getTime() != 0) {
mLastObservationTimeView.setText(dateFormatter.format(calendar.getTime()));
mLastObservationLabel.setVisibility(View.VISIBLE);
} else {
mLastObservationTimeView.setText(R.string.last_observation_none);
mLastObservationLabel.setVisibility(View.GONE);
}
}
@Override
public void updatePatientVitalsUI(Map<String, LocalizedObservation> observations) {
showObservation(mResponsiveness, observations.get(Concept.CONSCIOUS_STATE_UUID));
showObservation(mMobility, observations.get(Concept.MOBILITY_UUID));
showObservation(mDiet, observations.get(Concept.FLUIDS_UUID));
showObservation(mHydration, observations.get(Concept.HYDRATION_UUID));
// Temperature
LocalizedObservation observation = observations.get(Concept.TEMPERATURE_UUID);
if (observation != null && observation.localizedValue != null) {
double value = Double.parseDouble(observation.localizedValue);
mTemperatureTextView.setText(String.format("%.1f°", value));
if (value <= 37.5) {
mTemperature.setBackgroundColor(Color.parseColor("#417505"));
} else {
mTemperature.setBackgroundColor(Color.parseColor("#D0021B"));
}
}
// General Condition
observation = observations.get(Concept.GENERAL_CONDITION_UUID);
if (observation != null && observation.localizedValue != null) {
mGeneralCondition.setText(observation.localizedValue);
mGeneralConditionContainer.setBackgroundResource(
Concept.getColorResourceForGeneralCondition(observation.value));
}
// Special (Pregnancy and IV)
String specialText = new String();
observation = observations.get(Concept.PREGNANCY_UUID);
if (observation != null && observation.localizedValue != null && observation.localizedValue.equals("Yes")) {
specialText = "Pregnant";
}
observation = observations.get(Concept.IV_UUID);
if (observation != null && observation.localizedValue != null && observation.localizedValue.equals("Yes")) {
specialText += "\nIV";
}
if (specialText.isEmpty()) {
specialText = "-";
}
mVitalSpecial.setText(specialText);
// PCR
mVitalPcr.setText("Not\nImplemented");
}
@Override
public void setObservationHistory(List<LocalizedObservation> observations) {
if (mChartView != null) {
mRootView.removeView(mChartView);
}
mChartView = getChartView(observations);
// mChartView = getChartViewNew(observations);
mChartView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mRootView.addView(mChartView);
mRootView.invalidate();
}
private View getChartView(List<LocalizedObservation> observations) {
return new DataGridView.Builder()
.setDoubleWidthColumnHeaders(true)
.setDataGridAdapter(
new LocalizedChartDataGridAdapter(
PatientChartActivity.this,
observations,
getLayoutInflater()))
.build(PatientChartActivity.this);
}
private View getChartViewNew(List<LocalizedObservation> observations) {
return null;
}
@Override
public void setPatient(AppPatient patient) {
String zoneName = getString(R.string.unknown_zone);
String tentName = getString(R.string.unknown_tent);
// TODO: Don't use this singleton
LocationTree locationTree = LocationTree.SINGLETON_INSTANCE;
if (patient.locationUuid != null) {
LocationSubtree patientZone = locationTree.getZoneForUuid(patient.locationUuid);
LocationSubtree patientTent = locationTree.getTentForUuid(patient.locationUuid);
zoneName = (patientZone == null) ? zoneName : patientZone.toString();
tentName = (patientTent == null) ? tentName : patientTent.toString();
}
mPatientFullNameView.setText(patient.givenName + " " + patient.familyName);
mPatientIdView.setText(patient.id);
if (patient.age.getStandardDays() >= 2 * 365) {
mPatientAgeView.setText(patient.age.getStandardDays() / 365 + "-year-old ");
} else {
mPatientAgeView.setText(patient.age.getStandardDays() / 30 + "-month-old ");
}
mPatientGenderView.setText(patient.gender == AppPatient.GENDER_MALE ? "Male" : "Female");
mPatientLocationView.setText(zoneName + "/" + tentName);
int days = Days
.daysBetween(patient.admissionDateTime, DateTime.now())
.getDays();
switch (days) {
case 0:
mPatientAdmissionDateView.setText("Admitted Today");
break;
case 1:
mPatientAdmissionDateView.setText("Admitted Yesterday");
break;
default:
mPatientAdmissionDateView.setText("Admitted " + days + " days ago");
break;
}
}
@Override
public void fetchAndShowXform(
String formUuid,
int requestCode,
org.odk.collect.android.model.Patient patient,
PrepopulatableFields fields) {
if (mIsFetchingXform) {
return;
}
mIsFetchingXform = true;
OdkActivityLauncher.fetchAndShowXform(
PatientChartActivity.this, formUuid, requestCode, patient, fields);
}
}
}
|
package info.nightscout.androidaps;
public class Config {
public static int SUPPORTEDNSVERSION = 1002; // 0.10.00
// MAIN FUCTIONALITY
public static final boolean APS = BuildConfig.APS;
// PLUGINS
public static final boolean NSCLIENT = BuildConfig.NSCLIENTOLNY;
public static final boolean G5UPLOADER = BuildConfig.G5UPLOADER;
public static final boolean PUMPCONTROL = BuildConfig.PUMPCONTROL;
public static final boolean DANAR = BuildConfig.PUMPDRIVERS;
public static final boolean ACTION = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean VIRTUALPUMP = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean MDI = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean OTHERPROFILES = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean SAFETY = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean displayDeviationSlope = false;
public static final boolean detailedLog = true;
public static final boolean logFunctionCalls = true;
public static final boolean logIncommingData = true;
public static final boolean logAPSResult = true;
public static final boolean logPumpComm = true;
public static final boolean logPrefsChange = true;
public static final boolean logConfigBuilder = true;
public static final boolean logConstraintsChanges = true;
public static final boolean logNSUpload = true;
public static final boolean logPumpActions = true;
public static final boolean logCongigBuilderActions = true;
public static final boolean logAutosensData = false;
public static final boolean logEvents = false;
// DanaR specific
public static final boolean logDanaBTComm = true;
public static boolean logDanaMessageDetail = true;
public static final boolean logDanaSerialEngine = true;
}
|
package org.wikipedia.readinglist;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import org.wikipedia.Constants;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.analytics.ReadingListsFunnel;
import org.wikipedia.events.PageDownloadEvent;
import org.wikipedia.history.HistoryEntry;
import org.wikipedia.history.SearchActionModeCallback;
import org.wikipedia.main.MainActivity;
import org.wikipedia.page.ExclusiveBottomSheetPresenter;
import org.wikipedia.page.PageActivity;
import org.wikipedia.page.PageAvailableOfflineHandler;
import org.wikipedia.page.PageTitle;
import org.wikipedia.readinglist.database.ReadingList;
import org.wikipedia.readinglist.database.ReadingListDbHelper;
import org.wikipedia.readinglist.database.ReadingListPage;
import org.wikipedia.readinglist.sync.ReadingListSyncAdapter;
import org.wikipedia.readinglist.sync.ReadingListSyncEvent;
import org.wikipedia.settings.Prefs;
import org.wikipedia.settings.SiteInfoClient;
import org.wikipedia.util.DeviceUtil;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.ResourceUtil;
import org.wikipedia.util.ShareUtil;
import org.wikipedia.views.DefaultViewHolder;
import org.wikipedia.views.DrawableItemDecoration;
import org.wikipedia.views.MultiSelectActionModeCallback;
import org.wikipedia.views.PageItemView;
import org.wikipedia.views.SearchEmptyView;
import org.wikipedia.views.SwipeableItemTouchHelperCallback;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static org.wikipedia.Constants.InvokeSource.READING_LIST_ACTIVITY;
import static org.wikipedia.readinglist.ReadingListActivity.EXTRA_READING_LIST_ID;
import static org.wikipedia.readinglist.ReadingListsFragment.ARTICLE_ITEM_IMAGE_DIMENSION;
import static org.wikipedia.util.ResourceUtil.getThemedAttributeId;
import static org.wikipedia.views.CircularProgressBar.MAX_PROGRESS;
public class ReadingListFragment extends Fragment implements ReadingListItemActionsDialog.Callback {
@BindView(R.id.reading_list_toolbar) Toolbar toolbar;
@BindView(R.id.reading_list_toolbar_container) CollapsingToolbarLayout toolBarLayout;
@BindView(R.id.reading_list_app_bar) AppBarLayout appBarLayout;
@BindView(R.id.reading_list_header) ReadingListHeaderView headerImageView;
@BindView(R.id.reading_list_contents) RecyclerView recyclerView;
@BindView(R.id.reading_list_empty_text) TextView emptyView;
@BindView(R.id.search_empty_view) SearchEmptyView searchEmptyView;
@BindView(R.id.reading_list_swipe_refresh) SwipeRefreshLayout swipeRefreshLayout;
private Unbinder unbinder;
private CompositeDisposable disposables = new CompositeDisposable();
@Nullable private ReadingList readingList;
private long readingListId;
private ReadingListPageItemAdapter adapter = new ReadingListPageItemAdapter();
private ReadingListItemView headerView;
@Nullable private ActionMode actionMode;
private AppBarListener appBarListener = new AppBarListener();
private boolean showOverflowMenu;
private ReadingListsFunnel funnel = new ReadingListsFunnel();
private HeaderCallback headerCallback = new HeaderCallback();
private ReadingListItemCallback readingListItemCallback = new ReadingListItemCallback();
private ReadingListPageItemCallback readingListPageItemCallback = new ReadingListPageItemCallback();
private SearchCallback searchActionModeCallback = new SearchCallback();
private MultiSelectActionModeCallback multiSelectActionModeCallback = new MultiSelectCallback();
private ExclusiveBottomSheetPresenter bottomSheetPresenter = new ExclusiveBottomSheetPresenter();
private SwipeableItemTouchHelperCallback touchCallback;
private boolean toolbarExpanded = true;
private List<Object> displayedLists = new ArrayList<>();
private String currentSearchQuery;
private boolean articleLimitMessageShown = false;
@NonNull
public static ReadingListFragment newInstance(long listId) {
ReadingListFragment instance = new ReadingListFragment();
Bundle args = new Bundle();
args.putLong(EXTRA_READING_LIST_ID, listId);
instance.setArguments(args);
return instance;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_reading_list, container, false);
unbinder = ButterKnife.bind(this, view);
getAppCompatActivity().setSupportActionBar(toolbar);
getAppCompatActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getAppCompatActivity().getSupportActionBar().setTitle("");
DeviceUtil.updateStatusBarTheme(requireActivity(), toolbar, true);
appBarLayout.addOnOffsetChangedListener(appBarListener);
toolBarLayout.setCollapsedTitleTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.main_toolbar_icon_color));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
toolBarLayout.setStatusBarScrimColor(ResourceUtil.getThemedColor(requireContext(), R.attr.main_status_bar_color));
}
touchCallback = new SwipeableItemTouchHelperCallback(requireContext());
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(touchCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
recyclerView.addItemDecoration(new DrawableItemDecoration(requireContext(), R.attr.list_separator_drawable, true, false));
headerView = new ReadingListItemView(getContext());
headerView.setCallback(headerCallback);
headerView.setClickable(false);
headerView.setThumbnailVisible(false);
headerView.setTitleTextAppearance(R.style.ReadingListTitleTextAppearance);
headerView.setOverflowViewVisibility(VISIBLE);
readingListId = getArguments().getLong(EXTRA_READING_LIST_ID);
disposables.add(WikipediaApp.getInstance().getBus().subscribe(new EventBusConsumer()));
swipeRefreshLayout.setColorSchemeResources(getThemedAttributeId(requireContext(), R.attr.colorAccent));
swipeRefreshLayout.setOnRefreshListener(() -> ReadingListsFragment.refreshSync(ReadingListFragment.this, swipeRefreshLayout));
if (ReadingListSyncAdapter.isDisabledByRemoteConfig()) {
swipeRefreshLayout.setEnabled(false);
}
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
updateReadingListData();
}
@Override
public void onPause() {
super.onPause();
bottomSheetPresenter.dismiss(getChildFragmentManager());
}
@Override public void onDestroyView() {
disposables.clear();
recyclerView.setAdapter(null);
appBarLayout.removeOnOffsetChangedListener(appBarListener);
unbinder.unbind();
unbinder = null;
super.onDestroyView();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_reading_list, menu);
if (showOverflowMenu) {
inflater.inflate(R.menu.menu_reading_list_item, menu);
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem sortByNameItem = menu.findItem(R.id.menu_sort_by_name);
MenuItem sortByRecentItem = menu.findItem(R.id.menu_sort_by_recent);
int sortMode = Prefs.getReadingListPageSortMode(ReadingList.SORT_BY_NAME_ASC);
sortByNameItem.setTitle(sortMode == ReadingList.SORT_BY_NAME_ASC ? R.string.reading_list_sort_by_name_desc : R.string.reading_list_sort_by_name);
sortByRecentItem.setTitle(sortMode == ReadingList.SORT_BY_RECENT_DESC ? R.string.reading_list_sort_by_recent_desc : R.string.reading_list_sort_by_recent);
MenuItem searchItem = menu.findItem(R.id.menu_search_lists);
MenuItem sortOptionsItem = menu.findItem(R.id.menu_sort_options);
searchItem.getIcon().setColorFilter(toolbarExpanded ? getResources().getColor(android.R.color.white)
: ResourceUtil.getThemedColor(requireContext(), R.attr.main_toolbar_icon_color), PorterDuff.Mode.SRC_IN);
sortOptionsItem.getIcon().setColorFilter(toolbarExpanded ? getResources().getColor(android.R.color.white)
: ResourceUtil.getThemedColor(requireContext(), R.attr.main_toolbar_icon_color), PorterDuff.Mode.SRC_IN);
if (readingList != null && readingList.isDefault()) {
if (menu.findItem(R.id.menu_reading_list_rename) != null) {
menu.findItem(R.id.menu_reading_list_rename).setVisible(false);
}
if (menu.findItem(R.id.menu_reading_list_delete) != null) {
menu.findItem(R.id.menu_reading_list_delete).setVisible(false);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search_lists:
getAppCompatActivity().startSupportActionMode(searchActionModeCallback);
return true;
case R.id.menu_sort_by_name:
setSortMode(ReadingList.SORT_BY_NAME_ASC, ReadingList.SORT_BY_NAME_DESC);
return true;
case R.id.menu_sort_by_recent:
setSortMode(ReadingList.SORT_BY_RECENT_DESC, ReadingList.SORT_BY_RECENT_ASC);
return true;
case R.id.menu_reading_list_rename:
rename();
return true;
case R.id.menu_reading_list_delete:
delete();
return true;
case R.id.menu_reading_list_save_all_offline:
if (readingList != null) {
ReadingListBehaviorsUtil.INSTANCE.savePagesForOffline(requireActivity(), readingList.pages(), () -> {
adapter.notifyDataSetChanged();
update();
});
}
return true;
case R.id.menu_reading_list_remove_all_offline:
if (readingList != null) {
ReadingListBehaviorsUtil.INSTANCE.removePagesFromOffline(requireActivity(), readingList.pages(), () -> {
adapter.notifyDataSetChanged();
update();
});
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Nullable private Bundle getTransitionAnimationBundle(@NonNull PageTitle pageTitle) {
// TODO: add future transition animations.
return null;
}
private AppCompatActivity getAppCompatActivity() {
return (AppCompatActivity) getActivity();
}
private void update() {
update(readingList);
}
private void update(@Nullable ReadingList readingList) {
if (readingList == null) {
return;
}
emptyView.setVisibility(readingList.pages().isEmpty() ? VISIBLE : GONE);
headerView.setReadingList(readingList, ReadingListItemView.Description.DETAIL);
headerImageView.setReadingList(readingList);
ReadingList.sort(readingList, Prefs.getReadingListPageSortMode(ReadingList.SORT_BY_NAME_ASC));
setSearchQuery();
if (!toolbarExpanded) {
toolBarLayout.setTitle(readingList.title());
}
if (!articleLimitMessageShown && readingList.pages().size() >= SiteInfoClient.getMaxPagesPerReadingList()) {
String message = getString(R.string.reading_list_article_limit_message, readingList.title(), SiteInfoClient.getMaxPagesPerReadingList());
FeedbackUtil.makeSnackbar(getActivity(), message, FeedbackUtil.LENGTH_DEFAULT).show();
articleLimitMessageShown = true;
}
}
private void updateReadingListData() {
disposables.add(Observable.fromCallable(() -> ReadingListDbHelper.instance().getFullListById(readingListId))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(list -> {
swipeRefreshLayout.setRefreshing(false);
readingList = list;
if (readingList != null) {
searchEmptyView.setEmptyText(getString(R.string.search_reading_list_no_results,
readingList.title()));
}
update();
}, t -> {
// If we failed to retrieve the requested list, it means that the list is no
// longer in the database (likely removed due to sync).
// In this case, there's nothing for us to do, so just bail from the activity.
requireActivity().finish();
}));
}
private void setSearchQuery() {
setSearchQuery(currentSearchQuery);
}
private void setSearchQuery(@Nullable String query) {
if (readingList == null) {
return;
}
currentSearchQuery = query;
if (TextUtils.isEmpty(query)) {
displayedLists.clear();
displayedLists.addAll(readingList.pages());
adapter.notifyDataSetChanged();
updateEmptyState(query);
} else {
ReadingListBehaviorsUtil.INSTANCE.searchListsAndPages(query, lists -> {
displayedLists = lists;
adapter.notifyDataSetChanged();
updateEmptyState(query);
});
}
touchCallback.setSwipeableEnabled(TextUtils.isEmpty(query));
}
private void updateEmptyState(@Nullable String searchQuery) {
if (TextUtils.isEmpty(searchQuery)) {
searchEmptyView.setVisibility(GONE);
recyclerView.setVisibility(VISIBLE);
emptyView.setVisibility(displayedLists.isEmpty() ? VISIBLE : GONE);
} else {
recyclerView.setVisibility(displayedLists.isEmpty() ? GONE : VISIBLE);
searchEmptyView.setVisibility(displayedLists.isEmpty() ? VISIBLE : GONE);
emptyView.setVisibility(GONE);
}
}
private void setSortMode(int sortModeAsc, int sortModeDesc) {
int sortMode = Prefs.getReadingListPageSortMode(ReadingList.SORT_BY_NAME_ASC);
if (sortMode != sortModeAsc) {
sortMode = sortModeAsc;
} else {
sortMode = sortModeDesc;
}
Prefs.setReadingListPageSortMode(sortMode);
requireActivity().invalidateOptionsMenu();
update();
}
private void rename() {
ReadingListBehaviorsUtil.INSTANCE.renameReadingList(requireActivity(), readingList, () -> {
update();
funnel.logModifyList(readingList, 0);
});
}
private void finishActionMode() {
if (actionMode != null) {
actionMode.finish();
}
}
private void beginMultiSelect() {
if (SearchCallback.is(actionMode)) {
finishActionMode();
}
if (!MultiSelectCallback.is(actionMode)) {
getAppCompatActivity().startSupportActionMode(multiSelectActionModeCallback);
}
}
private void toggleSelectPage(@Nullable ReadingListPage page) {
if (page == null) {
return;
}
page.selected(!page.selected());
int selectedCount = getSelectedPageCount();
if (selectedCount == 0) {
finishActionMode();
} else if (actionMode != null) {
actionMode.setTitle(getString(R.string.multi_select_items_selected, selectedCount));
}
adapter.notifyDataSetChanged();
}
private int getSelectedPageCount() {
int selectedCount = 0;
for (Object list : displayedLists) {
if (list instanceof ReadingListPage && ((ReadingListPage) list).selected()) {
selectedCount++;
}
}
return selectedCount;
}
private void unselectAllPages() {
if (readingList == null) {
return;
}
for (ReadingListPage page : readingList.pages()) {
page.selected(false);
}
adapter.notifyDataSetChanged();
}
@NonNull
private List<ReadingListPage> getSelectedPages() {
List<ReadingListPage> result = new ArrayList<>();
if (readingList == null) {
return result;
}
for (Object list : displayedLists) {
if (list instanceof ReadingListPage && ((ReadingListPage) list).selected()) {
result.add((ReadingListPage) list);
((ReadingListPage) list).selected(false);
}
}
return result;
}
private void deleteSelectedPages() {
List<ReadingListPage> selectedPages = getSelectedPages();
if (!selectedPages.isEmpty()) {
ReadingListDbHelper.instance().markPagesForDeletion(readingList, selectedPages);
readingList.pages().removeAll(selectedPages);
funnel.logDeleteItem(readingList, 0);
ReadingListBehaviorsUtil.INSTANCE.showDeletePagesUndoSnackbar(requireActivity(), readingList, selectedPages, this::updateReadingListData);
update();
}
}
private void addSelectedPagesToList() {
List<ReadingListPage> selectedPages = getSelectedPages();
if (!selectedPages.isEmpty()) {
List<PageTitle> titles = new ArrayList<>();
for (ReadingListPage page : selectedPages) {
titles.add(ReadingListPage.toPageTitle(page));
}
bottomSheetPresenter.show(getChildFragmentManager(),
AddToReadingListDialog.newInstance(titles, READING_LIST_ACTIVITY));
update();
}
}
private void delete() {
ReadingListBehaviorsUtil.INSTANCE.deleteReadingList(requireActivity(), readingList, true, () -> {
startActivity(MainActivity.newIntent(requireActivity())
.putExtra(Constants.INTENT_EXTRA_DELETE_READING_LIST, readingList.title()));
requireActivity().finish();
});
}
@Override
public void onToggleItemOffline(@NonNull ReadingListPage page) {
ReadingListBehaviorsUtil.INSTANCE.togglePageOffline(requireActivity(), page, () -> {
adapter.notifyDataSetChanged();
update();
});
}
@Override
public void onShareItem(@NonNull ReadingListPage page) {
ShareUtil.shareText(getContext(), ReadingListPage.toPageTitle(page));
}
@Override
public void onAddItemToOther(@NonNull ReadingListPage page) {
bottomSheetPresenter.show(getChildFragmentManager(),
AddToReadingListDialog.newInstance(ReadingListPage.toPageTitle(page),
READING_LIST_ACTIVITY));
}
@Override
public void onSelectItem(@NonNull ReadingListPage page) {
if (actionMode == null || MultiSelectCallback.is(actionMode)) {
beginMultiSelect();
toggleSelectPage(page);
}
}
@Override
public void onDeleteItem(@NonNull ReadingListPage page) {
List<ReadingList> listsContainPage = TextUtils.isEmpty(currentSearchQuery) ? Collections.singletonList(readingList) : ReadingListBehaviorsUtil.INSTANCE.getListsContainPage(page);
ReadingListBehaviorsUtil.INSTANCE.deletePages(requireActivity(), listsContainPage, page, this::updateReadingListData, () -> {
// TODO: need to verify the log of delete item since this action will delete multiple items in the same time.
funnel.logDeleteItem(readingList, 0);
update();
});
}
private class AppBarListener implements AppBarLayout.OnOffsetChangedListener {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (verticalOffset > -appBarLayout.getTotalScrollRange() && showOverflowMenu) {
showOverflowMenu = false;
toolBarLayout.setTitle("");
getAppCompatActivity().supportInvalidateOptionsMenu();
toolbarExpanded = true;
} else if (verticalOffset <= -appBarLayout.getTotalScrollRange() && !showOverflowMenu) {
showOverflowMenu = true;
toolBarLayout.setTitle(readingList != null ? readingList.title() : null);
getAppCompatActivity().supportInvalidateOptionsMenu();
toolbarExpanded = false;
}
DeviceUtil.updateStatusBarTheme(requireActivity(), toolbar,
actionMode == null && (appBarLayout.getTotalScrollRange() + verticalOffset) > appBarLayout.getTotalScrollRange() / 2);
((ReadingListActivity) requireActivity()).updateNavigationBarColor();
// prevent swiping when collapsing the view
swipeRefreshLayout.setEnabled(verticalOffset == 0);
}
}
private class ReadingListItemHolder extends DefaultViewHolder<View> {
private ReadingListItemView itemView;
ReadingListItemHolder(ReadingListItemView itemView) {
super(itemView);
this.itemView = itemView;
}
void bindItem(ReadingList readingList) {
itemView.setReadingList(readingList, ReadingListItemView.Description.SUMMARY);
itemView.setSearchQuery(currentSearchQuery);
}
public ReadingListItemView getView() {
return itemView;
}
}
private class ReadingListPageItemHolder extends DefaultViewHolder<PageItemView<ReadingListPage>>
implements SwipeableItemTouchHelperCallback.Callback {
private ReadingListPage page;
ReadingListPageItemHolder(PageItemView<ReadingListPage> itemView) {
super(itemView);
}
void bindItem(ReadingListPage page) {
this.page = page;
getView().setItem(page);
getView().setTitle(page.title());
getView().setDescription(page.description());
getView().setImageUrl(page.thumbUrl());
getView().setSelected(page.selected());
getView().setSecondaryActionIcon(page.saving() ? R.drawable.ic_download_in_progress : R.drawable.ic_download_circle_gray_24dp,
!page.offline() || page.saving());
getView().setCircularProgressVisibility(page.downloadProgress() > 0 && page.downloadProgress() < MAX_PROGRESS);
getView().setProgress(page.downloadProgress() == MAX_PROGRESS ? 0 : page.downloadProgress());
getView().setSecondaryActionHint(R.string.reading_list_article_make_offline);
getView().setSearchQuery(currentSearchQuery);
getView().setListItemImageDimensions(getImageDimension(), getImageDimension());
PageAvailableOfflineHandler.INSTANCE.check(page, available -> getView().setViewsGreyedOut(!available));
if (!TextUtils.isEmpty(currentSearchQuery)) {
getView().setTitleMaxLines(2);
getView().setTitleEllipsis();
getView().setDescriptionMaxLines(2);
getView().setDescriptionEllipsis();
getView().setUpChipGroup(ReadingListBehaviorsUtil.INSTANCE.getListsContainPage(page));
} else {
getView().hideChipGroup();
}
}
@Override
public void onSwipe() {
if (TextUtils.isEmpty(currentSearchQuery)) {
ReadingListBehaviorsUtil.INSTANCE.deletePages(requireActivity(), Collections.singletonList(readingList), page, ReadingListFragment.this::updateReadingListData, () -> {
funnel.logDeleteItem(readingList, 0);
update();
});
}
}
private int getImageDimension() {
return DimenUtil.roundedDpToPx(TextUtils.isEmpty(currentSearchQuery)
? DimenUtil.getDimension(R.dimen.view_list_card_item_image) : ARTICLE_ITEM_IMAGE_DIMENSION);
}
}
private class ReadingListHeaderHolder extends RecyclerView.ViewHolder {
ReadingListHeaderHolder(View itemView) {
super(itemView);
}
}
private final class ReadingListPageItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_PAGE_ITEM = 2;
private int getHeaderCount() {
return (TextUtils.isEmpty(currentSearchQuery)) ? 1 : 0;
}
@Override
public int getItemViewType(int position) {
if (getHeaderCount() == 1 && position == 0) {
return TYPE_HEADER;
} else if (displayedLists.get(position - getHeaderCount()) instanceof ReadingList) {
return TYPE_ITEM;
} else {
return TYPE_PAGE_ITEM;
}
}
@Override
public int getItemCount() {
return getHeaderCount() + displayedLists.size();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {
if (type == TYPE_ITEM) {
ReadingListItemView view = new ReadingListItemView(getContext());
return new ReadingListItemHolder(view);
} else if (type == TYPE_HEADER) {
return new ReadingListHeaderHolder(headerView);
} else {
return new ReadingListPageItemHolder(new PageItemView<>(requireContext()));
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int pos) {
if (readingList != null) {
if (holder instanceof ReadingListItemHolder) {
((ReadingListItemHolder) holder).bindItem((ReadingList) displayedLists.get(pos - getHeaderCount()));
} else if (holder instanceof ReadingListPageItemHolder) {
((ReadingListPageItemHolder) holder).bindItem((ReadingListPage) displayedLists.get(pos - getHeaderCount()));
}
}
}
@Override public void onViewAttachedToWindow(@NonNull RecyclerView.ViewHolder holder) {
super.onViewAttachedToWindow(holder);
if (holder instanceof ReadingListItemHolder) {
((ReadingListItemHolder) holder).getView().setCallback(readingListItemCallback);
} else if (holder instanceof ReadingListPageItemHolder) {
((ReadingListPageItemHolder) holder).getView().setCallback(readingListPageItemCallback);
}
}
@Override public void onViewDetachedFromWindow(@NonNull RecyclerView.ViewHolder holder) {
if (holder instanceof ReadingListItemHolder) {
((ReadingListItemHolder) holder).getView().setCallback(null);
} else if (holder instanceof ReadingListPageItemHolder) {
((ReadingListPageItemHolder) holder).getView().setCallback(null);
}
super.onViewDetachedFromWindow(holder);
}
}
private class HeaderCallback implements ReadingListItemView.Callback {
@Override
public void onClick(@NonNull ReadingList readingList) {
}
@Override
public void onRename(@NonNull ReadingList readingList) {
rename();
}
@Override
public void onDelete(@NonNull ReadingList readingList) {
delete();
}
@Override
public void onSaveAllOffline(@NonNull ReadingList readingList) {
ReadingListBehaviorsUtil.INSTANCE.savePagesForOffline(requireActivity(), readingList.pages(), () -> {
adapter.notifyDataSetChanged();
update();
});
}
@Override
public void onRemoveAllOffline(@NonNull ReadingList readingList) {
ReadingListBehaviorsUtil.INSTANCE.removePagesFromOffline(requireActivity(), readingList.pages(), () -> {
adapter.notifyDataSetChanged();
update();
});
}
}
private class ReadingListItemCallback implements ReadingListItemView.Callback {
@Override
public void onClick(@NonNull ReadingList readingList) {
if (actionMode != null) {
actionMode.finish();
}
startActivity(ReadingListActivity.newIntent(requireContext(), readingList));
}
@Override
public void onRename(@NonNull ReadingList readingList) {
ReadingListBehaviorsUtil.INSTANCE.renameReadingList(requireActivity(), readingList, () -> update(readingList));
}
@Override
public void onDelete(@NonNull ReadingList readingList) {
ReadingListBehaviorsUtil.INSTANCE.deleteReadingList(requireActivity(), readingList, true, () -> {
ReadingListBehaviorsUtil.INSTANCE.showDeleteListUndoSnackbar(requireActivity(), readingList, ReadingListFragment.this::setSearchQuery);
setSearchQuery();
});
}
@Override
public void onSaveAllOffline(@NonNull ReadingList readingList) {
ReadingListBehaviorsUtil.INSTANCE.savePagesForOffline(requireActivity(), readingList.pages(), ReadingListFragment.this::setSearchQuery);
}
@Override
public void onRemoveAllOffline(@NonNull ReadingList readingList) {
ReadingListBehaviorsUtil.INSTANCE.removePagesFromOffline(requireActivity(), readingList.pages(), ReadingListFragment.this::setSearchQuery);
}
}
private class ReadingListPageItemCallback implements PageItemView.Callback<ReadingListPage> {
@Override
public void onClick(@Nullable ReadingListPage page) {
if (MultiSelectCallback.is(actionMode)) {
toggleSelectPage(page);
} else if (page != null) {
PageTitle title = ReadingListPage.toPageTitle(page);
HistoryEntry entry = new HistoryEntry(title, HistoryEntry.SOURCE_READING_LIST);
page.touch();
Completable.fromAction(() -> {
ReadingListDbHelper.instance().updateLists(ReadingListBehaviorsUtil.INSTANCE.getListsContainPage(page), false);
ReadingListDbHelper.instance().updatePage(page);
}).subscribeOn(Schedulers.io()).subscribe();
startActivity(PageActivity.newIntentForCurrentTab(requireContext(), entry, entry.getTitle()), getTransitionAnimationBundle(entry.getTitle()));
}
}
@Override
public boolean onLongClick(@Nullable ReadingListPage page) {
if (page == null) {
return false;
}
bottomSheetPresenter.show(getChildFragmentManager(),
ReadingListItemActionsDialog.newInstance(TextUtils.isEmpty(currentSearchQuery)
? Collections.singletonList(readingList) : ReadingListBehaviorsUtil.INSTANCE.getListsContainPage(page), page, actionMode != null));
return true;
}
@Override
public void onThumbClick(@Nullable ReadingListPage item) {
onClick(item);
}
@Override
public void onActionClick(@Nullable ReadingListPage page, @NonNull View view) {
if (page == null) {
return;
}
bottomSheetPresenter.show(getChildFragmentManager(),
ReadingListItemActionsDialog.newInstance(TextUtils.isEmpty(currentSearchQuery)
? Collections.singletonList(readingList) : ReadingListBehaviorsUtil.INSTANCE.getListsContainPage(page), page, actionMode != null));
}
@Override
public void onSecondaryActionClick(@Nullable ReadingListPage page, @NonNull View view) {
if (page != null) {
if (Prefs.isDownloadOnlyOverWiFiEnabled() && !DeviceUtil.isOnWiFi()
&& page.status() == ReadingListPage.STATUS_QUEUE_FOR_SAVE) {
page.offline(false);
}
if (page.saving()) {
Toast.makeText(getContext(), R.string.reading_list_article_save_in_progress, Toast.LENGTH_LONG).show();
} else {
ReadingListBehaviorsUtil.INSTANCE.toggleOffline(requireActivity(), page, () -> {
adapter.notifyDataSetChanged();
update();
});
}
}
}
@Override
public void onListChipClick(@NonNull ReadingList readingList) {
startActivity(ReadingListActivity.newIntent(requireContext(), readingList));
}
}
private void setStatusBarActionMode(boolean inActionMode) {
DeviceUtil.updateStatusBarTheme(requireActivity(), toolbar, toolbarExpanded && !inActionMode);
requireActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
requireActivity().getWindow().setStatusBarColor(!inActionMode
? Color.TRANSPARENT : ResourceUtil.getThemedColor(requireActivity(), R.attr.main_status_bar_color));
}
private class SearchCallback extends SearchActionModeCallback {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
actionMode = mode;
recyclerView.stopScroll();
appBarLayout.setExpanded(false, false);
setStatusBarActionMode(true);
return super.onCreateActionMode(mode, menu);
}
@Override
protected void onQueryChange(String s) {
setSearchQuery(s.trim());
}
@Override
public void onDestroyActionMode(ActionMode mode) {
super.onDestroyActionMode(mode);
actionMode = null;
currentSearchQuery = null;
setStatusBarActionMode(false);
updateReadingListData();
}
@Override
protected String getSearchHintString() {
return getString(R.string.search_hint_search_my_lists_and_articles);
}
@Override
protected Context getParentContext() {
return requireContext();
}
}
private class MultiSelectCallback extends MultiSelectActionModeCallback {
@Override public boolean onCreateActionMode(ActionMode mode, Menu menu) {
super.onCreateActionMode(mode, menu);
mode.getMenuInflater().inflate(R.menu.menu_action_mode_reading_list, menu);
actionMode = mode;
setStatusBarActionMode(true);
return true;
}
@Override public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_delete_selected:
onDeleteSelected();
finishActionMode();
return true;
case R.id.menu_remove_from_offline:
ReadingListBehaviorsUtil.INSTANCE.removePagesFromOffline(requireActivity(), getSelectedPages(), () -> {
adapter.notifyDataSetChanged();
update();
});
finishActionMode();
return true;
case R.id.menu_save_for_offline:
ReadingListBehaviorsUtil.INSTANCE.savePagesForOffline(requireActivity(), getSelectedPages(), () -> {
adapter.notifyDataSetChanged();
update();
});
finishActionMode();
return true;
case R.id.menu_add_to_another_list:
addSelectedPagesToList();
finishActionMode();
return true;
default:
}
return false;
}
@Override protected void onDeleteSelected() {
deleteSelectedPages();
}
@Override public void onDestroyActionMode(ActionMode mode) {
unselectAllPages();
actionMode = null;
setStatusBarActionMode(false);
super.onDestroyActionMode(mode);
}
}
private class EventBusConsumer implements Consumer<Object> {
@Override
public void accept(Object event) {
if (event instanceof ReadingListSyncEvent) {
updateReadingListData();
} else if (event instanceof PageDownloadEvent) {
int pagePosition = getPagePositionInList(((PageDownloadEvent) event).getPage());
if (pagePosition != -1 && displayedLists.get(pagePosition) instanceof ReadingListPage) {
((ReadingListPage) displayedLists.get(pagePosition)).downloadProgress(((PageDownloadEvent) event).getPage().downloadProgress());
adapter.notifyItemChanged(pagePosition + 1);
}
}
}
}
private int getPagePositionInList(ReadingListPage page) {
for (Object list : displayedLists) {
if (list instanceof ReadingListPage && ((ReadingListPage) list).id() == page.id()) {
return displayedLists.indexOf(list);
}
}
return -1;
}
}
|
package de.danoeh.antennapod.asynctask;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import de.danoeh.antennapod.core.R;
import de.danoeh.antennapod.core.opml.OpmlWriter;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.storage.DBReader;
import de.danoeh.antennapod.core.util.LangUtils;
/**
* Writes an OPML file into the export directory in the background.
*/
public class OpmlExportWorker extends AsyncTask<Void, Void, Void> {
private static final String TAG = "OpmlExportWorker";
private static final String DEFAULT_OUTPUT_NAME = "antennapod-feeds.opml";
public static final String EXPORT_DIR = "export/";
private Context context;
private File output;
private ProgressDialog progDialog;
private Exception exception;
public OpmlExportWorker(Context context, File output) {
this.context = context;
this.output = output;
}
public OpmlExportWorker(Context context) {
this.context = context;
}
@Override
protected Void doInBackground(Void... params) {
OpmlWriter opmlWriter = new OpmlWriter();
if (output == null) {
output = new File(
UserPreferences.getDataFolder(context, EXPORT_DIR),
DEFAULT_OUTPUT_NAME);
if (output.exists()) {
Log.w(TAG, "Overwriting previously exported file.");
output.delete();
}
}
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(output), LangUtils.UTF_8);
opmlWriter.writeDocument(DBReader.getFeedList(context), writer);
} catch (IOException e) {
e.printStackTrace();
exception = e;
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ioe) {
exception = ioe;
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
progDialog.dismiss();
AlertDialog.Builder alert = new AlertDialog.Builder(context)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
if (exception != null) {
alert.setTitle(R.string.export_error_label);
alert.setMessage(exception.getMessage());
} else {
alert.setTitle(R.string.opml_export_success_title);
alert.setMessage(context
.getString(R.string.opml_export_success_sum)
+ output.toString())
.setPositiveButton(R.string.share_label, (dialog, which) -> {
Uri outputUri = Uri.fromFile(output);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "OPML Export");
sendIntent.putExtra(Intent.EXTRA_STREAM, outputUri);
sendIntent.setType("text/plain");
context.startActivity(Intent.createChooser(sendIntent,
context.getResources().getText(R.string.share_label)));
});
}
alert.create().show();
}
@Override
protected void onPreExecute() {
progDialog = new ProgressDialog(context);
progDialog.setMessage(context.getString(R.string.exporting_label));
progDialog.setIndeterminate(true);
progDialog.show();
}
@SuppressLint("NewApi")
public void executeAsync() {
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
executeOnExecutor(THREAD_POOL_EXECUTOR);
} else {
execute();
}
}
}
|
package lib.morkim.mfw.usecase;
import lib.morkim.mfw.app.MorkimApp;
import lib.morkim.mfw.domain.Model;
import lib.morkim.mfw.repo.Repository;
@SuppressWarnings({"WeakerAccess", "unused"})
public abstract class MorkimTask<A extends MorkimApp<M, ?>, M extends Model, Req extends TaskRequest, Res extends TaskResult> {
protected A appContext;
protected M model;
protected Repository repo;
protected MorkimTaskListener<Res> listener;
private Req request;
public MorkimTask(A morkimApp, MorkimTaskListener<Res> listener) {
this.appContext = morkimApp;
this.model = appContext.getModel();
this.repo = appContext.getRepo();
if (listener == null)
this.listener = new MorkimTaskListener<Res>() {
@Override
public void onTaskStart(MorkimTask task) {}
@Override
public void onTaskUpdate(Res result) {}
@Override
public void onTaskComplete(Res result) {}
@Override
public void onTaskCancel() {}
};
else
this.listener = listener;
}
public void execute(Req request) {
setRequest(request);
onExecute(request);
}
public void execute() {
onExecute(null);
}
public void executeSync(Req request) {
setRequest(request);
onExecute(request);
}
public void executeSync() {
onExecute(null);
}
protected void updateProgress(Res result) {
updateListener(result);
}
protected abstract Res onExecute(Req request);
protected void updateListener(Res result) {
if (result != null) {
if (result.completionPercent != 100)
listener.onTaskUpdate(result);
else
listener.onTaskComplete(result);
} else
listener.onTaskComplete(null);
}
protected void onSaveModel() {}
public void setAppContext(A appContext) {
this.appContext = appContext;
}
protected Req getRequest() {
return request;
}
public void setRequest(Req request) {
this.request = request;
}
public MorkimTaskListener<Res> getListener() {
return listener;
}
public void setListener(MorkimTaskListener<Res> listener) {
this.listener = listener;
}
}
|
package info.zamojski.soft.towercollector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.acra.ACRA;
import org.acra.ACRAConstants;
import org.acra.ReportField;
import org.acra.config.CoreConfigurationBuilder;
import org.acra.config.HttpSenderConfigurationBuilder;
import org.acra.config.NotificationConfigurationBuilder;
import org.acra.data.StringFormat;
import org.acra.sender.HttpSender;
import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import info.zamojski.soft.towercollector.analytics.AnalyticsServiceFactory;
import info.zamojski.soft.towercollector.analytics.IAnalyticsReportingService;
import info.zamojski.soft.towercollector.dao.MeasurementsDatabase;
import info.zamojski.soft.towercollector.logging.ConsoleLoggingTree;
import info.zamojski.soft.towercollector.logging.FileLoggingTree;
import info.zamojski.soft.towercollector.providers.AppThemeProvider;
import info.zamojski.soft.towercollector.providers.preferences.PreferencesProvider;
import info.zamojski.soft.towercollector.utils.ExceptionUtils;
import info.zamojski.soft.towercollector.utils.HashUtils;
import info.zamojski.soft.towercollector.utils.PermissionUtils;
import android.Manifest;
import android.app.Application;
import android.app.NotificationManager;
import android.database.sqlite.SQLiteDatabaseCorruptException;
import android.os.Build;
import androidx.appcompat.app.AppCompatDelegate;
import android.os.DeadObjectException;
import android.util.Log;
import android.widget.Toast;
import timber.log.Timber;
public class MyApplication extends Application {
private static IAnalyticsReportingService analyticsService;
private static MyApplication application;
private static PreferencesProvider prefProvider;
private static Thread.UncaughtExceptionHandler defaultHandler;
private static int appTheme;
private static int popupTheme;
private static String backgroundTaskName = null;
private static Set<String> handledSilentExceptionHashes = new HashSet<>();
// don't use BuildConfig as it sometimes doesn't set DEBUG to true
private static final boolean EVENTBUS_SUBSCRIBER_CAN_THROW = true;
@Override
public void onCreate() {
super.onCreate();
application = this;
// Logging to file is dependent on preferences but this will skip logging of initialization
initPreferencesProvider();
initLogger();
initACRA();
// Exception handling must be initialized after ACRA to obtain crash details
initUnhandledExceptionHandler();
initEventBus();
initTheme();
initAnalytics();
}
static {
// Enable VectorDrawable support for API < 21
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
private void initUnhandledExceptionHandler() {
defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(@NotNull Thread thread, @NotNull Throwable ex) {
Timber.e(ex, "CRASHED");
if (ExceptionUtils.getRootCause(ex) instanceof SQLiteDatabaseCorruptException) {
MeasurementsDatabase.deleteDatabase(getApplication());
}
// strange but it happens that app is tested on devices with lower SDK - don't send ACRA reports
// also ignore errors caused by system failures
if (isSdkVersionSupported() && !hasSystemDied(ex) && !isAndroid10TelephonyManagerLambdaBug(ex)) {
defaultHandler.uncaughtException(thread, ex);
}
}
});
}
private boolean isSdkVersionSupported() {
return Build.VERSION.SDK_INT >= BuildConfig.MIN_SDK_VERSION;
}
private boolean hasSystemDied(Throwable ex) {
return ExceptionUtils.getRootCause(ex) instanceof DeadObjectException;
}
private boolean isAndroid10TelephonyManagerLambdaBug(Throwable ex) {
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.Q)
return false;
String stackTrace = ex.toString();
return (ex instanceof NullPointerException || stackTrace.contains("java.lang.NullPointerException"))
&& stackTrace.contains("ParcelableException.getCause()")
&& stackTrace.contains("TelephonyManager")
&& stackTrace.contains("lambda$onError");
}
public void initLogger() {
// Default configuration
int consoleLogLevel = BuildConfig.DEBUG ? Log.VERBOSE : Log.INFO;
// File logging based on preferences
String fileLoggingLevelString = getPreferencesProvider().getFileLoggingLevel();
if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_disabled))) {
if (Timber.forest().contains(FileLoggingTree.INSTANCE)) {
Timber.uproot(FileLoggingTree.INSTANCE);
}
} else {
if (PermissionUtils.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)) {
int fileLogLevel = Log.ERROR;
if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_debug))) {
fileLogLevel = Log.DEBUG;
} else if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_info))) {
fileLogLevel = Log.INFO;
} else if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_warning))) {
fileLogLevel = Log.WARN;
} else if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_error))) {
fileLogLevel = Log.ERROR;
}
consoleLogLevel = Math.min(consoleLogLevel, fileLogLevel);
if (Timber.forest().contains(FileLoggingTree.INSTANCE)) {
Timber.uproot(FileLoggingTree.INSTANCE);
}
Timber.plant(FileLoggingTree.INSTANCE.setPriority(fileLogLevel));
} else {
Toast.makeText(this, R.string.permission_logging_denied_temporarily_message, Toast.LENGTH_LONG).show();
}
}
Timber.plant(ConsoleLoggingTree.INSTANCE.setPriority(consoleLogLevel));
}
private void initEventBus() {
Timber.d("initEventBus(): Initializing EventBus");
EventBus.builder()
.throwSubscriberException(EVENTBUS_SUBSCRIBER_CAN_THROW)
.installDefaultEventBus();
}
private void initPreferencesProvider() {
Timber.d("initProviders(): Initializing preferences");
prefProvider = new PreferencesProvider(this);
}
public void initTheme() {
Timber.d("initTheme(): Initializing theme");
String appThemeName = getPreferencesProvider().getAppTheme();
AppThemeProvider themeProvider = new AppThemeProvider(this);
appTheme = themeProvider.getAppTheme(appThemeName);
popupTheme = themeProvider.getPopupTheme(appThemeName);
}
private void initAnalytics() {
Timber.d("initAnalytics(): Initializing analytics");
analyticsService = new AnalyticsServiceFactory().createInstance();
}
private void initACRA() {
Timber.d("initACRA(): Initializing ACRA");
CoreConfigurationBuilder configBuilder = new CoreConfigurationBuilder(this);
// Configure connection
configBuilder.setBuildConfigClass(BuildConfig.class);
configBuilder.setEnabled(BuildConfig.ACRA_SEND_REPORTS_IN_DEV_MODE);
configBuilder.setSendReportsInDevMode(BuildConfig.ACRA_SEND_REPORTS_IN_DEV_MODE);
configBuilder.setReportFormat(StringFormat.valueOf(BuildConfig.ACRA_REPORT_TYPE));
configBuilder.setExcludeMatchingSharedPreferencesKeys(getString(R.string.preferences_api_key_key));
configBuilder.setReportContent(getCustomAcraReportFields());
// Configure reported content
HttpSenderConfigurationBuilder httpPluginConfigBuilder = configBuilder.getPluginConfigurationBuilder(HttpSenderConfigurationBuilder.class);
httpPluginConfigBuilder.setUri(BuildConfig.ACRA_FORM_URI);
httpPluginConfigBuilder.setBasicAuthLogin(BuildConfig.ACRA_FORM_URI_BASIC_AUTH_LOGIN);
httpPluginConfigBuilder.setBasicAuthPassword(BuildConfig.ACRA_FORM_URI_BASIC_AUTH_PASSWORD);
httpPluginConfigBuilder.setHttpMethod(HttpSender.Method.valueOf(BuildConfig.ACRA_HTTP_METHOD));
httpPluginConfigBuilder.setEnabled(true);
// Configure interaction method
NotificationConfigurationBuilder notificationConfigBuilder = configBuilder.getPluginConfigurationBuilder(NotificationConfigurationBuilder.class);
notificationConfigBuilder.setResChannelName(R.string.error_reporting_notification_channel_name);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
notificationConfigBuilder.setResChannelImportance(NotificationManager.IMPORTANCE_DEFAULT);
}
notificationConfigBuilder.setResIcon(R.drawable.ic_notification);
notificationConfigBuilder.setResTitle(R.string.error_reporting_notification_title);
notificationConfigBuilder.setResText(R.string.error_reporting_notification_text);
notificationConfigBuilder.setResTickerText(R.string.error_reporting_notification_title);
notificationConfigBuilder.setResSendButtonText(R.string.dialog_send);
notificationConfigBuilder.setResDiscardButtonText(R.string.dialog_cancel);
notificationConfigBuilder.setSendOnClick(true);
notificationConfigBuilder.setResSendWithCommentButtonText(R.string.dialog_send_comment);
notificationConfigBuilder.setResCommentPrompt(R.string.error_reporting_notification_comment_prompt);
notificationConfigBuilder.setEnabled(!getPreferencesProvider().getReportErrorsSilently());
ACRA.init(this, configBuilder);
ACRA.getErrorReporter().putCustomData("APP_MARKET_NAME", BuildConfig.MARKET_NAME);
}
private ReportField[] getCustomAcraReportFields() {
List<ReportField> customizedFields = new ArrayList<ReportField>(Arrays.asList(ACRAConstants.DEFAULT_REPORT_FIELDS));
// remove Device ID to make sure it will not be included in report
customizedFields.remove(ReportField.DEVICE_ID);
// remove BuildConfig to avoid leakage of configuration data in report
customizedFields.remove(ReportField.BUILD_CONFIG);
return customizedFields.toArray(new ReportField[0]);
}
public static IAnalyticsReportingService getAnalytics() {
return analyticsService;
}
public static MyApplication getApplication() {
return application;
}
public static int getCurrentAppTheme() {
return appTheme;
}
public static int getCurrentPopupTheme() {
return popupTheme;
}
public static PreferencesProvider getPreferencesProvider() {
return prefProvider;
}
public synchronized static void startBackgroundTask(Object task) {
backgroundTaskName = task.getClass().getName();
}
public synchronized static void stopBackgroundTask() {
backgroundTaskName = null;
}
public synchronized static String getBackgroundTaskName() {
return backgroundTaskName;
}
public synchronized static boolean isBackgroundTaskRunning(Class clazz) {
return (backgroundTaskName != null && backgroundTaskName.equals(clazz.getName()));
}
public synchronized static void handleSilentException(Throwable throwable) {
String throwableHash = HashUtils.toSha1(throwable.toString());
if (!handledSilentExceptionHashes.contains(throwableHash)) {
handledSilentExceptionHashes.add(throwableHash);
ACRA.getErrorReporter().handleSilentException(throwable);
}
}
}
|
package me.ryanpetschek.gatekeeper;
import android.content.Intent;
import android.location.Location;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class Nearby extends FragmentActivity implements OnMapReadyCallback,
nearbyFragment.OnFragmentInteractionListener {
private final int REQUEST_CODE_ASK_PERMISSIONS = 1;
private LocationManager mLocMan;
private Location mLoc;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Nearby Buildings");
mLocMan = (LocationManager) getSystemService(LOCATION_SERVICE);
setContentView(R.layout.activity_nearby);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
getLocationPermission();
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_ASK_PERMISSIONS);
mMap = googleMap;
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter(){
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
View view = getLayoutInflater().inflate(R.layout.marker_window, null);
Building currBuilding = Building.buildings.get(Integer.parseInt(marker.getTitle()));
ImageView img = (ImageView) view.findViewById(R.id.marker_imageView);
TextView name = (TextView) view.findViewById(R.id.marker_Name);
TextView add = (TextView) view.findViewById(R.id.marker_Address);
img.setImageBitmap(currBuilding.getImage());
name.setText(currBuilding.getName());
add.setText(currBuilding.getAddress());
return view;
}
});
for (int i = 0; i < Building.buildings.size(); i++) {
Building b = Building.buildings.get(i);
LatLng loc = new LatLng(Double.parseDouble(b.getLatitude()), Double.parseDouble(b.getLongitude()));
mMap.addMarker(new MarkerOptions().position(loc).title(i + ""));
}
LatLngBounds bounds = new LatLngBounds(new LatLng(33.75, -84.44), new LatLng(33.8, -84.34));
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
int building = Integer.parseInt(marker.getTitle());
Building passed = Building.buildings.get(building);
Intent intent = new Intent(Nearby.this, BusinessActivity.class);
startActivity(intent);
}
});
// mLoc = mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// mMap.setMyLocationEnabled(true);
// LatLng me = new LatLng(mLoc.getLatitude(), mLoc.getLongitude());
// mMap.addMarker(new MarkerOptions().position(me).title("Me"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(me));
}
public void getLocationPermission() {
if (Build.VERSION.SDK_INT >= 23) {
int hasLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
if (hasLocationPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_ASK_PERMISSIONS);
}
return;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// locations-related task you need to do.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat
// int[] grantResults)
// for ActivityCompat
Log.d("LAT", String.valueOf(mLoc.getLatitude()));
Log.d("LONG", String.valueOf(mLoc.getLongitude()));
return;
} else {
}
mMap.setMyLocationEnabled(true);
return;
}
// other 'case' lines to check for other
}
}}
@Override
public void onFragmentInteraction(Uri uri) {
//empty b/c not implemented
}
}
|
package info.zamojski.soft.towercollector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.acra.ACRA;
import org.acra.ACRAConstants;
import org.acra.ReportField;
import org.acra.config.CoreConfigurationBuilder;
import org.acra.config.HttpSenderConfigurationBuilder;
import org.acra.config.NotificationConfigurationBuilder;
import org.acra.data.StringFormat;
import org.acra.sender.HttpSender;
import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import info.zamojski.soft.towercollector.analytics.AnalyticsServiceFactory;
import info.zamojski.soft.towercollector.analytics.IAnalyticsReportingService;
import info.zamojski.soft.towercollector.dao.MeasurementsDatabase;
import info.zamojski.soft.towercollector.logging.ConsoleLoggingTree;
import info.zamojski.soft.towercollector.logging.FileLoggingTree;
import info.zamojski.soft.towercollector.providers.AppThemeProvider;
import info.zamojski.soft.towercollector.providers.preferences.PreferencesProvider;
import info.zamojski.soft.towercollector.utils.ExceptionUtils;
import info.zamojski.soft.towercollector.utils.HashUtils;
import info.zamojski.soft.towercollector.utils.PermissionUtils;
import android.Manifest;
import android.app.Application;
import android.app.NotificationManager;
import android.database.sqlite.SQLiteDatabaseCorruptException;
import android.os.Build;
import androidx.appcompat.app.AppCompatDelegate;
import android.os.DeadObjectException;
import android.util.Log;
import android.widget.Toast;
import timber.log.Timber;
public class MyApplication extends Application {
private static IAnalyticsReportingService analyticsService;
private static MyApplication application;
private static PreferencesProvider prefProvider;
private static Thread.UncaughtExceptionHandler defaultHandler;
private static int appTheme;
private static int popupTheme;
private static String backgroundTaskName = null;
private static Set<String> handledSilentExceptionHashes = new HashSet<>();
// don't use BuildConfig as it sometimes doesn't set DEBUG to true
private static final boolean EVENTBUS_SUBSCRIBER_CAN_THROW = true;
@Override
public void onCreate() {
super.onCreate();
application = this;
// Logging to file is dependent on preferences but this will skip logging of initialization
initPreferencesProvider();
initLogger();
initACRA();
// Exception handling must be initialized after ACRA to obtain crash details
initUnhandledExceptionHandler();
initEventBus();
initTheme();
initAnalytics();
}
static {
// Enable VectorDrawable support for API < 21
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
private void initUnhandledExceptionHandler() {
defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(@NotNull Thread thread, @NotNull Throwable ex) {
Timber.e(ex, "CRASHED");
if (ExceptionUtils.getRootCause(ex) instanceof SQLiteDatabaseCorruptException) {
MeasurementsDatabase.deleteDatabase(getApplication());
}
// strange but it happens that app is tested on devices with lower SDK - don't send ACRA reports
// also ignore errors caused by system failures
if (isSdkVersionSupported() && !hasSystemDied(ex) && !isAndroid10TelephonyManagerLambdaBug(ex)) {
defaultHandler.uncaughtException(thread, ex);
}
}
});
}
private boolean isSdkVersionSupported() {
return Build.VERSION.SDK_INT >= BuildConfig.MIN_SDK_VERSION;
}
private boolean hasSystemDied(Throwable ex) {
return ExceptionUtils.getRootCause(ex) instanceof DeadObjectException;
}
private boolean isAndroid10TelephonyManagerLambdaBug(Throwable ex) {
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.Q)
return false;
String stackTrace = ex.toString();
return ex instanceof NullPointerException
&& stackTrace.contains("ParcelableException.getCause()")
&& stackTrace.contains("TelephonyManager")
&& stackTrace.contains("lambda$onError");
}
public void initLogger() {
// Default configuration
int consoleLogLevel = BuildConfig.DEBUG ? Log.VERBOSE : Log.INFO;
// File logging based on preferences
String fileLoggingLevelString = getPreferencesProvider().getFileLoggingLevel();
if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_disabled))) {
if (Timber.forest().contains(FileLoggingTree.INSTANCE)) {
Timber.uproot(FileLoggingTree.INSTANCE);
}
} else {
if (PermissionUtils.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)) {
int fileLogLevel = Log.ERROR;
if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_debug))) {
fileLogLevel = Log.DEBUG;
} else if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_info))) {
fileLogLevel = Log.INFO;
} else if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_warning))) {
fileLogLevel = Log.WARN;
} else if (fileLoggingLevelString.equals(getString(R.string.preferences_file_logging_level_entries_value_error))) {
fileLogLevel = Log.ERROR;
}
consoleLogLevel = Math.min(consoleLogLevel, fileLogLevel);
if (Timber.forest().contains(FileLoggingTree.INSTANCE)) {
Timber.uproot(FileLoggingTree.INSTANCE);
}
Timber.plant(FileLoggingTree.INSTANCE.setPriority(fileLogLevel));
} else {
Toast.makeText(this, R.string.permission_logging_denied_temporarily_message, Toast.LENGTH_LONG).show();
}
}
Timber.plant(ConsoleLoggingTree.INSTANCE.setPriority(consoleLogLevel));
}
private void initEventBus() {
Timber.d("initEventBus(): Initializing EventBus");
EventBus.builder()
.throwSubscriberException(EVENTBUS_SUBSCRIBER_CAN_THROW)
.installDefaultEventBus();
}
private void initPreferencesProvider() {
Timber.d("initProviders(): Initializing preferences");
prefProvider = new PreferencesProvider(this);
}
public void initTheme() {
Timber.d("initTheme(): Initializing theme");
String appThemeName = getPreferencesProvider().getAppTheme();
AppThemeProvider themeProvider = new AppThemeProvider(this);
appTheme = themeProvider.getAppTheme(appThemeName);
popupTheme = themeProvider.getPopupTheme(appThemeName);
}
private void initAnalytics() {
Timber.d("initAnalytics(): Initializing analytics");
analyticsService = new AnalyticsServiceFactory().createInstance();
}
private void initACRA() {
Timber.d("initACRA(): Initializing ACRA");
CoreConfigurationBuilder configBuilder = new CoreConfigurationBuilder(this);
// Configure connection
configBuilder.setBuildConfigClass(BuildConfig.class);
configBuilder.setSendReportsInDevMode(BuildConfig.ACRA_SEND_REPORTS_IN_DEV_MODE);
configBuilder.setReportFormat(StringFormat.valueOf(BuildConfig.ACRA_REPORT_TYPE));
configBuilder.setExcludeMatchingSharedPreferencesKeys(getString(R.string.preferences_api_key_key));
configBuilder.setReportContent(getCustomAcraReportFields());
// Configure reported content
HttpSenderConfigurationBuilder httpPluginConfigBuilder = configBuilder.getPluginConfigurationBuilder(HttpSenderConfigurationBuilder.class);
httpPluginConfigBuilder.setUri(BuildConfig.ACRA_FORM_URI);
httpPluginConfigBuilder.setBasicAuthLogin(BuildConfig.ACRA_FORM_URI_BASIC_AUTH_LOGIN);
httpPluginConfigBuilder.setBasicAuthPassword(BuildConfig.ACRA_FORM_URI_BASIC_AUTH_PASSWORD);
httpPluginConfigBuilder.setHttpMethod(HttpSender.Method.valueOf(BuildConfig.ACRA_HTTP_METHOD));
httpPluginConfigBuilder.setEnabled(true);
// Configure interaction method
NotificationConfigurationBuilder notificationConfigBuilder = configBuilder.getPluginConfigurationBuilder(NotificationConfigurationBuilder.class);
notificationConfigBuilder.setResChannelName(R.string.error_reporting_notification_channel_name);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
notificationConfigBuilder.setResChannelImportance(NotificationManager.IMPORTANCE_DEFAULT);
}
notificationConfigBuilder.setResIcon(R.drawable.ic_notification);
notificationConfigBuilder.setResTitle(R.string.error_reporting_notification_title);
notificationConfigBuilder.setResText(R.string.error_reporting_notification_text);
notificationConfigBuilder.setResTickerText(R.string.error_reporting_notification_title);
notificationConfigBuilder.setResSendButtonText(R.string.dialog_send);
notificationConfigBuilder.setResDiscardButtonText(R.string.dialog_cancel);
notificationConfigBuilder.setSendOnClick(true);
notificationConfigBuilder.setResSendWithCommentButtonText(R.string.dialog_send_comment);
notificationConfigBuilder.setResCommentPrompt(R.string.error_reporting_notification_comment_prompt);
notificationConfigBuilder.setEnabled(!getPreferencesProvider().getReportErrorsSilently());
ACRA.init(this, configBuilder);
ACRA.getErrorReporter().putCustomData("APP_MARKET_NAME", BuildConfig.MARKET_NAME);
}
private ReportField[] getCustomAcraReportFields() {
List<ReportField> customizedFields = new ArrayList<ReportField>(Arrays.asList(ACRAConstants.DEFAULT_REPORT_FIELDS));
// remove Device ID to make sure it will not be included in report
customizedFields.remove(ReportField.DEVICE_ID);
// remove BuildConfig to avoid leakage of configuration data in report
customizedFields.remove(ReportField.BUILD_CONFIG);
return customizedFields.toArray(new ReportField[0]);
}
public static IAnalyticsReportingService getAnalytics() {
return analyticsService;
}
public static MyApplication getApplication() {
return application;
}
public static int getCurrentAppTheme() {
return appTheme;
}
public static int getCurrentPopupTheme() {
return popupTheme;
}
public static PreferencesProvider getPreferencesProvider() {
return prefProvider;
}
public synchronized static void startBackgroundTask(Object task) {
backgroundTaskName = task.getClass().getName();
}
public synchronized static void stopBackgroundTask() {
backgroundTaskName = null;
}
public synchronized static String getBackgroundTaskName() {
return backgroundTaskName;
}
public synchronized static boolean isBackgroundTaskRunning(Class clazz) {
return (backgroundTaskName != null && backgroundTaskName.equals(clazz.getName()));
}
public synchronized static void handleSilentException(Throwable throwable) {
String throwableHash = HashUtils.toSha1(throwable.toString());
if (!handledSilentExceptionHashes.contains(throwableHash)) {
handledSilentExceptionHashes.add(throwableHash);
ACRA.getErrorReporter().handleSilentException(throwable);
}
}
}
|
package org.mozilla.focus.utils;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import org.mozilla.focus.R;
import java.lang.ref.WeakReference;
public class ViewUtils {
/**
* Flag of imeOptions: used to request that the IME does not update any personalized data such
* as typing history and personalized language model based on what the user typed on this text
* editing object.
*/
public static final int IME_FLAG_NO_PERSONALIZED_LEARNING = 0x01000000;
/**
* Runnable to show the keyboard for a specific view.
*/
private static class ShowKeyboard implements Runnable {
private static final int INTERVAL_MS = 100;
private final WeakReference<View> viewReferemce;
private final Handler handler;
private int tries;
private ShowKeyboard(View view) {
this.viewReferemce = new WeakReference<>(view);
this.handler = new Handler(Looper.getMainLooper());
this.tries = 10;
}
@Override
public void run() {
if (tries <= 0) {
return;
}
final View view = viewReferemce.get();
if (view == null) {
// The view is gone. No need to continue.
return;
}
if (!view.isFocusable() || !view.isFocusableInTouchMode()) {
// The view is not focusable - we can't show the keyboard for it.
return;
}
if (!view.requestFocus()) {
// Focus this view first.
post();
return;
}
final Activity activity = (Activity) view.getContext();
if (activity == null) {
return;
}
final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) {
return;
}
if (!imm.isActive(view)) {
// This view is not the currently active view for the input method yet.
post();
return;
}
if (!imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)) {
// Showing they keyboard failed. Try again later.
post();
}
}
private void post() {
tries
handler.postDelayed(this, INTERVAL_MS);
}
}
public static void showKeyboard(View view) {
final ShowKeyboard showKeyboard = new ShowKeyboard(view);
showKeyboard.post();
}
public static void hideKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) {
return;
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
/**
* Create a snackbar with Focus branding (See #193).
*/
public static void showBrandedSnackbar(View view, @StringRes int resId, int delayMillis) {
final Context context = view.getContext();
final Snackbar snackbar = Snackbar.make(view, resId, Snackbar.LENGTH_LONG);
final View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(ContextCompat.getColor(context, R.color.snackbarBackground));
final TextView snackbarTextView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
snackbarTextView.setTextColor(ContextCompat.getColor(context, R.color.snackbarTextColor));
snackbarTextView.setGravity(Gravity.CENTER);
snackbarTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
view.postDelayed(new Runnable() {
@Override
public void run() {
snackbar.show();
}
}, delayMillis);
}
public static boolean isRTL(View view) {
return ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_RTL;
}
}
|
package vn.mbm.phimp.me.base;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import vn.mbm.phimp.me.R;
import vn.mbm.phimp.me.accounts.AccountActivity;
import vn.mbm.phimp.me.leafpic.activities.LFMainActivity;
import vn.mbm.phimp.me.opencamera.Camera.CameraActivity;
public abstract class BaseActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
protected BottomNavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId());
navigationView = (BottomNavigationView) findViewById(R.id.bottombar);
navigationView.setOnNavigationItemSelectedListener(this);
}
@Override
protected void onStart() {
super.onStart();
updateNavigationBarState();
}
// Remove inter-activity transition to avoid screen tossing on tapping bottom navigation items
@Override
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
@Override
public boolean onNavigationItemSelected(@NonNull final MenuItem item) {
if (item.getItemId() != getNavigationMenuItemId()) {
switch (item.getItemId()) {
case R.id.navigation_camera:
startActivity(new Intent(this, CameraActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;
case R.id.navigation_home:
startActivity(new Intent(this, LFMainActivity.class));
break;
case R.id.navigation_accounts:
startActivity(new Intent(this, AccountActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;
}
}
return true;
}
private void updateNavigationBarState() {
int actionId = getNavigationMenuItemId();
selectBottomNavigationBarItem(actionId);
}
void selectBottomNavigationBarItem(int itemId) {
Menu menu = navigationView.getMenu();
for (int i = 0, size = menu.size(); i < size; i++) {
MenuItem item = menu.getItem(i);
boolean shouldBeChecked = item.getItemId() == itemId;
if (shouldBeChecked) {
item.setChecked(true);
break;
}
}
}
public abstract int getContentViewId();
public abstract int getNavigationMenuItemId();
public void setNavigationBarColor(int color) {
navigationView.setBackgroundColor(color);
}
}
|
package org.wikipedia.settings;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import org.wikipedia.BuildConfig;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.util.StringUtil;
/** UI code for app settings used by PreferenceFragment. */
public class SettingsPreferenceLoader extends BasePreferenceLoader {
private final Activity activity;
/*package*/ SettingsPreferenceLoader(@NonNull PreferenceFragment fragment) {
super(fragment);
activity = fragment.getActivity();
}
@Override
public void loadPreferences() {
loadPreferences(R.xml.preferences);
updateLanguagePrefSummary();
Preference languagePref = findPreference(R.string.preference_key_language);
Preference zeroWarnPref = findPreference(R.string.preference_key_zero_interstitial);
languagePref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
LanguagePreferenceDialog langPrefDialog = new LanguagePreferenceDialog(activity, false);
langPrefDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
String name = StringUtil.emptyIfNull(WikipediaApp.getInstance().getAppOrSystemLanguageLocalizedName());
if (!findPreference(R.string.preference_key_language).getSummary().equals(name)) {
findPreference(R.string.preference_key_language).setSummary(name);
activity.setResult(SettingsActivity.ACTIVITY_RESULT_LANGUAGE_CHANGED);
}
}
});
langPrefDialog.show();
return true;
}
});
zeroWarnPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue == Boolean.FALSE) {
WikipediaApp.getInstance().getWikipediaZeroHandler().getZeroFunnel().logExtLinkAlways();
}
return true;
}
});
if (!BuildConfig.APPLICATION_ID.equals("org.wikipedia")) {
overridePackageName();
}
}
private void overridePackageName() {
Preference aboutPref = findPreference("about");
aboutPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClass(activity, AboutActivity.class);
activity.startActivity(intent);
return true;
}
});
}
private void updateLanguagePrefSummary() {
Preference languagePref = findPreference(R.string.preference_key_language);
languagePref.setSummary(WikipediaApp.getInstance().getAppOrSystemLanguageLocalizedName());
}
private String getString(@StringRes int id) {
return activity.getString(id);
}
}
|
package gql.ratpack;
import gql.ratpack.GraphQLModuleConfig;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import ratpack.handling.Handler;
import ratpack.handling.Context;
/**
* GraphiQL endpoint. This handler will be exposing a given GraphiQL
* client.
*
* By default the handler is disable, so in order to enable it you
* should set the {@link GraphQLModuleConfig}#activateGraphiQL to
* true when enabling the module
*
* @since 0.2.0
*/
public class GraphiQLHandler implements Handler {
@Override
public void handle(Context ctx) throws Exception {
GraphQLModuleConfig config = ctx.get(GraphQLModuleConfig.class);
if (config.activateGraphiQL) {
ctx.render(getGraphiQLFile());
} else {
ctx.getResponse().status(404);
ctx.getResponse().send();
}
}
private Path getGraphiQLFile() throws URISyntaxException {
URL url = GraphiQLHandler.class.getResource("/static/index.html");
Path path = PathUtil.toPath(url);
return path;
}
}
|
package de.lmu.ios.geomelody.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.sql.DataSource;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import de.lmu.ios.geomelody.dom.Filters;
import de.lmu.ios.geomelody.dom.Location;
import de.lmu.ios.geomelody.dom.Song;
import de.lmu.ios.geomelody.mapper.SongMapper;
public class SongMappingServiceImpl implements SongMappingService {
private NamedParameterJdbcTemplate jdbcTemplate;
private static Map<String, Object> emptyMap = Collections
.unmodifiableMap(new LinkedHashMap<String, Object>());
public void setDataSource(final DataSource dataSource) {
this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
@Override
@Transactional
public void saveSong(final Song song) {
Map<String, Object> params = new HashMap<String, Object>(5);
params.put("soundcloud_song_id", song.getSoundCloudSongId());
params.put("soundcloud_user_id", song.getSoundCloudUserId());
params.put("comment", song.getComment());
params.put("longitude", song.getLocation().getLongitude());
params.put("latitude", song.getLocation().getLatitude());
jdbcTemplate
.update("INSERT INTO songs (soundcloud_song_id, soundcloud_user_id, comment, geom) "
+ "VALUES (:soundcloud_song_id, :soundcloud_user_id, :comment, "
+ "ST_SetSRID(ST_MakePoint(:longitude, :latitude), 4326))",
params);
final long songId = jdbcTemplate.queryForLong(
"SELECT CURRVAL('songs_id_seq')", emptyMap);
final List<String> tags = song.getTags();
if(tags != null) {
final Map<String, Integer> tagIdMap = jdbcTemplate.query(
"SELECT id, name FROM tags", emptyMap,
new ResultSetExtractor<Map<String, Integer>>() {
public Map<String, Integer> extractData(ResultSet rs)
throws SQLException {
Map<String, Integer> map = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
while (rs.next()) {
int col1 = rs.getInt("id");
String col2 = rs.getString("name");
map.put(col2, col1);
}
return map;
};
});
for(String tag : tags) {
Integer tagId;
if((tagId = tagIdMap.get(tag)) != null) {
Map<String, Object> insertMap = new HashMap<String, Object>(2);
insertMap.put("song_id", songId);
insertMap.put("tag_id", tagId);
jdbcTemplate.update(
"INSERT INTO songs_tags (song_id, tag_id) VALUES (:song_id, :tag_id)", insertMap);
}
}
}
}
@Override
public List<Song> getkNearestSongs(final Location location, final Filters filters, final int k) {
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("longitude", location.getLongitude());
params.addValue("latitude", location.getLatitude());
params.addValue("k", k);
StringBuilder sb = new StringBuilder()
.append("SELECT s.id, s.soundcloud_song_id, s.soundcloud_user_id, s.comment, ")
.append(" array_to_string(ARRAY(SELECT t.name ")
.append(" FROM tags AS T ")
.append(" INNER JOIN songs_tags AS st ON t.id = st.tag_id ")
.append(" WHERE ")
.append(" st.song_id = s.id), ',') as tags, ")
.append(" ST_X(geom) as longitude, ")
.append(" ST_Y(geom) as latitude ")
.append(" FROM songs AS s ")
.append(" INNER JOIN songs_tags AS st ON s.id = st.song_id ")
.append(" INNER JOIN tags AS t ON t.id = st.tag_id ");
if(filters != null && filters.getFilters() != null && filters.getFilters().size() > 0) {
params.addValue("filters", filters.getFilters());
sb.append(" WHERE ")
.append(" t.name IN (:filters) ");
}
sb.append(" GROUP BY ")
.append(" s.id ")
.append(" ORDER BY ")
.append(" s.geom <-> ST_SetSRID(ST_MakePoint(:longitude, :latitude), 4326) ")
.append(" LIMIT :k");
String query = sb.toString();
return jdbcTemplate
.query(query, params, new SongMapper());
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:20-02-14");
this.setApiVersion("15.17.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-10-30");
this.setApiVersion("17.12.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package com.smartdevicelink.protocol;
import android.support.annotation.NonNull;
import android.util.Log;
import com.smartdevicelink.exception.SdlException;
import com.smartdevicelink.exception.SdlExceptionCause;
import com.smartdevicelink.protocol.enums.ControlFrameTags;
import com.smartdevicelink.protocol.enums.FrameDataControlFrameType;
import com.smartdevicelink.protocol.enums.FrameType;
import com.smartdevicelink.protocol.enums.MessageType;
import com.smartdevicelink.protocol.enums.SessionType;
import com.smartdevicelink.proxy.rpc.ImageResolution;
import com.smartdevicelink.proxy.rpc.VideoStreamingFormat;
import com.smartdevicelink.proxy.rpc.enums.VideoStreamingCodec;
import com.smartdevicelink.proxy.rpc.enums.VideoStreamingProtocol;
import com.smartdevicelink.security.SdlSecurityBase;
import com.smartdevicelink.streaming.video.VideoStreamingParameters;
import com.smartdevicelink.transport.BaseTransportConfig;
import com.smartdevicelink.transport.TransportConstants;
import com.smartdevicelink.transport.TransportManagerBase;
import com.smartdevicelink.transport.enums.TransportType;
import com.smartdevicelink.transport.utl.TransportRecord;
import com.smartdevicelink.util.BitConverter;
import com.smartdevicelink.util.DebugTool;
import com.smartdevicelink.util.Version;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
public class SdlProtocolBase {
private static final String TAG ="SdlProtocol";
private final static String FailurePropagating_Msg = "Failure propagating ";
private static final int TLS_MAX_RECORD_SIZE = 16384;
private static final int PRIMARY_TRANSPORT_ID = 1;
private static final int SECONDARY_TRANSPORT_ID = 2;
/**
* Original header size based on version 1.0.0 only
*/
public static final int V1_HEADER_SIZE = 8;
/**
* Larger header size that is used by versions 2.0.0 and up
*/
public static final int V2_HEADER_SIZE = 12;
//If increasing MAX PROTOCOL VERSION major version, make sure to alter it in SdlPsm
private static final Version MAX_PROTOCOL_VERSION = new Version(5, 2, 0);
public static final int V1_V2_MTU_SIZE = 1500;
public static final int V3_V4_MTU_SIZE = 131072;
private static final List<SessionType> HIGH_BANDWIDTH_SERVICES
= Arrays.asList(SessionType.NAV, SessionType.PCM);
// Lock to ensure all frames are sent uninterrupted
private final Object FRAME_LOCK = new Object();
private final ISdlProtocol iSdlProtocol;
private final Hashtable<Integer, SdlProtocol.MessageFrameAssembler> _assemblerForMessageID = new Hashtable<>();
private final Hashtable<Byte, Object> _messageLocks = new Hashtable<>();
private final HashMap<SessionType, Long> mtus = new HashMap<>();
private final HashMap<SessionType, TransportRecord> activeTransports = new HashMap<>();
private final Map<TransportType, List<ISecondaryTransportListener>> secondaryTransportListeners = new HashMap<>();
private Version protocolVersion = new Version("1.0.0");
private int hashID = 0;
private int messageID = 0;
private int headerSize = V1_HEADER_SIZE;
/**
* Transport config that this protocol instance should use along with the supplied transport manager
*/
final BaseTransportConfig transportConfig;
/**
* The transport manager used for this protocol instance.
*/
TransportManagerBase transportManager;
/**
* Requested transports for primary and secondary
*/
List<TransportType> requestedPrimaryTransports, requestedSecondaryTransports;
/**
* List of secondary transports supported by the module
*/
List<TransportType> supportedSecondaryTransports;
/**
* Holds the priority of transports for a specific service when that service can be started
* on a primary or secondary transport.
*/
Map<SessionType, List<Integer>> transportPriorityForServiceMap;
boolean requiresHighBandwidth;
Map<TransportType, TransportRecord> secondaryTransportParams;
TransportRecord connectedPrimaryTransport;
public SdlProtocolBase(@NonNull ISdlProtocol iSdlProtocol, @NonNull BaseTransportConfig config) {
if (iSdlProtocol == null ) {
throw new IllegalArgumentException("Provided protocol listener interface reference is null");
} // end-if
this.iSdlProtocol = iSdlProtocol;
this.transportConfig = config;
if(!config.getTransportType().equals(TransportType.MULTIPLEX)) {
this.requestedPrimaryTransports = Collections.singletonList(transportConfig.getTransportType());
this.requestedSecondaryTransports = Collections.emptyList();
this.requiresHighBandwidth = false;
}
mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize));
} // end-ctor
void setTransportManager(TransportManagerBase transportManager){
this.transportManager = transportManager;
}
public void start(){
if(transportManager == null){
throw new IllegalStateException("Attempting to start without setting a transport manager.");
}
transportManager.start();
}
/**
* Retrieves the max payload size for a packet to be sent to the module
* @return the max transfer unit
*/
public int getMtu(){
return mtus.get(SessionType.RPC).intValue();
}
public long getMtu(SessionType type){
Long mtu = mtus.get(type);
if(mtu == null){
mtu = mtus.get(SessionType.RPC);
}
return mtu;
}
public void resetSession (){
if(transportManager == null){
throw new IllegalStateException("Attempting to reset session without setting a transport manager.");
}
transportManager.resetSession();
}
public boolean isConnected(){
return transportManager != null && transportManager.isConnected(null,null);
}
/**
* Resets the protocol to init status
*/
protected void reset(){
protocolVersion = new Version("1.0.0");
hashID = 0;
messageID = 0;
headerSize = V1_HEADER_SIZE;
this.activeTransports.clear();
this.mtus.clear();
mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize));
this.secondaryTransportParams = null;
this._assemblerForMessageID.clear();
this._messageLocks.clear();
}
/**
* For logging purposes, prints active services on each connected transport
*/
protected void printActiveTransports(){
StringBuilder activeTransportString = new StringBuilder();
activeTransportString.append("Active transports
for(Map.Entry entry : activeTransports.entrySet()){
String sessionString = null;
if(entry.getKey().equals(SessionType.NAV)) {
sessionString = "NAV";
}else if(entry.getKey().equals(SessionType.PCM)) {
sessionString = "PCM";
}else if(entry.getKey().equals(SessionType.RPC)) {
sessionString = "RPC";
}
if(sessionString != null){
activeTransportString.append("Session: ");
activeTransportString.append(sessionString);
activeTransportString.append(" Transport: ");
activeTransportString.append(entry.getValue().toString());
activeTransportString.append("\n");
}
}
Log.d(TAG, activeTransportString.toString());
}
protected void printSecondaryTransportDetails(List<String> secondary, List<Integer> audio, List<Integer> video){
StringBuilder secondaryDetailsBldr = new StringBuilder();
secondaryDetailsBldr.append("Checking secondary transport details \n");
if(secondary != null){
secondaryDetailsBldr.append("Supported secondary transports: ");
for(String s : secondary){
secondaryDetailsBldr.append(" ").append(s);
}
secondaryDetailsBldr.append("\n");
}else{
Log.d(TAG, "Supported secondary transports list is empty!");
}
if(audio != null){
secondaryDetailsBldr.append("Supported audio transports: ");
for(int a : audio){
secondaryDetailsBldr.append(" ").append(a);
}
secondaryDetailsBldr.append("\n");
}
if(video != null){
secondaryDetailsBldr.append("Supported video transports: ");
for(int v : video){
secondaryDetailsBldr.append(" ").append(v);
}
secondaryDetailsBldr.append("\n");
}
Log.d(TAG, secondaryDetailsBldr.toString());
}
private TransportRecord getTransportForSession(SessionType type){
return activeTransports.get(type);
}
private void setTransportPriorityForService(SessionType serviceType, List<Integer> order){
if(transportPriorityForServiceMap == null){
transportPriorityForServiceMap = new HashMap<>();
}
this.transportPriorityForServiceMap.put(serviceType, order);
for(SessionType service : HIGH_BANDWIDTH_SERVICES){
if (transportPriorityForServiceMap.get(service) != null
&& transportPriorityForServiceMap.get(service).contains(PRIMARY_TRANSPORT_ID)) {
if(connectedPrimaryTransport != null) {
activeTransports.put(service, connectedPrimaryTransport);
}
}
}
}
/**
* Handles when a secondary transport can be used to start services on or when the request as failed.
* @param transportRecord the transport type that the event has taken place on
* @param registered if the transport was successfully registered on
*/
private void handleSecondaryTransportRegistration(TransportRecord transportRecord, boolean registered){
if(registered) {
//Session has been registered on secondary transport
Log.d(TAG, transportRecord.getType().toString() + " transport was registered!");
if (supportedSecondaryTransports.contains(transportRecord.getType())) {
// If the transport type that is now available to be used it should be checked
// against the list of services that might be able to be started on it
for(SessionType secondaryService : HIGH_BANDWIDTH_SERVICES){
if (transportPriorityForServiceMap.containsKey(secondaryService)) {
// If this service type has extra information from the RPC StartServiceACK
// parse through it to find which transport should be used to start this
// specific service type
for(int transportNum : transportPriorityForServiceMap.get(secondaryService)){
if(transportNum == PRIMARY_TRANSPORT_ID){
break; // Primary is favored for this service type, break out...
}else if(transportNum == SECONDARY_TRANSPORT_ID){
// The secondary transport can be used to start this service
activeTransports.put(secondaryService, transportRecord);
break;
}
}
}
}
}
}else{
Log.d(TAG, transportRecord.toString() + " transport was NOT registered!");
}
//Notify any listeners for this secondary transport
List<ISecondaryTransportListener> listenerList = secondaryTransportListeners.remove(transportRecord.getType());
if(listenerList != null){
for(ISecondaryTransportListener listener : listenerList){
if(registered) {
listener.onConnectionSuccess(transportRecord);
}else{
listener.onConnectionFailure();
}
}
}
if(DebugTool.isDebugEnabled()){
printActiveTransports();
}
}
private void onTransportsConnectedUpdate(List<TransportRecord> transports){
//Log.d(TAG, "Connected transport update");
//Temporary: this logic should all be changed to handle multiple transports of the same type
ArrayList<TransportType> connectedTransports = new ArrayList<>();
if(transports != null) {
for (TransportRecord record : transports) {
connectedTransports.add(record.getType());
}
}
if(connectedPrimaryTransport != null && !connectedTransports.contains(connectedPrimaryTransport.getType())){
//The primary transport being used is no longer part of the connected transports
//The transport manager callbacks should handle the disconnect code
connectedPrimaryTransport = null;
notifyDevTransportListener();
return;
}
if(activeTransports.get(SessionType.RPC) == null){
//There is no currently active transport for the RPC service meaning no primary transport
TransportRecord preferredPrimaryTransport = getPreferredTransport(requestedPrimaryTransports,transports);
if(preferredPrimaryTransport != null) {
connectedPrimaryTransport = preferredPrimaryTransport;
startService(SessionType.RPC, (byte) 0x00, false);
}else{
onTransportNotAccepted("No transports match requested primary transport");
}
//Return to that the developer does not receive the transport callback at this time
// as it is better to wait until the RPC service is registered and secondary transport
//information is available
return;
}else if(secondaryTransportListeners != null
&& transports != null
&& iSdlProtocol!= null){
// Check to see if there is a listener for a given transport.
// If a listener exists, it can be assumed that the transport should be registered on
for(TransportRecord record: transports){
if(secondaryTransportListeners.get(record.getType()) != null
&& !secondaryTransportListeners.get(record.getType()).isEmpty()){
registerSecondaryTransport(iSdlProtocol.getSessionId(), record);
}
}
}
//Update the developer that a new transport has become available
notifyDevTransportListener();
}
/**
* Check to see if a transport is available to start/use the supplied service.
* @param serviceType the session that should be checked for transport availability
* @return true if there is either a supported
* transport currently connected or a transport is
* available to connect with for the supplied service type.
* <br>false if there is no
* transport connected to support the service type in question and
* no possibility in the foreseeable future.
*/
public boolean isTransportForServiceAvailable(@NonNull SessionType serviceType){
if(connectedPrimaryTransport == null){
//If there is no connected primary then there is no transport available for any service
return false;
}else if(activeTransports!= null && activeTransports.containsKey(serviceType)){
//There is an active transport that this service can be used on
//This should catch RPC, Bulk, and Control service types
return true;
}
if(transportPriorityForServiceMap != null) {
List<Integer> transportPriority = transportPriorityForServiceMap.get(serviceType);
if (transportPriority != null && !transportPriority.isEmpty()) {
if (transportPriority.contains(PRIMARY_TRANSPORT_ID)) {
//If the transport priority for this service type contains primary then
// the service can be used/started
return true;
} else if (transportPriority.contains(SECONDARY_TRANSPORT_ID)) {
//This would mean only secondary transport is supported for this service
return isSecondaryTransportAvailable(false);
}
}
}
//No transport priority for this service type
if(connectedPrimaryTransport.getType() == TransportType.USB || connectedPrimaryTransport.getType() == TransportType.TCP){
//Since the only service type that should reach this point are ones that require a high
//bandwidth, true can be returned if the primary transport is a high bandwidth transport
return true;
}else{
//Since the only service type that should reach this point are ones that require a high
//bandwidth, true can be returned if a secondary transport is a high bandwidth transport
return isSecondaryTransportAvailable(true);
}
}
/**
* Checks to see if a secondary transport is available for this session
* @param onlyHighBandwidth if only high bandwidth transports should be included in this check
* @return true if any connected or potential transport meets the criteria to be a secondary
* transport
*/
private boolean isSecondaryTransportAvailable(boolean onlyHighBandwidth){
if (supportedSecondaryTransports != null) {
for (TransportType supportedSecondary : supportedSecondaryTransports) {
if(!onlyHighBandwidth || supportedSecondary == TransportType.USB || supportedSecondary == TransportType.TCP) {
if (transportManager != null && transportManager.isConnected(supportedSecondary, null)) {
//A supported secondary transport is already connected
return true;
} else if (secondaryTransportParams != null && secondaryTransportParams.containsKey(supportedSecondary)) {
//A secondary transport is available to connect to
return true;
}
}
}
}
// No supported secondary transports
return false;
}
/**
* If the library allows for multiple transports per session this should be handled
*/
void notifyDevTransportListener (){
//Does nothing in base class
}
/**
* Retrieves the preferred transport for the given connected transport
* @param preferredList the list of preferred transports (primary or secondary)
* @param connectedTransports the current list of connected transports
* @return the preferred connected transport
*/
private TransportRecord getPreferredTransport(List<TransportType> preferredList, List<TransportRecord> connectedTransports) {
for (TransportType transportType : preferredList) {
for(TransportRecord record: connectedTransports) {
if (record.getType().equals(transportType)) {
return record;
}
}
}
return null;
}
private void onTransportNotAccepted(String info){
if(iSdlProtocol != null) {
iSdlProtocol.shutdown(info);
}
}
public Version getProtocolVersion(){
return this.protocolVersion;
}
/**
* This method will set the major protocol version that we should use. It will also set the default MTU based on version.
* @param version major version to use
*/
protected void setVersion(byte version) {
if (version > 5) {
this.protocolVersion = new Version("5.0.0"); //protect for future, proxy only supports v5 or lower
headerSize = V2_HEADER_SIZE;
mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE);
} else if (version == 5) {
this.protocolVersion = new Version("5.0.0");
headerSize = V2_HEADER_SIZE;
mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE);
}else if (version == 4) {
this.protocolVersion = new Version("4.0.0");
headerSize = V2_HEADER_SIZE;
mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); //versions 4 supports 128k MTU
} else if (version == 3) {
this.protocolVersion = new Version("3.0.0");
headerSize = V2_HEADER_SIZE;
mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); //versions 3 supports 128k MTU
} else if (version == 2) {
this.protocolVersion = new Version("2.0.0");
headerSize = V2_HEADER_SIZE;
mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize));
} else if (version == 1){
this.protocolVersion = new Version("1.0.0");
headerSize = V1_HEADER_SIZE;
mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize));
}
}
public void endSession(byte sessionID, int hashId) {
SdlPacket header = SdlPacketFactory.createEndSession(SessionType.RPC, sessionID, hashId, (byte)protocolVersion.getMajor(), hashId);
handlePacketToSend(header);
} // end-method
public void sendPacket(SdlPacket packet){
if(transportManager != null){
transportManager.sendPacket(packet);
}
}
public void sendMessage(ProtocolMessage protocolMsg) {
SessionType sessionType = protocolMsg.getSessionType();
byte sessionID = protocolMsg.getSessionID();
byte[] data;
if (protocolVersion.getMajor() > 1 && sessionType != SessionType.NAV && sessionType != SessionType.PCM) {
if (sessionType.eq(SessionType.CONTROL)) {
final byte[] secureData = protocolMsg.getData().clone();
data = new byte[headerSize + secureData.length];
final BinaryFrameHeader binFrameHeader =
SdlPacketFactory.createBinaryFrameHeader(protocolMsg.getRPCType(),protocolMsg.getFunctionID(), protocolMsg.getCorrID(), 0);
System.arraycopy(binFrameHeader.assembleHeaderBytes(), 0, data, 0, headerSize);
System.arraycopy(secureData, 0, data, headerSize, secureData.length);
}
else if (protocolMsg.getBulkData() != null) {
data = new byte[12 + protocolMsg.getJsonSize() + protocolMsg.getBulkData().length];
sessionType = SessionType.BULK_DATA;
} else {
data = new byte[12 + protocolMsg.getJsonSize()];
}
if (!sessionType.eq(SessionType.CONTROL)) {
BinaryFrameHeader binFrameHeader = SdlPacketFactory.createBinaryFrameHeader(protocolMsg.getRPCType(), protocolMsg.getFunctionID(), protocolMsg.getCorrID(), protocolMsg.getJsonSize());
System.arraycopy(binFrameHeader.assembleHeaderBytes(), 0, data, 0, 12);
System.arraycopy(protocolMsg.getData(), 0, data, 12, protocolMsg.getJsonSize());
if (protocolMsg.getBulkData() != null) {
System.arraycopy(protocolMsg.getBulkData(), 0, data, 12 + protocolMsg.getJsonSize(), protocolMsg.getBulkData().length);
}
}
} else {
data = protocolMsg.getData();
}
if (iSdlProtocol != null && protocolMsg.getPayloadProtected()){
if (data != null && data.length > 0) {
byte[] dataToRead = new byte[TLS_MAX_RECORD_SIZE];
SdlSecurityBase sdlSec = iSdlProtocol.getSdlSecurity();
if (sdlSec == null)
return;
Integer iNumBytes = sdlSec.encryptData(data, dataToRead);
if ((iNumBytes == null) || (iNumBytes <= 0))
return;
byte[] encryptedData = new byte[iNumBytes];
System.arraycopy(dataToRead, 0, encryptedData, 0, iNumBytes);
data = encryptedData;
}
}
// Get the message lock for this protocol session
Object messageLock = _messageLocks.get(sessionID);
if (messageLock == null) {
handleProtocolError("Error sending protocol message to SDL.",
new SdlException("Attempt to send protocol message prior to startSession ACK.", SdlExceptionCause.SDL_UNAVAILABLE));
return;
}
synchronized(messageLock) {
if (data.length > getMtu(sessionType)) {
messageID++;
// Assemble first frame.
Long mtu = getMtu(sessionType);
int frameCount = Long.valueOf(data.length / mtu).intValue();
if (data.length % mtu > 0) {
frameCount++;
}
byte[] firstFrameData = new byte[8];
// First four bytes are data size.
System.arraycopy(BitConverter.intToByteArray(data.length), 0, firstFrameData, 0, 4);
// Second four bytes are frame count.
System.arraycopy(BitConverter.intToByteArray(frameCount), 0, firstFrameData, 4, 4);
SdlPacket firstHeader = SdlPacketFactory.createMultiSendDataFirst(sessionType, sessionID, messageID, (byte)protocolVersion.getMajor(),firstFrameData,protocolMsg.getPayloadProtected());
firstHeader.setPriorityCoefficient(1+protocolMsg.priorityCoefficient);
firstHeader.setTransportRecord(activeTransports.get(sessionType));
//Send the first frame
handlePacketToSend(firstHeader);
int currentOffset = 0;
byte frameSequenceNumber = 0;
for (int i = 0; i < frameCount; i++) {
if (i < (frameCount - 1)) {
++frameSequenceNumber;
if (frameSequenceNumber ==
SdlPacket.FRAME_INFO_FINAL_CONNESCUTIVE_FRAME) {
// we can't use 0x00 as frameSequenceNumber, because
// it's reserved for the last frame
++frameSequenceNumber;
}
} else {
frameSequenceNumber = SdlPacket.FRAME_INFO_FINAL_CONNESCUTIVE_FRAME;
} // end-if
int bytesToWrite = data.length - currentOffset;
if (bytesToWrite > mtu) {
bytesToWrite = mtu.intValue();
}
SdlPacket consecHeader = SdlPacketFactory.createMultiSendDataRest(sessionType, sessionID, bytesToWrite, frameSequenceNumber , messageID, (byte)protocolVersion.getMajor(),data, currentOffset, bytesToWrite, protocolMsg.getPayloadProtected());
consecHeader.setTransportRecord(activeTransports.get(sessionType));
consecHeader.setPriorityCoefficient(i+2+protocolMsg.priorityCoefficient);
handlePacketToSend(consecHeader);
currentOffset += bytesToWrite;
}
} else {
messageID++;
SdlPacket header = SdlPacketFactory.createSingleSendData(sessionType, sessionID, data.length, messageID, (byte)protocolVersion.getMajor(),data, protocolMsg.getPayloadProtected());
header.setPriorityCoefficient(protocolMsg.priorityCoefficient);
header.setTransportRecord(activeTransports.get(sessionType));
handlePacketToSend(header);
}
}
}
protected void handlePacketReceived(SdlPacket packet){
//Check for a version difference
if (protocolVersion == null || protocolVersion.getMajor() == 1) {
setVersion((byte)packet.version);
}
SdlProtocolBase.MessageFrameAssembler assembler = getFrameAssemblerForFrame(packet);
assembler.handleFrame(packet);
}
protected SdlProtocolBase.MessageFrameAssembler getFrameAssemblerForFrame(SdlPacket packet) {
Integer iSessionId = packet.getSessionId();
Byte bySessionId = iSessionId.byteValue();
SdlProtocolBase.MessageFrameAssembler ret = _assemblerForMessageID.get(packet.getMessageId());
if (ret == null) {
ret = new SdlProtocolBase.MessageFrameAssembler();
_assemblerForMessageID.put(packet.getMessageId(), ret);
} // end-if
return ret;
} // end-method
private void registerSecondaryTransport(byte sessionId, TransportRecord transportRecord) {
SdlPacket header = SdlPacketFactory.createRegisterSecondaryTransport(sessionId, (byte)protocolVersion.getMajor());
header.setTransportRecord(transportRecord);
handlePacketToSend(header);
}
public void startService(SessionType serviceType, byte sessionID, boolean isEncrypted) {
final SdlPacket header = SdlPacketFactory.createStartSession(serviceType, 0x00, (byte)protocolVersion.getMajor(), sessionID, isEncrypted);
if(SessionType.RPC.equals(serviceType)){
if(connectedPrimaryTransport != null) {
header.setTransportRecord(connectedPrimaryTransport);
}
//This is going to be our primary transport
header.putTag(ControlFrameTags.RPC.StartService.PROTOCOL_VERSION, MAX_PROTOCOL_VERSION.toString());
handlePacketToSend(header);
return; // We don't need to go any further
}else if(serviceType.equals(SessionType.NAV)){
if(iSdlProtocol != null){
VideoStreamingParameters videoStreamingParameters = iSdlProtocol.getDesiredVideoParams();
if(videoStreamingParameters != null) {
ImageResolution desiredResolution = videoStreamingParameters.getResolution();
VideoStreamingFormat desiredFormat = videoStreamingParameters.getFormat();
if (desiredResolution != null) {
header.putTag(ControlFrameTags.Video.StartService.WIDTH, desiredResolution.getResolutionWidth());
header.putTag(ControlFrameTags.Video.StartService.HEIGHT, desiredResolution.getResolutionHeight());
}
if (desiredFormat != null) {
header.putTag(ControlFrameTags.Video.StartService.VIDEO_CODEC, desiredFormat.getCodec().toString());
header.putTag(ControlFrameTags.Video.StartService.VIDEO_PROTOCOL, desiredFormat.getProtocol().toString());
}
}
}
}
if(transportPriorityForServiceMap == null
|| transportPriorityForServiceMap.get(serviceType) == null
|| transportPriorityForServiceMap.get(serviceType).isEmpty()){
//If there is no transport priority for this service it can be assumed it's primary
header.setTransportRecord(connectedPrimaryTransport);
handlePacketToSend(header);
return;
}
int transportPriority = transportPriorityForServiceMap.get(serviceType).get(0);
if(transportPriority == PRIMARY_TRANSPORT_ID){
// Primary is favored, and we're already connected...
header.setTransportRecord(connectedPrimaryTransport);
handlePacketToSend(header);
}else if(transportPriority == SECONDARY_TRANSPORT_ID) {
// Secondary is favored
for(TransportType secondaryTransportType : supportedSecondaryTransports) {
if(!requestedSecondaryTransports.contains(secondaryTransportType)){
// Secondary transport is not accepted by the client
continue;
}
if(activeTransports.get(serviceType) != null
&& activeTransports.get(serviceType).getType() !=null
&& activeTransports.get(serviceType).getType().equals(secondaryTransportType)){
// Transport is already active and accepted
header.setTransportRecord(activeTransports.get(serviceType));
handlePacketToSend(header);
return;
}
//If the secondary transport isn't connected yet that will have to be performed first
List<ISecondaryTransportListener> listenerList = secondaryTransportListeners.get(secondaryTransportType);
if(listenerList == null){
listenerList = new ArrayList<>();
secondaryTransportListeners.put(secondaryTransportType, listenerList);
}
//Check to see if the primary transport can also be used as a backup
final boolean primaryTransportBackup = transportPriorityForServiceMap.get(serviceType).contains(PRIMARY_TRANSPORT_ID);
ISecondaryTransportListener secondaryListener = new ISecondaryTransportListener() {
@Override
public void onConnectionSuccess(TransportRecord transportRecord) {
header.setTransportRecord(transportRecord);
handlePacketToSend(header);
}
@Override
public void onConnectionFailure() {
if(primaryTransportBackup) {
// Primary is also supported as backup
header.setTransportRecord(connectedPrimaryTransport);
handlePacketToSend(header);
}else{
Log.d(TAG, "Failed to connect secondary transport, threw away StartService");
}
}
};
if(transportManager.isConnected(secondaryTransportType,null)){
//The transport is actually connected, however no service has been registered
listenerList.add(secondaryListener);
registerSecondaryTransport(sessionID,transportManager.getTransportRecord(secondaryTransportType,null));
}else if(secondaryTransportParams != null && secondaryTransportParams.containsKey(secondaryTransportType)) {
//No acceptable secondary transport is connected, so first one must be connected
header.setTransportRecord(new TransportRecord(secondaryTransportType,""));
listenerList.add(secondaryListener);
transportManager.requestSecondaryTransportConnection(sessionID,secondaryTransportParams.get(secondaryTransportType));
}else{
Log.w(TAG, "No params to connect to secondary transport");
//Unable to register or start a secondary connection. Use the callback in case
//there is a chance to use the primary transport for this service.
secondaryListener.onConnectionFailure();
}
}
}
}
private void sendHeartBeatACK(SessionType sessionType, byte sessionID) {
final SdlPacket heartbeat = SdlPacketFactory.createHeartbeatACK(SessionType.CONTROL, sessionID, (byte)protocolVersion.getMajor());
heartbeat.setTransportRecord(activeTransports.get(sessionType));
handlePacketToSend(heartbeat);
}
public void endService(SessionType serviceType, byte sessionID) {
if(serviceType.equals(SessionType.RPC)){ //RPC session will close all other sessions so we want to make sure we use the correct EndProtocolSession method
endSession(sessionID,hashID);
}else {
SdlPacket header = SdlPacketFactory.createEndSession(serviceType, sessionID, hashID, (byte)protocolVersion.getMajor(), new byte[0]);
TransportRecord transportRecord = activeTransports.get(serviceType);
if(transportRecord != null){
header.setTransportRecord(transportRecord);
handlePacketToSend(header);
}
}
}
// This method is called whenever a protocol has an entire frame to send
/**
* SdlPacket should have included payload at this point.
* @param packet packet that will be sent to the router service
*/
protected void handlePacketToSend(SdlPacket packet) {
synchronized(FRAME_LOCK) {
if(packet!=null){
iSdlProtocol.onProtocolMessageBytesToSend(packet);
}
}
}
/** This method handles the end of a protocol session. A callback is
* sent to the protocol listener.
**/
protected void handleServiceEndedNAK(SdlPacket packet, SessionType serviceType) {
if(packet.version >= 5){
if(DebugTool.isDebugEnabled()) {
//Currently this is only during a debugging session. Might pass back in the future
String rejectedTag = null;
if (serviceType.equals(SessionType.RPC)) {
rejectedTag = ControlFrameTags.RPC.EndServiceNAK.REJECTED_PARAMS;
} else if (serviceType.equals(SessionType.PCM)) {
rejectedTag = ControlFrameTags.Audio.EndServiceNAK.REJECTED_PARAMS;
} else if (serviceType.equals(SessionType.NAV)) {
rejectedTag = ControlFrameTags.Video.EndServiceNAK.REJECTED_PARAMS;
}
List<String> rejectedParams = (List<String>) packet.getTag(rejectedTag);
if(rejectedParams != null && rejectedParams.size() > 0){
StringBuilder builder = new StringBuilder();
builder.append("Rejected params for service type ");
builder.append(serviceType.getName());
builder.append(" :");
for(String rejectedParam : rejectedParams){
builder.append(rejectedParam);
builder.append(" ");
}
DebugTool.logWarning(builder.toString());
}
}
}
iSdlProtocol.onProtocolSessionEndedNACKed(serviceType, (byte)packet.getSessionId(), "");
}
// This method handles the end of a protocol session. A callback is
// sent to the protocol listener.
protected void handleServiceEnded(SdlPacket packet, SessionType sessionType) {
iSdlProtocol.onProtocolSessionEnded(sessionType, (byte)packet.getSessionId(), "");
}
/**
* This method handles the startup of a protocol session. A callback is sent
* to the protocol listener.
* @param packet StarServiceACK packet
* @param serviceType the service type that has just been started
*/
protected void handleProtocolSessionStarted(SdlPacket packet, SessionType serviceType) {
// Use this sessionID to create a message lock
Object messageLock = _messageLocks.get((byte)packet.getSessionId());
if (messageLock == null) {
messageLock = new Object();
_messageLocks.put((byte)packet.getSessionId(), messageLock);
}
if(packet.version >= 5){
String mtuTag = null;
if(serviceType.equals(SessionType.RPC)){
mtuTag = ControlFrameTags.RPC.StartServiceACK.MTU;
}else if(serviceType.equals(SessionType.PCM)){
mtuTag = ControlFrameTags.Audio.StartServiceACK.MTU;
}else if(serviceType.equals(SessionType.NAV)){
mtuTag = ControlFrameTags.Video.StartServiceACK.MTU;
}
Object mtu = packet.getTag(mtuTag);
if(mtu!=null){
mtus.put(serviceType,(Long) packet.getTag(mtuTag));
}
if(serviceType.equals(SessionType.RPC)){
hashID = (Integer) packet.getTag(ControlFrameTags.RPC.StartServiceACK.HASH_ID);
Object version = packet.getTag(ControlFrameTags.RPC.StartServiceACK.PROTOCOL_VERSION);
if(version!=null) {
//At this point we have confirmed the negotiated version between the module and the proxy
protocolVersion = new Version((String) version);
}else{
protocolVersion = new Version("5.0.0");
}
//Check to make sure this is a transport we are willing to accept
TransportRecord transportRecord = packet.getTransportRecord();
if(transportRecord == null || !requestedPrimaryTransports.contains(transportRecord.getType())){
onTransportNotAccepted("Transport is not in requested primary transports");
return;
}
// This enables custom behavior based on protocol version specifics
if (protocolVersion.isNewerThan(new Version("5.1.0")) >= 0) {
if (activeTransports.get(SessionType.RPC) == null) { //Might be a better way to handle this
ArrayList<String> secondary = (ArrayList<String>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.SECONDARY_TRANSPORTS);
ArrayList<Integer> audio = (ArrayList<Integer>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.AUDIO_SERVICE_TRANSPORTS);
ArrayList<Integer> video = (ArrayList<Integer>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.VIDEO_SERVICE_TRANSPORTS);
activeTransports.put(SessionType.RPC, transportRecord);
activeTransports.put(SessionType.BULK_DATA, transportRecord);
activeTransports.put(SessionType.CONTROL, transportRecord);
//Build out the supported secondary transports received from the
// RPC start service ACK.
supportedSecondaryTransports = new ArrayList<>();
if (secondary == null) {
// If no secondary transports were attached we should assume
// the Video and Audio services can be used on primary
if (requiresHighBandwidth
&& TransportType.BLUETOOTH.equals(transportRecord.getType())) {
//transport can't support high bandwidth
onTransportNotAccepted(transportRecord.getType() + " can't support high bandwidth requirement, and secondary transport not supported.");
return;
}
if (video == null || video.contains(PRIMARY_TRANSPORT_ID)) {
activeTransports.put(SessionType.NAV, transportRecord);
}
if (audio == null || audio.contains(PRIMARY_TRANSPORT_ID)) {
activeTransports.put(SessionType.PCM, transportRecord);
}
}else{
if(DebugTool.isDebugEnabled()){
printSecondaryTransportDetails(secondary,audio,video);
}
for (String s : secondary) {
switch (s) {
case TransportConstants.TCP_WIFI:
supportedSecondaryTransports.add(TransportType.TCP);
break;
case TransportConstants.AOA_USB:
supportedSecondaryTransports.add(TransportType.USB);
break;
case TransportConstants.SPP_BLUETOOTH:
supportedSecondaryTransports.add(TransportType.BLUETOOTH);
break;
}
}
}
setTransportPriorityForService(SessionType.PCM, audio);
setTransportPriorityForService(SessionType.NAV, video);
//Update the developer on the transport status
notifyDevTransportListener();
} else {
Log.w(TAG, "Received a start service ack for RPC service while already active on a different transport.");
return;
}
if(protocolVersion.isNewerThan(new Version(5,2,0)) >= 0){
String authToken = (String)packet.getTag(ControlFrameTags.RPC.StartServiceACK.AUTH_TOKEN);
if(authToken != null){
iSdlProtocol.onAuthTokenReceived(authToken);
}
}
}else {
//Version is either not included or lower than 5.1.0
if (requiresHighBandwidth
&& TransportType.BLUETOOTH.equals(transportRecord.getType())) {
//transport can't support high bandwidth
onTransportNotAccepted(transportRecord.getType() + " can't support high bandwidth requirement, and secondary transport not supported in this protocol version: " + version);
return;
}
activeTransports.put(SessionType.RPC, transportRecord);
activeTransports.put(SessionType.BULK_DATA, transportRecord);
activeTransports.put(SessionType.CONTROL, transportRecord);
activeTransports.put(SessionType.NAV, transportRecord);
activeTransports.put(SessionType.PCM, transportRecord);
//Inform the developer of the initial transport connection
notifyDevTransportListener();
}
}else if(serviceType.equals(SessionType.NAV)){
if(iSdlProtocol != null) {
ImageResolution acceptedResolution = new ImageResolution();
VideoStreamingFormat acceptedFormat = new VideoStreamingFormat();
acceptedResolution.setResolutionHeight((Integer) packet.getTag(ControlFrameTags.Video.StartServiceACK.HEIGHT));
acceptedResolution.setResolutionWidth((Integer) packet.getTag(ControlFrameTags.Video.StartServiceACK.WIDTH));
acceptedFormat.setCodec(VideoStreamingCodec.valueForString((String) packet.getTag(ControlFrameTags.Video.StartServiceACK.VIDEO_CODEC)));
acceptedFormat.setProtocol(VideoStreamingProtocol.valueForString((String) packet.getTag(ControlFrameTags.Video.StartServiceACK.VIDEO_PROTOCOL)));
VideoStreamingParameters agreedVideoParams = iSdlProtocol.getDesiredVideoParams();
agreedVideoParams.setResolution(acceptedResolution);
agreedVideoParams.setFormat(acceptedFormat);
iSdlProtocol.setAcceptedVideoParams(agreedVideoParams);
}
}
} else {
TransportRecord transportRecord = packet.getTransportRecord();
if(transportRecord == null || (requiresHighBandwidth
&& TransportType.BLUETOOTH.equals(transportRecord.getType()))){
//transport can't support high bandwidth
onTransportNotAccepted((transportRecord != null ? transportRecord.getType().toString() : "Transport") + "can't support high bandwidth requirement, and secondary transport not supported in this protocol version");
return;
}
//If version < 5 and transport is acceptable we need to just add these
activeTransports.put(SessionType.RPC, transportRecord);
activeTransports.put(SessionType.BULK_DATA, transportRecord);
activeTransports.put(SessionType.CONTROL, transportRecord);
activeTransports.put(SessionType.NAV, transportRecord);
activeTransports.put(SessionType.PCM, transportRecord);
if (protocolVersion.getMajor() > 1){
if (packet.payload!= null && packet.dataSize == 4){ //hashid will be 4 bytes in length
hashID = BitConverter.intFromByteArray(packet.payload, 0);
}
}
}
iSdlProtocol.onProtocolSessionStarted(serviceType, (byte) packet.getSessionId(), (byte)protocolVersion.getMajor(), "", hashID, packet.isEncrypted());
}
protected void handleProtocolSessionNAKed(SdlPacket packet, SessionType serviceType) {
List<String> rejectedParams = null;
if(packet.version >= 5){
if(DebugTool.isDebugEnabled()) {
//Currently this is only during a debugging session. Might pass back in the future
String rejectedTag = null;
if (serviceType.equals(SessionType.RPC)) {
rejectedTag = ControlFrameTags.RPC.StartServiceNAK.REJECTED_PARAMS;
} else if (serviceType.equals(SessionType.PCM)) {
rejectedTag = ControlFrameTags.Audio.StartServiceNAK.REJECTED_PARAMS;
} else if (serviceType.equals(SessionType.NAV)) {
rejectedTag = ControlFrameTags.Video.StartServiceNAK.REJECTED_PARAMS;
}
rejectedParams = (List<String>) packet.getTag(rejectedTag);
if(rejectedParams != null && rejectedParams.size() > 0){
StringBuilder builder = new StringBuilder();
builder.append("Rejected params for service type ");
builder.append(serviceType.getName());
builder.append(" :");
for(String rejectedParam : rejectedParams){
builder.append(rejectedParam);
builder.append(" ");
}
DebugTool.logWarning(builder.toString());
}
}
}
if (serviceType.eq(SessionType.NAV) || serviceType.eq(SessionType.PCM)) {
iSdlProtocol.onProtocolSessionNACKed(serviceType, (byte)packet.sessionId, (byte)protocolVersion.getMajor(), "", rejectedParams);
} else {
handleProtocolError("Got StartSessionNACK for protocol sessionID = " + packet.getSessionId(), null);
}
}
// This method handles protocol errors. A callback is sent to the protocol
// listener.
protected void handleProtocolError(String string, Exception ex) {
iSdlProtocol.onProtocolError(string, ex);
}
protected void handleProtocolHeartbeat(SessionType sessionType, byte sessionID) {
sendHeartBeatACK(sessionType,sessionID);
}
protected void handleServiceDataACK(SdlPacket packet, SessionType sessionType) {
if (packet.getPayload() != null && packet.getDataSize() == 4){ //service data ack will be 4 bytes in length
int serviceDataAckSize = BitConverter.intFromByteArray(packet.getPayload(), 0);
iSdlProtocol.onProtocolServiceDataACK(sessionType, serviceDataAckSize, (byte)packet.getSessionId ());
}
}
@SuppressWarnings("FieldCanBeLocal")
final TransportManagerBase.TransportEventListener transportEventListener = new TransportManagerBase.TransportEventListener() {
private boolean requestedSession = false;
@Override
public void onPacketReceived(SdlPacket packet) {
handlePacketReceived(packet);
}
@Override
public void onTransportConnected(List<TransportRecord> connectedTransports) {
Log.d(TAG, "onTransportConnected");
//In the future we should move this logic into the Protocol Layer
TransportRecord transportRecord = getTransportForSession(SessionType.RPC);
if(transportRecord == null && !requestedSession){ //There is currently no transport registered
requestedSession = true;
if (transportManager != null) {
transportManager.requestNewSession(getPreferredTransport(requestedPrimaryTransports, connectedTransports));
}
}
onTransportsConnectedUpdate(connectedTransports);
if(DebugTool.isDebugEnabled()){
printActiveTransports();
}
}
@Override
public void onTransportDisconnected(String info, TransportRecord disconnectedTransport, List<TransportRecord> connectedTransports) {
if (disconnectedTransport == null) {
Log.d(TAG, "onTransportDisconnected");
if (transportManager != null) {
transportManager.close(iSdlProtocol.getSessionId());
}
iSdlProtocol.shutdown("No transports left connected");
return;
} else {
Log.d(TAG, "onTransportDisconnected - " + disconnectedTransport.getType().name());
}
//In the future we will actually compare the record but at this point we can assume only
//a single transport record per transport.
//TransportType type = disconnectedTransport.getType();
if(getTransportForSession(SessionType.NAV) != null && disconnectedTransport.equals(getTransportForSession(SessionType.NAV))){
//stopVideoStream();
iSdlProtocol.stopStream(SessionType.NAV);
activeTransports.remove(SessionType.NAV);
}
if(getTransportForSession(SessionType.PCM) != null && disconnectedTransport.equals(getTransportForSession(SessionType.PCM))){
//stopAudioStream();
iSdlProtocol.stopStream(SessionType.PCM);
activeTransports.remove(SessionType.PCM);
}
if((getTransportForSession(SessionType.RPC) != null && disconnectedTransport.equals(getTransportForSession(SessionType.RPC))) || disconnectedTransport.equals(connectedPrimaryTransport)){
//transportTypes.remove(type);
boolean primaryTransportAvailable = false;
if(requestedPrimaryTransports != null && requestedPrimaryTransports.size() > 1){
for (TransportType transportType: requestedPrimaryTransports){ Log.d(TAG, "Checking " + transportType.name());
if(!disconnectedTransport.getType().equals(transportType)
&& transportManager != null
&& transportManager.isConnected(transportType,null)){
primaryTransportAvailable = true;
transportManager.updateTransportConfig(transportConfig);
break;
}
}
}
connectedPrimaryTransport = null;
if (transportManager != null) {
transportManager.close(iSdlProtocol.getSessionId());
}
transportManager = null;
requestedSession = false;
activeTransports.clear();
iSdlProtocol.onTransportDisconnected(info, primaryTransportAvailable, transportConfig);
} //else Transport was not primary, continuing to stay connected
//Update the developer since a transport just disconnected
notifyDevTransportListener();
}
@Override
public void onError(String info) {
iSdlProtocol.shutdown(info);
}
@Override
public boolean onLegacyModeEnabled(String info) {
//Await a connection from the legacy transport
if(requestedPrimaryTransports!= null && requestedPrimaryTransports.contains(TransportType.BLUETOOTH)
&& !SdlProtocolBase.this.requiresHighBandwidth){
Log.d(TAG, "Entering legacy mode; creating new protocol instance");
reset();
return true;
}else{
Log.d(TAG, "Bluetooth is not an acceptable transport; not moving to legacy mode");
return false;
}
}
};
protected class MessageFrameAssembler {
protected ByteArrayOutputStream accumulator = null;
protected int totalSize = 0;
protected void handleFirstDataFrame(SdlPacket packet) {
//The message is new, so let's figure out how big it is.
totalSize = BitConverter.intFromByteArray(packet.payload, 0) - headerSize;
try {
accumulator = new ByteArrayOutputStream(totalSize);
}catch(OutOfMemoryError e){
DebugTool.logError("OutOfMemory error", e); //Garbled bits were received
accumulator = null;
}
}
protected void handleRemainingFrame(SdlPacket packet) {
accumulator.write(packet.payload, 0, (int)packet.getDataSize());
notifyIfFinished(packet);
}
protected void notifyIfFinished(SdlPacket packet) {
if (packet.getFrameType() == FrameType.Consecutive && packet.getFrameInfo() == 0x0) {
ProtocolMessage message = new ProtocolMessage();
message.setPayloadProtected(packet.isEncrypted());
message.setSessionType(SessionType.valueOf((byte)packet.getServiceType()));
message.setSessionID((byte)packet.getSessionId());
//If it is WiPro 2.0 it must have binary header
if (protocolVersion.getMajor() > 1) {
BinaryFrameHeader binFrameHeader = BinaryFrameHeader.
parseBinaryHeader(accumulator.toByteArray());
if(binFrameHeader == null) {
return;
}
message.setVersion((byte)protocolVersion.getMajor());
message.setRPCType(binFrameHeader.getRPCType());
message.setFunctionID(binFrameHeader.getFunctionID());
message.setCorrID(binFrameHeader.getCorrID());
if (binFrameHeader.getJsonSize() > 0) message.setData(binFrameHeader.getJsonData());
if (binFrameHeader.getBulkData() != null) message.setBulkData(binFrameHeader.getBulkData());
} else{
message.setData(accumulator.toByteArray());
}
_assemblerForMessageID.remove(packet.getMessageId());
try {
iSdlProtocol.onProtocolMessageReceived(message);
} catch (Exception excp) {
DebugTool.logError(FailurePropagating_Msg + "onProtocolMessageReceived: " + excp.toString(), excp);
} // end-catch
accumulator = null;
} // end-if
} // end-method
protected void handleMultiFrameMessageFrame(SdlPacket packet) {
if (packet.getFrameType() == FrameType.First) {
handleFirstDataFrame(packet);
}
else{
if(accumulator != null){
handleRemainingFrame(packet);
}
}
} // end-method
protected void handleFrame(SdlPacket packet) {
if (packet.getPayload() != null && packet.getDataSize() > 0 && packet.isEncrypted() ) {
SdlSecurityBase sdlSec = iSdlProtocol.getSdlSecurity();
byte[] dataToRead = new byte[4096];
Integer iNumBytes = sdlSec.decryptData(packet.getPayload(), dataToRead);
if ((iNumBytes == null) || (iNumBytes <= 0)){
return;
}
byte[] decryptedData = new byte[iNumBytes];
System.arraycopy(dataToRead, 0, decryptedData, 0, iNumBytes);
packet.payload = decryptedData;
}
if (packet.getFrameType().equals(FrameType.Control)) {
handleControlFrame(packet);
} else {
// Must be a form of data frame (single, first, consecutive, etc.)
if ( packet.getFrameType() == FrameType.First
|| packet.getFrameType() == FrameType.Consecutive
) {
handleMultiFrameMessageFrame(packet);
} else {
handleSingleFrameMessageFrame(packet);
}
}
}
private void handleProtocolHeartbeatACK(SdlPacket packet) {
//Heartbeat is not supported in the SdlProtocol class beyond responding with ACKs to
//heartbeat messages. Receiving this ACK is suspicious and should be logged
DebugTool.logInfo("Received HeartbeatACK - " + packet.toString());
}
private void handleProtocolHeartbeat(SdlPacket packet) {
SdlProtocolBase.this.handleProtocolHeartbeat(SessionType.valueOf((byte)packet.getServiceType()),(byte)packet.getSessionId());
}
/**
* Directing method that will push the packet to the method that can handle it best
* @param packet a control frame packet
*/
private void handleControlFrame(SdlPacket packet) {
Integer frameTemp = packet.getFrameInfo();
Byte frameInfo = frameTemp.byteValue();
SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType());
if (frameInfo == FrameDataControlFrameType.Heartbeat.getValue()) {
handleProtocolHeartbeat(packet);
}else if (frameInfo == FrameDataControlFrameType.HeartbeatACK.getValue()) {
handleProtocolHeartbeatACK(packet);
}else if (frameInfo == FrameDataControlFrameType.StartSessionACK.getValue()) {
handleProtocolSessionStarted(packet, serviceType);
} else if (frameInfo == FrameDataControlFrameType.StartSessionNACK.getValue()) {
handleProtocolSessionNAKed(packet, serviceType);
} else if (frameInfo == FrameDataControlFrameType.EndSession.getValue()
|| frameInfo == FrameDataControlFrameType.EndSessionACK.getValue()) {
handleServiceEnded(packet,serviceType);
} else if (frameInfo == FrameDataControlFrameType.EndSessionNACK.getValue()) {
handleServiceEndedNAK(packet, serviceType);
} else if (frameInfo == FrameDataControlFrameType.ServiceDataACK.getValue()) {
handleServiceDataACK(packet, serviceType);
} else if (frameInfo == FrameDataControlFrameType.RegisterSecondaryTransportACK.getValue()) {
handleSecondaryTransportRegistration(packet.getTransportRecord(),true);
} else if (frameInfo == FrameDataControlFrameType.RegisterSecondaryTransportNACK.getValue()) {
String reason = (String) packet.getTag(ControlFrameTags.RPC.RegisterSecondaryTransportNAK.REASON);
DebugTool.logWarning(reason);
handleSecondaryTransportRegistration(packet.getTransportRecord(),false);
} else if (frameInfo == FrameDataControlFrameType.TransportEventUpdate.getValue()) {
// Get TCP params
String ipAddr = (String) packet.getTag(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS);
Integer port = (Integer) packet.getTag(ControlFrameTags.RPC.TransportEventUpdate.TCP_PORT);
if(secondaryTransportParams == null){
secondaryTransportParams = new HashMap<>();
}
if(ipAddr != null && port != null) {
String address = (port != null && port > 0) ? ipAddr + ":" + port : ipAddr;
secondaryTransportParams.put(TransportType.TCP, new TransportRecord(TransportType.TCP,address));
//A new secondary transport just became available. Notify the developer.
notifyDevTransportListener();
}
}
_assemblerForMessageID.remove(packet.getMessageId());
} // end-method
private void handleSingleFrameMessageFrame(SdlPacket packet) {
ProtocolMessage message = new ProtocolMessage();
message.setPayloadProtected(packet.isEncrypted());
SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType());
if (serviceType == SessionType.RPC) {
message.setMessageType(MessageType.RPC);
} else if (serviceType == SessionType.BULK_DATA) {
message.setMessageType(MessageType.BULK);
} // end-if
message.setSessionType(serviceType);
message.setSessionID((byte)packet.getSessionId());
//If it is WiPro 2.0 it must have binary header
boolean isControlService = message.getSessionType().equals(SessionType.CONTROL);
if (protocolVersion.getMajor() > 1 && !isControlService) {
BinaryFrameHeader binFrameHeader = BinaryFrameHeader.
parseBinaryHeader(packet.payload);
if(binFrameHeader == null) {
return;
}
message.setVersion((byte)protocolVersion.getMajor());
message.setRPCType(binFrameHeader.getRPCType());
message.setFunctionID(binFrameHeader.getFunctionID());
message.setCorrID(binFrameHeader.getCorrID());
if (binFrameHeader.getJsonSize() > 0){
message.setData(binFrameHeader.getJsonData());
}
if (binFrameHeader.getBulkData() != null){
message.setBulkData(binFrameHeader.getBulkData());
}
} else {
message.setData(packet.payload);
}
_assemblerForMessageID.remove(packet.getMessageId());
try {
iSdlProtocol.onProtocolMessageReceived(message);
} catch (Exception ex) {
DebugTool.logError(FailurePropagating_Msg + "onProtocolMessageReceived: " + ex.toString(), ex);
handleProtocolError(FailurePropagating_Msg + "onProtocolMessageReceived: ", ex);
} // end-catch
} // end-method
} // end-class
}
|
package com.health.control;
import java.awt.Container;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.health.EventList;
import com.health.EventSequence;
import com.health.Table;
import com.health.input.Input;
import com.health.input.InputException;
import com.health.interpreter.Interpreter;
import com.health.operations.Code;
import com.health.operations.TableWithDays;
import com.health.output.Output;
import com.health.script.runtime.BooleanValue;
import com.health.script.runtime.Context;
import com.health.script.runtime.NumberValue;
import com.health.script.runtime.ScriptType;
import com.health.script.runtime.StringValue;
import com.health.script.runtime.WrapperValue;
import com.health.visuals.BoxPlot;
import com.health.visuals.FreqBar;
import com.health.visuals.Histogram;
import com.health.visuals.StateTransitionMatrix;
public final class ControlModule {
private String script;
private List<InputData> data;
private Map<String, Object> output = new HashMap<String, Object>();
int numBoxPlots, numFreqBars, numTransitionMatrices, numHistograms;
/**
* Start analysis based on the script.
*
* @return nothing.
* @throws IOException
* if any I/O errors occur.
*/
public Context startAnalysis() throws IOException {
if (this.script == null) {
throw new IllegalStateException(
"Script cannot be null. Set the script to a String isntance using setScript(String).");
}
Context context = this.createContext();
this.loadAllData(context);
Interpreter.interpret(this.script, context);
return context;
}
public Map<String, Object> getOutput() {
return Collections.unmodifiableMap(this.output);
}
/**
* Gets the data of this control module.
*
* @return the data of this control module.
*/
public List<InputData> getData() {
return data;
}
/**
* Sets the data of this control module.
*
* @param data
* the data of this control module.
*/
public void setData(final List<InputData> data) {
this.data = data;
}
/**
* Gets the script of this control module.
*
* @return the script of this control module.
*/
public String getScript() {
return script;
}
/**
* Sets the script of this control module.
*
* @param script
* the script of this control module.
*/
public void setScript(final String script) {
this.script = script;
}
@Override
public String toString() {
return "ControlModule [data=" + data.toString() + ", script=" + script + "]";
}
private Context createContext() {
Context context = new Context();
context.declareStaticMethod("println", (args) -> {
System.out.println(((StringValue) args[0]).getValue());
return null;
});
context.declareStaticMethod("write", (args) -> {
String filename = ((StringValue) args[0]).getValue();
Table table = ((WrapperValue<Table>) args[1]).getValue();
if (args.length >= 3) {
Output.writeTable(
filename,
table,
((StringValue) args[2]).getValue());
} else {
Output.writeTable(filename, table);
}
this.output.put(new File(filename).getName(), table);
return null;
});
context.declareStaticMethod("freqbar", (args) -> {
Container frame;
if (args.length >= 2) {
frame = FreqBar.frequencyBar(
((WrapperValue<Table>) args[0]).getValue(),
((StringValue) args[1]).getValue());
} else {
frame = FreqBar.frequencyBar(((WrapperValue<Table>) args[0]).getValue());
}
this.output.put("freqbar" + ++numFreqBars, frame);
return null;
});
context.declareStaticMethod("boxplot", (args) -> {
JPanel panel;
if (args.length >= 2) {
panel = BoxPlot.boxPlot(((WrapperValue<Table>) args[0]).getValue(),
((StringValue) args[1]).getValue());
} else {
panel = BoxPlot.boxPlot(((WrapperValue<Table>) args[0]).getValue());
}
this.output.put("boxplot" + ++numBoxPlots, panel);
return null;
});
context.declareStaticMethod("hist", (args) -> {
JPanel panel = Histogram.createHistogram(
((WrapperValue<Table>) args[0]).getValue(),
((StringValue) args[1]).getValue(),
(int) ((NumberValue) args[2]).getValue());
this.output.put("histogram" + ++numHistograms, panel);
return null;
});
context.declareStaticMethod("sequence", (args) -> {
String[] sequence;
boolean connected = true;
if (args.length > 0 && args[args.length - 1] instanceof BooleanValue) {
connected = ((BooleanValue) args[args.length - 1]).getValue();
sequence = new String[args.length - 1];
for (int i = 0; i < args.length - 1; i++) {
sequence[i] = ((StringValue) args[i]).getValue();
}
} else {
sequence = new String[args.length];
for (int i = 0; i < args.length; i++) {
sequence[i] = ((StringValue) args[i]).getValue();
}
}
return new WrapperValue<EventSequence>(new EventSequence(sequence, connected));
});
context.declareStaticMethod("findSequences", (args) -> {
EventList events = ((WrapperValue<EventList>) args[0]).getValue();
EventSequence sequence = ((WrapperValue<EventSequence>) args[1]).getValue();
Code.fillEventSequence(sequence, events);
return new WrapperValue<List<EventList>>(sequence.getSequences());
});
context.declareStaticMethod(
"transitionMatrix",
(args) -> {
EventList codes = ((WrapperValue<EventList>) args[0]).getValue();
JTable table;
if (args.length >= 2) {
ScriptType eventSequenceType = WrapperValue.getWrapperType(EventSequence.class);
if ((args[1]).getType() == eventSequenceType) {
EventSequence sequence = ((WrapperValue<EventSequence>) args[1]).getValue();
table = StateTransitionMatrix.createStateTrans(codes,
Code.fillEventSequence(sequence, codes));
} else {
table = StateTransitionMatrix.createStateTrans(codes,
((WrapperValue<List<EventList>>) args[1]).getValue());
}
} else {
table = StateTransitionMatrix.createStateTrans(codes);
}
this.output.put("transitionMatrix" + ++numBoxPlots, table);
return null;
});
context.declareStaticMethod("tableWithDays", (args) -> {
return new WrapperValue<Table>(TableWithDays.TableDays(((WrapperValue<Table>) args[0]).getValue()));
});
return context;
}
private void loadAllData(final Context context) {
if (this.data != null) {
for (int i = 0; i < this.data.size(); i++) {
this.loadData(this.data.get(i), context);
}
}
}
private void loadData(final InputData input, final Context context) {
Table table = null;
try {
table = Input.readTable(input.getFilePath(), input.getConfigPath());
} catch (IOException | ParserConfigurationException
| SAXException | InputException e) {
System.out.println("Error: Something went wrong parsing the config and data!");
e.printStackTrace();
return;
}
WrapperValue<Table> value = new WrapperValue<Table>(table);
context.declareLocal(input.getName(), value.getType(), value);
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:22-02-12");
this.setApiVersion("17.18.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package org.basex.gui.view.project;
import static org.basex.core.Text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import org.basex.gui.*;
import org.basex.gui.layout.*;
import org.basex.io.*;
import org.basex.util.*;
import org.basex.util.hash.*;
import org.basex.util.list.*;
public class ProjectList extends JList {
/** Font metrics. */
private static FontMetrics fm;
/** Popup commands. */
final GUIPopupCmd[] commands = {
new GUIPopupCmd(OPEN, BaseXKeys.ENTER) {
@Override public void execute() { open(); }
},
new GUIPopupCmd(OPEN_EXTERNALLY, BaseXKeys.OPEN) {
@Override public void execute() { openExternal(); }
}, null,
new GUIPopupCmd(REFRESH, BaseXKeys.REFRESH) {
@Override public void execute() { project.filter.refresh(true); }
},
new GUIPopupCmd(COPY_PATH, BaseXKeys.COPYPATH) {
@Override public void execute() {
if(enabled(null)) BaseXLayout.copy(selectedValue());
}
@Override public boolean enabled(final GUI main) { return selectedValue() != null; }
}
};
/** Project view. */
private final ProjectView project;
/** Content search string. */
private String search;
/**
* Constructor.
* @param view project view
*/
ProjectList(final ProjectView view) {
project = view;
setBorder(new EmptyBorder(4, 4, 4, 4));
setCellRenderer(new CellRenderer());
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) open();
}
});
new BaseXPopup(this, view.gui, commands);
}
/**
* Assigns the specified list entries and selects the first entry.
* @param elements result elements
* @param srch content search string
*/
void setElements(final TokenSet elements, final String srch) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// set new values and selections
final int is = elements.size();
final String[] list = new String[is];
for(int i = 0; i < is; i++) list[i] = Token.string(elements.key(i + 1));
if(changed(list)) {
// check which old values had been selected
final Object[] old = getSelectedValues();
final IntList il = new IntList();
for(final Object o : old) {
for(int i = 0; i < is; i++) {
if(o.equals(elements.key(i + 1))) {
il.add(i);
break;
}
}
}
setListData(list);
setSelectedIndices(il.toArray());
}
search = srch;
}
});
}
/**
* Checks if the list contents have changed.
* @param list entries to set
* @return result of check
*/
boolean changed(final String[] list) {
final int sl = list.length, el = getModel().getSize();
if(sl != el) return true;
for(int i = 0; i < sl; i++) {
if(!list[i].equals(getModel().getElementAt(i))) return true;
}
return false;
}
/**
* Open all selected files.
*/
void open() {
for(final IOFile file : selectedValues()) project.open(file, search);
}
/**
* Open all selected files externally.
*/
void openExternal() {
for(final IOFile file : selectedValues()) {
try {
file.open();
} catch(final IOException ex) {
BaseXDialog.error(project.gui, Util.info(FILE_NOT_OPENED_X, file));
}
}
}
/** List cell renderer. */
class CellRenderer extends DefaultListCellRenderer {
/** Label. */
private final BaseXLabel label;
/** Current file. */
private IOFile file = new IOFile(".");
/**
* Constructor.
*/
CellRenderer() {
label = new BaseXLabel() {
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
BaseXLayout.hints(g);
if(fm == null) fm = g.getFontMetrics(label.getFont());
final int y = Math.min(fm.getHeight(), (int) label.getPreferredSize().getHeight()) - 2;
int x = (int) label.getPreferredSize().getWidth() + 2;
final String s = file.name();
g.setColor(label.getForeground());
g.drawString(s, x, y);
x += fm.stringWidth(s);
final String[] names = file.file().getParent().split("/|\\\\");
final StringBuilder sb = new StringBuilder(" ");
for(int n = names.length - 1; n >= 0; n--) sb.append('/').append(names[n]);
g.setColor(GUIConstants.GRAY);
g.drawString(sb.toString(), x, y);
}
};
label.setOpaque(true);
}
@Override
public Component getListCellRendererComponent(final JList list, final Object value,
final int index, final boolean selected, final boolean expanded) {
file = new IOFile(value.toString());
label.setIcon(BaseXImages.file(file));
label.setText("");
label.setToolTipText(ProjectFile.toString(file, true));
if(selected) {
label.setBackground(getSelectionBackground());
label.setForeground(getSelectionForeground());
} else {
label.setBackground(Color.WHITE);
label.setForeground(getForeground());
}
return label;
}
}
/**
* Returns a single selected node, or {@code null} if zero or more than node is selected.
* @return selected node
*/
private String selectedValue() {
final Object[] old = getSelectedValues();
return old.length == 1 ? old[0].toString() : null;
}
/**
* Returns a single selected node, or {@code null} if zero or more than node is selected.
* @return selected node
*/
private IOFile[] selectedValues() {
// nothing selected: select first entry
if(isSelectionEmpty() && getModel().getSize() != 0) setSelectedIndex(0);
final ArrayList<IOFile> list = new ArrayList<IOFile>();
for(final Object o : getSelectedValues()) list.add(new IOFile(o.toString()));
return list.toArray(new IOFile[list.size()]);
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-04-22");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:22-04-21");
this.setApiVersion("18.2.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package eu.fthevenet.binjr.data;
import java.util.ArrayList;
import java.util.List;
public class RamerDouglasPeucker {
// public static List<Point> simplify(List<Point> points, double epsilon){
// if (points.size() == 0)
// return points;
// return simplify(points, epsilon);
public static List<Point> simplify(List<Point> points, double epsilon) {
if (points.size() < 2) {
return points;
}
List<Point> resultList = new ArrayList<>();
double dmax = -1.0;
int index = 0;
int end = points.size() -1;
for (int i = 1; i < end-1; i++) {
double d = perpendicularDistance(points.get(i), points.get(0), points.get(end));
if (d > dmax) {
dmax = d;
index = i;
}
}
if (dmax > epsilon) {
List<Point> res1 = simplify(points.subList(0,index), epsilon);
List<Point> res2 = simplify(points.subList(index, end+1), epsilon);
resultList.addAll(res1);
resultList.addAll(res2);
}
else {
resultList.add(points.get(0));
resultList.add(points.get(end));
}
return resultList;
}
private static double perpendicularDistance(Point p, Point a, Point b) {
if (a.equals(b)){
return p.distance(a);
}
// double r = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / ((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y));
// if (r <= 0.0) return p.distance(a);
// if (r >= 1.0) return p.distance(b);
// double s = ((a.y - p.y) * (b.x - a.x) - (a.x - p.x) * (b.y - a.y)) / ((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y));
// return Math.abs(s) * Math.sqrt(((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y)));
double n = Math.abs((b.x - a.x) * (a.y - p.y) - (a.x - p.x) * (b.y - a.y));
double d = Math.sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y));
return n / d;
}
public static class Point {
final public double y;
final public double x;
public Point(double x, double y) {
this.y = y;
this.x = x;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point p = (Point) obj;
return x == p.x && y == p.y;
}
public double distance(Point p) {
double dx = x - p.x;
double dy = y - p.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
}
|
package hugo.weaving.internal;
import android.util.Log;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
@Aspect
public class Hugo {
private static final Pattern ANONYMOUS_CLASS = Pattern.compile("\\$\\d+$");
@Pointcut("execution(@hugo.weaving.DebugLog * *(..))")
public void debugLog() {}
@Around("debugLog()")
public Object debugLogMethod(ProceedingJoinPoint joinPoint) throws Throwable {
pushMethod(joinPoint);
long startNanos = System.nanoTime();
Object result = joinPoint.proceed();
long stopNanos = System.nanoTime();
long lengthMillis = TimeUnit.NANOSECONDS.toMillis(stopNanos - startNanos);
popMethod(joinPoint, result, lengthMillis);
return result;
}
private static void pushMethod(JoinPoint joinPoint) {
MethodSignature codeSignature = (MethodSignature) joinPoint.getSignature();
String className = codeSignature.getDeclaringTypeName();
String methodName = codeSignature.getName();
String[] parameterNames = codeSignature.getParameterNames();
Object[] parameterValues = joinPoint.getArgs();
StringBuilder builder = new StringBuilder("⇢ ");
builder.append(methodName).append('(');
for (int i = 0; i < parameterValues.length; i++) {
if (i > 0) {
builder.append(", ");
}
builder.append(parameterNames[i]).append('=');
appendObject(builder, parameterValues[i]);
}
builder.append(')');
Log.d(asTag(className), builder.toString());
}
private static void popMethod(JoinPoint joinPoint, Object result, long lengthMillis) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String className = signature.getDeclaringTypeName();
String methodName = signature.getName();
boolean hasReturnType = signature.getReturnType() != void.class;
StringBuilder builder = new StringBuilder("⇠ ")
.append(methodName)
.append(" [")
.append(lengthMillis)
.append("ms]");
if (hasReturnType) {
builder.append(" = ");
appendObject(builder, result);
}
Log.d(asTag(className), builder.toString());
}
private static void appendObject(StringBuilder builder, Object value) {
if (value == null) {
builder.append("null");
} else if (value instanceof String) {
builder.append('"').append(value).append('"');
} else if (value.getClass().isArray()) {
builder.append(arrayToString(value));
} else {
builder.append(value.toString());
}
}
private static String asTag(String className) {
Matcher m = ANONYMOUS_CLASS.matcher(className);
if (m.find()) {
className = m.replaceAll("");
}
return className.substring(className.lastIndexOf('.') + 1);
}
private static String arrayToString(final Object o) {
if (o instanceof Object[]) {
return Arrays.toString((Object[]) o);
}
//must be primitive array
final Class<?> clazz = o.getClass();
if (byte[].class.equals(clazz)) {
return Arrays.toString((byte[]) o);
}
if (short[].class.equals(clazz)) {
return Arrays.toString((short[]) o);
}
if (char[].class.equals(clazz)) {
return Arrays.toString((char[]) o);
}
if (int[].class.equals(clazz)) {
return Arrays.toString((int[]) o);
}
if (long[].class.equals(clazz)) {
return Arrays.toString((long[]) o);
}
if (float[].class.equals(clazz)) {
return Arrays.toString((float[]) o);
}
if (double[].class.equals(clazz)) {
return Arrays.toString((double[]) o);
}
if (boolean[].class.equals(clazz)) {
return Arrays.toString((boolean[]) o);
}
throw new IllegalArgumentException("Unknown array type: " + o.getClass());
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-06-03");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package org.intermine.bio.dataconversion;
import java.io.File;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.bio.ontology.OboParser;
import org.intermine.bio.ontology.OboRelation;
import org.intermine.bio.ontology.OboTerm;
import org.intermine.bio.ontology.OboTermSynonym;
import org.intermine.dataconversion.DataConverter;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.xml.full.Attribute;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.Reference;
/**
* Convert tree of OboTerms into Items.
*
* @author Thomas Riley
* @see DagConverter
*/
public class OboConverter extends DataConverter
{
private static final Logger LOG = Logger.getLogger(DataConverter.class);
protected String dagFilename;
protected String termClass;
protected int uniqueId = 0;
protected int uniqueSynId = 0;
protected Collection<OboTerm> oboTerms;
protected List<OboRelation> oboRelations;
protected Map<String, Item> nameToTerm = new HashMap<String, Item>();
protected Map<String, String> xrefs = new HashMap<String, String>();
protected Map<OboTermSynonym, Item> synToItem = new HashMap<OboTermSynonym, Item>();
protected Item ontology;
private boolean createRelations = true;
/**
* Constructor for this class.
*
* @param writer an ItemWriter used to handle the resultant Items
* @param model the Model
* @param dagFilename the name of the DAG file
* @param dagName the title of the dag, as present in any static data
* @param url the URL of the source of this ontology
* @param termClass the class of the Term
*/
public OboConverter(ItemWriter writer, Model model, String dagFilename, String dagName,
String url, String termClass) {
super(writer, model);
this.dagFilename = dagFilename;
this.termClass = termClass;
ontology = createItem("Ontology");
ontology.addAttribute(new Attribute("name", dagName));
ontology.addAttribute(new Attribute("url", url));
}
/**
* Set to false to prevent storing OntologyRelation objects that include the relationship types
* between terms.
* @param createrelations property to parse
*/
public void setCreaterelations(String createrelations) {
if ("true".equals(createrelations)) {
this.createRelations = true;
} else {
this.createRelations = false;
}
}
/**
* Process every DAG term and output it as a Item.
*
* @throws Exception if an error occurs in processing
*/
public void process() throws Exception {
nameToTerm = new HashMap<String, Item>();
synToItem = new HashMap<OboTermSynonym, Item>();
OboParser parser = new OboParser();
parser.processOntology(new FileReader(new File(dagFilename)));
parser.processRelations(dagFilename);
oboTerms = parser.getOboTerms();
oboRelations = parser.getOboRelations();
storeItems();
}
/**
* Convert DagTerms into Items and relation Items, and write them to the ItemWriter
*
* @throws ObjectStoreException if an error occurs while writing to the itemWriter
*/
protected void storeItems() throws ObjectStoreException {
long startTime = System.currentTimeMillis();
store(ontology);
for (OboTerm term : oboTerms) {
process(term);
}
for (OboRelation oboRelation : oboRelations) {
processRelation(oboRelation);
}
for (Item termItem: nameToTerm.values()) {
store(termItem);
}
for (Item synItem : synToItem.values()) {
store(synItem);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Ran storeItems, took: " + timeTaken + " ms");
}
/**
* @param oboTerms the oboTerms to set
*/
public void setOboTerms(Collection<OboTerm> oboTerms) {
this.oboTerms = oboTerms;
}
/**
* @param oboRelations the OboRelations to set
*/
public void setOboRelations(List<OboRelation> oboRelations) {
this.oboRelations = oboRelations;
}
/**
* Convert a OboTerm into an Item and relation Items, and write the relations to the writer.
*
* @param term a DagTerm
* @return an Item representing the term
* @throws ObjectStoreException if an error occurs while writing to the itemWriter
*/
protected Item process(OboTerm term) throws ObjectStoreException {
if (term.isObsolete()) {
LOG.info("Not processing obsolete OBO term: " + term.getId() + " " + term.getName());
return null;
}
String termId = (term.getId() == null ? term.getName() : term.getId());
Item item = nameToTerm.get(termId);
if (item == null) {
item = createItem(termClass);
nameToTerm.put(termId, item);
configureItem(termId, item, term);
} else {
if ((!term.getName().equals(item.getAttribute("name").getValue()))
|| ((item.getAttribute("identifier") == null) && (term.getId() != null))
|| ((item.getAttribute("identifier") != null)
&& (!item.getAttribute("identifier").getValue().equals(term.getId())))) {
throw new IllegalArgumentException("Dag is invalid - terms (" + term.getName()
+ ", " + term.getId() + ") and (" + item.getAttribute("name").getValue()
+ ", " + (item.getAttribute("identifier") == null ? "null"
: item.getAttribute("identifier").getValue()) + ") clash");
}
}
return item;
}
/**
* Set up attributes and references for the Item created from a DagTerm. Subclasses
* can override this method to perform extra setup, for example by casting the
* DagTerm to some someclass and retrieving extra attributes. Subclasses should call this
* inherited method first. This method will call process() for each child/component term,
* resulting in recursion.
*
* @param termId the term id
* @param item the Item created (see termClass field for type)
* @param term the source DagTerm
* @throws ObjectStoreException if an error occurs while writing to the itemWriter
*/
protected void configureItem(String termId, Item item, OboTerm term)
throws ObjectStoreException {
item.addAttribute(new Attribute("name", term.getName()));
item.addReference(new Reference("ontology", ontology.getIdentifier()));
if (term.getId() != null) {
item.addAttribute(new Attribute("identifier", term.getId()));
}
for (OboTermSynonym syn : term.getSynonyms()) {
Item synItem = synToItem.get(syn);
if (synItem == null) {
synItem = createItem("OntologyTermSynonym");
synToItem.put(syn, synItem);
configureSynonymItem(syn, synItem, term);
}
item.addToCollection("synonyms", synItem);
}
for (OboTerm xref : term.getXrefs()) {
String identifier = xref.getId();
String refId = xrefs.get(identifier);
if (refId == null) {
Item xrefTerm = createItem("OntologyTerm");
refId = xrefTerm.getIdentifier();
xrefs.put(identifier, refId);
xrefTerm.setAttribute("identifier", identifier);
xrefTerm.addToCollection("crossReferences", item.getIdentifier());
store(xrefTerm);
}
item.addToCollection("crossReferences", refId);
}
OboTerm oboterm = term;
if (!StringUtils.isEmpty(oboterm.getNamespace())) {
item.setAttribute("namespace", oboterm.getNamespace());
}
if (!StringUtils.isEmpty(oboterm.getDescription())) {
item.setAttribute("description", oboterm.getDescription());
}
item.setAttribute("obsolete", "" + oboterm.isObsolete());
// Term is its own parent
item.addToCollection("parents", item);
}
/**
* Set up attributes and references for the Item created from a DagTermSynonym. Subclasses
* can override this method to perform extra setup, for example by casting the
* DagTermSynonym to some someclass and retrieving extra attributes. Subclasses should call this
* inherited method first.
*
* @param syn the DagTermSynonym object (or a subclass of)
* @param item the Item created to store the synonym
* @param term the source DagTerm
* @throws ObjectStoreException if an error occurs while writing to the itemWriter
*/
protected void configureSynonymItem(OboTermSynonym syn, Item item, OboTerm term)
throws ObjectStoreException {
item.setAttribute("name", syn.getName());
item.setAttribute("type", syn.getType());
}
/**
* Process and store OboRelations
* @param oboRelation the relation to process
* @throws ObjectStoreException if problem storing
*/
protected void processRelation(OboRelation oboRelation)
throws ObjectStoreException {
// create the relation item
if (nameToTerm.get(oboRelation.getParentTermId()) != null
&& nameToTerm.get(oboRelation.getChildTermId()) != null) {
// add parent to term for easier querying in webapp
nameToTerm.get(oboRelation.getChildTermId()).addToCollection("parents",
nameToTerm.get(oboRelation.getParentTermId()));
if (createRelations) {
Item relation = createItem("OntologyRelation");
relation.setReference("parentTerm", nameToTerm
.get(oboRelation.getParentTermId()));
relation.setReference("childTerm", nameToTerm.get(oboRelation.getChildTermId()));
relation.setAttribute("relationship", oboRelation.getRelationship().getName());
relation.setAttribute("direct", Boolean.toString(oboRelation.isDirect()));
relation.setAttribute("redundant", Boolean.toString(oboRelation.isRedundant()));
// Set the reverse reference
nameToTerm.get(oboRelation.getParentTermId())
.addToCollection("relations", relation);
nameToTerm.get(oboRelation.getChildTermId())
.addToCollection("relations", relation);
store(relation);
}
} else {
LOG.info("GOTerm id not found for relation " + oboRelation.getParentTermId() + " "
+ oboRelation.getChildTermId());
}
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-02-16");
this.setApiVersion("16.16.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:20-01-12");
this.setApiVersion("15.15.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package com.sam.bubbleactions;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.ViewCompat;
import android.view.DragEvent;
import android.view.View;
import android.view.ViewGroup;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Inspired by the Pinterest Android app, BubbleActions make it easy to perform actions on ui
* elements by simply dragging your finger. BubbleActions uses a fluent interface to build and show
* actions similar to SnackBar or AlertDialog.
*/
public class BubbleActions {
private static final String TAG = BubbleActions.class.getSimpleName();
/**
* A {@link Callback#doAction()} call cooresponding to a particular action is invoked on the
* main thread when the user lifts their finger from the screen while on top of the action.
*/
public interface Callback {
void doAction();
}
private ViewGroup root;
private BubbleActionOverlay overlay;
private Method getLastTouchPoint;
private Object viewRootImpl;
private Point touchPoint = new Point();
private boolean showing = false;
Action[] actions = new Action[BubbleActionOverlay.MAX_ACTIONS];
int numActions = 0;
Drawable indicator;
private BubbleActions(ViewGroup root, Drawable indicator) {
this.indicator = indicator;
this.root = root;
overlay = new BubbleActionOverlay(root.getContext());
overlay.setOnDragListener(overlayDragListener);
// Use reflection to get the ViewRootImpl
try {
Method method = root.getClass().getMethod("getViewRootImpl");
viewRootImpl = method.invoke(root);
getLastTouchPoint = viewRootImpl.getClass().getMethod("getLastTouchPoint", Point.class);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
/**
* Opens up BubbleActions on the view argument.
*
* @param view the view that the BubbleActions are contextually connected to. The
* view must have a root view.
* @return a BubbleActions instance
*/
public static BubbleActions on(View view) {
return on(view, R.drawable.bubble_actions_indicator);
}
/**
* Open up BubbleActions on a view using the specified resource id as the indicator.
*
* @param view the view that the BubbleActions are contextually connected to. The
* view must have a root view.
* @param indicatorRes indicator resource id
* @return a BubbleActions instance
*/
public static BubbleActions on(View view, int indicatorRes) {
return on(view, ResourcesCompat.getDrawable(view.getResources(), indicatorRes, view.getContext().getTheme()));
}
/**
* Open up BubbleActions on a view, using the specified drawable as the indicator.
*
* @param view the view that the BubbleActions are contextually connected to. The
* view must have a root view.
* @param indicator indicator drawable
* @return a BubbleActions instance
*/
public static BubbleActions on(View view, Drawable indicator) {
View rootView = view.getRootView();
if (rootView == null) {
throw new IllegalArgumentException("View argument must have a root view.");
}
if (!(rootView instanceof ViewGroup)) {
throw new IllegalArgumentException("View argument must have a ViewGroup root view");
}
return new BubbleActions((ViewGroup) rootView, indicator);
}
/**
* Set the typeface of the labels for the BubbleActions.
*
* @param typeface the typeface to set on the labels
* @return the BubbleActions instance that called this method
*/
public BubbleActions withTypeface(Typeface typeface) {
overlay.setLabelTypeface(typeface);
return this;
}
/**
* Add an action using resource ids. The foreground is usually an icon signifying the action
* that the user will be performing. The background is used to determine shadow, although if the
* foreground does not take up the entire space of the bubble, it can be used to give user
* feedback. Check out the sample app for an example of this. Actions are not limited to
* circles.
*
* @param foregroundRes The content of the bubble action
* @param backgroundRes The background of the bubble action used to determine shadow
* @return the BubbleActions instance that called this method
*/
public BubbleActions addAction(CharSequence actionName, int foregroundRes, int backgroundRes, Callback callback) {
Resources resources = root.getResources();
Resources.Theme theme = root.getContext().getTheme();
addAction(actionName, ResourcesCompat.getDrawable(resources, foregroundRes, theme), ResourcesCompat.getDrawable(resources, backgroundRes, theme), callback);
return this;
}
/**
* Add an action using drawables. See the description at {@link #addAction(CharSequence, int, int, com.sam.bubbleactions.BubbleActions.Callback)} for
* details.
*
* @param foreground The content of the bubble action
* @param background The background of the bubble action used to determine shadow
* @return the BubbleActions instance that called this method
*/
public BubbleActions addAction(CharSequence actionName, Drawable foreground, Drawable background, Callback callback) {
if (numActions >= actions.length) {
throw new IllegalStateException(TAG + ": cannot add more than " + BubbleActionOverlay.MAX_ACTIONS + " actions.");
}
if (foreground == null) {
throw new IllegalArgumentException(TAG + ": the foreground drawable cannot resolve to null.");
}
if (background == null) {
throw new IllegalArgumentException(TAG + ": the background drawable cannot resolve to null.");
}
if (callback == null) {
throw new IllegalArgumentException(TAG + ": the callback must not be null.");
}
actions[numActions] = new Action(actionName, foreground, background, callback);
numActions++;
return this;
}
/**
* Show the bubble actions. Internally this will do 3 things:
* 1. Add the overlay to the root view
* 2. Use reflection to get the last touched xy location
* 3. Animate the overlay in
*/
public void show() {
if (showing) {
return;
}
if (overlay.getParent() == null) {
root.addView(overlay);
}
if (ViewCompat.isLaidOut(overlay)) {
setupAndShow();
} else {
overlay.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
setupAndShow();
overlay.removeOnLayoutChangeListener(this);
}
});
}
}
private void setupAndShow() {
// use reflection to get the last touched xy location
try {
getLastTouchPoint.invoke(viewRootImpl, touchPoint);
overlay.setupOverlay(touchPoint.x, touchPoint.y, this);
} catch (InvocationTargetException e) {
e.printStackTrace();
return;
} catch (IllegalAccessException e) {
e.printStackTrace();
return;
}
showing = true;
overlay.showOverlay();
}
void hideOverlay() {
showing = false;
root.removeView(overlay);
}
private View.OnDragListener overlayDragListener = new View.OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
final int action = event.getAction();
switch (action) {
case DragEvent.ACTION_DRAG_STARTED:
return overlay.dragStarted(event);
case DragEvent.ACTION_DRAG_ENDED:
return overlay.dragEnded(BubbleActions.this);
}
return false;
}
};
/**
* An abstraction of the bubble action. Each action has a foreground and a background drawable,
* as well as a callback.
*/
static class Action {
CharSequence actionName;
Drawable foregroundDrawable;
Drawable backgroundDrawable;
Callback callback;
private Action(CharSequence actionName, Drawable foregroundDrawable, Drawable backgroundDrawable, Callback callback) {
this.actionName = actionName;
this.foregroundDrawable = foregroundDrawable;
this.backgroundDrawable = backgroundDrawable;
this.callback = callback;
}
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-08-25");
this.setApiVersion("17.5.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-09-20");
this.setApiVersion("15.8.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-12-01");
this.setApiVersion("15.12.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package nl.tomudding.plugins.visibility.managers;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import nl.tomudding.plugins.visibility.Visibility;
public class ChatManager {
private static ChatManager instance = new ChatManager();
public static ChatManager getInstance() {
return instance;
}
private Class<?> getNMSClass(String nmsClassName) throws ClassNotFoundException {
return Class.forName("net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3] + "." + nmsClassName);
}
public void log(String s) {
Bukkit.getConsoleSender().sendMessage(ChatColor.BLUE + "Player Visibility >> " + ChatColor.translateAlternateColorCodes('&', s));
}
public void sendMessage(Player player, String message) {
if (Visibility.actionBar) {
try {
if ((Visibility.getServerVersion().equalsIgnoreCase("v1_9_R1")) || (Visibility.getServerVersion().equalsIgnoreCase("v1_9_R2")) || (Visibility.getServerVersion().equalsIgnoreCase("v1_10_R1"))) {
// if the server does not use this version it should have been disabled
Object chatComponentText = getNMSClass("ChatComponentText").getConstructor(new Class[] { String.class }).newInstance(new Object[] { ChatColor.translateAlternateColorCodes('&', message)});
Class<?> iChatBaseComponent = getNMSClass("IChatBaseComponent");
Object packetPlayOutChat = getNMSClass("PacketPlayOutChat").getConstructor(new Class[] { iChatBaseComponent, Byte.TYPE }).newInstance(new Object[] { chatComponentText, Byte.valueOf((byte) 2) });
Object playerNMS = player.getClass().getMethod("getHandle", new Class[0]).invoke(player, new Object[0]);
Object playerConnection = playerNMS.getClass().getField("playerConnection").get(playerNMS);
Class<?> playerPacket = getNMSClass("Packet");
playerConnection.getClass().getMethod("sendPacket", new Class[] { playerPacket }).invoke(playerConnection, new Object[] { packetPlayOutChat });
}
} catch (Exception exception) {
exception.printStackTrace();
}
} else {
player.sendMessage(ChatColor.translateAlternateColorCodes('&', Visibility.messagePrefix + message));
}
}
public void sendCommandMessage(Player player, String message) {
player.sendMessage(ChatColor.translateAlternateColorCodes('&', message));
}
}
|
package org.opencb.cellbase.app;
import org.opencb.cellbase.app.cli.*;
import java.io.IOException;
import java.net.URISyntaxException;
public class CellBaseMain {
public static final String VERSION = "3.1.0-RC";
public static void main(String[] args) {
CliOptionsParser cliOptionsParser = new CliOptionsParser();
cliOptionsParser.parse(args);
String parsedCommand = cliOptionsParser.getCommand();
if(parsedCommand == null || parsedCommand.isEmpty()) {
if(cliOptionsParser.getGeneralOptions().help) {
cliOptionsParser.printUsage();
}
if(cliOptionsParser.getGeneralOptions().version) {
System.out.println("Version " + VERSION);
}
}else {
CommandExecutor commandExecutor = null;
switch (parsedCommand) {
case "download":
if (cliOptionsParser.getDownloadCommandOptions().commonOptions.help) {
cliOptionsParser.printUsage();
} else {
commandExecutor = new DownloadCommandExecutor(cliOptionsParser.getDownloadCommandOptions());
}
break;
case "build":
if (cliOptionsParser.getBuildCommandOptions().commonOptions.help) {
cliOptionsParser.printUsage();
} else {
commandExecutor = new BuildCommandExecutor(cliOptionsParser.getBuildCommandOptions());
}
break;
case "load":
if (cliOptionsParser.getLoadCommandOptions().commonOptions.help) {
cliOptionsParser.printUsage();
} else {
commandExecutor = new LoadCommandExecutor(cliOptionsParser.getLoadCommandOptions());
}
break;
case "query":
if (cliOptionsParser.getQueryCommandOptions().commonOptions.help) {
cliOptionsParser.printUsage();
} else {
commandExecutor = new QueryCommandExecutor(cliOptionsParser.getQueryCommandOptions());
}
break;
case "variant-annotation":
if (cliOptionsParser.getQueryCommandOptions().commonOptions.help) {
cliOptionsParser.printUsage();
} else {
commandExecutor = new VariantAnnotationCommandExecutor(cliOptionsParser.getVariantAnnotationCommandOptions());
}
break;
default:
break;
}
if (commandExecutor != null) {
try {
commandExecutor.loadCellBaseConfiguration();
commandExecutor.execute();
} catch (IOException | URISyntaxException e) {
commandExecutor.getLogger().error("Error reading CellBase configuration: " + e.getMessage());
}
}
}
}
}
|
package ru.pravvich.start;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import ru.pravvich.models.Item;
public class TrackerTest {
/**
* @see Tracker#addCommit(String, String)
*/
@Test
public void whenCommitAddThenCommitAddInLists() {
Tracker tracker = new Tracker();
// add first obj
Item item = new Item();
item.header = "0";
tracker.add(item);
// add second obj
Item itemSecond = new Item();
itemSecond.header = "1";
tracker.add(itemSecond);
//use method for first item
tracker.addCommit("commit - 0", "0");
tracker.addCommit("commit - 1", "0");
//use method for second item
tracker.addCommit("commit(1) - 0", "1");
String resultForSecondItem = tracker.items[1].getCommits().get(0);
//check
String resultFirstCommitForFirstItem = tracker.items[0].getCommits().get(0);
String resultSecondCommitForFirstItem = tracker.items[0].getCommits().get(1);
assertThat(resultFirstCommitForFirstItem, is("commit - 0"));
assertThat(resultSecondCommitForFirstItem, is("commit - 1"));
assertThat(resultForSecondItem, is("commit(1) - 0"));
}
/**
* @see Tracker#editionCommit(String, String) method
*/
@Test
public void whenNewCommitAndOldCommitInThenMethodFindCommitByOldCommitAndReplaceCommit() {
Tracker tracker = new Tracker();
Item item = new Item();
item.header = "0";
tracker.add(item);
tracker.addCommit("commit - 0", "0");
tracker.addCommit("commit - 1", "0");
//use method
tracker.editionCommit("commit - 0", "Replace");
String result = tracker.items[0].getCommits().get(0);
assertThat(result, is("Replace"));
}
/**
* @see Tracker#deleteCommit(String) method
*/
@Test
public void whenCommitOfStringInThenThisCommitDelete() {
Tracker tracker = new Tracker();
// add first obj
Item item = new Item();
item.header = "0";
tracker.add(item);
// add second obj
Item itemSecond = new Item();
itemSecond.header = "1";
tracker.add(itemSecond);
//use method for first item
tracker.addCommit("commit - 0", "0");
tracker.addCommit("commit - 1", "0");
//check size commits list
tracker.deleteCommit("commit - 0");
int result = tracker.items[0].getCommits().size();
assertThat(result, is(1));
}
/**
* @see Tracker#findById(int) method
*/
@Test
public void whenIdInThenItemWithThisIdOut() {
Tracker tracker = new Tracker();
Item item = new Item();
item.description = "description";
item.header = "header";
tracker.add(item);
int id = item.getId();
Item result = tracker.findById(id);
assertThat(result, is(item));
}
/**
* @see Tracker#findByHeader(String)
*/
@Test
public void whenHeaderInThenItemWithThisHeaderOut() {
Tracker tracker = new Tracker();
Item item = new Item();
item.description = "description";
item.header = "header";
tracker.add(item);
String header = "header";
Item result = tracker.findByHeader(header);
assertThat(result, is(item));
}
/**
* @see Tracker#findByHeader(String)
* @see Tracker#initMessageNothingFound()
*/
@Test
public void WhenThen() {
Tracker tracker = new Tracker();
Item item = new Item();
item.description = "description";
item.header = "header";
tracker.add(item);
String header = "head";
tracker.findByHeader(header);
String result = tracker.getMessage();
assertThat(result, is("Nothing found./nPlease try again."));
}
/**
* @see Tracker#add(Item) test method
*/
@Test
public void whenObjectTypeItemInThenInArrayItemsInitOneCell() {
Tracker tracker = new Tracker();
Item item = new Item();
item.description = "description";
item.header = "header";
tracker.add(item);
assertThat(tracker.items[0], is(item));
}
/**
* @see Tracker#getMessage() test method
*/
@Test
public void whenAddMethodWorkAndInItemEqualsNullThenGetMessageInitMessage() {
Tracker tracker = new Tracker();
Item item = null;
tracker.add(item);
String result = tracker.getMessage();
String check = "Please header enter.";
assertThat(result, is(check));
}
/**
* @see Tracker#edition(String, String) method
*/
@Test
public void whenHeaderAndDescriptionInThenOldDescriptionReplacement() {
Tracker tracker = new Tracker();
// init and add Item
Item item = new Item();
item.description = "description";
item.header = "header";
tracker.add(item);
// test method
tracker.edition("header", "This is new description");
String result = tracker.items[0].description;
assertThat(result, is("This is new description"));
}
/**
* @see Tracker#edition(String, String) method(if new description == null)
*/
@Test
public void whenDescriptionForReplacementEqualsNullThenInitMessage() {
Tracker tracker = new Tracker();
// init and add Item
Item item = new Item();
item.description = "description";
item.header = "header";
tracker.add(item);
// test method
tracker.edition("header", null);
String result = tracker.getMessage();
String check = "New description enter require.";
assertThat(result, is(check));
}
/**
* @see Tracker#delete(String) checking method
*/
@Test
public void whenMethodWorkThenItemReplacementOnNullAndNullPushInAndArray() {
Tracker tracker = new Tracker();
// init and add first Item
Item itemFirst = new Item();
itemFirst.description = "description";
itemFirst.header = "header";
tracker.add(itemFirst);
// init and add second Item
Item itemSecond = new Item();
itemSecond.description = "description two";
itemSecond.header = "header two";
tracker.add(itemSecond);
//check method
tracker.delete("header");
// init result
Item result = tracker.items[0];
assertThat(result, is(itemSecond));
// test message about delete
String messageResult = tracker.getMessage();
String check = "Task have been deleted.";
assertThat(messageResult, is(check));
}
/**
* @see Tracker#getPrintArray()
*/
@Test
public void whenMethodWorkThenReturnListHeadersAllListsWeHave() {
Tracker tracker = new Tracker();
// init and add first Item
Item itemFirst = new Item();
itemFirst.description = "description";
itemFirst.header = "header";
tracker.add(itemFirst);
// init and add second Item
Item itemSecond = new Item();
itemSecond.description = "description two";
itemSecond.header = "header two";
tracker.add(itemSecond);
//check method
Item[] result = tracker.getPrintArray();
Item[] check = {itemFirst, itemSecond};
assertThat(result, is(check));
}
/**
* @see Tracker#getArrPrintFilter()
*/
@Test
public void whenMethodWorkThenReturnListHeadersInReverseOrder() {
Tracker tracker = new Tracker();
// init and add first Item
Item itemFirst = new Item();
itemFirst.description = "description";
itemFirst.header = "header";
tracker.add(itemFirst);
// init and add second Item
Item itemSecond = new Item();
itemSecond.description = "description two";
itemSecond.header = "header two";
tracker.add(itemSecond);
//check method
Item[] result = tracker.getArrPrintFilter();
Item[] check = {itemSecond, itemFirst};
assertThat(result, is(check));
}
}
|
package com.intellij.codeInsight.lookup;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.CompletionUtil;
import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.template.Template;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.meta.PsiMetaDataBase;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Iterator;
import java.util.Set;
public class LookupItemUtil{
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.lookup.LookupItemUtil");
private LookupItemUtil() {
}
@Nullable
public static LookupItem addLookupItem(Set<LookupItem> set, @NotNull Object object, String prefix) {
return addLookupItem(set, object, prefix, TailType.UNKNOWN);
}
@Nullable
public static LookupItem addLookupItem(Set<LookupItem> set, @NotNull Object object, String prefix, InsertHandler handler) {
LookupItem item = addLookupItem(set, object, prefix, TailType.UNKNOWN);
if (item != null) {
item.setAttribute(LookupItem.INSERT_HANDLER_ATTR, handler);
}
return item;
}
@Nullable
private static LookupItem addLookupItem(Set<LookupItem> set, @NotNull Object object, String prefix, TailType tailType) {
if (object instanceof PsiType) {
PsiType psiType = (PsiType)object;
for (final LookupItem lookupItem : set) {
Object o = lookupItem.getObject();
if (o.equals(psiType)) {
return lookupItem;
}
}
}
for (LookupItem lookupItem : set) {
if(lookupItem.getObject().equals(lookupItem)) return null;
}
LookupItem item = objectToLookupItem(object);
String text = item.getLookupString();
if (CompletionUtil.startsWith(text, prefix)) {
item.setLookupString(text);
if (tailType != TailType.UNKNOWN) {
item.setAttribute(CompletionUtil.TAIL_TYPE_ATTR, tailType);
}
return set.add(item) ? item : null;
}
return null;
}
public static void addLookupItems(Set<LookupItem> set, Object[] objects, String prefix) {
for (Object object : objects) {
LOG.assertTrue(object != null, "Lookup item can't be null!");
addLookupItem(set, object, prefix);
}
}
public static void removeLookupItem(Set<LookupItem> set, Object object) {
Iterator iter = set.iterator();
while (iter.hasNext()) {
LookupItem item = (LookupItem)iter.next();
if (object.equals(item.getObject())) {
iter.remove();
break;
}
}
}
public static boolean containsItem(Set<LookupItem> set, Object object) {
for (final Object aSet : set) {
final LookupItem item = (LookupItem)aSet;
if (object != null && object.equals(item.getObject())) {
return true;
}
}
return false;
}
public static LookupItem objectToLookupItem(Object object) {
if (object instanceof LookupItem) return (LookupItem)object;
String s = null;
LookupItem item = new LookupItem(object, "");
if (object instanceof PsiElement){
PsiElement element = (PsiElement) object;
if(element.getUserData(PsiUtil.ORIGINAL_KEY) != null){
element = element.getUserData(PsiUtil.ORIGINAL_KEY);
object = element;
item = new LookupItem(object, "");
}
s = PsiUtil.getName(element);
}
TailType tailType = TailType.NONE;
if (object instanceof PsiMethod) {
PsiMethod method = (PsiMethod)object;
s = method.getName();
PsiType type = method.getReturnType();
if (type == PsiType.VOID) {
tailType = TailType.SEMICOLON;
}
}
else if (object instanceof PsiPackage) {
tailType = TailType.DOT;
s = StringUtil.notNullize(s);
}
else if (object instanceof PsiKeyword) {
s = ((PsiKeyword)object).getText();
}
else if (object instanceof PsiExpression) {
s = ((PsiExpression)object).getText();
}
else if (object instanceof PsiType) {
PsiType type = (PsiType)object;
final PsiType original = type;
int dim = 0;
while (type instanceof PsiArrayType) {
type = ((PsiArrayType)type).getComponentType();
dim++;
}
if (type instanceof PsiClassType) {
PsiClassType.ClassResolveResult classResolveResult = ((PsiClassType)type).resolveGenerics();
final PsiClass psiClass = classResolveResult.getElement();
final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();
final String text = type.getCanonicalText();
String typeString = text;
if (text.indexOf('<') > 0) {
typeString = text.substring(0, text.indexOf('<'));
}
s = text.substring(typeString.lastIndexOf('.') + 1);
item = psiClass != null ? new LookupItem(psiClass, s) : new LookupItem(text, s);
item.setAttribute(LookupItem.SUBSTITUTOR, substitutor);
}
else {
s = type.getPresentableText();
}
if (dim > 0) {
item.setAttribute(LookupItem.TAIL_TEXT_SMALL_ATTR, "");
item.setAttribute(LookupItem.BRACKETS_COUNT_ATTR, dim);
}
item.setAttribute(LookupItem.TYPE, original);
}
else if (object instanceof PsiMetaDataBase) {
s = ((PsiMetaDataBase)object).getName();
}
else if (object instanceof String) {
s = (String)object;
}
else if (object instanceof Template) {
s = "";
}
else if (object instanceof PresentableLookupValue) {
s = ((PresentableLookupValue)object).getPresentation();
}
if (s == null) {
LOG.assertTrue(false, "Null string for object: " + object + " of class " + (object != null ?object.getClass():null));
}
if (object instanceof LookupValueWithTail) {
item.setAttribute(LookupItem.TAIL_TEXT_ATTR, " " + ((LookupValueWithTail)object).getTailText());
}
item.setLookupString(s);
item.setAttribute(CompletionUtil.TAIL_TYPE_ATTR, tailType);
return item;
}
public static int doSelectMostPreferableItem(final LookupItemPreferencePolicy itemPreferencePolicy,
final String prefix,
Object[] items) {
if (itemPreferencePolicy == null){
return -1;
}
else{
itemPreferencePolicy.setPrefix(prefix);
LookupItem prefItem = null;
int prefItemIndex = -1;
for(int i = 0; i < items.length; i++){
LookupItem item = (LookupItem)items[i];
final Object obj = item.getObject();
if (obj instanceof PsiElement && !((PsiElement)obj).isValid()) continue;
if (prefItem == null){
prefItem = item;
prefItemIndex = i;
}
else{
int d = itemPreferencePolicy.compare(item, prefItem);
if (d < 0){
prefItem = item;
prefItemIndex = i;
}
}
}
return prefItem != null ? prefItemIndex : -1;
}
}
}
|
package org.duracloud.common.queue.task;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a basic unit of work. In essence it describes "what" is to be
* done. It knows nothing of the "how".
*
* @author Daniel Bernstein
*
*/
public class Task {
public static final String KEY_TYPE = "type";
public enum Type {
BIT, BIT_REPORT, BIT_ERROR, DUP, AUDIT, NOOP;
}
private Type type;
private Map<String, String> properties = new HashMap<>();
private Integer visibilityTimeout;
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Map<String, String> getProperties() {
return properties;
}
public String getProperty(String key) {
return properties.get(key);
}
public void addProperty(String key, String value) {
properties.put(key, value);
}
public String removeProperty(String key) {
return properties.remove(key);
}
public Integer getVisibilityTimeout() {
return visibilityTimeout;
}
public void setVisibilityTimeout(Integer visibilityTimeout) {
this.visibilityTimeout = visibilityTimeout;
}
/**
* The number of completed attempts to process this task.
* @return
*/
public int getAttempts() {
String attempts = this.properties.get("attempts");
if(attempts == null){
attempts = "0";
}
return Integer.parseInt(attempts);
}
/**
* Increments the attempts property. This method should only be called by
* TaskQueue implementations.
*/
public void incrementAttempts() {
int attempts = getAttempts()+1;
this.properties.put("attempts", attempts+"");
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
package com.namelessmc.plugin.common;
import com.google.gson.JsonObject;
import com.namelessmc.java_api.NamelessAPI;
import com.namelessmc.java_api.exception.ApiError;
import com.namelessmc.java_api.exception.ApiException;
import com.namelessmc.java_api.exception.NamelessException;
import com.namelessmc.plugin.common.audiences.NamelessPlayer;
import com.namelessmc.plugin.common.command.AbstractScheduledTask;
import com.namelessmc.plugin.common.event.NamelessJoinEvent;
import com.namelessmc.plugin.common.event.NamelessPlayerQuitEvent;
import com.namelessmc.plugin.common.logger.AbstractLogger;
import org.checkerframework.checker.initialization.qual.UnknownInitialization;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurationNode;
import java.time.Duration;
import java.util.*;
public abstract class AbstractDataSender implements Runnable, Reloadable {
private final @NonNull NamelessPlugin plugin;
private @Nullable AbstractScheduledTask dataSenderTask;
private @Nullable List<@NonNull InfoProvider> globalInfoProviders;
private @Nullable List<@NonNull PlayerInfoProvider> playerInfoProviders;
private int serverId;
private final @NonNull Map<UUID, Long> playerLoginTime = new HashMap<>();
protected AbstractDataSender(final @NonNull NamelessPlugin plugin) {
this.plugin = plugin;
this.startLoginTimeTracking();
}
private void startLoginTimeTracking(@UnknownInitialization(AbstractDataSender.class) AbstractDataSender this) {
this.plugin.registerReloadable(new Reloadable() {
@Override
public void unload() {}
@Override
public void load() {
// If the plugin is loaded when the server is already started (e.g. using /reload on bukkit), add
// players manually because the join event is never called for them.
for (final NamelessPlayer player : AbstractDataSender.this.plugin.audiences().onlinePlayers()) {
if (!playerLoginTime.containsKey(player.uuid())) {
playerLoginTime.put(player.uuid(), System.currentTimeMillis());
}
};
}
});
this.plugin.events().subscribe(NamelessJoinEvent.class, event ->
playerLoginTime.put(event.player().uuid(), System.currentTimeMillis()));
this.plugin.events().subscribe(NamelessPlayerQuitEvent.class, event ->
playerLoginTime.remove(event.uuid()));
}
protected @NonNull NamelessPlugin getPlugin() {
return this.plugin;
}
@Override
public void unload() {
if (this.dataSenderTask != null) {
this.playerInfoProviders = null;
this.globalInfoProviders = null;
this.dataSenderTask.cancel();
this.dataSenderTask = null;
}
}
@Override
public void load() {
final CommentedConfigurationNode config = this.plugin.config().main().node("server-data-sender");
if (!config.node("enabled").getBoolean()) {
return;
}
this.serverId = config.node("server-id").getInt();
if (this.serverId <= 0) {
this.plugin.logger().warning("Server data sender is configured with invalid server id");
return;
}
final Duration interval = ConfigurationHandler.getDuration(config.node("interval"));
if (interval == null) {
this.plugin.logger().warning("Invalid server data sender interval.");
return;
}
this.dataSenderTask = this.plugin.scheduler().runTimer(this, interval);
this.globalInfoProviders = new ArrayList<>();
this.playerInfoProviders = new ArrayList<>();
this.registerBaseProviders();
this.registerCustomProviders();
}
private @NonNull JsonObject buildJsonBody() {
final List<InfoProvider> globalInfoProviders = this.globalInfoProviders;
final List<PlayerInfoProvider> playerInfoProviders = this.playerInfoProviders;
if (globalInfoProviders == null || playerInfoProviders == null) {
throw new IllegalStateException("Providers are null, is the data sender disabled?");
}
final JsonObject data = new JsonObject();
data.addProperty("server-id", this.serverId);
data.addProperty("time", System.currentTimeMillis());
for (final InfoProvider infoProvider : globalInfoProviders) {
try {
infoProvider.addInfoToJson(data);
} catch (final Exception e) {
e.printStackTrace();
}
}
final JsonObject players = new JsonObject();
for (final NamelessPlayer player : this.plugin.audiences().onlinePlayers()) {
JsonObject playerJson = new JsonObject();
playerJson.addProperty("name", player.username());
for (PlayerInfoProvider infoProvider : playerInfoProviders) {
try {
infoProvider.addInfoToJson(playerJson, player);
} catch (final Exception e) {
e.printStackTrace();
}
}
players.add(player.websiteUuid(), playerJson);
}
data.add("players", players);
return data;
}
@Override
public void run() {
final JsonObject data = buildJsonBody();
this.plugin.logger().fine(() -> "Sending server data to website: " + data);
this.plugin.scheduler().runAsync(() -> {
final NamelessAPI api = this.plugin.apiProvider().api();
if (api == null) {
return;
}
final AbstractLogger logger = this.plugin.logger();
try {
api.submitServerInfo(data);
} catch (final NamelessException e) {
if (e instanceof ApiException && ((ApiException) e).apiError() == ApiError.CORE_INVALID_SERVER_ID) {
logger.warning("Server ID is incorrect. Please enter a correct server ID or disable the server data sender.");
} else {
logger.logException(e);
}
}
});
}
protected void registerGlobalInfoProvider(InfoProvider globalInfoProvider) {
if (this.globalInfoProviders == null) {
throw new IllegalStateException("Cannot register info provider when data sender is disabled");
}
this.globalInfoProviders.add(globalInfoProvider);
}
protected void registerPlayerInfoProvider(PlayerInfoProvider playerInfoProvider) {
if (this.playerInfoProviders == null) {
throw new IllegalStateException("Cannot register info provider when data sender is disabled");
}
this.playerInfoProviders.add(playerInfoProvider);
}
protected abstract void registerCustomProviders();
private void registerBaseProviders() {
this.registerGlobalInfoProvider(json -> {
json.addProperty("free-memory", Runtime.getRuntime().freeMemory());
json.addProperty("max-memory", Runtime.getRuntime().maxMemory());
json.addProperty("allocated-memory", Runtime.getRuntime().totalMemory());
});
final ConfigurationNode commands = this.plugin.config().commands();
if (commands.hasChild("verify")) {
final String verifyCommand = "/" + commands.node("verify").getString();
this.registerGlobalInfoProvider(json -> json.addProperty("verify_command", verifyCommand));
}
this.registerPlayerInfoProvider((json, player) -> {
Long loginTime = this.playerLoginTime.get(player.uuid());
if (loginTime == null) {
this.plugin.logger().warning("Player " + player.username() + " is missing from login time map. If the plugin was loaded normally (e.g. not using a plugin manager), this is probably a bug.");
loginTime = System.currentTimeMillis();
}
json.addProperty("login-time", loginTime);
});
final AbstractPermissions permissions = this.plugin.permissions();
if (permissions != null) {
this.registerPlayerInfoProvider(permissions);
this.registerGlobalInfoProvider(permissions);
}
}
@FunctionalInterface
public interface InfoProvider {
void addInfoToJson(final @NonNull JsonObject json);
}
@FunctionalInterface
public interface PlayerInfoProvider {
void addInfoToJson(final @NonNull JsonObject json, final @NonNull NamelessPlayer player);
}
}
|
package com.comsysto.common.util;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
/**
* @author zutherb
*/
public class SeoUtilsTest {
@Test
public void testUrlFriendly() throws Exception {
String sentence = new String("Männer fahren gerne mit dem Floß und springen über Möhren, daß ist schön. [ ] 12.01.2012 ?*#.".getBytes(), "UTF8");
String urlfriendly = SeoUtils.urlFriendly(sentence);
assertEquals(new String("maenner-fahren-gerne-mit-dem-floss-und-springen-ueber-moehren-dass-ist-schoen-12-01-2012".getBytes(), "UTF8"), urlfriendly);
}
}
|
package loci.common.utests;
import loci.common.IniParser;
import loci.common.IniList;
import loci.common.IniTable;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Unit tests for {@link loci.common.IniParser}.
*/
public class IniParserTest {
private final IniParser parser = new IniParser();
private final Charset utf8charset = Charset.forName("UTF-8");
public BufferedReader stringToBufferedReader(String s) {
InputStream stream = new ByteArrayInputStream(s.getBytes(utf8charset));
return new BufferedReader(new InputStreamReader(stream));
}
@DataProvider(name = "simplekeyvalue")
public Object[][] createSimpleKeyValuePair() {
return new Object[][] {
{"key=value"},
{"key = value"}, // whitespaces around equal sign
{"key=value "}, // trailing whitespace
{" key=value"}, // leading whitespace
{"key=value#comment"}, // comment without whitespaces
{"key=value # comment"}, // comment with whitespaces
};
}
@Test(dataProvider="simplekeyvalue")
public void testSimpleKeyValue(String s) throws IOException {
BufferedReader reader = stringToBufferedReader(s);
IniTable table = new IniTable();
table.put(IniTable.HEADER_KEY, IniTable.DEFAULT_HEADER);
table.put("key", "value");
IniList list = new IniList();
list.add(table);
assertEquals(parser.parseINI(reader), list);
}
@DataProvider(name = "simpleheader")
public Object[][] createSimpleHeader() {
return new Object[][] {
{"key=value", IniTable.DEFAULT_HEADER},
{"[\nkey=value", IniTable.DEFAULT_HEADER},
{"{\nkey=value", IniTable.DEFAULT_HEADER},
{"{chapter}\nkey=value", IniTable.DEFAULT_HEADER},
{"{}\nkey=value", IniTable.DEFAULT_HEADER},
{"[]\nkey=value", ""},
{"[header]\nkey=value", "header"},
{"[ header ]\nkey=value", " header "},
{"[header\nkey=value", "header"},
{"[[header]]\nkey=value", "[header]"},
{"{chapter}\n[header]\nkey=value", "chapter: header"},
{"{chapter\n[header\nkey=value", "chapter: header"},
};
}
@Test(dataProvider="simpleheader")
public void testHeader(String s, String header) throws IOException {
BufferedReader reader = stringToBufferedReader(s);
IniTable table = new IniTable();
table.put(IniTable.HEADER_KEY, header);
table.put("key", "value");
IniList list = new IniList();
list.add(table);
assertEquals(parser.parseINI(reader), list);
}
@DataProvider(name = "invalidheader")
public Object[][] createSingleString() {
return new Object[][] {
{"["}, {"{"}
};
}
@Test(dataProvider="invalidheader")
public void testInvalidHeader(String s) throws IOException {
BufferedReader reader = stringToBufferedReader(s);
IniTable table = new IniTable();
table.put(IniTable.HEADER_KEY, IniTable.DEFAULT_HEADER);
IniList list = new IniList();
list.add(table);
assertEquals(parser.parseINI(reader), list);
}
public void testEmptyString() throws IOException {
BufferedReader reader = stringToBufferedReader("");
assertEquals(parser.parseINI(reader), new IniTable());
}
public void testNull() throws IOException {
BufferedReader reader = stringToBufferedReader(null);
assertEquals(parser.parseINI(reader), new IniTable());
}
public void testEmptyKeyValue() throws IOException {
BufferedReader reader = stringToBufferedReader("=");
IniTable table = new IniTable();
table.put(IniTable.HEADER_KEY, IniTable.DEFAULT_HEADER);
table.put("", "");
IniList list = new IniList();
list.add(table);
assertEquals(parser.parseINI(reader), list);
}
@Test
public void testMultiValueINI() throws IOException {
String s = "key1=value1 # comment\n\n" +
"key2=line1\\\nline2\n" +
"ignored line\n" +
"key3 = value3";
BufferedReader reader = stringToBufferedReader(s);
IniTable table = new IniTable();
table.put(IniTable.HEADER_KEY, IniTable.DEFAULT_HEADER);
table.put("key1", "value1");
table.put("key2", "line1 line2");
table.put("key3", "value3");
IniList list = new IniList();
list.add(table);
assertEquals(parser.parseINI(reader), list);
}
@Test
public void testMultiHeaderINI() throws IOException {
String s = "key0=value0\n" +
"[header1]\nkey1=value1\n" +
"{chapter}\n[header2]\nkey2=value2\n" +
"[header3]\nkey3=value3\n";
BufferedReader reader = stringToBufferedReader(s);
IniTable table0 = new IniTable();
table0.put(IniTable.HEADER_KEY, IniTable.DEFAULT_HEADER);
table0.put("key0", "value0");
IniTable table1 = new IniTable();
table1.put(IniTable.HEADER_KEY, "header1");
table1.put("key1", "value1");
IniTable table2 = new IniTable();
table2.put(IniTable.HEADER_KEY, "chapter: header2");
table2.put("key2", "value2");
IniTable table3 = new IniTable();
table3.put(IniTable.HEADER_KEY, "chapter: header3");
table3.put("key3", "value3");
IniList list = new IniList();
list.add(table0);
list.add(table1);
list.add(table2);
list.add(table3);
assertEquals(parser.parseINI(reader), list);
}
}
|
package de.pretrendr.service;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.AnonymousAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.google.common.collect.Lists;
import de.pretrendr.PretrendrTestBase;
import de.pretrendr.businesslogic.S3Service;
import de.pretrendr.businesslogic.S3ServiceImpl;
import de.pretrendr.model.CachedS3Bucket;
import de.pretrendr.model.CachedS3Object;
import de.pretrendr.model.CachedS3WordCountPair;
import de.pretrendr.model.CachedS3WordCountPair.CachedS3WordCountPairId;
import io.findify.s3mock.S3Mock;
public class S3ServiceTest extends PretrendrTestBase {
private final String BUCKETNAME = "test-bucket-name";
S3Mock api = new S3Mock.Builder().withPort(8001).withInMemoryBackend().build();
S3Service s3Service;
AmazonS3 client = null;
private CachedS3Bucket bucket;
private List<CachedS3Object> objects;
private List<CachedS3WordCountPairId> wordCountPairs;
@Before
public void setup() throws Exception {
if (client == null) {
EndpointConfiguration endpoint = new EndpointConfiguration("http://localhost:8001", "us-east-1");
client = AmazonS3ClientBuilder.standard().withPathStyleAccessEnabled(true)
.withEndpointConfiguration(endpoint)
.withCredentials(new AWSStaticCredentialsProvider(new AnonymousAWSCredentials())).build();
api.start();
client.createBucket(BUCKETNAME);
String n = System.lineSeparator();
client.putObject(BUCKETNAME, "file0001",
"word1\t1" + n + "word2\t2" + n + "word3\t3" + n + "word4\t4" + n + "");
client.putObject(BUCKETNAME, "file0002",
"word11\t1" + n + "word12\t2" + n + "word13\t3" + n + "word14\t4" + n);
client.putObject(BUCKETNAME, "file0003", "word24\t1" + n + "word23\t2" + n + "word22\t3" + n + "word21\t4");
client.putObject(BUCKETNAME, "file0004", "word31\t1" + n + "word34\t2" + n + "word32\t3" + n + "word33\t4");
client.putObject(BUCKETNAME, "file0005", "word43\t1" + n + "word42\t2" + n + "word41\t3" + n + "word44\t4");
s3Service = new S3ServiceImpl(client);
}
cachedS3BucketDAO.deleteAll();
cachedS3ObjectDAO.deleteAll();
cachedS3WordCountPairDAO.deleteAll();
bucket = new CachedS3Bucket(BUCKETNAME);
// cachedS3BucketDAO.save(new CachedS3Bucket(BUCKETNAME));
bucket.getObjects()
.addAll(Lists.newArrayList(new CachedS3Object(this.bucket, "file0001"),
new CachedS3Object(this.bucket, "file0002"), new CachedS3Object(this.bucket, "file0003"),
new CachedS3Object(this.bucket, "file0004")));
bucket.getWordCount()
.addAll(Lists.newArrayList(new CachedS3WordCountPair(bucket, "word1", 1),
new CachedS3WordCountPair(bucket, "word2", 2), new CachedS3WordCountPair(bucket, "word3", 3),
new CachedS3WordCountPair(bucket, "word4", 4), new CachedS3WordCountPair(bucket, "word5", 5)));
this.bucket = cachedS3BucketDAO.save(bucket);
}
@Test
public void test() throws Exception {
// s3Service.getWordCountMapFromBucketName(BUCKETNAME);
}
}
|
package org.intermine.bio.web.displayer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.intermine.api.InterMineAPI;
import org.intermine.api.results.ResultElement;
import org.intermine.api.util.PathUtil;
import org.intermine.model.bio.DataSet;
import org.intermine.model.bio.Gene;
import org.intermine.model.bio.Homologue;
import org.intermine.model.bio.Organism;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathException;
import org.intermine.web.displayer.ReportDisplayer;
import org.intermine.web.logic.config.ReportDisplayerConfig;
import org.intermine.web.logic.results.ReportObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Displayer for Homology
* @author Richard Smith
*/
public class HomologueDisplayer extends ReportDisplayer
{
protected static final Logger LOG = Logger.getLogger(HomologueDisplayer.class);
/**
* Construct with config information read from webconfig-model.xml and the API.
* @param config config information
* @param im the InterMine API
*/
public HomologueDisplayer(ReportDisplayerConfig config, InterMineAPI im) {
super(config, im);
}
@Override
public void display(HttpServletRequest request, ReportObject reportObject) {
Map<String, Set<ResultElement>> homologues =
new TreeMap<String, Set<ResultElement>>();
Map<String, String> organismIds = new HashMap<String, String>();
Path symbolPath = null;
Path primaryIdentifierPath = null;
try {
symbolPath = new Path(im.getModel(), "Gene.symbol");
primaryIdentifierPath = new Path(im.getModel(), "Gene.primaryIdentifier");
} catch (PathException e) {
return;
}
Gene gene = (Gene) reportObject.getObject();
Set<String> dataSets = new HashSet<String>();
JSONObject params = config.getParameterJson();
try {
JSONArray dataSetsArray = params.getJSONArray("dataSets");
for (int i = 0; i < dataSetsArray.length(); i++) {
dataSets.add(dataSetsArray.getString(i));
}
} catch (JSONException e) {
throw new RuntimeException("Error parsing configuration value 'dataSets'", e);
}
for (Homologue homologue : gene.getHomologues()) {
for (DataSet dataSet : homologue.getDataSets()) {
if (dataSets.contains(dataSet.getName())) {
Organism org = homologue.getHomologue().getOrganism();
organismIds.put(org.getSpecies(), org.getId().toString());
try {
if (PathUtil.resolvePath(symbolPath, homologue.getHomologue()) != null) {
ResultElement re = new ResultElement(homologue.getHomologue(),
symbolPath, true);
addToMap(homologues, org.getShortName(), re);
} else {
ResultElement re = new ResultElement(homologue.getHomologue(),
primaryIdentifierPath, true);
addToMap(homologues, org.getShortName(), re);
}
} catch (PathException e) {
LOG.error("Failed to resolve path: " + symbolPath + " for gene: " + gene);
}
}
}
}
request.setAttribute("organismIds", organismIds);
request.setAttribute("homologues", homologues);
}
private void addToMap(Map<String, Set<ResultElement>> homologues, String species,
ResultElement re) {
Set<ResultElement> speciesHomologues = homologues.get(species);
if (speciesHomologues == null) {
speciesHomologues = new HashSet<ResultElement>();
homologues.put(species, speciesHomologues);
}
if (re != null) {
speciesHomologues.add(re);
}
}
}
|
package org.biojava.nbio.phosphosite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
public class Site {
private final static Logger logger = LoggerFactory.getLogger(Site.class);
public Site(){
}
public static List<Site> parseSites(File f) throws IOException {
InputStream inStream = new FileInputStream(f);
InputStream gzipStream = new GZIPInputStream(inStream);
Reader decoder = new InputStreamReader(gzipStream);
BufferedReader buf = new BufferedReader(decoder);
String line = null;
List<Site > data = new ArrayList<Site>();
List<String> headerFields = null;
int proteinIndex = -1;
int uniprotIndex = -1;
int residueIndex = -1;
int orgIndex = -1;
int groupIndex = -1;
int geneIndex = -1;
boolean inHeader = true;
while ((line = buf.readLine()) != null){
if ( line.startsWith("GENE") ||
line.startsWith("PROTEIN")) {
headerFields = parseHeaderFields(line);
proteinIndex = headerFields.indexOf("PROTEIN");
uniprotIndex = headerFields.indexOf("ACC_ID");
residueIndex = headerFields.indexOf("MOD_RSD");
orgIndex = headerFields.indexOf("ORGANISM");
groupIndex = headerFields.indexOf("SITE_GRP_ID");
geneIndex = headerFields.indexOf("GENE");
inHeader = false;
continue;
}
if ( inHeader)
continue;
if ( line.trim().length() == 0)
continue;
// fields are:
String[] spl = line.split("\t");
if ( spl.length < 5){
logger.info("Found wrong line length: " + line);
continue;
}
String protein = spl[proteinIndex];
String uniprot = spl[uniprotIndex];
String residue = spl[residueIndex];
String[] resSpl = residue.split("-");
String modType = null;
if ( resSpl.length == 2) {
modType = resSpl[1];
}
String group = spl[groupIndex];
String organism = spl[orgIndex];
String geneSymb = spl[geneIndex];
Site s = new Site();
s.setProtein(protein);
s.setUniprot(uniprot);
s.setGeneSymb(geneSymb);
s.setModType(modType);
s.setResidue(residue);
s.setGroup(group);
s.setOrganism(organism);
data.add(s);
}
buf.close();
return data;
}
private static List<String> parseHeaderFields(String line) {
String[] spl = line.split("\t");
List<String> h = new ArrayList<String>();
for (String s: spl){
h.add(s);
}
return h;
}
String protein;
String uniprot;
String geneSymb;
String chrLoc;
String modType;
String residue ;
String group;
String organism;
public String getProtein() {
return protein;
}
public void setProtein(String protein) {
this.protein = protein;
}
public String getUniprot() {
return uniprot;
}
public void setUniprot(String uniprot) {
this.uniprot = uniprot;
}
public String getGeneSymb() {
return geneSymb;
}
public void setGeneSymb(String geneSymb) {
this.geneSymb = geneSymb;
}
public String getChrLoc() {
return chrLoc;
}
public void setChrLoc(String chrLoc) {
this.chrLoc = chrLoc;
}
public String getModType() {
return modType;
}
public void setModType(String modType) {
this.modType = modType;
}
public String getResidue() {
return residue;
}
public void setResidue(String residue) {
this.residue = residue;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getOrganism() {
return organism;
}
public void setOrganism(String organism) {
this.organism = organism;
}
@Override
public String toString() {
StringBuffer s = new StringBuffer();
s.append("Site{" +
"protein='" + protein + '\'');
if ( uniprot != null)
s.append(", uniprot='" + uniprot + '\'' );
if ( geneSymb != null)
s.append(
", geneSymb='" + geneSymb + '\'' );
if (chrLoc != null)
s.append(", chrLoc='" + chrLoc + '\'' );
if (modType != null)
s.append(", modType='" + modType + '\'' );
if (residue != null)
s.append( ", residue='" + residue + '\'' );
if ( group != null)
s.append(", group='" + group + '\'' );
if (organism != null)
s.append(", organism='" + organism + '\'' );
s.append( '}');
return s.toString();
}
}
|
package org.flymine.task;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
import java.io.File;
import org.flymine.metadata.Model;
import org.flymine.codegen.AxisModelOutput;
import org.flymine.codegen.OJBModelOutput;
import org.flymine.codegen.JavaModelOutput;
import org.flymine.codegen.ModelOutput;
import org.flymine.codegen.CastorModelOutput;
import org.flymine.codegen.OJBTorqueModelOutput;
import org.flymine.codegen.FlyMineTorqueModelOutput;
/**
* Creates and runs a ModelOutput process to generate java or config files.
*
* @author Richard Smith
*/
public class ModelOutputTask extends Task
{
protected File destDir;
protected Model model;
protected String type;
/**
* Sets the directory that output should be written to.
* @param destDir the directory location
*/
public void setDestDir(File destDir) {
this.destDir = destDir;
}
/**
* Set the type of model output required.
* @param type the type of output
*/
public void setType(String type) {
this.type = type.toLowerCase();
}
/**
* Set the model to be used.
* @param modelName the model to be used
*/
public void setModel(String modelName) {
try {
model = Model.getInstanceByName(modelName);
} catch (Exception e) {
throw new BuildException(e);
}
}
/**
* @see Task#execute
* @throws BuildException
*/
public void execute() throws BuildException {
if (this.destDir == null) {
throw new BuildException("destDir attribute is not set");
}
if (this.type == null) {
throw new BuildException("type attribute is not set");
}
if (this.model == null) {
throw new BuildException("model attribute is not set");
}
ModelOutput mo = null;
try {
if (type.equals("wsdd")) {
mo = new AxisModelOutput(model, destDir);
} else if (type.equals("ojb")) {
mo = new OJBModelOutput(model, destDir);
} else if (type.equals("java")) {
mo = new JavaModelOutput(model, destDir);
} else if (type.equals("castor")) {
mo = new CastorModelOutput(model, destDir);
} else if (type.equals("ojbtorque")) {
mo = new OJBTorqueModelOutput(model, destDir);
} else if (type.equals("flyminetorque")) {
mo = new FlyMineTorqueModelOutput(model, destDir);
} else {
throw new BuildException("Unrecognised value for output type: " + type);
}
} catch (Exception e) {
throw new BuildException(e);
}
if (mo != null) {
mo.process();
} else {
throw new BuildException("Error building ModelOutput");
}
}
}
|
package org.flymine.web.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.digester.*;
import org.xml.sax.SAXException;
/**
* Configuration object for web site
*
* @author Andrew Varley
*/
public class WebConfig
{
private Map types = new HashMap();
/**
* Parse a WebConfig XML file
*
* @param is the InputStream to parse
* @return a WebConfig object
* @throws SAXException if there is an error in the XML file
* @throws IOException if there is an error reading the XML file
*/
public static WebConfig parse(InputStream is)
throws IOException, SAXException {
if (is == null) {
throw new NullPointerException("Parameter 'is' cannot be null");
}
Digester digester = new Digester();
digester.setValidating(false);
digester.addObjectCreate("webconfig", WebConfig.class);
digester.addObjectCreate("webconfig/class", Type.class);
digester.addSetProperties("webconfig/class", "name", "name");
digester.addObjectCreate("webconfig/class/shortdisplayers/displayer", Displayer.class);
digester.addSetProperties("webconfig/class/shortdisplayers/displayer", "src", "src");
digester.addSetNext("webconfig/class/shortdisplayers/displayer", "addShortDisplayer");
digester.addObjectCreate("webconfig/class/longdisplayers/displayer", Displayer.class);
digester.addSetProperties("webconfig/class/longdisplayers/displayer", "src", "src");
digester.addSetNext("webconfig/class/longdisplayers/displayer", "addLongDisplayer");
digester.addSetNext("webconfig/class", "addType");
return (WebConfig) digester.parse(is);
}
/**
* Add a type
*
* @param type the Type to add
*/
public void addType(Type type) {
types.put(type.getName(), type);
}
/**
* Get the types
*
* @return the types
*/
public Map getTypes() {
return this.types;
}
/**
* @see Object#equals
*
* @param obj the Object to compare with
* @return true if this is equal to obj
*/
public boolean equals(Object obj) {
if (!(obj instanceof WebConfig)) {
return false;
}
return types.equals(((WebConfig) obj).types);
}
/**
* @see Object#hashCode
*
* @return the hashCode for this WebConfig object
*/
public int hashCode() {
return types.hashCode();
}
}
|
package github.banana.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* demo
*/
public class DemoServer extends Thread {
private static final CountDownLatch latch = new CountDownLatch(1);
private static volatile boolean isRunning = true;
private ServerSocket serverSocket;
private int getPort() {
return serverSocket.getLocalPort();
}
@Override
public void run() {
try {
serverSocket = new ServerSocket(0);
latch.countDown();
System.out.println("port: " + serverSocket.getLocalPort());
ExecutorService executorService = Executors.newFixedThreadPool(5);
while (isRunning) {
executorService.execute(new RequestHandler(serverSocket.accept()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.exit(0);
}
public static void main(String[] args) throws IOException {
DemoServer server = new DemoServer();
server.start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Server start...");
for (int i = 0; i < 10; i++) {
try (Socket client = new Socket("127.0.0.1", server.getPort())) {
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
reader.lines().forEach(line -> System.out.println("READ: " + line));
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isRunning = false;
new Socket("127.0.0.1", server.getPort());
}
}
class RequestHandler extends Thread {
private Socket socket;
public RequestHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (PrintWriter out = new PrintWriter(socket.getOutputStream())) {
out.println("DATE: " + new Date());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
// RobotComm - UDP based communications for robot status and commands.
package com.rinworks.robotutils;
import java.io.Closeable;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import com.rinworks.robotutils.RobotComm.DatagramTransport.RemoteNode;
import com.rinworks.robotutils.RobotComm.MessageHeader.CmdStatus;
import com.rinworks.robotutils.RobotComm.SentCommand.COMMAND_STATUS;
/**
* Class to implement simple 2-way message passing over UDP
*
*/
public class RobotComm implements Closeable {
private static final String PROTOCOL_SIGNATURE = "3wIC"; // About 1 of 10E7 combnations.
private final DatagramTransport transport;
private final StructuredLogger.Log log;
private boolean commClosed; // set to false when close() is called.
private final ConcurrentHashMap<String, ChannelImplementation> channels;
private final Object listenLock;
private final Random cmdIdRand; // Used for generating command Ids
private volatile DatagramTransport.Listener listener;
interface Address {
String stringRepresentation();
};
interface SentCommand {
enum COMMAND_STATUS {
STATUS_SUBMITTED, STATUS_REMOTE_QUEUED, STATUS_REMOTE_COMPUTING, STATUS_COMPLETED, STATUS_REMOTE_REJECTED, STATUS_ERROR_TIMEOUT, STATUS_ERROR_COMM, STATUS_CLIENT_CANCELED
}
// These are set when the command is submitted.
long cmdId();
String cmdType();
String command();
long submittedTime();
// Status can be checked anytime.
COMMAND_STATUS status();
// True if the command is still pending.
default boolean pending() {
COMMAND_STATUS stat = status();
return stat == COMMAND_STATUS.STATUS_SUBMITTED || stat == COMMAND_STATUS.STATUS_REMOTE_QUEUED
|| stat == COMMAND_STATUS.STATUS_REMOTE_COMPUTING;
}
// These three fields only return valid values if the status
// is STATUS_COMPLETED
String respType();
String response();
long respondedTime();
void cancel();
}
public interface ReceivedMessage {
String message();
String msgType();
Address remoteAddress();
long receivedTimestamp(); // when it was received.
Channel channel();
}
interface ReceivedCommand extends ReceivedMessage {
long cmdId();
void respond(String respType, String resp);
}
public interface Channel extends Closeable {
String name();
void startReceivingMessages();
void stopReceivingMessages(); // will drop incoming messages in queue
void startReceivingCommands();
void stopReceivingCommands(); // will drop incoming commands in queue
// This channel will only communicate with the specified remote node,
// including received messages and commands.
// Can be changed on the fly. Set to null to clear.
void bindToRemoteNode(Address remoteAddress);
Address remoteAddress(); // Can be null
ReceivedMessage pollReceivedMessage();
ReceivedCommand pollReceivedCommand();
// Will drop message if not bound to a remote node.
void sendMessage(String msgType, String message);
void sendMessage(String msgType, String message, Address addr);
SentCommand sendCommand(String cmdType, String command, boolean addToCompletionQueue);
SentCommand pollCompletedCommand();
void close();
}
public interface DatagramTransport extends Closeable {
interface RemoteNode {
Address remoteAddress();
void send(String msg);
}
interface Listener extends Closeable {
/**
* Listens for messages.
*
* @param handler
* called when a message arrives. Will likely be called in some other
* thread's context. The handler is expected NOT to block. If time
* consuming operations need to be performed, queue the message for
* further processing, or implement a state machine. The handler
* *may* be reentered or called concurrently from another thread.
* Call close to stop new messages from being received.
*/
void listen(BiConsumer<String, RemoteNode> handler);
Address getAddress();
void close(); // idempotent. handler MAY get called after close() returns.
}
Address resolveAddress(String address);
Listener newListener(Address localAddress);
RemoteNode newRemoteNode(Address remoteAddress);
void close(); // Closes all open listeners and remote notes.
}
public RobotComm(DatagramTransport transport, StructuredLogger.Log log) {
this.transport = transport;
this.log = log;
this.listenLock = new Object();
this.cmdIdRand = new Random();
this.channels = new ConcurrentHashMap<>();
}
public Address resolveAddress(String address) {
return this.transport.resolveAddress(address);
}
/*
* Channels must be unique. An attempt to create a channel that already exists
* produces a DuplicateKey exception
*/
public Channel newChannel(String channelName) {
if (commClosed) {
throw new IllegalStateException("Robot comm is closed!");
}
final String BAD_CHANNEL_CHARS = ", \t\f\r\n";
if (containsChars(channelName, BAD_CHANNEL_CHARS)) {
throw new IllegalArgumentException("channel name has invalid characters: " + channelName);
}
ChannelImplementation ch = this.channels.get(channelName);
if (ch != null) {
throw new UnsupportedOperationException("Channel with name " + channelName + " exists");
} else {
ch = new ChannelImplementation(channelName);
ChannelImplementation prevCh = this.channels.put(channelName, ch);
if (prevCh != null) {
ch = prevCh;
}
}
return ch;
}
// Idempotent, thread safe
public void startListening() {
DatagramTransport.Listener listener = null;
synchronized (listenLock) {
if (this.listener == null) {
listener = this.transport.newListener(null);
this.listener = listener;
}
}
if (listener != null) {
log.info("STARTED LISTENING");
listener.listen((String msg, DatagramTransport.RemoteNode rn) -> {
Address remoteAddr = rn.remoteAddress();
if (!msg.startsWith(PROTOCOL_SIGNATURE)) {
log.trace("WARN_DROPPING_RECIEVED_MESSAGE", "Incorrect protocol signature.");
return; // EARLY RETURN
}
int headerLength = msg.indexOf("\n");
String headerStr = "";
if (headerLength < 0) {
log.trace("WARN_DROPPING_RECIEVED_MESSAGE", "Malformed header.");
return; // EARLY RETURN
}
headerStr = msg.substring(0, headerLength);
MessageHeader header = MessageHeader.parse(headerStr, remoteAddr, log);
if (header == null) {
return; // EARLY RETURN
}
ChannelImplementation ch = channels.get(header.channel);
if (ch == null) {
handleMsgToUnknownChannel(header);
} else {
String msgBody = msg.substring(headerLength + 1);
if (header.dgType == MessageHeader.DgType.DG_MSG) {
ch.handleReceivedMessage(header, msgBody, remoteAddr);
} else if (header.dgType == MessageHeader.DgType.DG_CMD) {
ch.srvHandleReceivedCommand(header, msgBody, remoteAddr);
} else if (header.dgType == MessageHeader.DgType.DG_CMDRESP) {
ch.cliHandleReceivedCommandResponse(header, msgBody, remoteAddr);
} else if (header.dgType == MessageHeader.DgType.DG_CMDRESPACK) {
ch.srvHandleReceivedCommandResponseAck(header, msgBody, remoteAddr);
} else {
assert false; // we have already validated the message, so shouldn't get here.
}
}
});
}
}
// Idempotent, threada safe
public void stopListening() {
DatagramTransport.Listener li = null;
synchronized (listenLock) {
if (this.listener != null) {
li = this.listener;
this.listener = null;
}
}
log.info("STOPPED LISTENING");
if (li != null) {
li.close();
}
}
public boolean isListening() {
// Not synchronized as there is no point
return this.listener != null;
}
public void close() {
// THis will cause subsequent attempts to create channels to
// fail with an invalid state exception.
this.commClosed = true;
stopListening();
// Close all channels
for (ChannelImplementation ch : channels.values()) {
ch.close();
}
// Channels should pull themselves off the list as they close...
assert channels.size() == 0;
transport.close();
}
private void handleMsgToUnknownChannel(MessageHeader header) {
// TODO Auto-generated method stub
}
static class MessageHeader {
enum DgType {
DG_MSG, DG_CMD, DG_CMDRESP, DG_CMDRESPACK
};
final static String STR_DG_MSG = "MSG";
final static String STR_DG_CMD = "CMD";
final static String STR_DG_CMDRESP = "CMDRESP";
final static String STR_DG_CMDRESPACK = "CMDRESPACK";
final static String STR_STATUS_PENDING_QUEUED = "QUEUED";
final static String STR_STATUS_PENDING_COMPUTING = "COMPUTING";
final static String STR_STATUS_COMPLETED = "COMPLETED";
final static String STR_STATUS_REJECTED = "REJECTED";
final static int INDEX_PROTO = 0;
final static int INDEX_DG_TYPE = 1;
final static int INDEX_CHANNEL = 2;
final static int INDEX_MSG_TYPE = 3;
final static int INDEX_CMDID = 4;
final static int INDEX_CMDSTATUS = 5;
final DgType dgType;
final String channel;
final String msgType;
final long cmdId;
enum CmdStatus {
STATUS_PENDING_QUEUED, STATUS_PENDING_COMPUTING, STATUS_COMPLETED, STATUS_REJECTED, STATUS_NOVALUE // Don't
// use
};
final CmdStatus status;
private MessageHeader(DgType dgType, String channel, String msgType, long cmdId, CmdStatus status) {
this.dgType = dgType;
this.channel = channel;
this.msgType = msgType;
this.cmdId = cmdId;
this.status = status;
}
public boolean isPending() {
return this.dgType == DgType.DG_CMDRESP && (this.status == CmdStatus.STATUS_PENDING_COMPUTING
|| this.status == CmdStatus.STATUS_PENDING_QUEUED);
}
public boolean isComplete() {
return this.dgType == DgType.DG_CMDRESP && !!!isPending();
}
// Examples
// - "1309JHI,MY_CHANNEL,MSG,MY_MSG_TYPE"
// - "1309JHI,MY_CHANNEL,CMD,MY_COMMAND_TYPE,2888AB89"
// - "1309JHI,MY_CHANNEL,CMDRESP,MY_RESPONSE_TYPE,2888AB89,OK"
static MessageHeader parse(String headerStr, Address remoteAddr, StructuredLogger.Log log) {
final String BAD_HEADER_CHARS = " \t\f\n\r";
if (containsChars(headerStr, BAD_HEADER_CHARS)) {
log.trace("WARN_DROPPING_RECIEVED_MESSAGE", "Header contains invalid chars");
return null;
}
String[] header = headerStr.split(",");
if (header.length < 4) {
log.trace("WARN_DROPPING_RECIEVED_MESSAGE", "Malformed header");
return null;
}
// This fact should have been checked before calling us
assert header[INDEX_PROTO].equals(PROTOCOL_SIGNATURE);
String dgTypeStr = header[INDEX_DG_TYPE];
DgType dgType;
boolean getCmdId = false;
boolean getStatus = false;
if (dgTypeStr.equals(STR_DG_MSG)) {
dgType = DgType.DG_MSG;
} else if (dgTypeStr.equals(STR_DG_CMD)) {
dgType = DgType.DG_CMD;
getCmdId = true;
} else if (dgTypeStr.equals(STR_DG_CMDRESP)) {
dgType = DgType.DG_CMDRESP;
getCmdId = true;
getStatus = true;
} else if (dgTypeStr.equals(STR_DG_CMDRESPACK)) {
dgType = DgType.DG_CMDRESPACK;
} else {
log.trace("WARN_DROPPING_RECIEVED_MESSAGE", "Malformed header - unknown DG type");
return null;
}
String channel = header[INDEX_CHANNEL];
if (channel.length() == 0) {
log.trace("WARN_DROPPING_RECEIVED_MESSGAGE", "Missing channel name");
return null;
}
String msgType = header[INDEX_MSG_TYPE];
// We do not do special error checking on user msgType...
long cmdId = 0;
if (getCmdId) {
if (header.length <= INDEX_CMDID) {
log.trace("WARN_DROPPING_RECIEVED_MESSAGE", "Malformed header - missing cmd ID");
return null;
}
try {
cmdId = Long.parseLong(header[INDEX_CMDID], 16); // Hex
} catch (NumberFormatException e) {
log.trace("WARN_DROPPING_RECIEVED_MESSAGE", "Malformed header - invalid cmd ID");
return null;
}
}
CmdStatus status = CmdStatus.STATUS_NOVALUE;
if (getStatus) {
if (header.length <= INDEX_CMDSTATUS) {
log.trace("WARN_DROPPING_RECIEVED_MESSAGE", "Malformed header - missing cmd status");
return null;
}
String statusStr = header[INDEX_CMDSTATUS];
if (statusStr.equals(STR_STATUS_PENDING_QUEUED)) {
status = CmdStatus.STATUS_PENDING_QUEUED;
} else if (statusStr.equals(STR_STATUS_PENDING_COMPUTING)) {
status = CmdStatus.STATUS_PENDING_COMPUTING;
} else if (statusStr.equals(STR_STATUS_COMPLETED)) {
status = CmdStatus.STATUS_COMPLETED;
} else if (statusStr.equals(STR_STATUS_REJECTED)) {
status = CmdStatus.STATUS_REJECTED;
} else {
log.trace("WARN_DROPPING_RECIEVED_MESSAGE", "Malformed header - unknown status");
return null;
}
}
return new MessageHeader(dgType, channel, msgType, cmdId, status);
}
public String serialize(String additionalText) {
String dgTypeStr = dgTypeToString();
String cmdIdStr = cmdIdToString();
String statusStr = statusToString() + '\n' + additionalText;
return String.join(",", PROTOCOL_SIGNATURE, dgTypeStr, this.channel, this.msgType, cmdIdStr, statusStr);
}
private String statusToString() {
if (this.status == CmdStatus.STATUS_PENDING_QUEUED) {
return STR_STATUS_PENDING_QUEUED;
}
if (this.status == CmdStatus.STATUS_PENDING_COMPUTING) {
return STR_STATUS_PENDING_COMPUTING;
} else if (this.status == CmdStatus.STATUS_COMPLETED) {
return STR_STATUS_COMPLETED;
} else if (this.status == CmdStatus.STATUS_REJECTED) {
return STR_STATUS_REJECTED;
} else if (this.status == CmdStatus.STATUS_NOVALUE) {
return "";
} else {
assert false;
return "UNKNOWN";
}
}
private String cmdIdToString() {
return cmdId == 0 ? "" : Long.toHexString(cmdId);
}
private String dgTypeToString() {
if (this.dgType == DgType.DG_MSG) {
return STR_DG_MSG;
} else if (this.dgType == DgType.DG_CMD) {
return STR_DG_CMD;
} else if (this.dgType == DgType.DG_CMDRESP) {
return STR_DG_CMDRESP;
} else if (this.dgType == DgType.DG_CMDRESPACK) {
return STR_DG_CMDRESPACK;
} else {
assert false;
return "UNKNOWN";
}
}
}
private class ChannelImplementation implements Channel {
private final String name;
private DatagramTransport.RemoteNode remoteNode;
// Initialized to a random value and then incremented for each new command on
// this channel.
private final AtomicLong nextCmdId;
// Receiving messages
private final ConcurrentLinkedQueue<ReceivedMessageImplementation> pendingRecvMessages;
// Sending of commands
private final ConcurrentHashMap<Long, SentCommandImplementation> cliPendingSentCommands;
private final ConcurrentLinkedQueue<SentCommandImplementation> cliCompletedSentCommands;
// Receiving of commands
private final ConcurrentHashMap<Long, ReceivedCommandImplementation> srvRecvCommandsMap;
private final ConcurrentLinkedQueue<ReceivedCommandImplementation> srvPendingRecvCommands;
private final ConcurrentLinkedQueue<ReceivedCommandImplementation> srvCompletedRecvCommands;
final Object receiverLock;
DatagramTransport.Listener listener;
private boolean receiveMessages;
private boolean receiveCommands;
private class ReceivedMessageImplementation implements ReceivedMessage {
private final String msg;
private final String msgType;
private final Address remoteAddress;
private long recvdTimeStamp;
private final Channel ch;
ReceivedMessageImplementation(String msgType, String msg, Address remoteAddress, Channel ch) {
this.msg = msg;
this.msgType = msgType;
this.remoteAddress = remoteAddress;
this.recvdTimeStamp = System.currentTimeMillis();
this.ch = ch;
}
@Override
public String message() {
return this.msg;
}
@Override
public String msgType() {
return this.msgType;
}
@Override
public Address remoteAddress() {
return this.remoteAddress;
}
@Override
public long receivedTimestamp() {
return recvdTimeStamp;
}
@Override
public Channel channel() {
return ch;
}
}
// Client side
private class SentCommandImplementation implements SentCommand {
private final long cmdId;
private final String cmdType;
private final String cmd;
private final long submittedTime;
private final boolean addToCompletionQueue;
private COMMAND_STATUS stat;
private String resp;
private String respType;
private long respTime;
SentCommandImplementation(long cmdId, String cmdType, String cmd, boolean addToCompletionQueue) {
this.cmdId = cmdId;
this.cmdType = cmdType;
this.cmd = cmd;
this.addToCompletionQueue = addToCompletionQueue;
this.submittedTime = System.currentTimeMillis();
this.stat = COMMAND_STATUS.STATUS_SUBMITTED;
}
@Override
public long cmdId() {
// TODO Auto-generated method stub
return this.cmdId;
}
@Override
public String cmdType() {
return cmdType;
}
@Override
public String command() {
return cmd;
}
@Override
public long submittedTime() {
return submittedTime;
}
@Override
public COMMAND_STATUS status() {
return stat;
}
@Override
public String respType() {
return respType;
}
@Override
public String response() {
return resp;
}
@Override
public long respondedTime() {
return respTime;
}
@Override
public void cancel() {
// TODO Auto-generated method stub
}
// LK ==> caller should ensure locking
public void updateRemoteStatusLK(MessageHeader header) {
if (localStatusOrder() < remoteStatusOrder(header)) {
this.stat = mapRemoteStatus(header.status);
}
}
private int localStatusOrder() {
switch (this.stat) {
case STATUS_SUBMITTED:
return 0;
case STATUS_REMOTE_QUEUED:
return 1;
case STATUS_REMOTE_COMPUTING:
return 2;
default:
assert !this.pending(); // can't get here as we should have handled all the cases.
return 100;
}
}
private int remoteStatusOrder(MessageHeader header) {
switch (header.status) {
case STATUS_PENDING_QUEUED:
return 1;
case STATUS_PENDING_COMPUTING:
return 2;
default:
assert header.isComplete(); // can't get here as we should have handled all the cases.
return 50;
}
}
COMMAND_STATUS mapRemoteStatus(MessageHeader.CmdStatus rStatus) {
switch (rStatus) {
case STATUS_PENDING_QUEUED:
return COMMAND_STATUS.STATUS_REMOTE_QUEUED;
case STATUS_PENDING_COMPUTING:
return COMMAND_STATUS.STATUS_REMOTE_COMPUTING;
case STATUS_COMPLETED:
return COMMAND_STATUS.STATUS_COMPLETED;
case STATUS_REJECTED:
return COMMAND_STATUS.STATUS_REMOTE_REJECTED;
default:
assert false; // should never get here.
return this.stat;
}
}
}
// Server Side
private class ReceivedCommandImplementation implements ReceivedCommand {
private final long cmdId;
private final String cmdBody;
private final String cmdType;
private final Address remoteAddress;
private final DatagramTransport.RemoteNode rn;
private long recvdTimeStamp;
private final ChannelImplementation ch;
public ReceivedCommandImplementation(long cmdId, String msgType, String msgBody, Address remoteAddr,
ChannelImplementation ch) {
this.cmdId = cmdId;
this.cmdBody = msgBody;
this.cmdType = msgType;
this.remoteAddress = remoteAddr;
this.rn = transport.newRemoteNode(remoteAddr);
this.recvdTimeStamp = System.currentTimeMillis();
this.ch = ch;
}
@Override
public long cmdId() {
return this.cmdId;
}
@Override
public String message() {
return this.cmdBody;
}
@Override
public String msgType() {
return this.cmdType;
}
@Override
public Address remoteAddress() {
return this.remoteAddress;
}
@Override
public long receivedTimestamp() {
return this.recvdTimeStamp;
}
@Override
public Channel channel() {
return this.ch;
}
@Override
public void respond(String respType, String resp) {
// Server code is responding with the result of performing a command.
srvHandleComputedResponse(this, respType, resp);
}
}
public ChannelImplementation(String channelName) {
this.name = channelName;
this.remoteNode = null;
this.nextCmdId = new AtomicLong(cmdIdRand.nextLong());
// For receiving messages
this.pendingRecvMessages = new ConcurrentLinkedQueue<>();
// For sending commands
this.cliPendingSentCommands = new ConcurrentHashMap<>();
this.cliCompletedSentCommands = new ConcurrentLinkedQueue<>();
// For receiving commands
this.srvPendingRecvCommands = new ConcurrentLinkedQueue<>();
this.srvCompletedRecvCommands = new ConcurrentLinkedQueue<>();
this.srvRecvCommandsMap = new ConcurrentHashMap<>();
this.receiverLock = new Object();
}
@Override
public String name() {
return this.name;
}
@Override
public void bindToRemoteNode(Address remoteAddress) {
DatagramTransport.RemoteNode node = transport.newRemoteNode(remoteAddress());
this.remoteNode = node; // Could override an existing one. That's ok
}
@Override
public Address remoteAddress() {
DatagramTransport.RemoteNode rn = this.remoteNode; // can be null
return rn == null ? null : rn.remoteAddress();
}
@Override
public void sendMessage(String msgType, String message) {
DatagramTransport.RemoteNode rn = this.remoteNode; // can be null
if (validSendParams(msgType, message, rn, "DISCARDING_SEND_MESSAGE")) {
MessageHeader hdr = new MessageHeader(MessageHeader.DgType.DG_MSG, name, msgType, 0,
MessageHeader.CmdStatus.STATUS_NOVALUE);
rn.send(hdr.serialize(message));
}
}
@Override
public void sendMessage(String msgType, String message, Address addr) {
// TODO Auto-generated method stub
}
@Override
public void close() {
// TODO: If necessary remote nodes of channel closing.
// then remove ourselves from the channels queue.
log.trace("Removing channel " + name + " from list of channels.");
channels.remove(name, this);
}
@Override
public ReceivedMessage pollReceivedMessage() {
return pendingRecvMessages.poll();
}
@Override
public SentCommand sendCommand(String cmdType, String command, boolean addToCompletionQueue) {
if (!isListening()) {
throw new IllegalStateException(
"Attempt to call sendCommand on a RobotComm instance that is not listening.");
}
DatagramTransport.RemoteNode rn = this.remoteNode; // can be null
if (validSendParams(cmdType, command, rn, "DISCARDING_SEND_COMMAND")) {
long cmdId = cliNewCommandId();
MessageHeader hdr = new MessageHeader(MessageHeader.DgType.DG_CMD, name, cmdType, cmdId,
MessageHeader.CmdStatus.STATUS_NOVALUE);
SentCommandImplementation sc = new SentCommandImplementation(cmdId, cmdType, command,
addToCompletionQueue);
this.cliPendingSentCommands.put(cmdId, sc);
rn.send(hdr.serialize(command));
return sc;
} else {
throw new IllegalArgumentException();
}
}
@Override
public SentCommand pollCompletedCommand() {
// TODO Auto-generated method stub
return null;
}
@Override
public void startReceivingMessages() {
this.receiveMessages = true;
}
@Override
public void stopReceivingMessages() {
// TODO Close resources related to receiving
this.receiveMessages = false;
}
@Override
public void startReceivingCommands() {
this.receiveCommands = true;
}
@Override
public void stopReceivingCommands() {
// TODO Close resources related to receiving,
// and cancel all outstanding client and server-side command state.
this.receiveCommands = false;
}
@Override
public ReceivedCommand pollReceivedCommand() {
return srvPendingRecvCommands.poll();
}
private long cliNewCommandId() {
return nextCmdId.getAndIncrement();
}
// Client gets this
void cliHandleReceivedCommandResponse(MessageHeader header, String msgBody, Address remoteAddr) {
if (header.isPending()) {
SentCommandImplementation sc = this.cliPendingSentCommands.get(header.cmdId);
if (sc != null) {
synchronized (sc) {
sc.updateRemoteStatusLK(header);
}
}
// We don't respond to CMDRESP messages with pending status.
return;
}
assert !header.isPending();
SentCommandImplementation sc = this.cliPendingSentCommands.remove(header.cmdId);
if (sc == null) {
cliQueueCmdRespAck(header, remoteAddr);
return;
}
synchronized (sc) {
// If it *was* in the pending sent queue, it *must* be pending.
assert sc.pending();
sc.updateRemoteStatusLK(header);
assert !sc.pending();
}
if (sc.addToCompletionQueue) {
this.cliCompletedSentCommands.add(sc);
}
}
private void cliQueueCmdRespAck(MessageHeader header, Address remoteAddr) {
// TODO: Validate remoteAddr and add eventually send a CMDRESPACK.
// For now we do nothing.
}
// Server gets this
void srvHandleReceivedCommand(MessageHeader header, String msgBody, Address remoteAddr) {
if (!this.receiveCommands) {
return;
}
// TODO: we should incorporate the remoteAddr into the key :-(. Otherwise two
// incoming commands
// from different remote nodes could potentially clash. For the moment we don't
// take this to account
// because our own client generates completely random long cmdIds, so the risk
// of collision is
// miniscule. But it is completely valid for remote clients to generate very
// simple cmdIds which could
// easily collide.
long cmdId = header.cmdId;
ReceivedCommandImplementation rc = this.srvRecvCommandsMap.get(cmdId);
if (rc != null) {
srvRespondToExistingReceivedCommand(rc, header, remoteAddr);
return;
}
// We haven't seen this request below, let's make a new one.
ReceivedCommandImplementation rmNew = new ReceivedCommandImplementation(cmdId, header.msgType, msgBody,
remoteAddr, this);
ReceivedCommandImplementation rmPrev = this.srvRecvCommandsMap.putIfAbsent(cmdId, rmNew);
if (rmPrev != null) {
// In the tiny amount of time before the previous check, another CMD for this
// same cmdID was
// processed and inserted into the map! We will simply drop this current one. No
// need to respond
// because clearly we only recently inserted it into the map.
return;
}
this.srvPendingRecvCommands.add(rmNew);
}
private void srvRespondToExistingReceivedCommand(ReceivedCommandImplementation rc, MessageHeader header,
Address remoteAddr) {
// TODO Auto-generated method stub
}
public void srvHandleComputedResponse(ReceivedCommandImplementation rc, String respType, String resp) {
// TODO Auto-generated method stub
MessageHeader header = new MessageHeader(MessageHeader.DgType.DG_CMDRESP, respType, respType, rc.cmdId,
MessageHeader.CmdStatus.STATUS_COMPLETED);
}
// Server gets this
void srvHandleReceivedCommandResponseAck(MessageHeader header, String msgBody, Address remoteAddr) {
// TODO Auto-generated method stub
}
void handleReceivedMessage(MessageHeader header, String msgBody, Address remoteAddr) {
if (this.receiveMessages) {
ReceivedMessageImplementation rm = new ReceivedMessageImplementation(header.msgType, msgBody,
remoteAddr, this);
this.pendingRecvMessages.add(rm);
}
}
}
private boolean validSendParams(String msgType, String message, RemoteNode rn, String logMsgType) {
final String BAD_MSGTYPE_CHARS = ", \t\f\n\r";
boolean ret = false;
if (rn == null) {
log.trace(logMsgType, "No default send node");
} else if (containsChars(msgType, BAD_MSGTYPE_CHARS)) {
log.trace(logMsgType, "Message type has invalid chars: " + msgType);
} else {
ret = true;
}
return ret;
}
/**
* Creates a remote UDP port - for sending
*
* @param nameOrAddress
* - either a name to be resolved or an dotted IP address
* @param port
* - port number (0-65535)
* @return remote port object
*/
public static Address makeUDPRemoteAddress(String nameOrAddress, int port) {
return null;
}
private static boolean containsChars(String str, String chars) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (chars.indexOf(c) >= 0) {
return true;
}
}
return false;
}
}
|
package net.bull.javamelody;
import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.LoggerFactory;
final class LOG {
static final boolean LOG4J_ENABLED = isLog4jEnabled();
static final boolean LOGBACK_ENABLED = isLogbackEnabled();
private static final String INTERNAL_LOGGER_NAME = "net.bull.javamelody";
private LOG() {
super();
}
@SuppressWarnings("unused")
static void logHttpRequest(HttpServletRequest httpRequest, String requestName, long duration,
boolean systemError, int responseSize, String filterName) {
// dans les 3 cas, on ne construit le message de log
if (LOG.LOGBACK_ENABLED) {
logback(httpRequest, duration, systemError, responseSize, filterName);
} else if (LOG.LOG4J_ENABLED) {
log4j(httpRequest, duration, systemError, responseSize, filterName);
} else {
final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(filterName);
if (logger.isLoggable(Level.INFO)) {
logger.info(buildLogMessage(httpRequest, duration, systemError, responseSize));
}
}
}
private static void log4j(HttpServletRequest httpRequest, long duration, boolean systemError,
int responseSize, String filterName) {
final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(filterName);
if (logger.isInfoEnabled()) {
logger.info(buildLogMessage(httpRequest, duration, systemError, responseSize));
}
}
private static void logback(HttpServletRequest httpRequest, long duration, boolean systemError,
int responseSize, String filterName) {
final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(filterName);
if (logger.isInfoEnabled()) {
logger.info(buildLogMessage(httpRequest, duration, systemError, responseSize));
}
}
private static String buildLogMessage(HttpServletRequest httpRequest, long duration,
boolean systemError, int responseSize) {
final StringBuilder msg = new StringBuilder();
msg.append("remoteAddr = ").append(httpRequest.getRemoteAddr());
final String forwardedFor = httpRequest.getHeader("X-Forwarded-For");
if (forwardedFor != null) {
msg.append(", forwardedFor = ").append(forwardedFor);
}
msg.append(", request = ").append(
httpRequest.getRequestURI().substring(httpRequest.getContextPath().length()));
if (httpRequest.getQueryString() != null) {
msg.append('?').append(httpRequest.getQueryString());
}
msg.append(' ').append(httpRequest.getMethod());
msg.append(": ").append(duration).append(" ms");
if (systemError) {
msg.append(", erreur");
}
msg.append(", ").append(responseSize / 1024).append(" Ko");
return msg.toString();
}
static void debug(String msg) {
if (LOGBACK_ENABLED) {
org.slf4j.LoggerFactory.getLogger(INTERNAL_LOGGER_NAME).debug(msg);
} else if (LOG4J_ENABLED) {
final org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger(INTERNAL_LOGGER_NAME);
logger.debug(msg);
} else {
final java.util.logging.Logger logger = java.util.logging.Logger
.getLogger(INTERNAL_LOGGER_NAME);
logger.log(Level.FINE, msg);
}
}
static void debug(String msg, Throwable throwable) {
if (LOGBACK_ENABLED) {
org.slf4j.LoggerFactory.getLogger(INTERNAL_LOGGER_NAME).debug(msg, throwable);
} else if (LOG4J_ENABLED) {
final org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger(INTERNAL_LOGGER_NAME);
logger.debug(msg, throwable);
} else {
final java.util.logging.Logger logger = java.util.logging.Logger
.getLogger(INTERNAL_LOGGER_NAME);
logger.log(Level.FINE, msg, throwable);
}
}
static void info(String msg, Throwable throwable) {
if (LOGBACK_ENABLED) {
org.slf4j.LoggerFactory.getLogger(INTERNAL_LOGGER_NAME).info(msg, throwable);
} else if (LOG4J_ENABLED) {
final org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger(INTERNAL_LOGGER_NAME);
logger.info(msg, throwable);
} else {
final java.util.logging.Logger logger = java.util.logging.Logger
.getLogger(INTERNAL_LOGGER_NAME);
logger.log(Level.INFO, msg, throwable);
}
}
static void warn(String msg, Throwable throwable) {
try {
if (LOGBACK_ENABLED) {
org.slf4j.LoggerFactory.getLogger(INTERNAL_LOGGER_NAME).warn(msg, throwable);
} else if (LOG4J_ENABLED) {
final org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger(INTERNAL_LOGGER_NAME);
logger.warn(msg, throwable);
} else {
final java.util.logging.Logger logger = java.util.logging.Logger
.getLogger(INTERNAL_LOGGER_NAME);
logger.log(Level.WARNING, msg, throwable);
}
} catch (final Throwable t) { // NOPMD
t.printStackTrace(System.err);
}
}
private static boolean isLog4jEnabled() {
try {
Class.forName("org.apache.log4j.Logger");
// org.apache.log4j.Logger mais pas org.apache.log4j.AppenderSkeleton
Class.forName("org.apache.log4j.AppenderSkeleton");
return true;
} catch (final ClassNotFoundException e) {
return false;
}
}
private static boolean isLogbackEnabled() {
try {
Class.forName("ch.qos.logback.classic.Logger");
return Class.forName("ch.qos.logback.classic.LoggerContext").isAssignableFrom(
LoggerFactory.getILoggerFactory().getClass());
} catch (final ClassNotFoundException e) {
return false;
}
}
}
|
package com.rahul.bounce.library;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.ListView;
import android.widget.ScrollView;
public class BounceTouchListener implements View.OnTouchListener {
private static final int DEFAULT_ANIMATION_TIME = 600;
private boolean downCalled = false;
private OnTranslateListener onTranslateListener;
private View mMainView;
private View mContent;
private long mAnimationTime = DEFAULT_ANIMATION_TIME;
private float mDownY;
private boolean mSwipingDown, mSwipingUp;
private float mTranslationY;
private Interpolator mInterpolator = new DecelerateInterpolator(3f);
private boolean swipUpEnabled = true;
private int mActivePointerId = -99;
private float mLastTouchX = -99;
private float mLastTouchY = -99;
private int mMaxAbsTranslation = -99;
public BounceTouchListener(View mainScrollableView) {
this.mMainView = mainScrollableView;
this.mContent = this.mMainView;
}
public BounceTouchListener(View mainScrollableView, int contentResId) {
this.mMainView = mainScrollableView;
this.mContent = this.mMainView.findViewById(contentResId);
}
public void setOnTranslateListener(OnTranslateListener onTranslateListener) {
this.onTranslateListener = onTranslateListener;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
final int action = MotionEventCompat.getActionMasked(motionEvent);
switch (action) {
case MotionEvent.ACTION_DOWN: {
onDownMotionEvent(motionEvent);
view.onTouchEvent(motionEvent);
downCalled = true;
if (mContent.getTranslationY() == 0) {
return false;
}
}
case MotionEvent.ACTION_MOVE: {
if (mActivePointerId == -99) {
onDownMotionEvent(motionEvent);
downCalled = true;
}
final int pointerIndex =
MotionEventCompat.findPointerIndex(motionEvent, mActivePointerId);
final float x = MotionEventCompat.getX(motionEvent, pointerIndex);
final float y = MotionEventCompat.getY(motionEvent, pointerIndex);
if (!hasHitTop() && !hasHitBottom() || !downCalled) {
if (!downCalled) {
downCalled = true;
}
mDownY = y;
view.onTouchEvent(motionEvent);
return false;
}
float deltaY = y - mDownY;
if (Math.abs(deltaY) > 0 && hasHitTop() && deltaY > 0) {
mSwipingDown = true;
sendCancelEventToView(view, motionEvent);
}
if (swipUpEnabled) {
if (Math.abs(deltaY) > 0 && hasHitBottom() && deltaY < 0) {
mSwipingUp = true;
sendCancelEventToView(view, motionEvent);
}
}
if (mSwipingDown || mSwipingUp) {
mTranslationY = deltaY;
if ((deltaY <= 0 && mSwipingDown) || (deltaY >= 0 && mSwipingUp)) {
mTranslationY = 0;
mDownY = 0;
mSwipingDown = false;
mSwipingUp = false;
downCalled = false;
MotionEvent downEvent = MotionEvent.obtain(motionEvent);
downEvent.setAction(MotionEvent.ACTION_DOWN |
(MotionEventCompat.getActionIndex(motionEvent) << MotionEventCompat.ACTION_POINTER_INDEX_SHIFT));
view.onTouchEvent(downEvent);
break;
}
int translation = (int) ((deltaY / Math.abs(deltaY)) * Math.pow(Math.abs(deltaY), .8f));
if (mMaxAbsTranslation > 0) {
if (translation < 0) {
translation = Math.max(-mMaxAbsTranslation, translation);
} else {
translation = Math.min(mMaxAbsTranslation, translation);
}
}
mContent.setTranslationY(translation);
if (onTranslateListener != null)
onTranslateListener.onTranslate(mContent.getTranslationY());
return true;
}
break;
}
case MotionEvent.ACTION_UP: {
mActivePointerId = -99;
// cancel
mContent.animate()
.setInterpolator(mInterpolator)
.translationY(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
((ValueAnimator) animation).addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (onTranslateListener != null) {
onTranslateListener.onTranslate(mContent.getTranslationY());
}
}
});
super.onAnimationStart(animation);
}
});
mTranslationY = 0;
mDownY = 0;
mSwipingDown = false;
mSwipingUp = false;
downCalled = false;
break;
}
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = -99;
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = MotionEventCompat.getActionIndex(motionEvent);
final int pointerId = MotionEventCompat.getPointerId(motionEvent, pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = MotionEventCompat.getX(motionEvent, newPointerIndex);
mLastTouchY = MotionEventCompat.getY(motionEvent, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(motionEvent, newPointerIndex);
if (mContent.getTranslationY() > 0) {
mDownY = mLastTouchY - (int) Math.pow(mContent.getTranslationY(), 10f / 8f);
mContent.animate().cancel();
} else if (mContent.getTranslationY() < 0) {
mDownY = mLastTouchY + (int) Math.pow(-mContent.getTranslationY(), 10f / 8f);
mContent.animate().cancel();
}
}
break;
}
}
return false;
}
private void sendCancelEventToView(View view, MotionEvent motionEvent) {
((ViewGroup) view).requestDisallowInterceptTouchEvent(true);
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(MotionEventCompat.getActionIndex(motionEvent) << MotionEventCompat.ACTION_POINTER_INDEX_SHIFT));
view.onTouchEvent(cancelEvent);
}
private void onDownMotionEvent(MotionEvent motionEvent) {
final int pointerIndex = MotionEventCompat.getActionIndex(motionEvent);
final float x = MotionEventCompat.getX(motionEvent, pointerIndex);
final float y = MotionEventCompat.getY(motionEvent, pointerIndex);
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = MotionEventCompat.getPointerId(motionEvent, 0);
if (mContent.getTranslationY() > 0) {
mDownY = mLastTouchY - (int) Math.pow(mContent.getTranslationY(), 10f / 8f);
mContent.animate().cancel();
} else if (mContent.getTranslationY() < 0) {
mDownY = mLastTouchY + (int) Math.pow(-mContent.getTranslationY(), 10f / 8f);
mContent.animate().cancel();
} else {
mDownY = mLastTouchY;
}
}
private boolean hasHitBottom() {
if (mMainView instanceof ScrollView) {
ScrollView scrollView = (ScrollView) mMainView;
View view = scrollView.getChildAt(scrollView.getChildCount() - 1);
int diff = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));// Calculate the scrolldiff
return diff == 0;
} else if (mMainView instanceof ListView) {
ListView listView = (ListView) mMainView;
if (listView.getAdapter() != null) {
if (listView.getAdapter().getCount() > 0) {
return listView.getLastVisiblePosition() == listView.getAdapter().getCount() - 1 &&
listView.getChildAt(listView.getChildCount() - 1).getBottom() <= listView.getHeight();
}
}
} else if (mMainView instanceof RecyclerView) {
RecyclerView recyclerView = (RecyclerView) mMainView;
if (recyclerView.getAdapter() != null && recyclerView.getLayoutManager() != null) {
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter.getItemCount() > 0) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
return linearLayoutManager.findLastCompletelyVisibleItemPosition() == adapter.getItemCount() - 1;
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
int[] checks = staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(null);
for (int check : checks) {
if (check == adapter.getItemCount() - 1)
return true;
}
}
}
}
}
return false;
}
private boolean hasHitTop() {
if (mMainView instanceof ScrollView) {
ScrollView scrollView = (ScrollView) mMainView;
return scrollView.getScrollY() == 0;
} else if (mMainView instanceof ListView) {
ListView listView = (ListView) mMainView;
if (listView.getAdapter() != null) {
if (listView.getAdapter().getCount() > 0) {
return listView.getFirstVisiblePosition() == 0 &&
listView.getChildAt(0).getTop() >= 0;
}
}
} else if (mMainView instanceof RecyclerView) {
RecyclerView recyclerView = (RecyclerView) mMainView;
if (recyclerView.getAdapter() != null && recyclerView.getLayoutManager() != null) {
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter.getItemCount() > 0) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
return linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0;
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
int[] checks = staggeredGridLayoutManager.findFirstCompletelyVisibleItemPositions(null);
for (int check : checks) {
if (check == 0)
return true;
}
}
}
}
}
return false;
}
public void setMaxAbsTranslation(int maxAbsTranslation) {
this.mMaxAbsTranslation = maxAbsTranslation;
}
public interface OnTranslateListener {
void onTranslate(float translation);
}
}
|
package com.cloud.storage.resource;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckHealthAnswer;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.GetStorageStatsAnswer;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingStorageCommand;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.SecStorageFirewallCfgCommand;
import com.cloud.agent.api.SecStorageSetupCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.SecStorageFirewallCfgCommand.PortConfig;
import com.cloud.agent.api.storage.CreateEntityDownloadURLCommand;
import com.cloud.agent.api.storage.DeleteEntityDownloadURLCommand;
import com.cloud.agent.api.storage.DeleteTemplateCommand;
import com.cloud.agent.api.storage.DownloadCommand;
import com.cloud.agent.api.storage.DownloadProgressCommand;
import com.cloud.agent.api.storage.UploadCommand;
import com.cloud.host.Host;
import com.cloud.host.Host.Type;
import com.cloud.resource.ServerResource;
import com.cloud.resource.ServerResourceBase;
import com.cloud.storage.Storage;
import com.cloud.storage.StorageLayer;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.template.DownloadManager;
import com.cloud.storage.template.DownloadManagerImpl;
import com.cloud.storage.template.TemplateInfo;
import com.cloud.storage.template.UploadManager;
import com.cloud.storage.template.UploadManagerImpl;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.net.NfsUtils;
import com.cloud.utils.script.Script;
public class NfsSecondaryStorageResource extends ServerResourceBase implements ServerResource {
private static final Logger s_logger = Logger.getLogger(NfsSecondaryStorageResource.class);
int _timeout;
String _instance;
String _parent;
String _dc;
String _pod;
String _guid;
String _nfsPath;
String _mountParent;
Map<String, Object> _params;
StorageLayer _storage;
boolean _inSystemVM = false;
boolean _sslCopy = false;
Random _rand = new Random(System.currentTimeMillis());
DownloadManager _dlMgr;
UploadManager _upldMgr;
private String _configSslScr;
private String _configAuthScr;
private String _configIpFirewallScr;
private String _publicIp;
private String _hostname;
private String _localgw;
private String _eth1mask;
private String _eth1ip;
@Override
public void disconnected() {
if (_parent != null && !_inSystemVM) {
Script script = new Script(!_inSystemVM, "umount", _timeout, s_logger);
script.add(_parent);
script.execute();
File file = new File(_parent);
file.delete();
}
}
@Override
public Answer executeRequest(Command cmd) {
if (cmd instanceof DownloadProgressCommand) {
return _dlMgr.handleDownloadCommand((DownloadProgressCommand)cmd);
} else if (cmd instanceof DownloadCommand) {
return _dlMgr.handleDownloadCommand((DownloadCommand)cmd);
}else if (cmd instanceof UploadCommand) {
return _upldMgr.handleUploadCommand((UploadCommand)cmd);
}else if (cmd instanceof CreateEntityDownloadURLCommand){
return _upldMgr.handleCreateEntityURLCommand((CreateEntityDownloadURLCommand)cmd);
}else if(cmd instanceof DeleteEntityDownloadURLCommand){
return _upldMgr.handleDeleteEntityDownloadURLCommand((DeleteEntityDownloadURLCommand)cmd);
}else if (cmd instanceof GetStorageStatsCommand) {
return execute((GetStorageStatsCommand)cmd);
} else if (cmd instanceof CheckHealthCommand) {
return new CheckHealthAnswer((CheckHealthCommand)cmd, true);
} else if (cmd instanceof DeleteTemplateCommand) {
return execute((DeleteTemplateCommand) cmd);
} else if (cmd instanceof ReadyCommand) {
return new ReadyAnswer((ReadyCommand)cmd);
} else if (cmd instanceof SecStorageFirewallCfgCommand){
return execute((SecStorageFirewallCfgCommand)cmd);
} else if (cmd instanceof SecStorageSetupCommand){
return execute((SecStorageSetupCommand)cmd);
} else {
return Answer.createUnsupportedCommandAnswer(cmd);
}
}
private Answer execute(SecStorageSetupCommand cmd) {
if (!_inSystemVM){
return new Answer(cmd, true, null);
}
boolean success = true;
StringBuilder result = new StringBuilder();
for (String cidr: cmd.getAllowedInternalSites()) {
String tmpresult = allowOutgoingOnPrivate(cidr);
if (tmpresult != null) {
result.append(", ").append(tmpresult);
success = false;
}
}
if (success) {
if (cmd.getCopyPassword() != null && cmd.getCopyUserName() != null) {
String tmpresult = configureAuth(cmd.getCopyUserName(), cmd.getCopyPassword());
if (tmpresult != null) {
result.append("Failed to configure auth for copy ").append(tmpresult);
success = false;
}
}
}
return new Answer(cmd, success, result.toString());
}
private String allowOutgoingOnPrivate(String destCidr) {
Script command = new Script("/bin/bash", s_logger);
String intf = "eth1";
command.add("-c");
command.add("iptables -I OUTPUT -o " + intf + " -d " + destCidr + " -p tcp -m state --state NEW -m tcp -j ACCEPT");
String result = command.execute();
if (result != null) {
s_logger.warn("Error in allowing outgoing to " + destCidr + ", err=" + result );
return "Error in allowing outgoing to " + destCidr + ", err=" + result;
}
addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, destCidr);
return null;
}
private Answer execute(SecStorageFirewallCfgCommand cmd) {
if (!_inSystemVM){
return new Answer(cmd, true, null);
}
List<String> ipList = new ArrayList<String>();
for (PortConfig pCfg:cmd.getPortConfigs()){
if (pCfg.isAdd()) {
ipList.add(pCfg.getSourceIp());
}
}
boolean success = true;
String result;
result = configureIpFirewall(ipList);
if (result !=null)
success = false;
return new Answer(cmd, success, result);
}
protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) {
final long usedSize = getUsedSize();
final long totalSize = getTotalSize();
if (usedSize == -1 || totalSize == -1) {
return new GetStorageStatsAnswer(cmd, "Unable to get storage stats");
} else {
return new GetStorageStatsAnswer(cmd, totalSize, usedSize) ;
}
}
protected Answer execute(final DeleteTemplateCommand cmd) {
String relativeTemplatePath = cmd.getTemplatePath();
String parent = _parent;
if (relativeTemplatePath.startsWith(File.separator)) {
relativeTemplatePath = relativeTemplatePath.substring(1);
}
if (!parent.endsWith(File.separator)) {
parent += File.separator;
}
String absoluteTemplatePath = parent + relativeTemplatePath;
File tmpltParent = new File(absoluteTemplatePath).getParentFile();
String details = null;
if (!tmpltParent.exists()) {
details = "template parent directory " + tmpltParent.getName() + " doesn't exist";
s_logger.debug(details);
return new Answer(cmd, true, details);
}
File[] tmpltFiles = tmpltParent.listFiles();
if (tmpltFiles == null || tmpltFiles.length == 0) {
details = "No files under template parent directory " + tmpltParent.getName();
s_logger.debug(details);
} else {
boolean found = false;
for (File f : tmpltFiles) {
if (!found && f.getName().equals("template.properties")) {
found = true;
}
if (!f.delete()) {
return new Answer(cmd, false, "Unable to delete file " + f.getName() + " under Template path "
+ relativeTemplatePath);
}
}
if (!found) {
details = "Can not find template.properties under " + tmpltParent.getName();
s_logger.debug(details);
}
}
if (!tmpltParent.delete()) {
details = "Unable to delete directory " + tmpltParent.getName() + " under Template path "
+ relativeTemplatePath;
s_logger.debug(details);
return new Answer(cmd, false, details);
}
return new Answer(cmd, true, null);
}
protected long getUsedSize() {
return _storage.getUsedSpace(_parent);
}
protected long getTotalSize() {
return _storage.getTotalSpace(_parent);
}
protected long convertFilesystemSize(final String size) {
if (size == null || size.isEmpty()) {
return -1;
}
long multiplier = 1;
if (size.endsWith("T")) {
multiplier = 1024l * 1024l * 1024l * 1024l;
} else if (size.endsWith("G")) {
multiplier = 1024l * 1024l * 1024l;
} else if (size.endsWith("M")) {
multiplier = 1024l * 1024l;
} else {
assert (false) : "Well, I have no idea what this is: " + size;
}
return (long)(Double.parseDouble(size.substring(0, size.length() - 1)) * multiplier);
}
@Override
public Type getType() {
return Host.Type.SecondaryStorage;
}
@Override
public PingCommand getCurrentStatus(final long id) {
return new PingStorageCommand(Host.Type.Storage, id, new HashMap<String, Boolean>());
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_eth1ip = (String)params.get("eth1ip");
if (_eth1ip != null) { //can only happen inside service vm
params.put("private.network.device", "eth1");
} else {
s_logger.warn("Wait, what's going on? eth1ip is null!!");
}
String eth2ip = (String) params.get("eth2ip");
if (eth2ip != null) {
params.put("public.network.device", "eth2");
}
_publicIp = (String) params.get("eth2ip");
_hostname = (String) params.get("name");
super.configure(name, params);
_params = params;
String value = (String)params.get("scripts.timeout");
_timeout = NumbersUtil.parseInt(value, 1440) * 1000;
_storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey);
if (_storage == null) {
value = (String)params.get(StorageLayer.ClassConfigKey);
if (value == null) {
value = "com.cloud.storage.JavaStorageLayer";
}
try {
Class<?> clazz = Class.forName(value);
_storage = (StorageLayer)ComponentLocator.inject(clazz);
_storage.configure("StorageLayer", params);
} catch (ClassNotFoundException e) {
throw new ConfigurationException("Unable to find class " + value);
}
}
_configSslScr = Script.findScript(getDefaultScriptsDir(), "config_ssl.sh");
if (_configSslScr != null) {
s_logger.info("config_ssl.sh found in " + _configSslScr);
}
_configAuthScr = Script.findScript(getDefaultScriptsDir(), "config_auth.sh");
if (_configSslScr != null) {
s_logger.info("config_auth.sh found in " + _configAuthScr);
}
_configIpFirewallScr = Script.findScript(getDefaultScriptsDir(), "ipfirewall.sh");
if (_configIpFirewallScr != null) {
s_logger.info("_configIpFirewallScr found in " + _configIpFirewallScr);
}
_guid = (String)params.get("guid");
if (_guid == null) {
throw new ConfigurationException("Unable to find the guid");
}
_dc = (String)params.get("zone");
if (_dc == null) {
throw new ConfigurationException("Unable to find the zone");
}
_pod = (String)params.get("pod");
_instance = (String)params.get("instance");
_mountParent = (String)params.get("mount.parent");
if (_mountParent == null) {
_mountParent = File.separator + "mnt";
}
if (_instance != null) {
_mountParent = _mountParent + File.separator + _instance;
}
_nfsPath = (String)params.get("mount.path");
if (_nfsPath == null) {
throw new ConfigurationException("Unable to find mount.path");
}
String inSystemVM = (String)params.get("secondary.storage.vm");
if (inSystemVM == null || "true".equalsIgnoreCase(inSystemVM)) {
_inSystemVM = true;
_localgw = (String)params.get("localgw");
if (_localgw != null) { //can only happen inside service vm
_eth1mask = (String)params.get("eth1mask");
String internalDns1 = (String)params.get("dns1");
String internalDns2 = (String)params.get("dns2");
if (internalDns1 == null) {
s_logger.warn("No DNS entry found during configuration of NfsSecondaryStorage");
} else {
addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, internalDns1);
}
String mgmtHost = (String)params.get("host");
String nfsHost = NfsUtils.getHostPart(_nfsPath);
if (nfsHost == null) {
s_logger.error("Invalid or corrupt nfs url " + _nfsPath);
throw new CloudRuntimeException("Unable to determine host part of nfs path");
}
try {
InetAddress nfsHostAddr = InetAddress.getByName(nfsHost);
nfsHost = nfsHostAddr.getHostAddress();
} catch (UnknownHostException uhe) {
s_logger.error("Unable to resolve nfs host " + nfsHost);
throw new CloudRuntimeException("Unable to resolve nfs host to an ip address " + nfsHost);
}
addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, nfsHost);
addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, mgmtHost);
if (internalDns2 != null) {
addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, internalDns2);
}
}
String useSsl = (String)params.get("sslcopy");
if (useSsl != null) {
_sslCopy = Boolean.parseBoolean(useSsl);
if (_sslCopy) {
configureSSL();
}
}
startAdditionalServices();
_params.put("install.numthreads", "50");
_params.put("secondary.storage.vm", "true");
}
_parent = mount(_nfsPath, _mountParent);
if (_parent == null) {
throw new ConfigurationException("Unable to create mount point");
}
s_logger.info("Mount point established at " + _parent);
try {
_params.put("template.parent", _parent);
_params.put(StorageLayer.InstanceConfigKey, _storage);
_dlMgr = new DownloadManagerImpl();
_dlMgr.configure("DownloadManager", _params);
_upldMgr = new UploadManagerImpl();
_upldMgr.configure("UploadManager", params);
} catch (ConfigurationException e) {
s_logger.warn("Caught problem while configuring DownloadManager", e);
return false;
}
return true;
}
private void startAdditionalServices() {
Script command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("if [ -f /etc/init.d/ssh ]; then service ssh restart; else service sshd restart; fi ");
String result = command.execute();
if (result != null) {
s_logger.warn("Error in starting sshd service err=" + result );
}
command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("iptables -I INPUT -i eth1 -p tcp -m state --state NEW -m tcp --dport 3922 -j ACCEPT");
result = command.execute();
if (result != null) {
s_logger.warn("Error in opening up ssh port err=" + result );
}
}
private void addRouteToInternalIpOrCidr(String localgw, String eth1ip, String eth1mask, String destIpOrCidr) {
s_logger.debug("addRouteToInternalIp: localgw=" + localgw + ", eth1ip=" + eth1ip + ", eth1mask=" + eth1mask + ",destIp=" + destIpOrCidr);
if (destIpOrCidr == null) {
s_logger.debug("addRouteToInternalIp: destIp is null");
return;
}
if (!NetUtils.isValidIp(destIpOrCidr) && !NetUtils.isValidCIDR(destIpOrCidr)){
s_logger.warn(" destIp is not a valid ip address or cidr destIp=" + destIpOrCidr);
return;
}
boolean inSameSubnet = false;
if (NetUtils.isValidIp(destIpOrCidr)) {
if (eth1ip != null && eth1mask != null) {
inSameSubnet = NetUtils.sameSubnet(eth1ip, destIpOrCidr, eth1mask);
} else {
s_logger.warn("addRouteToInternalIp: unable to determine same subnet: _eth1ip=" + eth1ip + ", dest ip=" + destIpOrCidr + ", _eth1mask=" + eth1mask);
}
} else {
inSameSubnet = NetUtils.isNetworkAWithinNetworkB(destIpOrCidr, NetUtils.ipAndNetMaskToCidr(eth1ip, eth1mask));
}
if (inSameSubnet) {
s_logger.debug("addRouteToInternalIp: dest ip " + destIpOrCidr + " is in the same subnet as eth1 ip " + eth1ip);
return;
}
Script command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("ip route delete " + destIpOrCidr);
command.execute();
command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("ip route add " + destIpOrCidr + " via " + localgw);
String result = command.execute();
if (result != null) {
s_logger.warn("Error in configuring route to internal ip err=" + result );
} else {
s_logger.debug("addRouteToInternalIp: added route to internal ip=" + destIpOrCidr + " via " + localgw);
}
}
private void configureSSL() {
Script command = new Script(_configSslScr);
command.add(_publicIp);
command.add(_hostname);
String result = command.execute();
if (result != null) {
s_logger.warn("Unable to configure httpd to use ssl");
}
}
private String configureAuth(String user, String passwd) {
Script command = new Script(_configAuthScr);
command.add(user);
command.add(passwd);
String result = command.execute();
if (result != null) {
s_logger.warn("Unable to configure httpd to use auth");
}
return result;
}
private String configureIpFirewall(List<String> ipList){
Script command = new Script(_configIpFirewallScr);
for (String ip : ipList){
command.add(ip);
}
String result = command.execute();
if (result != null) {
s_logger.warn("Unable to configure firewall for command : " +command);
}
return result;
}
protected String mount(String path, String parent) {
String mountPoint = null;
for (int i = 0; i < 10; i++) {
String mntPt = parent + File.separator + Integer.toHexString(_rand.nextInt(Integer.MAX_VALUE));
File file = new File(mntPt);
if (!file.exists()) {
if (_storage.mkdir(mntPt)) {
mountPoint = mntPt;
break;
}
}
s_logger.debug("Unable to create mount: " + mntPt);
}
if (mountPoint == null) {
s_logger.warn("Unable to create a mount point");
return null;
}
Script script = null;
String result = null;
script = new Script(!_inSystemVM, "umount", _timeout, s_logger);
script.add(path);
result = script.execute();
if( _parent != null ) {
script = new Script("rmdir", _timeout, s_logger);
script.add(_parent);
result = script.execute();
}
Script command = new Script(!_inSystemVM, "mount", _timeout, s_logger);
command.add("-t", "nfs");
if (_inSystemVM) {
//Fedora Core 12 errors out with any -o option executed from java
command.add("-o", "soft,timeo=133,retrans=2147483647,tcp,acdirmax=0,acdirmin=0");
}
command.add(path);
command.add(mountPoint);
result = command.execute();
if (result != null) {
s_logger.warn("Unable to mount " + path + " due to " + result);
File file = new File(mountPoint);
if (file.exists())
file.delete();
return null;
}
// XXX: Adding the check for creation of snapshots dir here. Might have to move it somewhere more logical later.
if (!checkForSnapshotsDir(mountPoint)) {
return null;
}
// Create the volumes dir
if (!checkForVolumesDir(mountPoint)) {
return null;
}
return mountPoint;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public StartupCommand[] initialize() {
/*disconnected();
_parent = mount(_nfsPath, _mountParent);
if( _parent == null ) {
s_logger.warn("Unable to mount the nfs server");
return null;
}
try {
_params.put("template.parent", _parent);
_params.put(StorageLayer.InstanceConfigKey, _storage);
_dlMgr = new DownloadManagerImpl();
_dlMgr.configure("DownloadManager", _params);
} catch (ConfigurationException e) {
s_logger.warn("Caught problem while configuring folers", e);
return null;
}*/
final StartupStorageCommand cmd = new StartupStorageCommand(_parent, StoragePoolType.NetworkFilesystem, getTotalSize(), new HashMap<String, TemplateInfo>());
cmd.setResourceType(Storage.StorageResourceType.SECONDARY_STORAGE);
cmd.setIqn(null);
fillNetworkInformation(cmd);
cmd.setDataCenter(_dc);
cmd.setPod(_pod);
cmd.setGuid(_guid);
cmd.setName(_guid);
cmd.setVersion(NfsSecondaryStorageResource.class.getPackage().getImplementationVersion());
/* gather TemplateInfo in second storage */
final Map<String, TemplateInfo> tInfo = _dlMgr.gatherTemplateInfo();
cmd.setTemplateInfo(tInfo);
cmd.getHostDetails().put("mount.parent", _mountParent);
cmd.getHostDetails().put("mount.path", _nfsPath);
String tok[] = _nfsPath.split(":");
cmd.setNfsShare("nfs://" + tok[0] + tok[1]);
if (cmd.getHostDetails().get("orig.url") == null) {
if (tok.length != 2) {
throw new CloudRuntimeException("Not valid NFS path" + _nfsPath);
}
String nfsUrl = "nfs://" + tok[0] + tok[1];
cmd.getHostDetails().put("orig.url", nfsUrl);
}
InetAddress addr;
try {
addr = InetAddress.getByName(tok[0]);
cmd.setPrivateIpAddress(addr.getHostAddress());
} catch (UnknownHostException e) {
cmd.setPrivateIpAddress(tok[0]);
}
return new StartupCommand [] {cmd};
}
protected boolean checkForSnapshotsDir(String mountPoint) {
String snapshotsDirLocation = mountPoint + File.separator + "snapshots";
return createDir("snapshots", snapshotsDirLocation, mountPoint);
}
protected boolean checkForVolumesDir(String mountPoint) {
String volumesDirLocation = mountPoint + "/" + "volumes";
return createDir("volumes", volumesDirLocation, mountPoint);
}
protected boolean createDir(String dirName, String dirLocation, String mountPoint) {
boolean dirExists = false;
File dir = new File(dirLocation);
if (dir.exists()) {
if (dir.isDirectory()) {
s_logger.debug(dirName + " already exists on secondary storage, and is mounted at " + mountPoint);
dirExists = true;
} else {
if (dir.delete() && _storage.mkdir(dirLocation)) {
dirExists = true;
}
}
} else if (_storage.mkdir(dirLocation)) {
dirExists = true;
}
if (dirExists) {
s_logger.info(dirName + " directory created/exists on Secondary Storage.");
} else {
s_logger.info(dirName + " directory does not exist on Secondary Storage.");
}
return dirExists;
}
@Override
protected String getDefaultScriptsDir() {
return "./scripts/storage/secondary";
}
}
|
package com.malhartech.bufferserver.util;
/**
*
* @author Chetan Narsude <chetan@malhar-inc.com>
*/
public class Codec
{
/**
* Writes the Variable Sized Integer of Length 32. Assumes that the buffer has 5 positions at least starting with offset.
*
* @param value
* @param offset
* @return int
*/
public static int writeRawVarint32(int value, byte[] buffer, int offset)
{
while (true) {
if ((value & ~0x7F) == 0) {
buffer[offset++] = (byte)value;
return offset;
}
else {
buffer[offset++] = (byte)((value & 0x7F) | 0x80);
value >>>= 7;
}
}
}
public static int writeRawVarint32(int value, byte[] buffer, int offset, int size)
{
int i = writeRawVarint32(value, buffer, offset);
int expectedOffset = offset + size;
if (i < expectedOffset
buffer[i - 1] |= 0x80;
while (i < expectedOffset) {
buffer[i++] = (byte)0x80;
}
buffer[i++] = 0;
}
return i;
}
public static int getSizeOfRawVarint32(int value)
{
int offset = 0;
while (true) {
if ((value & ~0x7F) == 0) {
return ++offset;
}
else {
++offset;
value >>>= 7;
}
}
}
/**
*
* @param current
*/
public static void readRawVarInt32(SerializedData current)
{
final byte[] data = current.bytes;
int offset = current.offset;
byte tmp = data[offset++];
if (tmp >= 0) {
current.dataOffset = offset;
current.size = tmp + offset - current.offset;
return;
}
int result = tmp & 0x7f;
if ((tmp = data[offset++]) >= 0) {
result |= tmp << 7;
}
else {
result |= (tmp & 0x7f) << 7;
if ((tmp = data[offset++]) >= 0) {
result |= tmp << 14;
}
else {
result |= (tmp & 0x7f) << 14;
if ((tmp = data[offset++]) >= 0) {
result |= tmp << 21;
}
else {
result |= (tmp & 0x7f) << 21;
result |= (tmp = data[offset++]) << 28;
if (tmp < 0) {
// Discard upper 32 bits.
for (int i = 0; i < 5; i++) {
if (data[offset++] >= 0) {
current.dataOffset = offset;
current.size = result + offset - current.offset;
return;
}
}
current.size = -1;
return;
}
}
}
}
current.dataOffset = offset;
current.size = result + offset - current.offset;
}
public static String getStringWindowId(long windowId)
{
return String.valueOf(windowId >> 32) + "[" + (int)windowId + "]";
}
}
|
/**
* Implements the CFML Function dateconvert
*/
package lucee.runtime.functions.dateTime;
import lucee.runtime.PageContext;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.FunctionException;
import lucee.runtime.ext.function.Function;
import lucee.runtime.type.dt.DateTime;
import lucee.runtime.type.dt.DateTimeImpl;
public final class DateConvert implements Function {
public static DateTime call(PageContext pc , String conversionType, DateTime date) throws FunctionException {
//throw new ApplicationException("This function is no longer supported, because it gives you the wrong impression that the timezone is part of the date object, what is wrong!" +
int offset = pc.getTimeZone().getOffset(date.getTime());
conversionType=conversionType.toLowerCase();
if(conversionType.equals("local2utc")) {
return new DateTimeImpl(pc,date.getTime()-offset,false);
}
else if(conversionType.equals("utc2local")) {
return new DateTimeImpl(pc,date.getTime()+offset,false);
}
throw new FunctionException(pc,"DateConvert",1,"conversionType","invalid conversion-type ["+conversionType+"] for function dateConvert");
}
}
|
package com.jenjinstudios.jgcf;
import com.jenjinstudios.message.Message;
import com.jenjinstudios.world.ClientObject;
import com.jenjinstudios.world.ClientPlayer;
import com.jenjinstudios.world.state.MoveState;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The WorldClient class is used to connect to a WorldServer and stores information about the environment immediately
* surrounding the player.
* @author Caleb Brinkman
*/
public class WorldClient extends AuthClient
{
/** The logger associated with this class. */
private static final Logger LOGGER = Logger.getLogger(WorldClient.class.getName());
/** Actors other than the player. */
private final TreeMap<Integer, ClientObject> visibleObjects;
/** The password used to login to the world. */
private final String password;
/** The actor representing the player controlled by this client. */
private ClientPlayer player;
/** The number of milliseconds before a blocking method should time out. */
public static long TIMEOUT_MILLIS = 30000;
/**
* Construct a client connecting to the given address over the given port. This client <i>must</i> have a username and
* password.
* @param address The address to which this client will attempt to connect.
* @param port The port over which this client will attempt to connect.
* @param username The username that will be used by this client.
* @param password The password that will be used by this client.
*/
public WorldClient(String address, int port, String username, String password) {
super(address, port, username, password);
visibleObjects = new TreeMap<>();
this.password = password;
// Create the update loop and add it to the task list.
/* The loop used to update non-player objects. */
addRepeatedTask(new Runnable()
{
@Override
public void run() {
Set<Integer> keys = visibleObjects.keySet();
for (int i : keys)
{
ClientObject currentObject = visibleObjects.get(i);
currentObject.update();
}
if (player != null)
{
player.update();
LinkedList<MoveState> newStates = player.getSavedStates();
while (!newStates.isEmpty())
sendStateChangeRequest(newStates.remove());
}
}
});
}
/**
* Send a state change request to the server.
* @param moveState The move state used to generate the request.
*/
private void sendStateChangeRequest(MoveState moveState) {
Message stateChangeRequest = generateStateChangeRequest(moveState);
queueMessage(stateChangeRequest);
}
/**
* Generate a state change request for the given move state.
* @param moveState The state used to generate a state change request.
* @return The generated message.
*/
private Message generateStateChangeRequest(MoveState moveState) {
Message stateChangeRequest = new Message("StateChangeRequest");
stateChangeRequest.setArgument("relativeAngle", moveState.relativeAngle);
stateChangeRequest.setArgument("absoluteAngle", moveState.absoluteAngle);
stateChangeRequest.setArgument("stepsUntilChange", moveState.stepsUntilChange);
return stateChangeRequest;
}
/** Log the player into the world, and set the returned player as the actor for this client. */
@Override
public void sendBlockingLoginRequest() {
sendLoginRequest();
long startTime = System.currentTimeMillis();
long timepast = System.currentTimeMillis() - startTime;
while (!hasReceivedLoginResponse() && (timepast < TIMEOUT_MILLIS))
{
try
{
Thread.sleep(1);
} catch (InterruptedException e)
{
LOGGER.log(Level.WARNING, "Interrupted while waiting for login response.", e);
}
timepast = System.currentTimeMillis() - startTime;
}
}
/** Log the player out of the world. Blocks until logout is confirmed, or the 30 second timeout is reached. */
@Override
public void sendBlockingLogoutRequest() {
sendLogoutRequest();
long startTime = System.currentTimeMillis();
long timepast = System.currentTimeMillis() - startTime;
while (!hasReceivedLogoutResponse() && (timepast < TIMEOUT_MILLIS))
{
try
{
Thread.sleep(10);
} catch (InterruptedException e)
{
LOGGER.log(Level.WARNING, "Interrupted while waiting for login response.", e);
}
timepast = System.currentTimeMillis() - startTime;
}
}
/** Send a LogoutRequest to the server. */
private void sendLogoutRequest() {
Message logoutRequest = new Message("WorldLogoutRequest");
// Send the request, continue when response is received.
setReceivedLogoutResponse(false);
queueMessage(logoutRequest);
}
/** Send a LoginRequest to the server. */
private void sendLoginRequest() {
Message loginRequest = generateLoginRequest();
setReceivedLoginResponse(false);
queueMessage(loginRequest);
}
/**
* Generate a LoginRequest message.
* @return The LoginRequest message.
*/
private Message generateLoginRequest() {
Message loginRequest = new Message("WorldLoginRequest");
loginRequest.setArgument("username", getUsername());
loginRequest.setArgument("password", password);
return loginRequest;
}
/**
* Add an object to the list of visible objects. This method should be called synchronously.
* @param object The object to add to the visible objects list.
*/
public void addNewVisible(ClientObject object) {
visibleObjects.put(object.getId(), object);
}
/**
* Remove an object from the player's view.
* @param id the id of the object to remove.
*/
public void removeVisible(int id) {
visibleObjects.remove(id);
}
/**
* Get the map of visible objects.
* @return The map of visible objects.
*/
public TreeMap<Integer, ClientObject> getVisibleObjects() {
return visibleObjects;
}
/**
* Get the player associated with this client.
* @return The player (ClientActor) associated with this client.
*/
public ClientPlayer getPlayer() {
return player;
}
/**
* Set the player being controlled by this client.
* @param player The player to be controlled by this client.
*/
public void setPlayer(ClientPlayer player) {
if (this.player != null)
throw new IllegalStateException("Player already set!");
this.player = player;
}
/**
* Get the ClientObject with the given ID.
* @param id The ID of the object to retrieve.
* @return The object with the given ID.
*/
public ClientObject getObject(int id) {
return visibleObjects.get(id);
}
}
|
package me.lucko.luckperms.api.vault.cache;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.LPBukkitPlugin;
import me.lucko.luckperms.api.Contexts;
import me.lucko.luckperms.api.Node;
import me.lucko.luckperms.api.vault.VaultPermissionHook;
import me.lucko.luckperms.users.User;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@RequiredArgsConstructor
public class VaultUser {
private final LPBukkitPlugin plugin;
private final VaultPermissionHook vault;
@Getter
private final User user;
@Getter
private final Map<Map<String, String>, ContextCache> contextData = new ConcurrentHashMap<>();
@Getter
private final Map<Map<String, String>, ChatCache> chatData = new ConcurrentHashMap<>();
public boolean hasPermission(Map<String, String> context, String permission) {
ContextCache cd = contextData.computeIfAbsent(context, map -> calculatePermissions(map, false));
return cd.getPermissionValue(permission).asBoolean();
}
public ChatCache processChatData(Map<String, String> context) {
return chatData.computeIfAbsent(context, map -> calculateChat(map, false));
}
public ContextCache calculatePermissions(Map<String, String> context, boolean apply) {
Map<String, Boolean> toApply = user.exportNodes(
new Contexts(context, vault.isIncludeGlobal(), true, true, true, true),
Collections.emptyList(),
true
);
ContextCache existing = contextData.get(context);
if (existing == null) {
existing = new ContextCache(user, context, plugin, plugin.getDefaultsProvider());
if (apply) {
contextData.put(context, existing);
}
}
boolean different = false;
if (toApply.size() != existing.getPermissionCache().size()) {
different = true;
} else {
for (Map.Entry<String, Boolean> e : existing.getPermissionCache().entrySet()) {
if (toApply.containsKey(e.getKey()) && toApply.get(e.getKey()) == e.getValue()) {
continue;
}
different = true;
break;
}
}
if (!different) return existing;
existing.getPermissionCache().clear();
existing.invalidateCache();
existing.getPermissionCache().putAll(toApply);
return existing;
}
public ChatCache calculateChat(Map<String, String> context, boolean apply) {
ChatCache existing = chatData.get(context);
if (existing == null) {
existing = new ChatCache(context);
if (apply) {
chatData.put(context, existing);
}
}
Map<String, String> contexts = new HashMap<>(context);
String server = contexts.get("server");
String world = contexts.get("world");
contexts.remove("server");
contexts.remove("world");
existing.invalidateCache();
// Load meta
for (Node n : user.getPermissions(true)) {
if (!n.getValue()) {
continue;
}
if (!n.isMeta()) {
continue;
}
if (!n.shouldApplyOnServer(server, vault.isIncludeGlobal(), false)) {
continue;
}
if (!n.shouldApplyOnWorld(world, true, false)) {
continue;
}
if (!n.shouldApplyWithContext(contexts, false)) {
continue;
}
Map.Entry<String, String> meta = n.getMeta();
existing.getMeta().put(meta.getKey(), meta.getValue());
}
// Load prefixes & suffixes
int prefixPriority = Integer.MIN_VALUE;
int suffixPriority = Integer.MIN_VALUE;
for (Node n : user.getAllNodes(null, new Contexts(context, vault.isIncludeGlobal(), true, true, true, true))) {
if (!n.getValue()) {
continue;
}
if (!n.isPrefix() && !n.isSuffix()) {
continue;
}
if (!n.shouldApplyOnServer(server, vault.isIncludeGlobal(), false)) {
continue;
}
if (!n.shouldApplyOnWorld(world, true, false)) {
continue;
}
if (!n.shouldApplyWithContext(contexts, false)) {
continue;
}
if (n.isPrefix()) {
Map.Entry<Integer, String> value = n.getPrefix();
if (value.getKey() > prefixPriority) {
existing.setPrefix(value.getValue());
prefixPriority = value.getKey();
}
} else {
Map.Entry<Integer, String> value = n.getSuffix();
if (value.getKey() > suffixPriority) {
existing.setSuffix(value.getValue());
suffixPriority = value.getKey();
}
}
}
return existing;
}
}
|
package org.jtrim.image;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.util.Arrays;
import java.util.Map;
import org.jtrim.collections.CollectionsEx;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
*
* @author Kelemen Attila
*/
public class ImageDataTest {
private static final Map<Integer, Double> EXPECTED_PIXEL_SIZES;
private static final int TEST_IMG_WIDTH = 8;
private static final int TEST_IMG_HEIGHT = 9;
private static final int[][] TEST_PIXELS;
static {
TEST_PIXELS = new int[TEST_IMG_HEIGHT][TEST_IMG_WIDTH];
int pos = 0;
for (int y = 0; y < TEST_IMG_HEIGHT; y++) {
@SuppressWarnings("MismatchedReadAndWriteOfArray")
int[] line = TEST_PIXELS[y];
for (int x = 0; x < TEST_IMG_WIDTH; x++) {
int gray = (0xFF * pos) / (TEST_IMG_WIDTH * TEST_IMG_HEIGHT);
line[x] = gray | (gray << 8) | (gray << 16) | 0xFF00_0000;
pos++;
}
}
EXPECTED_PIXEL_SIZES = CollectionsEx.newHashMap(32);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_3BYTE_BGR, 3.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_4BYTE_ABGR, 4.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_4BYTE_ABGR_PRE, 4.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_BYTE_BINARY, 1.0 / 8.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_BYTE_GRAY, 1.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_BYTE_INDEXED, 1.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_INT_ARGB, 4.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_INT_ARGB_PRE, 4.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_INT_BGR, 4.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_INT_RGB, 4.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_USHORT_555_RGB, 2.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_USHORT_565_RGB, 2.0);
EXPECTED_PIXEL_SIZES.put(BufferedImage.TYPE_USHORT_GRAY, 2.0);
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getStoredPixelSize method, of class ImageData.
*/
@Test
public void testGetStoredPixelSize() {
for (Map.Entry<Integer, Double> sizeEntry: EXPECTED_PIXEL_SIZES.entrySet()) {
double size = ImageData.getStoredPixelSize(getColorModelForType(sizeEntry.getKey()));
assertEquals("Size for buffer type: " + sizeEntry.getKey(),
sizeEntry.getValue().doubleValue(), size, 0.001);
}
}
/**
* Test of getApproxSize method, of class ImageData.
*/
@Test
public void testGetApproxSize() {
for (Map.Entry<Integer, Double> sizeEntry: EXPECTED_PIXEL_SIZES.entrySet()) {
int width = 8;
int height = 9;
BufferedImage image = new BufferedImage(width, height, sizeEntry.getKey());
long expectedSize = Math.round(sizeEntry.getValue().doubleValue() * (double)width * (double)height);
long approxSize = ImageData.getApproxSize(image);
assertEquals("Approximate size for buffer: " + sizeEntry.getKey(), expectedSize, approxSize);
}
}
private static ColorModel getColorModelForType(int imageType) {
BufferedImage image = new BufferedImage(1, 1, imageType);
return image.getColorModel();
}
private static boolean isNoAlphaRgbType(int imageType) {
switch (imageType) {
case BufferedImage.TYPE_3BYTE_BGR:
case BufferedImage.TYPE_INT_BGR:
case BufferedImage.TYPE_INT_RGB:
return true;
default:
return false;
}
}
private static boolean isAlphaRgbType(int imageType) {
switch (imageType) {
case BufferedImage.TYPE_4BYTE_ABGR:
case BufferedImage.TYPE_4BYTE_ABGR_PRE:
case BufferedImage.TYPE_INT_ARGB:
case BufferedImage.TYPE_INT_ARGB_PRE:
return true;
default:
return false;
}
}
private static boolean isRgbType(int imageType) {
return isAlphaRgbType(imageType) || isNoAlphaRgbType(imageType);
}
private static void testGetCompatibleBufferTypeExact(int imageType) {
int receivedType = ImageData.getCompatibleBufferType(getColorModelForType(imageType));
assertTrue("Compatible buffer for type: " + imageType + ", received type: " + receivedType,
imageType == receivedType || receivedType == BufferedImage.TYPE_CUSTOM);
}
private static void testGetCompatibleBufferTypeRgb(int imageType) {
int receivedType = ImageData.getCompatibleBufferType(getColorModelForType(imageType));
assertTrue("Compatible buffer for type: " + imageType + ", received type: " + receivedType,
isRgbType(receivedType) || receivedType == BufferedImage.TYPE_CUSTOM);
}
private static void testGetCompatibleBufferTypeAlphaRgb(int imageType) {
int receivedType = ImageData.getCompatibleBufferType(getColorModelForType(imageType));
assertTrue("Compatible buffer for type: " + imageType + ", received type: " + receivedType,
isAlphaRgbType(receivedType) || receivedType == BufferedImage.TYPE_CUSTOM);
}
/**
* Test of getCompatibleBufferType method, of class ImageData.
*/
@Test
public void testGetCompatibleBufferType() {
testGetCompatibleBufferTypeRgb(BufferedImage.TYPE_3BYTE_BGR);
testGetCompatibleBufferTypeAlphaRgb(BufferedImage.TYPE_4BYTE_ABGR);
testGetCompatibleBufferTypeAlphaRgb(BufferedImage.TYPE_4BYTE_ABGR_PRE);
testGetCompatibleBufferTypeAlphaRgb(BufferedImage.TYPE_INT_ARGB);
testGetCompatibleBufferTypeAlphaRgb(BufferedImage.TYPE_INT_ARGB_PRE);
testGetCompatibleBufferTypeRgb(BufferedImage.TYPE_INT_BGR);
testGetCompatibleBufferTypeRgb(BufferedImage.TYPE_INT_RGB);
testGetCompatibleBufferTypeExact(BufferedImage.TYPE_BYTE_BINARY);
testGetCompatibleBufferTypeExact(BufferedImage.TYPE_BYTE_GRAY);
testGetCompatibleBufferTypeExact(BufferedImage.TYPE_BYTE_INDEXED);
testGetCompatibleBufferTypeExact(BufferedImage.TYPE_USHORT_555_RGB);
testGetCompatibleBufferTypeExact(BufferedImage.TYPE_USHORT_565_RGB);
testGetCompatibleBufferTypeExact(BufferedImage.TYPE_USHORT_GRAY);
}
private static void testCreateCompatibleBuffer(int imageType) {
BufferedImage origImage = new BufferedImage(1, 1, imageType);
int width = 8;
int height = 9;
BufferedImage compatibleBuffer = ImageData.createCompatibleBuffer(origImage, width, height);
assertEquals(width, compatibleBuffer.getWidth());
assertEquals(height, compatibleBuffer.getHeight());
int compatibleType = compatibleBuffer.getType();
assertTrue("Compatible buffer for type: " + imageType + ", received type: " + compatibleType,
imageType == compatibleType || compatibleType == BufferedImage.TYPE_CUSTOM);
}
/**
* Test of createCompatibleBuffer method, of class ImageData.
*/
@Test
public void testCreateCompatibleBuffer() {
for (Map.Entry<Integer, Double> sizeEntry: EXPECTED_PIXEL_SIZES.entrySet()) {
testCreateCompatibleBuffer(sizeEntry.getKey());
}
}
private static BufferedImage createTestImage(int imageType) {
BufferedImage bufferedImage = new BufferedImage(TEST_IMG_WIDTH, TEST_IMG_HEIGHT, imageType);
for (int y = 0; y < TEST_IMG_HEIGHT; y++) {
for (int x = 0; x < TEST_IMG_WIDTH; x++) {
bufferedImage.setRGB(x, y, TEST_PIXELS[y][x]);
}
}
return bufferedImage;
}
private static boolean rgbEquals(int rgb1, int rgb2, int tolerancePerComponent) {
for (int i = 0; i < 4; i++) {
int bitOffset = 8 * i;
int mask = 0xFF << bitOffset;
int c1 = (rgb1 & mask) >>> bitOffset;
int c2 = (rgb2 & mask) >>> bitOffset;
if (Math.abs(c1 - c2) > tolerancePerComponent) {
return false;
}
}
return true;
}
private static void checkIfTestImage(BufferedImage image, int tolerancePerComponent) {
assertEquals(TEST_IMG_WIDTH, image.getWidth());
assertEquals(TEST_IMG_HEIGHT, image.getHeight());
for (int y = 0; y < TEST_IMG_HEIGHT; y++) {
for (int x = 0; x < TEST_IMG_WIDTH; x++) {
int rgb = image.getRGB(x, y);
int expected = TEST_PIXELS[y][x];
assertTrue("Pixels must match. Expected: "
+ Integer.toHexString(expected)
+ ". Received: "
+ Integer.toHexString(rgb),
rgbEquals(rgb, expected, tolerancePerComponent));
}
}
}
/**
* Test of cloneImage method, of class ImageData.
*/
@Test
public void testCloneImage() {
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_3BYTE_BGR)), 0);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_4BYTE_ABGR)), 0);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_4BYTE_ABGR_PRE)), 0);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_INT_ARGB)), 0);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_INT_ARGB_PRE)), 0);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_INT_BGR)), 0);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_INT_RGB)), 0);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_USHORT_555_RGB)), 5);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_USHORT_565_RGB)), 5);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_BYTE_GRAY)), 10);
checkIfTestImage(ImageData.cloneImage(createTestImage(BufferedImage.TYPE_USHORT_GRAY)), 10);
}
/**
* Test of createNewAcceleratedBuffer method, of class ImageData.
*/
@Test
public void testCreateNewAcceleratedBuffer() {
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_3BYTE_BGR)), 0);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_4BYTE_ABGR)), 0);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_4BYTE_ABGR_PRE)), 0);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_INT_ARGB)), 0);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_INT_ARGB_PRE)), 0);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_INT_BGR)), 0);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_INT_RGB)), 0);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_555_RGB)), 5);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_565_RGB)), 5);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_BYTE_GRAY)), 10);
checkIfTestImage(ImageData.createAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_GRAY)), 10);
}
/**
* Test of createAcceleratedBuffer method, of class ImageData.
*/
@Test
public void testCreateAcceleratedBuffer() {
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_3BYTE_BGR)), 0);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_4BYTE_ABGR)), 0);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_4BYTE_ABGR_PRE)), 0);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_INT_ARGB)), 0);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_INT_ARGB_PRE)), 0);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_INT_BGR)), 0);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_INT_RGB)), 0);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_555_RGB)), 5);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_565_RGB)), 5);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_BYTE_GRAY)), 10);
checkIfTestImage(ImageData.createNewAcceleratedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_GRAY)), 10);
}
/**
* Test of createNewOptimizedBuffer method, of class ImageData.
*/
@Test
public void testCreateNewOptimizedBuffer() {
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_3BYTE_BGR)), 0);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_4BYTE_ABGR)), 0);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_4BYTE_ABGR_PRE)), 0);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_INT_ARGB)), 0);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_INT_ARGB_PRE)), 0);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_INT_BGR)), 0);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_INT_RGB)), 0);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_555_RGB)), 5);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_565_RGB)), 5);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_BYTE_GRAY)), 10);
checkIfTestImage(ImageData.createNewOptimizedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_GRAY)), 10);
}
/**
* Test of createOptimizedBuffer method, of class ImageData.
*/
@Test
public void testCreateOptimizedBuffer() {
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_3BYTE_BGR)), 0);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_4BYTE_ABGR)), 0);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_4BYTE_ABGR_PRE)), 0);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_INT_ARGB)), 0);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_INT_ARGB_PRE)), 0);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_INT_BGR)), 0);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_INT_RGB)), 0);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_555_RGB)), 5);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_565_RGB)), 5);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_BYTE_GRAY)), 10);
checkIfTestImage(ImageData.createOptimizedBuffer(
createTestImage(BufferedImage.TYPE_USHORT_GRAY)), 10);
}
private static BufferedImage createRgbImage(int width, int height) {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
/**
* Test of properties of a newly created ImageData.
*/
@Test
public void testProperties() {
int width = 8;
int height = 9;
for (BufferedImage image: Arrays.asList(null, createRgbImage(width, height))) {
for (ImageMetaData metaData: Arrays.asList(null, new ImageMetaData(width, height, true))) {
for (ImageReceiveException exception: Arrays.asList(null, mock(ImageReceiveException.class))) {
ImageData data = new ImageData(image, metaData, exception);
assertSame(image, data.getImage());
assertSame(metaData, data.getMetaData());
assertSame(exception, data.getException());
assertEquals(ImageData.getApproxSize(image), data.getApproxMemorySize());
if (image != null || metaData != null) {
assertEquals(width, data.getWidth());
assertEquals(height, data.getHeight());
}
else {
assertEquals(-1, data.getWidth());
assertEquals(-1, data.getHeight());
}
}
}
}
}
}
|
package com.github.resource4j;
import static org.junit.Assert.*;
import java.util.Optional;
import java.util.function.Supplier;
import org.junit.Test;
public abstract class OptionalValueContracts extends ResourceValueContracts {
@Override
protected abstract OptionalValue<String> createValue(ResourceKey key, String content);
@Test
public void testOrDefaultReturnsOptionalValueContentWhenNotNull() throws Exception {
String content = someContent();
OptionalValue<String> value = createValue(anyKey(), content);
assertSame(content, value.orDefault("Another content"));
}
@Test
public void testOrReturnsMandatoryValueWithSameContentWhenNotNull() throws Exception {
String content = someContent();
OptionalValue<String> value = createValue(anyKey(), content);
MandatoryValue<String> mandatoryValue = value.or("Another content");
assertSame(value.asIs(), mandatoryValue.asIs());
assertSame(value.key(), mandatoryValue.key());
}
@Test
public void testOrReturnsMandatoryValueWithDefaultContentWhenNull() throws Exception {
String content = someContent();
OptionalValue<String> value = createValue(anyKey(), null);
MandatoryValue<String> mandatoryValue = value.or(content);
assertSame(content, mandatoryValue.asIs());
assertSame(value.key(), mandatoryValue.key());
}
@Test(expected = NullPointerException.class)
public void testOrThrowsNullPointerExceptionIfDefaultValueIsNull() throws Exception {
OptionalValue<String> value = createValue(anyKey(), someContent());
value.or((String) null);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test(expected = NullPointerException.class)
public void testOrThrowsNullPointerExceptionIfSupplierIsNull() throws Exception {
OptionalValue<String> value = createValue(anyKey(), someContent());
value.orElseGet((Supplier) null);
}
@Test(expected = NullPointerException.class)
public void testOrDefaultNullPointerExceptionIfDefaultValueIsNull() throws Exception {
OptionalValue<String> value = createValue(anyKey(), someContent());
value.orDefault(null);
}
@Test
public void testNotNullReturnsMandatoryValueWithSameContentWhenNotNull() throws Exception {
String content = someContent();
OptionalValue<String> value = createValue(anyKey(), content);
MandatoryValue<String> mandatoryValue = value.notNull();
assertSame(value.asIs(), mandatoryValue.asIs());
assertSame(value.key(), mandatoryValue.key());
}
@Test(expected = MissingValueException.class)
public void testNotNullThrowsMissingValueExceptionWhenNull() throws Exception {
OptionalValue<String> value = createValue(anyKey(), null);
value.notNull();
}
@Test
public void testStdReturnsJavaUtilOptional() {
OptionalValue<String> value = createValue(anyKey(), someContent());
Optional<String> s = value.std();
assertEquals(s.get(), value.asIs());
}
@Test
public void testStdReturnsJavaUtilOptionalOfNull() {
OptionalValue<String> value = createValue(anyKey(), null);
Optional<String> s = value.std();
assertFalse(s.isPresent());
}
}
|
package com.questdb.factory;
import com.questdb.JournalWriter;
import com.questdb.factory.configuration.JournalStructure;
import com.questdb.test.tools.AbstractTest;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
public class CachingWriterFactoryTest extends AbstractTest {
@Test
public void testOneThreadGetRelease() throws Exception {
JournalStructure s = new JournalStructure("x").$date("ts").$();
CachingWriterFactory wf = theFactory.getCachingWriterFactory();
JournalWriter x;
JournalWriter y;
x = wf.writer(s);
try {
Assert.assertEquals(0, wf.countFreeWriters());
Assert.assertNotNull(x);
Assert.assertTrue(x.isOpen());
Assert.assertTrue(x == wf.writer(s));
} finally {
x.close();
}
Assert.assertEquals(1, wf.countFreeWriters());
y = wf.writer(s);
try {
Assert.assertNotNull(y);
Assert.assertTrue(y.isOpen());
Assert.assertTrue(y == x);
} finally {
y.close();
}
Assert.assertEquals(1, wf.countFreeWriters());
}
@Test
public void testTwoThreadsRaceToAllocate() throws Exception {
final JournalStructure s = new JournalStructure("x").$date("ts").$();
final CachingWriterFactory wf = theFactory.getCachingWriterFactory();
int n = 2;
final CyclicBarrier barrier = new CyclicBarrier(n);
final CountDownLatch halt = new CountDownLatch(n);
final AtomicInteger errors = new AtomicInteger();
final AtomicInteger writerCount = new AtomicInteger();
for (int i = 0; i < n; i++) {
new Thread() {
@Override
public void run() {
try {
barrier.await();
try (JournalWriter w = wf.writer(s)) {
if (w != null) {
writerCount.incrementAndGet();
}
}
} catch (Exception e) {
e.printStackTrace();
errors.incrementAndGet();
} finally {
halt.countDown();
}
}
}.start();
}
halt.await();
// this check is unreliable on slow build servers
// it is very often the case that there are limited number of cores
// available and threads execute sequentially rather than
// simultaneously. We should check that none of the threads
// receive error.
// Assert.assertEquals(1, writerCount.get());
Assert.assertEquals(0, errors.get());
Assert.assertEquals(1, wf.countFreeWriters());
}
}
|
package com.example.mobilesafe;
import com.example.mobilesafe.service.AddressService;
import com.example.mobilesafe.ui.SettingClickView;
import com.example.mobilesafe.ui.SettingItemView;
import com.example.mobilesafe.utils.ServiceUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class SettingActivity extends Activity {
private SettingItemView siv_update;
private SettingItemView siv_show_address;
private Intent showAddress;
private SharedPreferences sp;
private SettingClickView scv_changebg;
/**
* Activity
*/
@Override
protected void onResume() {
// TODO
super.onResume();
showAddress=new Intent(this,AddressService.class);
boolean isServiceRunning=ServiceUtils.isServiceRunning(SettingActivity.this,"com.example.mobilesafe.service.AddressService");
if(isServiceRunning){
siv_show_address.setChecked(true);
}else{
siv_show_address.setChecked(false);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sp=getSharedPreferences("config",MODE_PRIVATE);
siv_update=(SettingItemView) findViewById(R.id.siv_update);
boolean update=sp.getBoolean("update", false);
if(update){
siv_update.setChecked(update);
// siv_update.setDesc(update);
}else{
siv_update.setChecked(update);
// siv_update.setDesc(update);
// siv_update.setStatus(update);
}
siv_update.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Editor editor=sp.edit();
if(siv_update.isChecked()){
siv_update.setChecked(false);
// siv_update.setDesc(false);
// siv_update.setStatus(false);
editor.putBoolean("update",false);
}else{
siv_update.setChecked(true);
// siv_update.setDesc(true);
// siv_update.setStatus(true);
editor.putBoolean("update",true);
}
editor.commit();
}
});
siv_show_address=(SettingItemView) findViewById(R.id.siv_show_address);
showAddress=new Intent(this,AddressService.class);
boolean isServiceRunning=ServiceUtils.isServiceRunning(SettingActivity.this,"com.example.mobilesafe.service.AddressService");
if(isServiceRunning){
siv_show_address.setChecked(true);
}else{
siv_show_address.setChecked(false);
}
siv_show_address.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(siv_show_address.isChecked()){
siv_show_address.setChecked(false);
stopService(showAddress);
}else{
siv_show_address.setChecked(true);
startService(showAddress);
}
}
});
scv_changebg=(SettingClickView) findViewById(R.id.scv_changebg);
scv_changebg.setTitle("");
final String[] items={"","","","",""};
int which=sp.getInt("which",0);
scv_changebg.setDesc(items[which]);
scv_changebg.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int dd=sp.getInt("which",0);
AlertDialog.Builder builder=new Builder(SettingActivity.this);
builder.setTitle("");
builder.setSingleChoiceItems(items, dd, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
Editor editor=sp.edit();
editor.putInt("which",which);
editor.commit();
scv_changebg.setDesc(items[which]);
dialog.dismiss();
}
});
builder.setNegativeButton("",null);
builder.show();
}
});
}
}
|
package org.treetank.access;
import static org.treetank.access.PageReadTrx.nodePageKey;
import static org.treetank.access.PageReadTrx.nodePageOffset;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.QName;
import org.treetank.api.INode;
import org.treetank.api.IPageWriteTrx;
import org.treetank.api.ISession;
import org.treetank.cache.BerkeleyPersistenceLog;
import org.treetank.cache.LRUCache;
import org.treetank.cache.LogKey;
import org.treetank.cache.NodePageContainer;
import org.treetank.exception.TTException;
import org.treetank.exception.TTIOException;
import org.treetank.io.IBackendWriter;
import org.treetank.page.IConstants;
import org.treetank.page.IndirectPage;
import org.treetank.page.NamePage;
import org.treetank.page.NodePage;
import org.treetank.page.NodePage.DeletedNode;
import org.treetank.page.RevisionRootPage;
import org.treetank.page.UberPage;
import org.treetank.utils.NamePageHash;
/**
* <h1>PageWriteTrx</h1>
*
* <p>
* See {@link PageReadTrx}.
* </p>
*/
public final class PageWriteTrx implements IPageWriteTrx {
/** Page writer to serialize. */
private final IBackendWriter mPageWriter;
/** Cache to store the changes in this writetransaction. */
private final LRUCache mLog;
/** Last reference to the actual revRoot. */
private final RevisionRootPage mNewRoot;
/** Last reference to the actual namePage. */
private final NamePage mNamePage;
/** Delegate for read access. */
private PageReadTrx mDelegate;
/**
* Standard constructor.
*
*
* @param pSession
* {@link ISession} reference
* @param pUberPage
* root of resource
* @param pWriter
* writer where this transaction should write to
* @param pRepresentRev
* revision represent
* @param pStoreRev
* revision store
* @throws TTIOException
* if IO Error
*/
protected PageWriteTrx(final ISession pSession, final UberPage pUberPage, final IBackendWriter pWriter,
final long pRepresentRev) throws TTException {
mDelegate = new PageReadTrx(pSession, pUberPage, pRepresentRev, pWriter);
mPageWriter = pWriter;
mLog =
new LRUCache(new BerkeleyPersistenceLog(new File(pSession.getConfig().mProperties
.getProperty(org.treetank.access.conf.ContructorProps.STORAGEPATH)),
pSession.getConfig().mNodeFac));
// Get previous revision root page..
final RevisionRootPage previousRevRoot =
(RevisionRootPage)mPageWriter.read(mDelegate.dereferenceLeafOfTree(mDelegate.getUberPage()
.getReferenceKeys()[UberPage.INDIRECT_REFERENCE_OFFSET], pRepresentRev));
// ...and using this data to initialize a fresh revision root including the pointers.
mNewRoot =
new RevisionRootPage(mDelegate.getUberPage().incrementPageCounter(), pRepresentRev + 1,
previousRevRoot.getMaxNodeKey());
mNewRoot.setReferenceKey(RevisionRootPage.INDIRECT_REFERENCE_OFFSET, previousRevRoot
.getReferenceKeys()[RevisionRootPage.INDIRECT_REFERENCE_OFFSET]);
// Prepare indirect tree to hold reference to prepared revision root
// nodePageReference.
LogKey indirectKey =
preparePathToLeaf(true,
mDelegate.getUberPage().getReferenceKeys()[UberPage.INDIRECT_REFERENCE_OFFSET], mDelegate
.getUberPage().getRevisionNumber());
NodePageContainer indirectContainer = mLog.get(indirectKey);
int offset = nodePageOffset(mDelegate.getUberPage().getRevisionNumber());
((IndirectPage)indirectContainer.getModified()).setReferenceKey(offset, mNewRoot.getPageKey());
mLog.put(indirectKey, indirectContainer);
// Setting up a new namepage
mNamePage = new NamePage(mDelegate.getUberPage().incrementPageCounter());
mNewRoot.setReferenceKey(RevisionRootPage.NAME_REFERENCE_OFFSET, mNamePage.getPageKey());
}
/**
* Prepare a node for modification. This is getting the node from the
* (persistence) layer, storing the page in the cache and setting up the
* node for upcoming modification. Note that this only occurs for {@link INode}s.
*
* @param pNodeKey
* key of the node to be modified
* @return an {@link INode} instance
* @throws TTIOException
* if IO Error
*/
public INode prepareNodeForModification(final long pNodeKey) throws TTException {
if (pNodeKey < 0) {
throw new IllegalArgumentException("paramNodeKey must be >= 0!");
}
final long seqNodePageKey = nodePageKey(pNodeKey);
final int nodePageOffset = nodePageOffset(pNodeKey);
NodePageContainer container = prepareNodePage(seqNodePageKey);
INode node = ((NodePage)container.getModified()).getNode(nodePageOffset);
if (node == null) {
final INode oldNode = ((NodePage)container.getComplete()).getNode(nodePageOffset);
if (oldNode == null) {
throw new TTIOException("Cannot retrieve node from cache");
}
node = oldNode;
((NodePage)container.getModified()).setNode(nodePageOffset, node);
}
return node;
}
/**
* Finishing the node modification. That is storing the node including the
* page in the cache.
*
* @param pNode
* the node to be modified
* @throws TTIOException
*/
public void finishNodeModification(final INode pNode) throws TTIOException {
final long seqNodePageKey = nodePageKey(pNode.getNodeKey());
final int nodePageOffset = nodePageOffset(pNode.getNodeKey());
LogKey key = new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, seqNodePageKey);
NodePageContainer container = mLog.get(key);
NodePage page = (NodePage)container.getModified();
page.setNode(nodePageOffset, pNode);
mLog.put(key, container);
}
/**
* Create fresh node and prepare node nodePageReference for modifications
* (COW).
*
* @param pNode
* node to add
* @return Unmodified node from parameter for convenience.
* @throws TTIOException
* if IO Error
*/
public <T extends INode> T createNode(final T pNode) throws TTException {
// Allocate node key and increment node count.
mNewRoot.incrementMaxNodeKey();
final long nodeKey = mNewRoot.getMaxNodeKey();
final long seqPageKey = nodePageKey(nodeKey);
final int nodePageOffset = nodePageOffset(nodeKey);
NodePageContainer container = prepareNodePage(seqPageKey);
final NodePage page = ((NodePage)container.getModified());
page.setNode(nodePageOffset, pNode);
mLog.put(new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, seqPageKey), container);
return pNode;
}
/**
* Removing a node from the storage.
*
* @param pNode
* {@link INode} to be removed
* @throws TTIOException
* if the removal fails
*/
public void removeNode(final INode pNode) throws TTException {
assert pNode != null;
final long nodePageKey = nodePageKey(pNode.getNodeKey());
NodePageContainer container = prepareNodePage(nodePageKey);
final INode delNode = new DeletedNode(pNode.getNodeKey());
((NodePage)container.getModified()).setNode(nodePageOffset(pNode.getNodeKey()), delNode);
((NodePage)container.getModified()).setNode(nodePageOffset(pNode.getNodeKey()), delNode);
mLog.put(new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, nodePageKey), container);
}
/**
* {@inheritDoc}
*/
public INode getNode(final long pNodeKey) throws TTException {
// Calculate page and node part for given nodeKey.
final long nodePageKey = nodePageKey(pNodeKey);
final int nodePageOffset = nodePageOffset(pNodeKey);
final NodePageContainer container =
mLog.get(new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, nodePageKey));
// Page was not modified yet, delegate to read or..
if (container == null) {
return mDelegate.getNode(pNodeKey);
}// ...page was modified, but not this node, take the complete part, or...
else if (((NodePage)container.getModified()).getNode(nodePageOffset) == null) {
final INode item = ((NodePage)container.getComplete()).getNode(nodePageOffset);
return mDelegate.checkItemIfDeleted(item);
}// ...page was modified and the modification touched this node.
else {
final INode item = ((NodePage)container.getModified()).getNode(nodePageOffset);
return mDelegate.checkItemIfDeleted(item);
}
}
/**
* Getting the name corresponding to the given key.
*
* @param pNameKey
* for the term searched
* @return the name
*/
public String getName(final int pNameKey) {
String returnVal;
// if currentNamePage == null -> state was commited and no
// prepareNodepage was invoked yet
if (mNamePage.getName(pNameKey) == null) {
returnVal = mDelegate.getName(pNameKey);
} else {
returnVal = mNamePage.getName(pNameKey);
}
return returnVal;
}
/**
* Creating a namekey for a given name.
*
* @param pName
* for which the key should be created.
* @return an int, representing the namekey
* @throws TTIOException
* if something odd happens while storing the new key
*/
public int createNameKey(final String pName) throws TTIOException {
final String string = (pName == null ? "" : pName);
final int nameKey = NamePageHash.generateHashForString(string);
if (mNamePage.getName(nameKey) == null) {
mNamePage.setName(nameKey, string);
}
return nameKey;
}
public void commit() throws TTException {
final UberPage uberPage =
new UberPage(mDelegate.getUberPage().getPageKey(), mDelegate.getUberPage().getRevisionNumber(),
mDelegate.getUberPage().getPageCounter());
// uberPage.setReferenceKey(UberPage.INDIRECT_REFERENCE_OFFSET, mLog.get(pKey))
mDelegate.getUberPage();
mPageWriter.writeUberPage(uberPage);
Iterator<Map.Entry<LogKey, NodePageContainer>> entries = mLog.getIterator();
while (entries.hasNext()) {
Map.Entry<LogKey, NodePageContainer> next = entries.next();
mPageWriter.write(next.getValue().getModified());
}
// Remember succesfully committed uber page in session state.
// TODO This is one of the dirtiest hacks I ever did! Sorry Future-ME!
((Session)mDelegate.mSession).setLastCommittedUberPage(uberPage);
}
/**
* {@inheritDoc}
*
* @throws TTIOException
* if something weird happened in the storage
*/
public void close() throws TTIOException {
mDelegate.mSession.deregisterPageTrx(this);
mDelegate.close();
mLog.clear();
// mPageWriter.close();
}
public long getMaxNodeKey() {
return mNewRoot.getMaxNodeKey();
}
private NodePageContainer prepareNodePage(final long pSeqPageKey) throws TTException {
LogKey key = new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, pSeqPageKey);
// See if on nodePageLevel, there are any pages...
NodePageContainer container = mLog.get(key);
// ... and start dereferencing of not.
if (container == null) {
LogKey indirectKey =
preparePathToLeaf(false,
mNewRoot.getReferenceKeys()[RevisionRootPage.INDIRECT_REFERENCE_OFFSET], pSeqPageKey);
NodePageContainer indirectContainer = mLog.get(indirectKey);
int offset = nodePageOffset(pSeqPageKey);
long pageKey = ((IndirectPage)indirectContainer.getModified()).getReferenceKeys()[offset];
NodePage newPage = new NodePage(mDelegate.getUberPage().incrementPageCounter());
if (pageKey != 0) {
NodePage oldPage = (NodePage)mPageWriter.read(pageKey);
container = new NodePageContainer(oldPage, newPage);
} else {
container = new NodePageContainer(newPage, newPage);
((IndirectPage)(indirectContainer.getModified())).setReferenceKey(offset, newPage
.getPageKey());
mLog.put(indirectKey, indirectContainer);
}
mLog.put(key, container);
}
return container;
}
/**
* Getting a NodePageContainer containing the last IndirectPage with the reference to any new/modified
* page.
*
* @param pIsRootLevel
* is this dereferencing walk based on the the search after a RevRoot or a NodePage. Needed
* because of the same keys in both subtrees.
* @param pStartKey
* start key where to start the tree-walk: either from an UberPage (related to new
* RevisionRootPages) or from a RevisionRootPage (related to new NodePages).
* @param pSeqPageKey
* the key of the page mapped to the layer
* @return the key the container representing the last level
* @throws TTException
*/
private LogKey
preparePathToLeaf(final boolean pIsRootLevel, final long pStartKey, final long pSeqPageKey)
throws TTException {
// Initial state pointing to the indirect page of level 0.
int offset = 0;
long levelKey = pSeqPageKey;
long pageKey = pStartKey;
LogKey key = null;
// Iterate through all levels.
for (int level = 0; level < IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length; level++) {
offset = (int)(levelKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[level]);
levelKey -= offset << IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[level];
// for each level, take a sharp look if the indirectpage was already modified within this
// transaction
key = new LogKey(pIsRootLevel, level, levelKey);
NodePageContainer container = mLog.get(key);
// if not...
if (container == null) {
IndirectPage newPage = new IndirectPage(mDelegate.getUberPage().incrementPageCounter());
//...point to this new indirect reference from either the UberPage or the RevRoot and...
if(level==0) {
if(pIsRootLevel) {
mDelegate.getUberPage().setReferenceKey(UberPage.INDIRECT_REFERENCE_OFFSET, newPage.getPageKey());
} else {
mNewRoot.setReferenceKey(RevisionRootPage.INDIRECT_REFERENCE_OFFSET, newPage.getPageKey());
}
}
// ...check if there is an existing indirect page...
if (pageKey != 0) {
// ..read it, copy all references and put it in the transaction log.
IndirectPage oldPage = (IndirectPage)mPageWriter.read(pageKey);
for (int i = 0; i < oldPage.getReferenceKeys().length; i++) {
newPage.setReferenceKey(i, oldPage.getReferenceKeys()[i]);
}
container = new NodePageContainer(oldPage, newPage);
}// ...otherwise a fresh page is necessary.
else {
container = new NodePageContainer(newPage, newPage);
}
}
mLog.put(key, container);
// finally, set the new pagekey for the next level
pageKey = ((IndirectPage)container.getModified()).getReferenceKeys()[offset];
}
// Return reference to leaf of indirect tree.
return key;
}
/**
* Current reference to actual rev-root page.
*
* @return the current revision root page
*/
public RevisionRootPage getActualRevisionRootPage() {
return mNewRoot;
}
/**
* Building name consisting out of prefix and name. NamespaceUri is not used
* over here.
*
* @param pQName
* the {@link QName} of an element
* @return a string with [prefix:]localname
*/
public static String buildName(final QName pQName) {
if (pQName == null) {
throw new NullPointerException("mQName must not be null!");
}
String name;
if (pQName.getPrefix().isEmpty()) {
name = pQName.getLocalPart();
} else {
name = new StringBuilder(pQName.getPrefix()).append(":").append(pQName.getLocalPart()).toString();
}
return name;
}
/**
* {@inheritDoc}
*/
@Override
public UberPage getUberPage() {
return mDelegate.getUberPage();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosed() {
return mDelegate.isClosed();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PageWriteTrx [mPageWriter=");
builder.append(mPageWriter);
builder.append(", mLog=");
builder.append(mLog);
builder.append(", mNewRoot=");
builder.append(mNewRoot);
builder.append(", mDelegate=");
builder.append(mDelegate);
builder.append("]");
return builder.toString();
}
}
|
package functionalTests.activeobject.futurecallbacks;
import java.util.concurrent.Future;
import org.objectweb.proactive.api.PAEventProgramming;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.core.util.MutableInteger;
public class A {
private A brother;
public static int counter = 0;
public A() {
}
public void myCallback(Future<MutableInteger> f) throws Exception {
MutableInteger i = f.get();
i.getValue();
synchronized (A.class) {
A.counter++;
A.class.notifyAll();
}
}
public void start() throws NoSuchMethodException {
MutableInteger slow = this.brother.slow();
PAEventProgramming.addActionOnFuture(slow, "myCallback");
MutableInteger fast = this.brother.fast();
PAFuture.waitFor(fast);
PAEventProgramming.addActionOnFuture(fast, "myCallback");
}
public MutableInteger slow() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new MutableInteger();
}
public MutableInteger fast() {
return new MutableInteger();
}
public void giveBrother(A a) {
this.brother = a;
}
}
|
package plugin.google.maps;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaResourceApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class PluginGroundOverlay extends MyPlugin implements MyPluginInterface {
/**
* Create ground overlay
*
* @param args
* @param callbackContext
* @throws JSONException
*/
public void create(JSONArray args, CallbackContext callbackContext) throws JSONException {
JSONObject opts = args.getJSONObject(1);
_createGroundOverlay(opts, callbackContext);
}
public void _createGroundOverlay(final JSONObject opts, final CallbackContext callbackContext) throws JSONException {
final GroundOverlayOptions options = new GroundOverlayOptions();
final JSONObject properties = new JSONObject();
if (opts.has("anchor")) {
JSONArray anchor = opts.getJSONArray("anchor");
options.anchor((float)anchor.getDouble(0), (float)anchor.getDouble(1));
}
if (opts.has("bearing")) {
options.bearing((float)opts.getDouble("bearing"));
}
if (opts.has("opacity")) {
options.transparency(1 - (float)opts.getDouble("opacity"));
}
if (opts.has("zIndex")) {
options.zIndex((float)opts.getDouble("zIndex"));
}
if (opts.has("visible")) {
options.visible(opts.getBoolean("visible"));
}
if (opts.has("bounds")) {
JSONArray points = opts.getJSONArray("bounds");
LatLngBounds bounds = PluginUtil.JSONArray2LatLngBounds(points);
options.positionFromBounds(bounds);
}
if (opts.has("clickable")) {
properties.put("isClickable", opts.getBoolean("clickable"));
} else {
properties.put("isClickable", true);
}
properties.put("isVisible", options.isVisible());
// Since this plugin provide own click detection,
// disable default clickable feature.
options.clickable(false);
// Load image
final String imageUrl = opts.getString("url");
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
setImage_(options, imageUrl, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
GroundOverlay groundOverlay = (GroundOverlay)object;
String id = "groundoverlay_" + groundOverlay.getId();
self.objects.put(id, groundOverlay);
String boundsId = "groundoverlay_bounds_" + groundOverlay.getId();
self.objects.put(boundsId, groundOverlay.getBounds());
String propertyId = "groundoverlay_property_" + groundOverlay.getId();
self.objects.put(propertyId, properties);
JSONObject result = new JSONObject();
try {
result.put("hashCode", groundOverlay.hashCode());
result.put("id", id);
self.objects.put("groundoverlay_property_" + groundOverlay.getId(), opts);
} catch (Exception e) {}
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
}
});
}
/**
* Remove this tile layer
* @param args
* @param callbackContext
* @throws JSONException
*/
public void remove(JSONArray args, CallbackContext callbackContext) throws JSONException {
String id = args.getString(0);
GroundOverlay groundOverlay = (GroundOverlay)self.objects.get(id);
if (groundOverlay == null) {
this.sendNoResult(callbackContext);
return;
}
String propertyId = "groundoverlay_property_" + id;
self.objects.remove(propertyId);
groundOverlay.remove();
this.sendNoResult(callbackContext);
}
/**
* Set image of the ground-overlay
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setImage(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(0);
GroundOverlay groundOverlay = (GroundOverlay)self.objects.get(id);
String url = args.getString(1);
String propertyId = "groundoverlay_property_" + id;
JSONObject opts = (JSONObject) self.objects.get(propertyId);
opts.put("url", url);
_createGroundOverlay(opts, callbackContext);
}
/**
* Set bounds
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setBounds(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(0);
GroundOverlay groundOverlay = (GroundOverlay)self.objects.get(id);
JSONArray points = args.getJSONArray(1);
LatLngBounds bounds = PluginUtil.JSONArray2LatLngBounds(points);
groundOverlay.setPositionFromBounds(bounds);
String boundsId = "groundoverlay_bounds_" + groundOverlay.getId();
self.objects.put(boundsId, groundOverlay.getBounds());
this.sendNoResult(callbackContext);
}
/**
* Set opacity
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setOpacity(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float alpha = (float)args.getDouble(1);
String id = args.getString(0);
this.setFloat("setTransparency", id, 1 - alpha, callbackContext);
}
/**
* Set bearing
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setBearing(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float bearing = (float)args.getDouble(1);
String id = args.getString(0);
this.setFloat("setBearing", id, bearing, callbackContext);
}
/**
* set z-index
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setZIndex(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(0);
float zIndex = (float) args.getDouble(1);
this.setFloat("setZIndex", id, zIndex, callbackContext);
}
/**
* Set visibility for the object
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException {
String id = args.getString(0);
final boolean isVisible = args.getBoolean(1);
final GroundOverlay groundOverlay = this.getGroundOverlay(id);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
groundOverlay.setVisible(isVisible);
}
});
String propertyId = "groundoverlay_property_" + groundOverlay.getId();
JSONObject properties = (JSONObject)self.objects.get(propertyId);
properties.put("isVisible", isVisible);
self.objects.put(propertyId, properties);
this.sendNoResult(callbackContext);
}
/**
* Set clickable for the object
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setClickable(JSONArray args, CallbackContext callbackContext) throws JSONException {
String id = args.getString(0);
final boolean clickable = args.getBoolean(1);
String propertyId = id.replace("groundoverlay_", "groundoverlay_property_");
JSONObject properties = (JSONObject)self.objects.get(propertyId);
properties.put("isClickable", clickable);
self.objects.put(propertyId, properties);
this.sendNoResult(callbackContext);
}
private void setImage_(final GroundOverlayOptions options, String iconUrl, final PluginAsyncInterface callback) {
if (iconUrl == null) {
callback.onPostExecute(null);
return;
}
if (!iconUrl.contains(":
!iconUrl.startsWith("/") &&
!iconUrl.startsWith("www/") &&
!iconUrl.startsWith("data:image") &&
!iconUrl.startsWith("./") &&
!iconUrl.startsWith("../")) {
iconUrl = "./" + iconUrl;
}
if (iconUrl.startsWith("./") || iconUrl.startsWith("../")) {
iconUrl = iconUrl.replace("././", "./");
String currentPage = PluginGroundOverlay.this.webView.getUrl();
currentPage = currentPage.replaceAll("[^\\/]*$", "");
iconUrl = currentPage + "/" + iconUrl;
}
if (iconUrl == null) {
callback.onPostExecute(null);
return;
}
final String imageUrl = iconUrl;
cordova.getThreadPool().submit(new Runnable() {
@Override
public void run() {
if (imageUrl.indexOf("http") != 0) {
// Load icon from local file
AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
String iconUrl = imageUrl;
if (iconUrl == null) {
return null;
}
Bitmap image = null;
if (iconUrl.indexOf("cdvfile:
CordovaResourceApi resourceApi = webView.getResourceApi();
iconUrl = PluginUtil.getAbsolutePathFromCDVFilePath(resourceApi, iconUrl);
}
if (iconUrl == null) {
return null;
}
if (iconUrl.indexOf("data:image/") == 0 && iconUrl.contains(";base64,")) {
String[] tmp = iconUrl.split(",");
image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]);
} else if (iconUrl.indexOf("file:
!iconUrl.contains("file:///android_asset/")) {
iconUrl = iconUrl.replace("file:
File tmp = new File(iconUrl);
if (tmp.exists()) {
image = BitmapFactory.decodeFile(iconUrl);
} else {
//if (PluginMarker.this.mapCtrl.mPluginLayout.isDebug) {
Log.w(TAG, "icon is not found (" + iconUrl + ")");
}
} else {
//Log.d(TAG, "iconUrl = " + iconUrl);
if (iconUrl.indexOf("file:///android_asset/") == 0) {
iconUrl = iconUrl.replace("file:///android_asset/", "");
}
//Log.d(TAG, "iconUrl = " + iconUrl);
if (iconUrl.contains("./")) {
try {
boolean isAbsolutePath = iconUrl.startsWith("/");
File relativePath = new File(iconUrl);
iconUrl = relativePath.getCanonicalPath();
//Log.d(TAG, "iconUrl = " + iconUrl);
if (!isAbsolutePath) {
iconUrl = iconUrl.substring(1);
}
//Log.d(TAG, "iconUrl = " + iconUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
AssetManager assetManager = PluginGroundOverlay.this.cordova.getActivity().getAssets();
InputStream inputStream;
try {
inputStream = assetManager.open(iconUrl);
image = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
if (image == null) {
return null;
}
return image;
}
@Override
protected void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(null);
return;
}
GroundOverlay groundOverlay = null;
try {
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
options.image(bitmapDescriptor);
groundOverlay = self.map.addGroundOverlay(options);
callback.onPostExecute(groundOverlay);
} catch (Exception e) {
Log.e(TAG,"PluginMarker: Warning - marker method called when marker has been disposed, wait for addMarker callback before calling more methods on the marker (setIcon etc).");
//e.printStackTrace();
try {
if (groundOverlay != null) {
groundOverlay.remove();
}
} catch (Exception ignore) {
ignore = null;
}
callback.onError(e.getMessage() + "");
}
}
};
task.execute();
return;
}
if (imageUrl.indexOf("http") == 0) {
// Load icon from on the internet
int width = -1;
int height = -1;
AsyncLoadImage task = new AsyncLoadImage(width, height, new AsyncLoadImageInterface() {
@Override
public void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(null);
return;
}
GroundOverlay groundOverlay = null;
try {
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
options.image(bitmapDescriptor);
groundOverlay = self.map.addGroundOverlay(options);
image.recycle();
callback.onPostExecute(groundOverlay);
} catch (Exception e) {
//e.printStackTrace();
try {
if (groundOverlay != null) {
groundOverlay.remove();
}
} catch (Exception ignore) {
ignore = null;
}
callback.onError(e.getMessage() + "");
}
}
});
task.execute(imageUrl);
}
}
});
}
}
|
package com.badoo.hprof.cruncher;
import com.badoo.hprof.cruncher.bmd.BmdTag;
import com.badoo.hprof.cruncher.bmd.DataWriter;
import com.badoo.hprof.library.HprofReader;
import com.badoo.hprof.library.Tag;
import com.badoo.hprof.library.model.HprofString;
import com.badoo.hprof.library.processor.DiscardProcessor;
import com.sun.istack.internal.Nullable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
public class CrunchProcessor extends DiscardProcessor {
private class CrunchBdmWriter extends DataWriter {
protected CrunchBdmWriter(OutputStream out) {
super(out);
}
public void writeHeader(int version, @Nullable byte[] metadata) throws IOException {
writeInt32(version);
writeByteArrayWithLength(metadata != null? metadata : new byte[]{});
}
public void writeString(HprofString string, boolean hashed) throws IOException {
writeInt32(hashed? BmdTag.HASHED_STRING : BmdTag.STRING);
writeInt32(string.getId());
if (hashed) {
writeInt32(string.getValue().hashCode());
} else {
writeByteArrayWithLength(string.getValue().getBytes());
}
}
}
private final CrunchBdmWriter writer;
private int nextStringId;
private Map<Integer, Integer> stringIds = new HashMap<Integer, Integer>(); // Maps original to updated string ids
public CrunchProcessor(OutputStream out) {
this.writer = new CrunchBdmWriter(out);
}
@Override
public void onRecord(int tag, int timestamp, int length, HprofReader reader) throws IOException {
switch (tag) {
case Tag.STRING:
HprofString string = reader.readStringRecord(length, timestamp);
// We replace the original string id with one starting from 0 as these are more efficient to store
stringIds.put(string.getId(), nextStringId); // Save the original id so we can update references later
string.setId(nextStringId);
nextStringId++;
System.out.println("Read string: " + string.getId());
writer.writeString(string, true);
break;
default:
//TODO Wrap into legacy record
super.onRecord(tag, timestamp, length, reader);
}
}
@Override
public void onHeader(String text, int idSize, int timeHigh, int timeLow) throws IOException {
writer.writeHeader(1, text.getBytes());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.