Lint fixes

This commit is contained in:
Christian Basler 2016-10-20 05:49:07 +02:00
parent 2b1fb436a9
commit b3dd53a5df
20 changed files with 192 additions and 262 deletions

View File

@ -37,7 +37,7 @@ public abstract class AbstractItemListFragment<T> extends ListFragment implement
* A dummy implementation of the {@link ListSelectionListener} interface that does * A dummy implementation of the {@link ListSelectionListener} interface that does
* nothing. Used only when this fragment is not attached to an activity. * nothing. Used only when this fragment is not attached to an activity.
*/ */
private static ListSelectionListener<Object> dummyCallbacks = plaintext -> { private static final ListSelectionListener<Object> dummyCallbacks = plaintext -> {
}; };
/** /**
* The fragment's current callback object, which is notified of list item * The fragment's current callback object, which is notified of list item

View File

@ -144,11 +144,6 @@ public class AddressListFragment extends AbstractItemListFragment<BitmessageAddr
return view; return view;
} }
@Override
public void startActivityForResult(Intent intent, int requestCode) {
super.startActivityForResult(intent, requestCode);
}
@Override @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null && data.hasExtra("SCAN_RESULT")) { if (data != null && data.hasExtra("SCAN_RESULT")) {

View File

@ -20,7 +20,6 @@ import android.app.Activity;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.Switch; import android.widget.Switch;
@ -61,34 +60,28 @@ public class CreateAddressActivity extends AppCompatActivity {
} }
final Button cancel = (Button) findViewById(R.id.cancel); final Button cancel = (Button) findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() { cancel.setOnClickListener(v -> {
@Override setResult(Activity.RESULT_CANCELED);
public void onClick(View v) { finish();
setResult(Activity.RESULT_CANCELED);
finish();
}
}); });
final Button ok = (Button) findViewById(R.id.do_import); final Button ok = (Button) findViewById(R.id.do_import);
ok.setOnClickListener(new View.OnClickListener() { ok.setOnClickListener(v -> {
@Override String addressText = String.valueOf(address.getText()).trim();
public void onClick(View v) { try {
String addressText = String.valueOf(address.getText()).trim(); BitmessageAddress bmAddress = new BitmessageAddress(addressText);
try { bmAddress.setAlias(label.getText().toString());
BitmessageAddress bmAddress = new BitmessageAddress(addressText);
bmAddress.setAlias(label.getText().toString());
BitmessageContext bmc = Singleton.getBitmessageContext BitmessageContext bmc = Singleton.getBitmessageContext
(CreateAddressActivity.this); (CreateAddressActivity.this);
bmc.addContact(bmAddress); bmc.addContact(bmAddress);
if (subscribe.isChecked()) { if (subscribe.isChecked()) {
bmc.addSubscribtion(bmAddress); bmc.addSubscribtion(bmAddress);
}
setResult(Activity.RESULT_OK);
finish();
} catch (RuntimeException e) {
address.setError(getString(R.string.error_illegal_address));
} }
setResult(Activity.RESULT_OK);
finish();
} catch (RuntimeException e) {
address.setError(getString(R.string.error_illegal_address));
} }
}); });
} }

View File

@ -12,7 +12,7 @@ import com.mikepenz.materialize.MaterializeBuilder;
/** /**
* @author Christian Basler * @author Christian Basler
*/ */
public class DetailActivity extends AppCompatActivity { public abstract class DetailActivity extends AppCompatActivity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {

View File

@ -31,10 +31,10 @@ public class Identicon extends Drawable {
private static final int CENTER_COLUMN = 5; private static final int CENTER_COLUMN = 5;
private final Paint paint; private final Paint paint;
private int color; private final int color;
private int background; private final int background;
private boolean[][] fields; private final boolean[][] fields;
private boolean chan; private final boolean chan;
private final TextPaint textPaint; private final TextPaint textPaint;
public Identicon(BitmessageAddress input) { public Identicon(BitmessageAddress input) {

View File

@ -28,7 +28,6 @@ import android.view.ViewGroup;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.github.angads25.filepicker.controller.DialogSelectionListener;
import com.github.angads25.filepicker.model.DialogConfigs; import com.github.angads25.filepicker.model.DialogConfigs;
import com.github.angads25.filepicker.model.DialogProperties; import com.github.angads25.filepicker.model.DialogProperties;
import com.github.angads25.filepicker.view.FilePickerDialog; import com.github.angads25.filepicker.view.FilePickerDialog;
@ -61,19 +60,16 @@ public class InputWifFragment extends Fragment {
View view = inflater.inflate(R.layout.fragment_import_input, container, false); View view = inflater.inflate(R.layout.fragment_import_input, container, false);
wifData = (TextView) view.findViewById(R.id.wif_input); wifData = (TextView) view.findViewById(R.id.wif_input);
view.findViewById(R.id.next).setOnClickListener(new View.OnClickListener() { view.findViewById(R.id.next).setOnClickListener(v -> {
@Override Bundle bundle = new Bundle();
public void onClick(View v) { bundle.putString(WIF_DATA, wifData.getText().toString());
Bundle bundle = new Bundle();
bundle.putString(WIF_DATA, wifData.getText().toString());
ImportIdentitiesFragment fragment = new ImportIdentitiesFragment(); ImportIdentitiesFragment fragment = new ImportIdentitiesFragment();
fragment.setArguments(bundle); fragment.setArguments(bundle);
getFragmentManager().beginTransaction() getFragmentManager().beginTransaction()
.replace(R.id.content, fragment) .replace(R.id.content, fragment)
.commit(); .commit();
}
}); });
return view; return view;
} }
@ -93,26 +89,23 @@ public class InputWifFragment extends Fragment {
properties.extensions = null; properties.extensions = null;
FilePickerDialog dialog = new FilePickerDialog(getActivity(), properties); FilePickerDialog dialog = new FilePickerDialog(getActivity(), properties);
dialog.setTitle(getString(R.string.select_file_title)); dialog.setTitle(getString(R.string.select_file_title));
dialog.setDialogSelectionListener(new DialogSelectionListener() { dialog.setDialogSelectionListener(files -> {
@Override if (files.length > 0) {
public void onSelectedFilePaths(String[] files) { try (InputStream in = new FileInputStream(files[0])) {
if (files.length > 0) { ByteArrayOutputStream data = new ByteArrayOutputStream();
try (InputStream in = new FileInputStream(files[0])) { byte[] buffer = new byte[1024];
ByteArrayOutputStream data = new ByteArrayOutputStream(); int length;
byte[] buffer = new byte[1024]; //noinspection ConstantConditions
int length; while ((length = in.read(buffer)) != -1) {
//noinspection ConstantConditions data.write(buffer, 0, length);
while ((length = in.read(buffer)) != -1) {
data.write(buffer, 0, length);
}
wifData.setText(data.toString("UTF-8"));
} catch (IOException e) {
Toast.makeText(
getActivity(),
R.string.error_loading_data,
Toast.LENGTH_SHORT
).show();
} }
wifData.setText(data.toString("UTF-8"));
} catch (IOException e) {
Toast.makeText(
getActivity(),
R.string.error_loading_data,
Toast.LENGTH_SHORT
).show();
} }
} }
}); });

View File

@ -130,15 +130,12 @@ public class MessageListFragment extends Fragment implements ListHolder {
// Show the dummy content as text in a TextView. // Show the dummy content as text in a TextView.
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id
.fab_compose_message); .fab_compose_message);
fab.setOnClickListener(new View.OnClickListener() { fab.setOnClickListener(view -> {
@Override Intent intent = new Intent(getActivity().getApplicationContext(),
public void onClick(View view) { ComposeMessageActivity.class);
Intent intent = new Intent(getActivity().getApplicationContext(), intent.putExtra(ComposeMessageActivity.EXTRA_IDENTITY, Singleton.getIdentity
ComposeMessageActivity.class); (getActivity()));
intent.putExtra(ComposeMessageActivity.EXTRA_IDENTITY, Singleton.getIdentity startActivity(intent);
(getActivity()));
startActivity(intent);
}
}); });
// touch guard manager (this class is required to suppress scrolling while swipe-dismiss // touch guard manager (this class is required to suppress scrolling while swipe-dismiss
@ -173,7 +170,7 @@ public class MessageListFragment extends Fragment implements ListHolder {
} }
@Override @Override
public void onItemViewClicked(View v, boolean pinned) { public void onItemViewClicked(View v) {
int position = recyclerView.getChildAdapterPosition(v); int position = recyclerView.getChildAdapterPosition(v);
adapter.setSelectedPosition(position); adapter.setSelectedPosition(position);
if (position != RecyclerView.NO_POSITION) { if (position != RecyclerView.NO_POSITION) {

View File

@ -36,8 +36,8 @@ import static ch.dissem.apps.abit.util.Constants.PREFERENCE_TRUSTED_NODE;
* @author Christian Basler * @author Christian Basler
*/ */
public class SettingsFragment public class SettingsFragment
extends PreferenceFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener { implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -46,27 +46,21 @@ public class SettingsFragment
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
Preference about = findPreference("about"); Preference about = findPreference("about");
about.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { about.setOnPreferenceClickListener(preference -> {
@Override new LibsBuilder()
public boolean onPreferenceClick(Preference preference) { .withActivityTitle(getActivity().getString(R.string.about))
new LibsBuilder() .withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR)
.withActivityTitle(getActivity().getString(R.string.about)) .withAboutIconShown(true)
.withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR) .withAboutVersionShown(true)
.withAboutIconShown(true) .withAboutDescription(getString(R.string.about_app))
.withAboutVersionShown(true) .start(getActivity());
.withAboutDescription(getString(R.string.about_app)) return true;
.start(getActivity());
return true;
}
}); });
Preference status = findPreference("status"); Preference status = findPreference("status");
status.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { status.setOnPreferenceClickListener(preference -> {
@Override startActivity(new Intent(getActivity(), StatusActivity.class));
public boolean onPreferenceClick(Preference preference) { return true;
startActivity(new Intent(getActivity(), StatusActivity.class));
return true;
}
}); });
} }
@ -74,7 +68,7 @@ public class SettingsFragment
public void onAttach(Context ctx) { public void onAttach(Context ctx) {
super.onAttach(ctx); super.onAttach(ctx);
PreferenceManager.getDefaultSharedPreferences(ctx) PreferenceManager.getDefaultSharedPreferences(ctx)
.registerOnSharedPreferenceChangeListener(this); .registerOnSharedPreferenceChangeListener(this);
} }
@Override @Override
@ -97,4 +91,4 @@ public class SettingsFragment
break; break;
} }
} }
} }

