Replace anonymous type with lambda

This commit is contained in:
Martin Fietz 2018-01-14 17:47:43 +01:00
parent 7257a6c76e
commit 332943effb
7 changed files with 203 additions and 251 deletions

View File

@ -168,44 +168,38 @@ public abstract class NanoHTTPD {
myServerSocket = new ServerSocket();
myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
myThread = new Thread(new Runnable() {
@Override
public void run() {
do {
try {
final Socket finalAccept = myServerSocket.accept();
registerConnection(finalAccept);
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept.getInputStream();
asyncRunner.exec(new Runnable() {
@Override
public void run() {
OutputStream outputStream = null;
try {
outputStream = finalAccept.getOutputStream();
TempFileManager tempFileManager = tempFileManagerFactory.create();
HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
while (!finalAccept.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
unRegisterConnection(finalAccept);
}
myThread = new Thread(() -> {
do {
try {
final Socket finalAccept = myServerSocket.accept();
registerConnection(finalAccept);
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept.getInputStream();
asyncRunner.exec(() -> {
OutputStream outputStream = null;
try {
outputStream = finalAccept.getOutputStream();
TempFileManager tempFileManager = tempFileManagerFactory.create();
HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
while (!finalAccept.isClosed()) {
session.execute();
}
});
} catch (IOException e) {
}
} while (!myServerSocket.isClosed());
}
} catch (Exception e) {
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
unRegisterConnection(finalAccept);
}
});
} catch (IOException e) {
}
} while (!myServerSocket.isClosed());
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");

View File

@ -75,53 +75,50 @@ public class AboutActivity extends AppCompatActivity {
}
private void loadAsset(String filename) {
subscription = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
InputStream input = null;
try {
TypedArray res = AboutActivity.this.getTheme().obtainStyledAttributes(
new int[] { android.R.attr.textColorPrimary });
int colorResource = res.getColor(0, 0);
String colorString = String.format("#%06X", 0xFFFFFF & colorResource);
res.recycle();
input = getAssets().open(filename);
String webViewData = IOUtils.toString(input, Charset.defaultCharset());
if(!webViewData.startsWith("<!DOCTYPE html>")) {
//webViewData = webViewData.replace("\n\n", "</p><p>");
webViewData = webViewData.replace("%", "&#37;");
webViewData =
"<!DOCTYPE html>" +
"<html>" +
"<head>" +
" <meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\">" +
" <style type=\"text/css\">" +
" @font-face {" +
" font-family: 'Roboto-Light';" +
" src: url('file:///android_asset/Roboto-Light.ttf');" +
" }" +
" * {" +
" color: %s;" +
" font-family: roboto-Light;" +
" font-size: 8pt;" +
" }" +
" </style>" +
"</head><body><p>" + webViewData + "</p></body></html>";
webViewData = webViewData.replace("\n", "<br/>");
depth++;
} else {
depth = 0;
}
webViewData = String.format(webViewData, colorString);
subscriber.onNext(webViewData);
} catch (IOException e) {
subscriber.onError(e);
} finally {
IOUtils.closeQuietly(input);
}
subscriber.onCompleted();
}
})
subscription = Observable.create((Observable.OnSubscribe<String>) subscriber -> {
InputStream input = null;
try {
TypedArray res = AboutActivity.this.getTheme().obtainStyledAttributes(
new int[] { android.R.attr.textColorPrimary });
int colorResource = res.getColor(0, 0);
String colorString = String.format("#%06X", 0xFFFFFF & colorResource);
res.recycle();
input = getAssets().open(filename);
String webViewData = IOUtils.toString(input, Charset.defaultCharset());
if(!webViewData.startsWith("<!DOCTYPE html>")) {
//webViewData = webViewData.replace("\n\n", "</p><p>");
webViewData = webViewData.replace("%", "&#37;");
webViewData =
"<!DOCTYPE html>" +
"<html>" +
"<head>" +
" <meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\">" +
" <style type=\"text/css\">" +
" @font-face {" +
" font-family: 'Roboto-Light';" +
" src: url('file:///android_asset/Roboto-Light.ttf');" +
" }" +
" * {" +
" color: %s;" +
" font-family: roboto-Light;" +
" font-size: 8pt;" +
" }" +
" </style>" +
"</head><body><p>" + webViewData + "</p></body></html>";
webViewData = webViewData.replace("\n", "<br/>");
depth++;
} else {
depth = 0;
}
webViewData = String.format(webViewData, colorString);
subscriber.onNext(webViewData);
} catch (IOException e) {
subscriber.onError(e);
} finally {
IOUtils.closeQuietly(input);
}
subscriber.onCompleted();
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(

View File

@ -243,47 +243,44 @@ public class ProxyDialog {
txtvMessage.setTextColor(textColorPrimary);
txtvMessage.setText("{fa-circle-o-notch spin} " + checking);
txtvMessage.setVisibility(View.VISIBLE);
subscription = Observable.create(new Observable.OnSubscribe<Response>() {
@Override
public void call(Subscriber<? super Response> subscriber) {
String type = (String) spType.getSelectedItem();
String host = etHost.getText().toString();
String port = etPort.getText().toString();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
int portValue = 8080;
if(!TextUtils.isEmpty(port)) {
portValue = Integer.valueOf(port);
}
SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase());
Proxy proxy = new Proxy(proxyType, address);
OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.proxy(proxy);
builder.interceptors().clear();
OkHttpClient client = builder.build();
if(!TextUtils.isEmpty(username)) {
String credentials = Credentials.basic(username, password);
client.interceptors().add(chain -> {
Request request = chain.request().newBuilder()
.header("Proxy-Authorization", credentials).build();
return chain.proceed(request);
});
}
Request request = new Request.Builder()
.url("http://www.google.com")
.head()
.build();
try {
Response response = client.newCall(request).execute();
subscriber.onNext(response);
} catch(IOException e) {
subscriber.onError(e);
}
subscriber.onCompleted();
}
})
subscription = Observable.create((Observable.OnSubscribe<Response>) subscriber -> {
String type = (String) spType.getSelectedItem();
String host = etHost.getText().toString();
String port = etPort.getText().toString();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
int portValue = 8080;
if(!TextUtils.isEmpty(port)) {
portValue = Integer.valueOf(port);
}
SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase());
Proxy proxy = new Proxy(proxyType, address);
OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.proxy(proxy);
builder.interceptors().clear();
OkHttpClient client = builder.build();
if(!TextUtils.isEmpty(username)) {
String credentials = Credentials.basic(username, password);
client.interceptors().add(chain -> {
Request request = chain.request().newBuilder()
.header("Proxy-Authorization", credentials).build();
return chain.proceed(request);
});
}
Request request = new Request.Builder()
.url("http://www.google.com")
.head()
.build();
try {
Response response = client.newCall(request).execute();
subscriber.onNext(response);
} catch(IOException e) {
subscriber.onError(e);
}
subscriber.onCompleted();
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(

View File

@ -710,52 +710,49 @@ public class LocalPSMP extends PlaybackServiceMediaPlayer {
@Override
public void onAudioFocusChange(final int focusChange) {
executor.submit(new Runnable() {
@Override
public void run() {
playerLock.lock();
executor.submit(() -> {
playerLock.lock();
// If there is an incoming call, playback should be paused permanently
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final int callState = (tm != null) ? tm.getCallState() : 0;
Log.i(TAG, "Call state:" + callState);
// If there is an incoming call, playback should be paused permanently
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final int callState = (tm != null) ? tm.getCallState() : 0;
Log.i(TAG, "Call state:" + callState);
if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
(!UserPreferences.shouldResumeAfterCall() && callState != TelephonyManager.CALL_STATE_IDLE)) {
Log.d(TAG, "Lost audio focus");
pause(true, false);
callback.shouldStop();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
Log.d(TAG, "Gained audio focus");
if (pausedBecauseOfTransientAudiofocusLoss) { // we paused => play now
resume();
} else { // we ducked => raise audio level back
setVolumeSync(UserPreferences.getLeftVolume(),
UserPreferences.getRightVolume());
}
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
if (playerStatus == PlayerStatus.PLAYING) {
if (!UserPreferences.shouldPauseForFocusLoss()) {
Log.d(TAG, "Lost audio focus temporarily. Ducking...");
final float DUCK_FACTOR = 0.25f;
setVolumeSync(DUCK_FACTOR * UserPreferences.getLeftVolume(),
DUCK_FACTOR * UserPreferences.getRightVolume());
pausedBecauseOfTransientAudiofocusLoss = false;
} else {
Log.d(TAG, "Lost audio focus temporarily. Could duck, but won't, pausing...");
pause(false, false);
pausedBecauseOfTransientAudiofocusLoss = true;
}
}
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
if (playerStatus == PlayerStatus.PLAYING) {
Log.d(TAG, "Lost audio focus temporarily. Pausing...");
if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
(!UserPreferences.shouldResumeAfterCall() && callState != TelephonyManager.CALL_STATE_IDLE)) {
Log.d(TAG, "Lost audio focus");
pause(true, false);
callback.shouldStop();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
Log.d(TAG, "Gained audio focus");
if (pausedBecauseOfTransientAudiofocusLoss) { // we paused => play now
resume();
} else { // we ducked => raise audio level back
setVolumeSync(UserPreferences.getLeftVolume(),
UserPreferences.getRightVolume());
}
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
if (playerStatus == PlayerStatus.PLAYING) {
if (!UserPreferences.shouldPauseForFocusLoss()) {
Log.d(TAG, "Lost audio focus temporarily. Ducking...");
final float DUCK_FACTOR = 0.25f;
setVolumeSync(DUCK_FACTOR * UserPreferences.getLeftVolume(),
DUCK_FACTOR * UserPreferences.getRightVolume());
pausedBecauseOfTransientAudiofocusLoss = false;
} else {
Log.d(TAG, "Lost audio focus temporarily. Could duck, but won't, pausing...");
pause(false, false);
pausedBecauseOfTransientAudiofocusLoss = true;
}
}
playerLock.unlock();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
if (playerStatus == PlayerStatus.PLAYING) {
Log.d(TAG, "Lost audio focus temporarily. Pausing...");
pause(false, false);
pausedBecauseOfTransientAudiofocusLoss = true;
}
}
playerLock.unlock();
});
}
};

View File

@ -112,63 +112,60 @@ public class NetworkUtils {
}
public static Observable<Long> getFeedMediaSizeObservable(FeedMedia media) {
return Observable.create(new Observable.OnSubscribe<Long>() {
@Override
public void call(Subscriber<? super Long> subscriber) {
if (!NetworkUtils.isDownloadAllowed()) {
return Observable.create((Observable.OnSubscribe<Long>) subscriber -> {
if (!NetworkUtils.isDownloadAllowed()) {
subscriber.onNext(0L);
subscriber.onCompleted();
return;
}
long size = Integer.MIN_VALUE;
if (media.isDownloaded()) {
File mediaFile = new File(media.getLocalMediaUrl());
if (mediaFile.exists()) {
size = mediaFile.length();
}
} else if (!media.checkedOnSizeButUnknown()) {
// only query the network if we haven't already checked
String url = media.getDownload_url();
if(TextUtils.isEmpty(url)) {
subscriber.onNext(0L);
subscriber.onCompleted();
return;
}
long size = Integer.MIN_VALUE;
if (media.isDownloaded()) {
File mediaFile = new File(media.getLocalMediaUrl());
if (mediaFile.exists()) {
size = mediaFile.length();
}
} else if (!media.checkedOnSizeButUnknown()) {
// only query the network if we haven't already checked
String url = media.getDownload_url();
if(TextUtils.isEmpty(url)) {
subscriber.onNext(0L);
subscriber.onCompleted();
return;
}
OkHttpClient client = AntennapodHttpClient.getHttpClient();
Request.Builder httpReq = new Request.Builder()
.url(url)
.header("Accept-Encoding", "identity")
.head();
try {
Response response = client.newCall(httpReq.build()).execute();
if (response.isSuccessful()) {
String contentLength = response.header("Content-Length");
try {
size = Integer.parseInt(contentLength);
} catch (NumberFormatException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
OkHttpClient client = AntennapodHttpClient.getHttpClient();
Request.Builder httpReq = new Request.Builder()
.url(url)
.header("Accept-Encoding", "identity")
.head();
try {
Response response = client.newCall(httpReq.build()).execute();
if (response.isSuccessful()) {
String contentLength = response.header("Content-Length");
try {
size = Integer.parseInt(contentLength);
} catch (NumberFormatException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
} catch (IOException e) {
subscriber.onNext(0L);
subscriber.onCompleted();
Log.e(TAG, Log.getStackTraceString(e));
return; // better luck next time
}
} catch (IOException e) {
subscriber.onNext(0L);
subscriber.onCompleted();
Log.e(TAG, Log.getStackTraceString(e));
return; // better luck next time
}
Log.d(TAG, "new size: " + size);
if (size <= 0) {
// they didn't tell us the size, but we don't want to keep querying on it
media.setCheckedOnSizeButUnknown();
} else {
media.setSize(size);
}
subscriber.onNext(size);
subscriber.onCompleted();
DBWriter.setFeedMedia(media);
}
Log.d(TAG, "new size: " + size);
if (size <= 0) {
// they didn't tell us the size, but we don't want to keep querying on it
media.setCheckedOnSizeButUnknown();
} else {
media.setSize(size);
}
subscriber.onNext(size);
subscriber.onCompleted();
DBWriter.setFeedMedia(media);
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());

View File

@ -176,13 +176,7 @@ public class FlattrUtils {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.access_revoked_title);
builder.setMessage(R.string.access_revoked_info);
builder.setNeutralButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton(android.R.string.ok, (dialog, which) -> dialog.cancel());
builder.create().show();
}
@ -197,27 +191,15 @@ public class FlattrUtils {
builder.setTitle(R.string.no_flattr_token_title);
builder.setMessage(R.string.no_flattr_token_msg);
builder.setPositiveButton(R.string.authenticate_now_label,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
context.startActivity(
ClientConfig.flattrCallbacks.getFlattrAuthenticationActivityIntent(context));
}
}
(dialog, which) -> context.startActivity(
ClientConfig.flattrCallbacks.getFlattrAuthenticationActivityIntent(context))
);
builder.setNegativeButton(R.string.visit_website_label,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse(url);
context.startActivity(new Intent(Intent.ACTION_VIEW,
uri));
}
(dialog, which) -> {
Uri uri = Uri.parse(url);
context.startActivity(new Intent(Intent.ACTION_VIEW,
uri));
}
);
builder.create().show();
@ -231,13 +213,7 @@ public class FlattrUtils {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.error_label);
builder.setMessage(msg);
builder.setNeutralButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton(android.R.string.ok, (dialog, which) -> dialog.cancel());
builder.create().show();
}

View File

@ -87,13 +87,7 @@ public abstract class PlaybackController {
Thread t = new Thread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}, new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r,
ThreadPoolExecutor executor) {
Log.w(TAG, "Rejected execution of runnable in schedExecutor");
}
}
}, (r, executor) -> Log.w(TAG, "Rejected execution of runnable in schedExecutor")
);
}