View File

@ -21,7 +21,6 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView; import android.widget.TextView;
import java.util.ArrayList; import java.util.ArrayList;
@ -69,19 +68,16 @@ public class AddressSelectorAdapter
static class ViewHolder extends RecyclerView.ViewHolder { static class ViewHolder extends RecyclerView.ViewHolder {
public Selectable<BitmessageAddress> data; public Selectable<BitmessageAddress> data;
public CheckBox checkbox; public final CheckBox checkbox;
public TextView address; public final TextView address;
private ViewHolder(View v) { private ViewHolder(View v) {
super(v); super(v);
checkbox = (CheckBox) v.findViewById(R.id.checkbox); checkbox = (CheckBox) v.findViewById(R.id.checkbox);
address = (TextView) v.findViewById(R.id.address); address = (TextView) v.findViewById(R.id.address);
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
@Override if (data != null) {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { data.selected = isChecked;
if (data != null) {
data.selected = isChecked;
}
} }
}); });
} }

View File

@ -59,8 +59,8 @@ public class SwipeableMessageAdapter
private List<Plaintext> data = Collections.emptyList(); private List<Plaintext> data = Collections.emptyList();
private EventListener eventListener; private EventListener eventListener;
private View.OnClickListener itemViewOnClickListener; private final View.OnClickListener itemViewOnClickListener;
private View.OnClickListener swipeableViewContainerOnClickListener; private final View.OnClickListener swipeableViewContainerOnClickListener;
private Label label; private Label label;
private int selectedPosition; private int selectedPosition;
@ -75,12 +75,12 @@ public class SwipeableMessageAdapter
void onItemArchived(Plaintext item); void onItemArchived(Plaintext item);
void onItemViewClicked(View v, boolean pinned); void onItemViewClicked(View v);
} }
@SuppressWarnings("WeakerAccess") @SuppressWarnings("WeakerAccess")
static class ViewHolder extends AbstractSwipeableItemViewHolder { static class ViewHolder extends AbstractSwipeableItemViewHolder {
public FrameLayout container; public final FrameLayout container;
public final ImageView avatar; public final ImageView avatar;
public final TextView sender; public final TextView sender;
public final TextView subject; public final TextView subject;
@ -102,18 +102,8 @@ public class SwipeableMessageAdapter
} }
public SwipeableMessageAdapter() { public SwipeableMessageAdapter() {
itemViewOnClickListener = new View.OnClickListener() { itemViewOnClickListener = this::onItemViewClick;
@Override swipeableViewContainerOnClickListener = this::onSwipeableViewContainerClick;
public void onClick(View v) {
onItemViewClick(v);
}
};
swipeableViewContainerOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
onSwipeableViewContainerClick(v);
}
};
// SwipeableItemAdapter requires stable ID, and also // SwipeableItemAdapter requires stable ID, and also
// have to implement the getItemId() method appropriately. // have to implement the getItemId() method appropriately.
@ -127,14 +117,14 @@ public class SwipeableMessageAdapter
private void onItemViewClick(View v) { private void onItemViewClick(View v) {
if (eventListener != null) { if (eventListener != null) {
eventListener.onItemViewClicked(v, true); // pinned eventListener.onItemViewClicked(v);
} }
} }
private void onSwipeableViewContainerClick(View v) { private void onSwipeableViewContainerClick(View v) {
if (eventListener != null) { if (eventListener != null) {
eventListener.onItemViewClicked( eventListener.onItemViewClicked(
RecyclerViewAdapterUtils.getParentViewHolderItemView(v), false); // not pinned RecyclerViewAdapterUtils.getParentViewHolderItemView(v));
} }
} }

View File

@ -19,7 +19,6 @@ package ch.dissem.apps.abit.dialog;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
@ -61,56 +60,47 @@ public class AddIdentityDialogFragment extends AppCompatDialogFragment {
getDialog().setTitle(R.string.add_identity); getDialog().setTitle(R.string.add_identity);
View view = inflater.inflate(R.layout.dialog_add_identity, container, false); View view = inflater.inflate(R.layout.dialog_add_identity, container, false);
final RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup); final RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
view.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() { view.findViewById(R.id.ok).setOnClickListener(v -> {
@Override final Context ctx = getActivity().getBaseContext();
public void onClick(View v) { switch (radioGroup.getCheckedRadioButtonId()) {
final Context ctx = getActivity().getBaseContext(); case R.id.create_identity:
switch (radioGroup.getCheckedRadioButtonId()) { Toast.makeText(ctx,
case R.id.create_identity: R.string.toast_long_running_operation,
Toast.makeText(ctx, Toast.LENGTH_SHORT).show();
R.string.toast_long_running_operation, new AsyncTask<Void, Void, BitmessageAddress>() {
Toast.LENGTH_SHORT).show(); @Override
new AsyncTask<Void, Void, BitmessageAddress>() { protected BitmessageAddress doInBackground(Void... args) {
@Override return bmc.createIdentity(false, Pubkey.Feature.DOES_ACK);
protected BitmessageAddress doInBackground(Void... args) { }
return bmc.createIdentity(false, Pubkey.Feature.DOES_ACK);
}
@Override @Override
protected void onPostExecute(BitmessageAddress chan) { protected void onPostExecute(BitmessageAddress chan) {
Toast.makeText(ctx, Toast.makeText(ctx,
R.string.toast_identity_created, R.string.toast_identity_created,
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
MainActivity mainActivity = MainActivity.getInstance(); MainActivity mainActivity = MainActivity.getInstance();
if (mainActivity != null) { if (mainActivity != null) {
mainActivity.addIdentityEntry(chan); mainActivity.addIdentityEntry(chan);
}
} }
}.execute(); }
break; }.execute();
case R.id.import_identity: break;
startActivity(new Intent(ctx, ImportIdentityActivity.class)); case R.id.import_identity:
break; startActivity(new Intent(ctx, ImportIdentityActivity.class));
case R.id.add_chan: break;
addChanDialog(); case R.id.add_chan:
break; addChanDialog();
case R.id.add_deterministic_address: break;
new DeterministicIdentityDialogFragment().show(getFragmentManager(), case R.id.add_deterministic_address:
"dialog"); new DeterministicIdentityDialogFragment().show(getFragmentManager(),
break; "dialog");
default: break;
return; default:
} return;
dismiss();
} }
dismiss();
}); });
view.findViewById(R.id.dismiss) view.findViewById(R.id.dismiss).setOnClickListener(v -> dismiss());
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
return view; return view;
} }
@ -123,34 +113,31 @@ public class AddIdentityDialogFragment extends AppCompatDialogFragment {
new AlertDialog.Builder(activity) new AlertDialog.Builder(activity)
.setTitle(R.string.add_chan) .setTitle(R.string.add_chan)
.setView(dialogView) .setView(dialogView)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { .setPositiveButton(R.string.ok, (dialogInterface, i) -> {
@Override TextView passphrase = (TextView) dialogView.findViewById(R.id.passphrase);
public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(ctx, R.string.toast_long_running_operation,
TextView passphrase = (TextView) dialogView.findViewById(R.id.passphrase); Toast.LENGTH_SHORT).show();
Toast.makeText(ctx, R.string.toast_long_running_operation, new AsyncTask<String, Void, BitmessageAddress>() {
Toast.LENGTH_SHORT).show(); @Override
new AsyncTask<String, Void, BitmessageAddress>() { protected BitmessageAddress doInBackground(String... args) {
@Override String pass = args[0];
protected BitmessageAddress doInBackground(String... args) { BitmessageAddress chan = bmc.createChan(pass);
String pass = args[0]; chan.setAlias(pass);
BitmessageAddress chan = bmc.createChan(pass); bmc.addresses().save(chan);
chan.setAlias(pass); return chan;
bmc.addresses().save(chan); }
return chan;
}
@Override @Override
protected void onPostExecute(BitmessageAddress chan) { protected void onPostExecute(BitmessageAddress chan) {
Toast.makeText(ctx, Toast.makeText(ctx,
R.string.toast_chan_created, R.string.toast_chan_created,
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
MainActivity mainActivity = MainActivity.getInstance(); MainActivity mainActivity = MainActivity.getInstance();
if (mainActivity != null) { if (mainActivity != null) {
mainActivity.addIdentityEntry(chan); mainActivity.addIdentityEntry(chan);
}
} }
}.execute(passphrase.getText().toString()); }
} }.execute(passphrase.getText().toString());
}) })
.setNegativeButton(R.string.cancel, null) .setNegativeButton(R.string.cancel, null)
.show(); .show();

View File

@ -29,11 +29,13 @@ import ch.dissem.bitmessage.BitmessageContext;
public class WifiReceiver extends BroadcastReceiver { public class WifiReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context ctx, Intent intent) { public void onReceive(Context ctx, Intent intent) {
if (Preferences.isWifiOnly(ctx)) { if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
BitmessageContext bmc = Singleton.getBitmessageContext(ctx); if (Preferences.isWifiOnly(ctx)) {
BitmessageContext bmc = Singleton.getBitmessageContext(ctx);
if (isConnectedToMeteredNetwork(ctx) && bmc.isRunning()) { if (isConnectedToMeteredNetwork(ctx) && bmc.isRunning()) {
bmc.shutdown(); bmc.shutdown();
}
} }
} }
} }
@ -43,7 +45,7 @@ public class WifiReceiver extends BroadcastReceiver {
if (netInfo == null || !netInfo.isConnectedOrConnecting()) { if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
return false; return false;
} }
switch (netInfo.getType()){ switch (netInfo.getType()) {
case ConnectivityManager.TYPE_ETHERNET: case ConnectivityManager.TYPE_ETHERNET:
case ConnectivityManager.TYPE_WIFI: case ConnectivityManager.TYPE_WIFI:
return false; return false;

View File

@ -31,7 +31,7 @@ import ch.dissem.apps.abit.R;
public class ErrorNotification extends AbstractNotification { public class ErrorNotification extends AbstractNotification {
public static final int ERROR_NOTIFICATION_ID = 4; public static final int ERROR_NOTIFICATION_ID = 4;
private NotificationCompat.Builder builder; private final NotificationCompat.Builder builder;
public ErrorNotification(Context ctx) { public ErrorNotification(Context ctx) {
super(ctx); super(ctx);

View File

@ -17,14 +17,12 @@
package ch.dissem.apps.abit.pow; package ch.dissem.apps.abit.pow;
import android.content.Context; import android.content.Context;
import android.support.annotation.NonNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import ch.dissem.apps.abit.service.Singleton; import ch.dissem.apps.abit.service.Singleton;
import ch.dissem.apps.abit.synchronization.SyncAdapter; import ch.dissem.apps.abit.synchronization.SyncAdapter;
@ -42,7 +40,7 @@ import static ch.dissem.bitmessage.utils.Singleton.cryptography;
* @author Christian Basler * @author Christian Basler
*/ */
public class ServerPowEngine implements ProofOfWorkEngine, InternalContext public class ServerPowEngine implements ProofOfWorkEngine, InternalContext
.ContextHolder { .ContextHolder {
private static final Logger LOG = LoggerFactory.getLogger(ServerPowEngine.class); private static final Logger LOG = LoggerFactory.getLogger(ServerPowEngine.class);
private final Context ctx; private final Context ctx;
@ -52,40 +50,34 @@ public class ServerPowEngine implements ProofOfWorkEngine, InternalContext
public ServerPowEngine(Context ctx) { public ServerPowEngine(Context ctx) {
this.ctx = ctx; this.ctx = ctx;
pool = Executors.newCachedThreadPool(new ThreadFactory() { pool = Executors.newCachedThreadPool(r -> {
@Override Thread thread = Executors.defaultThreadFactory().newThread(r);
public Thread newThread(@NonNull Runnable r) { thread.setPriority(Thread.MIN_PRIORITY);
Thread thread = Executors.defaultThreadFactory().newThread(r); return thread;
thread.setPriority(Thread.MIN_PRIORITY);
return thread;
}
}); });
} }
@Override @Override
public void calculateNonce(final byte[] initialHash, final byte[] target, Callback callback) { public void calculateNonce(final byte[] initialHash, final byte[] target, Callback callback) {
pool.execute(new Runnable() { pool.execute(() -> {
@Override BitmessageAddress identity = Singleton.getIdentity(ctx);
public void run() { if (identity == null) throw new RuntimeException("No Identity for calculating POW");
BitmessageAddress identity = Singleton.getIdentity(ctx);
if (identity == null) throw new RuntimeException("No Identity for calculating POW");
ProofOfWorkRequest request = new ProofOfWorkRequest(identity, initialHash, ProofOfWorkRequest request = new ProofOfWorkRequest(identity, initialHash,
CALCULATE, target); CALCULATE, target);
SyncAdapter.startPowSync(ctx); SyncAdapter.startPowSync(ctx);
try { try {
CryptoCustomMessage<ProofOfWorkRequest> cryptoMsg = new CryptoCustomMessage<> CryptoCustomMessage<ProofOfWorkRequest> cryptoMsg = new CryptoCustomMessage<>
(request); (request);
cryptoMsg.signAndEncrypt( cryptoMsg.signAndEncrypt(
identity, identity,
cryptography().createPublicKey(identity.getPublicDecryptionKey()) cryptography().createPublicKey(identity.getPublicDecryptionKey())
); );
context.getNetworkHandler().send( context.getNetworkHandler().send(
Preferences.getTrustedNode(ctx), Preferences.getTrustedNodePort(ctx), Preferences.getTrustedNode(ctx), Preferences.getTrustedNodePort(ctx),
cryptoMsg); cryptoMsg);
} catch (Exception e) { } catch (Exception e) {
LOG.error(e.getMessage(), e); LOG.error(e.getMessage(), e);
}
} }
}); });
} }

View File

@ -169,14 +169,10 @@ public class AndroidAddressRepository implements AddressRepository {
@Override @Override
public void save(BitmessageAddress address) { public void save(BitmessageAddress address) {
try { if (exists(address)) {
if (exists(address)) { update(address);
update(address); } else {
} else { insert(address);
insert(address);
}
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} }
} }
@ -191,7 +187,7 @@ public class AndroidAddressRepository implements AddressRepository {
} }
} }
private void update(BitmessageAddress address) throws IOException { private void update(BitmessageAddress address) {
try { try {
SQLiteDatabase db = sql.getWritableDatabase(); SQLiteDatabase db = sql.getWritableDatabase();
// Create a new map of values, where column names are the keys // Create a new map of values, where column names are the keys
@ -224,7 +220,7 @@ public class AndroidAddressRepository implements AddressRepository {
} }
} }
private void insert(BitmessageAddress address) throws IOException { private void insert(BitmessageAddress address) {
try { try {
SQLiteDatabase db = sql.getWritableDatabase(); SQLiteDatabase db = sql.getWritableDatabase();
// Create a new map of values, where column names are the keys // Create a new map of values, where column names are the keys

View File

@ -275,14 +275,12 @@ public class AndroidMessageRepository extends AbstractMessageRepository {
db.setTransactionSuccessful(); db.setTransactionSuccessful();
} catch (SQLiteConstraintException e) { } catch (SQLiteConstraintException e) {
LOG.trace(e.getMessage(), e); LOG.trace(e.getMessage(), e);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} finally { } finally {
db.endTransaction(); db.endTransaction();
} }
} }
private void insert(SQLiteDatabase db, Plaintext message) throws IOException { private void insert(SQLiteDatabase db, Plaintext message) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(COLUMN_IV, message.getInventoryVector() == null ? null : message values.put(COLUMN_IV, message.getInventoryVector() == null ? null : message
.getInventoryVector().getHash()); .getInventoryVector().getHash());
@ -302,7 +300,7 @@ public class AndroidMessageRepository extends AbstractMessageRepository {
message.setId(id); message.setId(id);
} }
private void update(SQLiteDatabase db, Plaintext message) throws IOException { private void update(SQLiteDatabase db, Plaintext message) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(COLUMN_IV, message.getInventoryVector() == null ? null : message values.put(COLUMN_IV, message.getInventoryVector() == null ? null : message
.getInventoryVector().getHash()); .getInventoryVector().getHash());

View File

@ -27,10 +27,10 @@ import ch.dissem.apps.abit.util.Assets;
*/ */
public class SqlHelper extends SQLiteOpenHelper { public class SqlHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version. // If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 5; private static final int DATABASE_VERSION = 5;
public static final String DATABASE_NAME = "jabit.db"; private static final String DATABASE_NAME = "jabit.db";
protected final Context ctx; private final Context ctx;
public SqlHelper(Context ctx) { public SqlHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION); super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
@ -65,7 +65,7 @@ public class SqlHelper extends SQLiteOpenHelper {
} }
} }
protected void executeMigration(SQLiteDatabase db, String name) { private void executeMigration(SQLiteDatabase db, String name) {
for (String statement : Assets.readSqlStatements(ctx, "db/migration/" + name + ".sql")) { for (String statement : Assets.readSqlStatements(ctx, "db/migration/" + name + ".sql")) {
db.execSQL(statement); db.execSQL(statement);
} }

View File

@ -37,9 +37,9 @@ import static ch.dissem.apps.abit.notification.ProofOfWorkNotification.ONGOING_N
*/ */
public class ProofOfWorkService extends Service { public class ProofOfWorkService extends Service {
// Object to use as a thread-safe lock // Object to use as a thread-safe lock
private static ProofOfWorkEngine engine = new MultiThreadedPOWEngine(); private static final ProofOfWorkEngine engine = new MultiThreadedPOWEngine();
private static boolean calculating;
private static final Queue<PowItem> queue = new LinkedList<>(); private static final Queue<PowItem> queue = new LinkedList<>();
private static boolean calculating;
private ProofOfWorkNotification notification; private ProofOfWorkNotification notification;
@Override @Override

View File

@ -38,14 +38,14 @@ public class ServicePowEngine implements ProofOfWorkEngine {
private final Context ctx; private final Context ctx;
private static final Object lock = new Object(); private static final Object lock = new Object();
private Queue<PowItem> queue = new LinkedList<>(); private final Queue<PowItem> queue = new LinkedList<>();
private PowBinder service; private PowBinder service;
public ServicePowEngine(Context ctx) { public ServicePowEngine(Context ctx) {
this.ctx = ctx; this.ctx = ctx;
} }
private ServiceConnection connection = new ServiceConnection() { private final ServiceConnection connection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName name, IBinder service) { public void onServiceConnected(ComponentName name, IBinder service) {
synchronized (lock) { synchronized (lock) {
@ -75,4 +75,4 @@ public class ServicePowEngine implements ProofOfWorkEngine {
} }
} }
} }
} }

View File

@ -20,9 +20,6 @@ import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;