answer
stringlengths
17
10.2M
package com.renard.ocr.install; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import java.util.concurrent.ExecutionException; /** * This Fragment manages a single background task and retains * itself across configuration changes. */ public class TaskFragment extends Fragment { /** * Callback interface through which the fragment will report the * task's progress and results back to the Activity. */ interface TaskCallbacks { void onPreExecute(); void onProgressUpdate(int percent); void onCancelled(); void onPostExecute(InstallResult result); } private InstallTask mTask; /** * Hold a reference to the parent Activity so we can report the * task's current progress and results. The Android framework * will pass us a reference to the newly created Activity after * each configuration change. */ @Override public void onStart() { super.onStart(); mTask.setTaskCallbacks((TaskCallbacks) getActivity()); } /** * This method will only be called once when the retained * Fragment is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Retain this fragment across configuration changes. setRetainInstance(true); // Create and execute the background task. mTask = new InstallTask((TaskCallbacks) getActivity(), getActivity().getAssets()); mTask.execute(); } /** * Set the callback to null so we don't accidentally leak the * Activity instance. */ @Override public void onDetach() { super.onDetach(); mTask.setTaskCallbacks(null); } @Nullable public InstallResult getInstallResult() { final AsyncTask.Status status = mTask.getStatus(); if (status == AsyncTask.Status.FINISHED) { try { return mTask.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return new InstallResult(InstallResult.Result.UNSPECIFIED_ERROR); } else { return null; } } }
package com.samourai.wallet; import android.Manifest; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.text.InputType; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AnticipateInterpolator; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.util.Log; import org.apache.commons.lang3.tuple.Triple; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.DumpedPrivateKey; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.TransactionWitness; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.crypto.BIP38PrivateKey; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.wallet.JSONRPC.JSONRPC; import com.samourai.wallet.JSONRPC.PoW; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.api.Tx; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.paynym.ClaimPayNymActivity; import com.samourai.wallet.bip47.rpc.PaymentAddress; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.bip69.BIP69OutputComparator; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_Address; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.permissions.PermissionsUtil; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.segwit.bech32.Bech32; import com.samourai.wallet.segwit.bech32.Bech32Util; import com.samourai.wallet.send.BlockedUTXO; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionInput; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFSpend; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.SweepUtil; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.PushTx; import com.samourai.wallet.service.RefreshService; import com.samourai.wallet.service.WebSocketService; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.BlockExplorerUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.DateUtil; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.MessageSignUtil; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.PrivKeyReader; import com.samourai.wallet.util.TimeOutUtil; import com.samourai.wallet.util.TorUtil; import com.samourai.wallet.util.TypefaceUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.encoders.DecoderException; import net.i2p.android.ext.floatingactionbutton.FloatingActionButton; import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu; import com.yanzhenjie.zbar.Symbol; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Vector; import info.guardianproject.netcipher.proxy.OrbotHelper; public class BalanceActivity extends Activity { private final static int SCAN_COLD_STORAGE = 2011; private final static int SCAN_QR = 2012; private LinearLayout layoutAlert = null; private LinearLayout tvBalanceBar = null; private TextView tvBalanceAmount = null; private TextView tvBalanceUnits = null; private ListView txList = null; private List<Tx> txs = null; private HashMap<String, Boolean> txStates = null; private TransactionAdapter txAdapter = null; private SwipeRefreshLayout swipeRefreshLayout = null; private FloatingActionsMenu ibQuickSend = null; private FloatingActionButton actionReceive = null; private FloatingActionButton actionSend = null; private FloatingActionButton actionBIP47 = null; private boolean isBTC = true; private PoWTask powTask = null; private RBFTask rbfTask = null; private CPFPTask cpfpTask = null; private ProgressDialog progress = null; public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH"; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { final boolean notifTx = intent.getBooleanExtra("notifTx", false); final boolean fetch = intent.getBooleanExtra("fetch", false); final String rbfHash; final String blkHash; if(intent.hasExtra("rbf")) { rbfHash = intent.getStringExtra("rbf"); } else { rbfHash = null; } if(intent.hasExtra("hash")) { blkHash = intent.getStringExtra("hash"); } else { blkHash = null; } Handler handler = new Handler(); handler.post(new Runnable() { public void run() { refreshTx(notifTx, false, false); if(BalanceActivity.this != null) { if(rbfHash != null) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming)) .setCancelable(true) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doExplorerView(rbfHash); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } } } }); if(BalanceActivity.this != null && blkHash != null && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true && TrustedNodeUtil.getInstance().isSet()) { // BalanceActivity.this.runOnUiThread(new Runnable() { // @Override handler.post(new Runnable() { public void run() { if(powTask == null || powTask.getStatus().equals(AsyncTask.Status.FINISHED)) { powTask = new PoWTask(); powTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, blkHash); } } }); } } } }; public static final String DISPLAY_INTENT = "com.samourai.wallet.BalanceFragment.DISPLAY"; protected BroadcastReceiver receiverDisplay = new BroadcastReceiver() { @Override public void onReceive(final Context context, Intent intent) { if(DISPLAY_INTENT.equals(intent.getAction())) { updateDisplay(); List<UTXO> utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(false); for(UTXO utxo : utxos) { List<MyTransactionOutPoint> outpoints = utxo.getOutpoints(); for(MyTransactionOutPoint out : outpoints) { byte[] scriptBytes = out.getScriptBytes(); String address = null; try { if(Bech32Util.getInstance().isBech32Script(Hex.toHexString(scriptBytes))) { address = Bech32Util.getInstance().getAddressFromScript(Hex.toHexString(scriptBytes)); } else { address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } } catch(Exception e) { ; } String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(address); if(path != null && path.startsWith("M/1/")) { continue; } final String hash = out.getHash().toString(); final int idx = out.getTxOutputN(); final long amount = out.getValue().longValue(); if(amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD && !BlockedUTXO.getInstance().contains(hash, idx) && !BlockedUTXO.getInstance().containsNotDusted(hash, idx)) { // BalanceActivity.this.runOnUiThread(new Runnable() { // @Override Handler handler = new Handler(); handler.post(new Runnable() { public void run() { String message = BalanceActivity.this.getString(R.string.dusting_attempt); message += "\n\n"; message += BalanceActivity.this.getString(R.string.dusting_attempt_amount); message += " "; message += Coin.valueOf(amount).toPlainString(); message += " BTC\n"; message += BalanceActivity.this.getString(R.string.dusting_attempt_id); message += " "; message += hash + "-" + idx; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.dusting_tx) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { BlockedUTXO.getInstance().add(hash, idx, amount); } }).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { BlockedUTXO.getInstance().addNotDusted(hash, idx); } }); if(!isFinishing()) { dlg.show(); } } }); } } } } } }; protected BroadcastReceiver torStatusReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("BalanceActivity", "torStatusReceiver onReceive()"); if (OrbotHelper.ACTION_STATUS.equals(intent.getAction())) { boolean enabled = (intent.getStringExtra(OrbotHelper.EXTRA_STATUS).equals(OrbotHelper.STATUS_ON)); Log.i("BalanceActivity", "status:" + enabled); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(enabled); } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_balance); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if(SamouraiWallet.getInstance().isTestNet()) { setTitle(getText(R.string.app_name) + ":" + "TestNet"); } LayoutInflater inflator = BalanceActivity.this.getLayoutInflater(); tvBalanceBar = (LinearLayout)inflator.inflate(R.layout.balance_layout, null); tvBalanceBar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(isBTC) { isBTC = false; } else { isBTC = true; } displayBalance(); txAdapter.notifyDataSetChanged(); return false; } }); tvBalanceAmount = (TextView)tvBalanceBar.findViewById(R.id.BalanceAmount); tvBalanceUnits = (TextView)tvBalanceBar.findViewById(R.id.BalanceUnits); ibQuickSend = (FloatingActionsMenu)findViewById(R.id.wallet_menu); actionSend = (FloatingActionButton)findViewById(R.id.send); actionSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("via_menu", true); startActivity(intent); } }); actionReceive = (FloatingActionButton)findViewById(R.id.receive); actionReceive.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { try { HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get(); if(hdw != null) { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } }); actionBIP47 = (FloatingActionButton)findViewById(R.id.bip47); actionBIP47.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, com.samourai.wallet.bip47.BIP47Activity.class); startActivity(intent); } }); txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); txList = (ListView)findViewById(R.id.txList); txAdapter = new TransactionAdapter(); txList.setAdapter(txAdapter); txList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { if(position == 0) { return; } long viewId = view.getId(); View v = (View)view.getParent(); final Tx tx = txs.get(position - 1); ImageView ivTxStatus = (ImageView)v.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)v.findViewById(R.id.ConfirmationCount); if(viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) { if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } } else { String message = getString(R.string.options_unconfirmed_tx); // RBF if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0 && RBFUtil.getInstance().contains(tx.getHash())) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(rbfTask == null || rbfTask.getStatus().equals(AsyncTask.Status.FINISHED)) { rbfTask = new RBFTask(); rbfTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP receive else if(tx.getConfirmations() < 1 && tx.getAmount() >= 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP spend else if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } else { doExplorerView(tx.getHash()); return; } } } }); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().post(new Runnable() { @Override public void run() { refreshTx(false, true, false); swipeRefreshLayout.setRefreshing(false); } }); } }); swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); IntentFilter filterDisplay = new IntentFilter(DISPLAY_INTENT); LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiverDisplay, filterDisplay); // TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); registerReceiver(torStatusReceiver, new IntentFilter(OrbotHelper.ACTION_STATUS)); if(!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE) || !PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.READ_WRITE_EXTERNAL_PERMISSION_CODE); } if(!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.CAMERA)) { PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.CAMERA_PERMISSION_CODE); } if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, false) == false) { doFeaturePayNymUpdate(); } else if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == false && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_REFUSED, false) == false) { doClaimPayNym(); } else { ; } if(!AppUtil.getInstance(BalanceActivity.this).isClipboardSeen()) { doClipboardCheck(); } final Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(true); progress.setTitle(R.string.app_name); progress.setMessage(getText(R.string.refresh_tx_pre)); progress.show(); } }); final Handler delayedHandler = new Handler(); delayedHandler.postDelayed(new Runnable() { @Override public void run() { boolean notifTx = false; Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey("notifTx")) { notifTx = extras.getBoolean("notifTx"); } refreshTx(notifTx,false, true); // updateDisplay(); } }, 100L); if(!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } } @Override public void onResume() { super.onResume(); // IntentFilter filter = new IntentFilter(ACTION_INTENT); // LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); } AppUtil.getInstance(BalanceActivity.this).checkTimeOut(); Intent intent = new Intent("com.samourai.wallet.MainActivity2.RESTART_SERVICE"); LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent); } @Override public void onPause() { super.onPause(); ibQuickSend.collapse(); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } } @Override public void onDestroy() { LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiverDisplay); unregisterReceiver(torStatusReceiver); if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { menu.findItem(R.id.action_tor).setVisible(false); } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_on); } else { menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_off); } menu.findItem(R.id.action_refresh).setVisible(false); menu.findItem(R.id.action_share_receive).setVisible(false); menu.findItem(R.id.action_ricochet).setVisible(false); menu.findItem(R.id.action_empty_ricochet).setVisible(false); menu.findItem(R.id.action_sign).setVisible(false); menu.findItem(R.id.action_fees).setVisible(false); menu.findItem(R.id.action_batch).setVisible(false); return super.onCreateOptionsMenu(menu); } @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) { doSettings(); } else if (id == R.id.action_support) { doSupport(); } else if (id == R.id.action_sweep) { if(!AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) { doSweep(); } else { Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show(); } } else if (id == R.id.action_utxo) { doUTXO(); } else if (id == R.id.action_tor) { if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { ; } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { item.setIcon(R.drawable.tor_off); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); } else { OrbotHelper.requestStartTor(BalanceActivity.this); item.setIcon(R.drawable.tor_on); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(true); } return true; } else if (id == R.id.action_backup) { if(SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { try { if(HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { doBackup(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); }}); if(!isFinishing()) { alert.show(); } } } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(IOException ioe) { ; } } else { Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show(); } } else if (id == R.id.action_scan_qr) { doScan(); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); doPrivKey(strResult); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) { ; } else if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(strResult)); try { if(privKeyReader.getFormat() != null) { doPrivKey(strResult); } else { Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("uri", strResult); startActivity(intent); } } catch(Exception e) { ; } } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_SINGLE_TOP); BalanceActivity.this.startActivity(intent); }}); alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); if(!isFinishing()) { alert.show(); } return true; } else { ; } return false; } private void updateDisplay() { txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs(); if(txs != null) { Collections.sort(txs, new APIFactory.TxMostRecentDateComparator()); } tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); displayBalance(); txAdapter.notifyDataSetChanged(); if(progress != null && progress.isShowing()) { progress.dismiss(); progress.cancel(); progress = null; } } private void doClaimPayNym() { Intent intent = new Intent(BalanceActivity.this, ClaimPayNymActivity.class); startActivity(intent); } private void doSettings() { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class); startActivity(intent); } private void doSupport() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://samourai.kayako.com/")); startActivity(intent); } private void doUTXO() { Intent intent = new Intent(BalanceActivity.this, UTXOActivity.class); startActivity(intent); } private void doScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_QR); } private void doSweepViaScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_COLD_STORAGE); } private void doSweep() { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.action_sweep) .setCancelable(true) .setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final EditText privkey = new EditText(BalanceActivity.this); privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.enter_privkey) .setView(privkey) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String strPrivKey = privkey.getText().toString(); if(strPrivKey != null && strPrivKey.length() > 0) { doPrivKey(strPrivKey); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } }).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doSweepViaScan(); } }); if(!isFinishing()) { dlg.show(); } } private void doPrivKey(final String data) { PrivKeyReader privKeyReader = null; String format = null; try { privKeyReader = new PrivKeyReader(new CharSequenceX(data), null); format = privKeyReader.getFormat(); } catch(Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } if(format != null) { if(format.equals(PrivKeyReader.BIP38)) { final PrivKeyReader pvr = privKeyReader; final EditText password38 = new EditText(BalanceActivity.this); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.bip38_pw) .setView(password38) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String password = password38.getText().toString(); ProgressDialog progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.decrypting_bip38)); progress.show(); boolean keyDecoded = false; try { BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data); final ECKey ecKey = bip38.decrypt(password); if(ecKey != null && ecKey.hasPrivKey()) { if(progress != null && progress.isShowing()) { progress.cancel(); } pvr.setPassword(new CharSequenceX(password)); keyDecoded = true; Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show(); } } catch(Exception e) { e.printStackTrace(); Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.cancel(); } if(keyDecoded) { SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, SweepUtil.TYPE_P2PKH); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } }); if(!isFinishing()) { dlg.show(); } } else if(privKeyReader != null) { SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, SweepUtil.TYPE_P2PKH); } else { ; } } else { Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show(); } } private void doBackup() { try { final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String[] export_methods = new String[2]; export_methods[0] = getString(R.string.export_to_clipboard); export_methods[1] = getString(R.string.export_to_email); new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.options_export) .setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch (IOException ioe) { ; } catch (JSONException je) { ; } catch (DecryptionException de) { ; } catch (MnemonicException.MnemonicLengthException mle) { ; } String encrypted = null; try { encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations); } catch (Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { if (encrypted == null) { Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show(); return; } } JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true); if (which == 0) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Wallet backup", obj.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } else { Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup"); email.putExtra(Intent.EXTRA_TEXT, obj.toString()); email.setType("message/rfc822"); startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client))); } dialog.dismiss(); } } ).show(); } catch(IOException ioe) { ioe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } } private void doClipboardCheck() { final android.content.ClipboardManager clipboard = (android.content.ClipboardManager)BalanceActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE); if(clipboard.hasPrimaryClip()) { final ClipData clip = clipboard.getPrimaryClip(); ClipData.Item item = clip.getItemAt(0); if(item.getText() != null) { String text = item.getText().toString(); String[] s = text.split("\\s+"); try { for(int i = 0; i < s.length; i++) { PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(s[i])); if(privKeyReader.getFormat() != null && (privKeyReader.getFormat().equals(PrivKeyReader.WIF_COMPRESSED) || privKeyReader.getFormat().equals(PrivKeyReader.WIF_UNCOMPRESSED) || privKeyReader.getFormat().equals(PrivKeyReader.BIP38) || FormatsUtil.getInstance().isValidXprv(s[i]) ) ) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.privkey_clipboard) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { clipboard.setPrimaryClip(ClipData.newPlainText("", "")); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } } } catch(Exception e) { ; } } } } private class TransactionAdapter extends BaseAdapter { private LayoutInflater inflater = null; private static final int TYPE_ITEM = 0; private static final int TYPE_BALANCE = 1; TransactionAdapter() { inflater = (LayoutInflater)BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } return txs.size() + 1; } @Override public String getItem(int position) { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } if(position == 0) { return ""; } return txs.get(position - 1).toString(); } @Override public long getItemId(int position) { return position - 1; } @Override public int getItemViewType(int position) { return position == 0 ? TYPE_BALANCE : TYPE_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { View view = null; int type = getItemViewType(position); if(convertView == null) { if(type == TYPE_BALANCE) { view = tvBalanceBar; } else { view = inflater.inflate(R.layout.tx_layout_simple, parent, false); } } else { view = convertView; } if(type == TYPE_BALANCE) { ; } else { view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); Tx tx = txs.get(position - 1); TextView tvTodayLabel = (TextView)view.findViewById(R.id.TodayLabel); String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS()); if(position == 1) { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } else { Tx prevTx = txs.get(position - 2); String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS()); if(strPrevDateGroup.equals(strDateGroup)) { tvTodayLabel.setVisibility(View.GONE); } else { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } } String strDetails = null; String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS()); long _amount = 0L; if(tx.getAmount() < 0.0) { _amount = Math.abs((long)tx.getAmount()); strDetails = BalanceActivity.this.getString(R.string.you_sent); } else { _amount = (long)tx.getAmount(); strDetails = BalanceActivity.this.getString(R.string.you_received); } String strAmount = null; String strUnits = null; if(isBTC) { strAmount = getBTCDisplayAmount(_amount); strUnits = getBTCDisplayUnits(); } else { strAmount = getSatoshiDisplayAmount(_amount); strUnits = getSatoshiDisplayUnits(); } TextView tvDirection = (TextView)view.findViewById(R.id.TransactionDirection); TextView tvDirection2 = (TextView)view.findViewById(R.id.TransactionDirection2); TextView tvDetails = (TextView)view.findViewById(R.id.TransactionDetails); ImageView ivTxStatus = (ImageView)view.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)view.findViewById(R.id.ConfirmationCount); tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface()); if(tx.getAmount() < 0.0) { tvDirection.setTextColor(Color.RED); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up)); } else { tvDirection.setTextColor(Color.GREEN); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down)); } if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits); if(tx.getPaymentCode() != null) { String strTaggedTS = strTS + " "; String strSubText = " " + BIP47Meta.getInstance().getDisplayLabel(tx.getPaymentCode()) + " "; strTaggedTS += strSubText; tvDetails.setText(strTaggedTS); } else { tvDetails.setText(strTS); } } return view; } } private void refreshTx(final boolean notifTx, final boolean dragged, final boolean launch) { if(AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) { Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show(); /* CoordinatorLayout coordinatorLayout = new CoordinatorLayout(BalanceActivity.this); Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.in_offline_mode, Snackbar.LENGTH_LONG); snackbar.show(); */ } Intent intent = new Intent(BalanceActivity.this, RefreshService.class); intent.putExtra("notifTx", notifTx); intent.putExtra("dragged", dragged); intent.putExtra("launch", launch); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(intent); } else { startService(intent); } } private void displayBalance() { long balance = 0L; if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance(); } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(NullPointerException npe) { ; } } } } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount()).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(NullPointerException npe) { ; } } } if(isBTC) { tvBalanceAmount.setText(getBTCDisplayAmount(balance)); tvBalanceUnits.setText(getBTCDisplayUnits()); } else { tvBalanceAmount.setText(getSatoshiDisplayAmount(balance)); tvBalanceUnits.setText(getSatoshiDisplayUnits()); } } private String getBTCDisplayAmount(long value) { return Coin.valueOf(value).toPlainString(); } private String getSatoshiDisplayAmount(long value) { DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setGroupingSeparator(' '); DecimalFormat df = new DecimalFormat("#", symbols); df.setMinimumIntegerDigits(1); df.setMaximumIntegerDigits(16); df.setGroupingUsed(true); df.setGroupingSize(3); return df.format(value); } private String getBTCDisplayUnits() { return MonetaryUtil.getInstance().getBTCUnits(); } private String getSatoshiDisplayUnits() { return MonetaryUtil.getInstance().getSatoshiUnits(); } private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) { if(heads) { if(confirmations == 0) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_query_builder_white); tvConfirmationCount.setVisibility(View.GONE); } else if(confirmations > 3) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_done_white); tvConfirmationCount.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } } else { if(confirmations < 100) { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText("\u221e"); ivTxStatus.setVisibility(View.GONE); } } } private void rotateTxStatus(View view, boolean clockwise) { float degrees = 360f; if(!clockwise) { degrees = -360f; } ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees); animation.setDuration(1000); animation.setRepeatCount(0); animation.setInterpolator(new AnticipateInterpolator()); animation.start(); } private void doExplorerView(String strHash) { if(strHash != null) { int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0); if(sel >= BlockExplorerUtil.getInstance().getBlockExplorerTxUrls().length) { sel = 0; } CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerTxUrls()[sel]; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + strHash)); startActivity(browserIntent); } } private class PoWTask extends AsyncTask<String, Void, String> { private boolean isOK = true; private String strBlockHash = null; @Override protected String doInBackground(String... params) { strBlockHash = params[0]; JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort()); JSONObject nodeObj = jsonrpc.getBlockHeader(strBlockHash); if(nodeObj != null && nodeObj.has("hash")) { PoW pow = new PoW(strBlockHash); String hash = pow.calcHash(nodeObj); if(hash != null && hash.toLowerCase().equals(strBlockHash.toLowerCase())) { JSONObject headerObj = APIFactory.getInstance(BalanceActivity.this).getBlockHeader(strBlockHash); if(headerObj != null && headerObj.has("")) { if(!pow.check(headerObj, nodeObj, hash)) { isOK = false; } } } else { isOK = false; } } return "OK"; } @Override protected void onPostExecute(String result) { if(!isOK) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(getString(R.string.trusted_node_pow_failed) + "\n" + "Block hash:" + strBlockHash) .setCancelable(false) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } } @Override protected void onPreExecute() { ; } } private class CPFPTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(true); } @Override protected String doInBackground(String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(txObj.has("inputs") && txObj.has("outputs")) { final SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); int p2pkh = 0; int p2sh_p2wpkh = 0; int p2wpkh = 0; for(int i = 0; i < inputs.length(); i++) { if(inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) { String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey"); Script script = new Script(Hex.decode(scriptpubkey)); String address = null; if(Bech32Util.getInstance().isBech32Script(scriptpubkey)) { try { address = Bech32Util.getInstance().getAddressFromScript(scriptpubkey); } catch(Exception e) { ; } } else { address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } if(FormatsUtil.getInstance().isValidBech32(address)) { p2wpkh++; } else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { p2sh_p2wpkh++; } else { p2pkh++; } } } FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, outputs.length()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; UTXO utxo = null; for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String addr = obj.getString("address"); Log.d("BalanceActivity", "checking address:" + addr); if(utxo == null) { utxo = getUTXO(addr); } else { break; } } } boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); if(utxo != null) { Log.d("BalanceActivity", "utxo found"); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); selectedUTXO.add(utxo); int selected = utxo.getOutpoints().size(); long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "remaining fee:" + remainingFee); int receiveIdx = AddressFactory.getInstance(BalanceActivity.this).getHighestTxReceiveIdx(0); Log.d("BalanceActivity", "receive index:" + receiveIdx); final String addr; if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == true) { addr = utxo.getOutpoints().get(0).getAddress(); } else { addr = outputs.getJSONObject(0).getString("address"); } final String ownReceiveAddr; if(FormatsUtil.getInstance().isValidBech32(addr)) { ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).getBIP84(AddressFactory.RECEIVE_CHAIN).getBech32AsString(); } else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString(); } else { ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); } Log.d("BalanceActivity", "receive address:" + ownReceiveAddr); long totalAmount = utxo.getValue(); Log.d("BalanceActivity", "amount before fee:" + totalAmount); Triple<Integer,Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(utxo.getOutpoints())); BigInteger cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 1); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); p2pkh = outpointTypes.getLeft(); p2sh_p2wpkh = outpointTypes.getMiddle(); p2wpkh = outpointTypes.getRight(); if(totalAmount < (cpfpFee.longValue() + remainingFee)) { Log.d("BalanceActivity", "selecting additional utxo"); Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { totalAmount += _utxo.getValue(); selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(utxo.getOutpoints())); p2pkh += outpointTypes.getLeft(); p2sh_p2wpkh += outpointTypes.getMiddle(); p2wpkh += outpointTypes.getRight(); cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, 1); if(totalAmount > (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { break; } } if(totalAmount < (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); FeeUtil.getInstance().setSuggestedFee(suggestedFee); return "KO"; } } cpfpFee = cpfpFee.add(BigInteger.valueOf(remainingFee)); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for(UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } long _totalAmount = 0L; for(MyTransactionOutPoint outpoint : outPoints) { _totalAmount += outpoint.getValue().longValue(); } Log.d("BalanceActivity", "checked total amount:" + _totalAmount); assert(_totalAmount == totalAmount); long amount = totalAmount - cpfpFee.longValue(); Log.d("BalanceActivity", "amount after fee:" + amount); if(amount < SamouraiWallet.bDust.longValue()) { Log.d("BalanceActivity", "dust output"); Toast.makeText(BalanceActivity.this, R.string.cannot_output_dust, Toast.LENGTH_SHORT).show(); } final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(ownReceiveAddr, BigInteger.valueOf(amount)); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); Transaction tx = SendFactory.getInstance(BalanceActivity.this).makeTransaction(0, outPoints, receivers); if(tx != null) { tx = SendFactory.getInstance(BalanceActivity.this).signTransaction(tx); final String hexTx = new String(Hex.encode(tx.bitcoinSerialize())); Log.d("BalanceActivity", hexTx); final String strTxHash = tx.getHashAsString(); Log.d("BalanceActivity", strTxHash); boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_spent, Toast.LENGTH_SHORT).show(); FeeUtil.getInstance().setSuggestedFee(suggestedFee); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); // reset receive index upon tx fail if(FormatsUtil.getInstance().isValidBech32(addr)) { int prevIdx = BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else { int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } } } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { if(Bech32Util.getInstance().isBech32Script(addr)) { int prevIdx = BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else { int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { dialog.dismiss(); } } }); if(!isFinishing()) { dlg.show(); } } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_cpfp, Toast.LENGTH_SHORT).show(); } }); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "cpfp:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } }); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private UTXO getUTXO(String address) { UTXO ret = null; int idx = -1; for(int i = 0; i < utxos.size(); i++) { UTXO utxo = utxos.get(i); Log.d("BalanceActivity", "utxo address:" + utxo.getOutpoints().get(0).getAddress()); if(utxo.getOutpoints().get(0).getAddress().equals(address)) { ret = utxo; idx = i; break; } } if(ret != null) { utxos.remove(idx); return ret; } return null; } } private class RBFTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; private RBFSpend rbf = null; private HashMap<String,Long> input_values = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(true); input_values = new HashMap<String,Long>(); } @Override protected String doInBackground(final String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); rbf = RBFUtil.getInstance().get(params[0]); Log.d("BalanceActivity", "rbf:" + rbf.toJSON().toString()); final Transaction tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams(), Hex.decode(rbf.getSerializedTx())); Log.d("BalanceActivity", "tx serialized:" + rbf.getSerializedTx()); Log.d("BalanceActivity", "tx inputs:" + tx.getInputs().size()); Log.d("BalanceActivity", "tx outputs:" + tx.getOutputs().size()); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(tx != null && txObj.has("inputs") && txObj.has("outputs")) { try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); int p2pkh = 0; int p2sh_p2wpkh = 0; int p2wpkh = 0; for(int i = 0; i < inputs.length(); i++) { if(inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) { String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey"); Script script = new Script(Hex.decode(scriptpubkey)); String address = null; if(Bech32Util.getInstance().isBech32Script(scriptpubkey)) { try { address = Bech32Util.getInstance().getAddressFromScript(scriptpubkey); } catch(Exception e) { ; } } else { address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } if(FormatsUtil.getInstance().isValidBech32(address)) { p2wpkh++; } else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { p2sh_p2wpkh++; } else { p2pkh++; } } } SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, outputs.length()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; long total_change = 0L; List<String> selfAddresses = new ArrayList<String>(); for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); String key = objPrev.getString("txid") + ":" + objPrev.getLong("vout"); input_values.put(key, objPrev.getLong("value")); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String _addr = null; if(obj.has("address")) { _addr = obj.getString("address"); } selfAddresses.add(_addr); if(_addr != null && rbf.getChangeAddrs().contains(_addr.toString())) { total_change += obj.getLong("value"); } } } boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "total change:" + total_change); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); Log.d("BalanceActivity", "remaining fee:" + remainingFee); List<TransactionOutput> txOutputs = new ArrayList<TransactionOutput>(); txOutputs.addAll(tx.getOutputs()); long remainder = remainingFee; if(total_change > remainder) { for(TransactionOutput output : txOutputs) { Script script = output.getScriptPubKey(); String scriptPubKey = Hex.toHexString(script.getProgram()); Address _p2sh = output.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()); Address _p2pkh = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); try { if((Bech32Util.getInstance().isBech32Script(scriptPubKey) && rbf.getChangeAddrs().contains(Bech32Util.getInstance().getAddressFromScript(scriptPubKey))) || (_p2sh != null && rbf.getChangeAddrs().contains(_p2sh.toString())) || (_p2pkh != null && rbf.getChangeAddrs().contains(_p2pkh.toString()))) { if(output.getValue().longValue() >= (remainder + SamouraiWallet.bDust.longValue())) { output.setValue(Coin.valueOf(output.getValue().longValue() - remainder)); remainder = 0L; break; } else { remainder -= output.getValue().longValue(); output.setValue(Coin.valueOf(0L)); // output will be discarded later } } } catch(Exception e) { ; } } } // original inputs are not modified List<MyTransactionInput> _inputs = new ArrayList<MyTransactionInput>(); List<TransactionInput> txInputs = tx.getInputs(); for(TransactionInput input : txInputs) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], input.getOutpoint(), input.getOutpoint().getHash().toString(), (int)input.getOutpoint().getIndex()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add outpoint:" + _input.getOutpoint().toString()); } Triple<Integer,Integer,Integer> outpointTypes = null; if(remainder > 0L) { List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long selectedAmount = 0L; int selected = 0; long _remainingFee = remainder; Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { Log.d("BalanceActivity", "utxo value:" + _utxo.getValue()); // do not select utxo that are change outputs in current rbf tx boolean isChange = false; boolean isSelf = false; for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { if(rbf.containsChangeAddr(outpoint.getAddress())) { Log.d("BalanceActivity", "is change:" + outpoint.getAddress()); Log.d("BalanceActivity", "is change:" + outpoint.getValue().longValue()); isChange = true; break; } if(selfAddresses.contains(outpoint.getAddress())) { Log.d("BalanceActivity", "is self:" + outpoint.getAddress()); Log.d("BalanceActivity", "is self:" + outpoint.getValue().longValue()); isSelf = true; break; } } if(isChange || isSelf) { continue; } selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); Log.d("BalanceActivity", "selected utxo:" + selected); selectedAmount += _utxo.getValue(); Log.d("BalanceActivity", "selected utxo value:" + _utxo.getValue()); outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(_utxo.getOutpoints())); p2pkh += outpointTypes.getLeft(); p2sh_p2wpkh += outpointTypes.getMiddle(); p2wpkh += outpointTypes.getRight(); _remainingFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, outputs.length() == 1 ? 2 : outputs.length()).longValue(); Log.d("BalanceActivity", "_remaining fee:" + _remainingFee); if(selectedAmount >= (_remainingFee + SamouraiWallet.bDust.longValue())) { break; } } long extraChange = 0L; if(selectedAmount < (_remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); return "KO"; } else { extraChange = selectedAmount - _remainingFee; Log.d("BalanceActivity", "extra change:" + extraChange); } boolean addedChangeOutput = false; // parent tx didn't have change output if(outputs.length() == 1 && extraChange > 0L) { try { boolean isSegwitChange = (FormatsUtil.getInstance().isValidBech32(outputs.getJSONObject(0).getString("address")) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outputs.getJSONObject(0).getString("address")).isP2SHAddress()) || PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false; String change_address = null; if(isSegwitChange) { int changeIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); change_address = BIP49Util.getInstance(BalanceActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, changeIdx).getAddressAsString(); } else { int changeIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddrIdx(); change_address = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddressAt(changeIdx).getAddressString(); } Script toOutputScript = ScriptBuilder.createOutputScript(org.bitcoinj.core.Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), change_address)); TransactionOutput output = new TransactionOutput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, Coin.valueOf(extraChange), toOutputScript.getProgram()); txOutputs.add(output); addedChangeOutput = true; } catch(MnemonicException.MnemonicLengthException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } } // parent tx had change output else { for(TransactionOutput output : txOutputs) { Script script = output.getScriptPubKey(); String scriptPubKey = Hex.toHexString(script.getProgram()); String _addr = null; if(Bech32Util.getInstance().isBech32Script(scriptPubKey)) { try { _addr = Bech32Util.getInstance().getAddressFromScript(scriptPubKey); } catch(Exception e) { ; } } if(_addr == null) { Address _address = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(_address == null) { _address = output.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()); } _addr = _address.toString(); } Log.d("BalanceActivity", "checking for change:" + _addr); if(rbf.containsChangeAddr(_addr)) { Log.d("BalanceActivity", "before extra:" + output.getValue().longValue()); output.setValue(Coin.valueOf(extraChange + output.getValue().longValue())); Log.d("BalanceActivity", "after extra:" + output.getValue().longValue()); addedChangeOutput = true; break; } } } // sanity check if(extraChange > 0L && !addedChangeOutput) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } // update keyBag w/ any new paths final HashMap<String,String> keyBag = rbf.getKeyBag(); for(UTXO _utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], outpoint, outpoint.getTxHash().toString(), outpoint.getTxOutputN()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add selected outpoint:" + _input.getOutpoint().toString()); String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(outpoint.getAddress()); if(path != null) { if(FormatsUtil.getInstance().isValidBech32(outpoint.getAddress())) { rbf.addKey(outpoint.toString(), path + "/84"); } else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outpoint.getAddress()) != null && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outpoint.getAddress()).isP2SHAddress()) { rbf.addKey(outpoint.toString(), path + "/49"); } else { rbf.addKey(outpoint.toString(), path); } Log.d("BalanceActivity", "outpoint address:" + outpoint.getAddress()); } else { String pcode = BIP47Meta.getInstance().getPCode4Addr(outpoint.getAddress()); int idx = BIP47Meta.getInstance().getIdx4Addr(outpoint.getAddress()); rbf.addKey(outpoint.toString(), pcode + "/" + idx); } } } rbf.setKeyBag(keyBag); } // BIP69 sort of outputs/inputs final Transaction _tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams()); List<TransactionOutput> _txOutputs = new ArrayList<TransactionOutput>(); _txOutputs.addAll(txOutputs); Collections.sort(_txOutputs, new BIP69OutputComparator()); for(TransactionOutput to : _txOutputs) { // zero value outputs discarded here if(to.getValue().longValue() > 0L) { _tx.addOutput(to); } } List<MyTransactionInput> __inputs = new ArrayList<MyTransactionInput>(); __inputs.addAll(_inputs); Collections.sort(__inputs, new SendFactory.BIP69InputComparator()); for(TransactionInput input : __inputs) { _tx.addInput(input); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Transaction __tx = signTx(_tx); final String hexTx = new String(Hex.encode(__tx.bitcoinSerialize())); Log.d("BalanceActivity", "hex tx:" + hexTx); final String strTxHash = __tx.getHashAsString(); Log.d("BalanceActivity", "tx hash:" + strTxHash); if(__tx != null) { boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.rbf_spent, Toast.LENGTH_SHORT).show(); RBFSpend _rbf = rbf; // includes updated 'keyBag' _rbf.setSerializedTx(hexTx); _rbf.setHash(strTxHash); _rbf.setPrevHash(params[0]); RBFUtil.getInstance().add(_rbf); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); } } catch(final DecoderException de) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "rbf:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } else { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private Transaction signTx(Transaction tx) { HashMap<String,ECKey> keyBag = new HashMap<String,ECKey>(); HashMap<String,ECKey> keyBag49 = new HashMap<String,ECKey>(); HashMap<String,ECKey> keyBag84 = new HashMap<String,ECKey>(); HashMap<String,String> keys = rbf.getKeyBag(); for(String outpoint : keys.keySet()) { ECKey ecKey = null; String[] s = keys.get(outpoint).split("/"); Log.i("BalanceActivity", "path length:" + s.length); if(s.length == 4) { if(s[3].equals("84")) { HD_Address addr = BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChain(Integer.parseInt(s[1])).getAddressAt(Integer.parseInt(s[2])); ecKey = addr.getECKey(); } else { HD_Address addr = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChain(Integer.parseInt(s[1])).getAddressAt(Integer.parseInt(s[2])); ecKey = addr.getECKey(); } } else if(s.length == 3) { HD_Address hd_address = AddressFactory.getInstance(BalanceActivity.this).get(0, Integer.parseInt(s[1]), Integer.parseInt(s[2])); String strPrivKey = hd_address.getPrivateKeyString(); DumpedPrivateKey pk = new DumpedPrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), strPrivKey); ecKey = pk.getKey(); } else if(s.length == 2) { try { PaymentAddress address = BIP47Util.getInstance(BalanceActivity.this).getReceiveAddress(new PaymentCode(s[0]), Integer.parseInt(s[1])); ecKey = address.getReceiveECKey(); } catch(Exception e) { ; } } else { ; } Log.i("BalanceActivity", "outpoint:" + outpoint); Log.i("BalanceActivity", "path:" + keys.get(outpoint)); // Log.i("BalanceActivity", "ECKey address from ECKey:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); if(ecKey != null) { if(s.length == 4) { if(s[3].equals("84")) { keyBag84.put(outpoint, ecKey); } else { keyBag49.put(outpoint, ecKey); } } else { keyBag.put(outpoint, ecKey); } } else { throw new RuntimeException("ECKey error: cannot process private key"); // Log.i("ECKey error", "cannot process private key"); } } List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { ECKey ecKey = null; String address = null; if(inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString()) || keyBag84.containsKey(inputs.get(i).getOutpoint().toString())) { if(keyBag84.containsKey(inputs.get(i).getOutpoint().toString())) { ecKey = keyBag84.get(inputs.get(i).getOutpoint().toString()); SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = segwitAddress.getBech32AsString(); } else { ecKey = keyBag49.get(inputs.get(i).getOutpoint().toString()); SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = segwitAddress.getAddressAsString(); } } else { ecKey = keyBag.get(inputs.get(i).getOutpoint().toString()); address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } Log.d("BalanceActivity", "pubKey:" + Hex.toHexString(ecKey.getPubKey())); Log.d("BalanceActivity", "address:" + address); if(inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString()) || keyBag84.containsKey(inputs.get(i).getOutpoint().toString())) { final SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); Script scriptPubKey = segwitAddress.segWitOutputScript(); final Script redeemScript = segwitAddress.segWitRedeemScript(); System.out.println("redeem script:" + Hex.toHexString(redeemScript.getProgram())); final Script scriptCode = redeemScript.scriptCode(); System.out.println("script code:" + Hex.toHexString(scriptCode.getProgram())); TransactionSignature sig = tx.calculateWitnessSignature(i, ecKey, scriptCode, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Transaction.SigHash.ALL, false); final TransactionWitness witness = new TransactionWitness(2); witness.setPush(0, sig.encodeToBitcoin()); witness.setPush(1, ecKey.getPubKey()); tx.setWitness(i, witness); if(!FormatsUtil.getInstance().isValidBech32(address) && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { final ScriptBuilder sigScript = new ScriptBuilder(); sigScript.data(redeemScript.getProgram()); tx.getInput(i).setScriptSig(sigScript.build()); tx.getInput(i).getScriptSig().correctlySpends(tx, i, scriptPubKey, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Script.ALL_VERIFY_FLAGS); } } else { Log.i("BalanceActivity", "sign outpoint:" + inputs.get(i).getOutpoint().toString()); Log.i("BalanceActivity", "ECKey address from keyBag:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); Log.i("BalanceActivity", "script:" + ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()))); Log.i("BalanceActivity", "script:" + Hex.toHexString(ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram())); TransactionSignature sig = tx.calculateSignature(i, ecKey, ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram(), Transaction.SigHash.ALL, false); tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(sig, ecKey)); } } return tx; } } private void doFeaturePayNymUpdate() { new Thread(new Runnable() { private Handler handler = new Handler(); @Override public void run() { Looper.prepare(); try { JSONObject obj = new JSONObject(); obj.put("code", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString()); // Log.d("BalanceActivity", obj.toString()); String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL("application/json", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/token", obj.toString()); // Log.d("BalanceActivity", res); JSONObject responseObj = new JSONObject(res); if(responseObj.has("token")) { String token = responseObj.getString("token"); String sig = MessageSignUtil.getInstance(BalanceActivity.this).signMessage(BIP47Util.getInstance(BalanceActivity.this).getNotificationAddress().getECKey(), token); // Log.d("BalanceActivity", sig); obj = new JSONObject(); obj.put("nym", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString()); obj.put("code", BIP47Util.getInstance(BalanceActivity.this).getFeaturePaymentCode().toString()); obj.put("signature", sig); // Log.d("BalanceActivity", "nym/add:" + obj.toString()); res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL("application/json", token, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/nym/add", obj.toString()); // Log.d("BalanceActivity", res); responseObj = new JSONObject(res); if(responseObj.has("segwit") && responseObj.has("token")) { PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true); } else if(responseObj.has("claimed") && responseObj.getBoolean("claimed") == true) { PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true); } else { ; } } else { ; } } catch(JSONException je) { je.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } Looper.loop(); } }).start(); } }
package fr.nelaupe.spreedsheet; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.TextView; import org.fluttercode.datafactory.impl.DataFactory; import fr.nelaupe.spreadsheetlib.AnnotationFields; import fr.nelaupe.spreadsheetlib.SimpleTextAdaptor; import fr.nelaupe.spreadsheetlib.SpreadSheetAdaptor; import fr.nelaupe.spreadsheetlib.SpreadSheetView; public class MainActivity extends Activity { private long start; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); start = System.currentTimeMillis(); setContentView(R.layout.activity_main); SpreadSheetView spreadSheetView = (SpreadSheetView) findViewById(R.id.spread_sheet); PersonAdaptor personAdaptor = new PersonAdaptor(this); spreadSheetView.setAdaptor(personAdaptor.with(Person.class)); for (int i = 0; i < 30; i++) { spreadSheetView.getAdaptor().add(generateDummyData(i)); } spreadSheetView.invalidate(); } private Person generateDummyData(int i) { return new Person(i, new DataFactory()); } @Override protected void onResume() { super.onResume(); long diff = System.currentTimeMillis() - start; System.out.println("TIME TO LOAD : " + diff); } private View inflateTextView(String text) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.cell_textview, null, false); TextView textView = (TextView) view.findViewById(R.id.text); textView.setText(text); return view; } private View inflateCheckbox(Boolean bool) { CheckBox checkBox = new CheckBox(MainActivity.this); checkBox.setChecked(bool); checkBox.setEnabled(false); return checkBox; } private class PersonAdaptor extends SimpleTextAdaptor<Person> { public PersonAdaptor(Context context) { super(context); } @Override public View getCellView(AnnotationFields cell, Object object) { if (object.getClass().equals(Boolean.class)) { return inflateCheckbox((Boolean) object); } else { return inflateTextView(object.toString()); } } } }
package me.devsaki.hentoid.util; import android.content.Context; import androidx.annotation.NonNull; import androidx.documentfile.provider.DocumentFile; import com.annimon.stream.Stream; import com.google.firebase.crashlytics.FirebaseCrashlytics; import java.io.IOException; import java.util.List; import me.devsaki.hentoid.R; import me.devsaki.hentoid.database.CollectionDAO; import me.devsaki.hentoid.database.domains.Attribute; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.Group; import me.devsaki.hentoid.database.domains.GroupItem; import me.devsaki.hentoid.enums.Grouping; import me.devsaki.hentoid.json.JsonContentCollection; import timber.log.Timber; /** * Utility class for Group-related operations */ public final class GroupHelper { private GroupHelper() { throw new IllegalStateException("Utility class"); } public static Group getOrCreateNoArtistGroup(@NonNull final Context context, @NonNull final CollectionDAO dao) { String noArtistGroupName = context.getResources().getString(R.string.no_artist_group_name); Group result = dao.selectGroupByName(Grouping.ARTIST.getId(), noArtistGroupName); if (null == result) { result = new Group(Grouping.ARTIST, noArtistGroupName, -1); result.id = dao.insertGroup(result); } return result; } /** * Add the given Content to the given Group, and associate the latter with the given Attribute (if no prior association) * * @param dao DAO to be used * @param group Group to add the given Content to, and to associate with the given Attribute * @param attribute Attribute the given Group should be associated with, if it has no prior association * @param newContent Content to put in the given Group */ public static void addContentToAttributeGroup(CollectionDAO dao, Group group, Attribute attribute, Content newContent) { addContentsToAttributeGroup(dao, group, attribute, Stream.of(newContent).toList()); } /** * Add the given Contents to the given Group, and associate the latter with the given Attribute (if no prior association) * * @param dao DAO to be used * @param group Group to add the given Content to, and to associate with the given Attribute * @param attribute Attribute the given Group should be associated with, if it has no prior association * @param newContents List of Content to put in the given Group */ public static void addContentsToAttributeGroup(CollectionDAO dao, Group group, Attribute attribute, List<Content> newContents) { int nbContents; // Create group if it doesn't exist if (0 == group.id) { group.id = dao.insertGroup(group); if (attribute != null) attribute.putGroup(group); nbContents = 0; } else { nbContents = group.getItems().size(); } for (Content book : newContents) { GroupItem item = new GroupItem(book, group, nbContents++); dao.insertGroupItem(item); } } /** * Update the JSON file that stores the groups with all the groups of the app * * @param context Context to be used * @param dao DAO to be used * @return True if the groups JSON file has been updated properly; false instead */ public static boolean updateGroupsJson(@NonNull Context context, @NonNull CollectionDAO dao) { Helper.assertNonUiThread(); List<Group> customGroups = dao.selectGroups(Grouping.CUSTOM.getId()); // Save custom groups (to be able to restore them in case the app gets uninstalled) JsonContentCollection contentCollection = new JsonContentCollection(); contentCollection.setCustomGroups(customGroups); DocumentFile rootFolder = FileHelper.getFolderFromTreeUriString(context, Preferences.getStorageUri()); if (null == rootFolder) return false; try { JsonHelper.jsonToFile(context, contentCollection, JsonContentCollection.class, rootFolder, Consts.GROUPS_JSON_FILE_NAME); } catch (IOException | IllegalArgumentException e) { // even though all the file existence checks are in place // ("Failed to determine if primary:.Hentoid/groups.json is child of primary:.Hentoid: java.io.FileNotFoundException: Missing file for primary:.Hentoid/groups.json at /storage/emulated/0/.Hentoid/groups.json") Timber.e(e); FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance(); crashlytics.recordException(e); return false; } return true; } }
package me.devsaki.hentoid.util; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import me.devsaki.hentoid.BuildConfig; import timber.log.Timber; import static android.os.Build.VERSION_CODES.P; public final class Preferences { private static final int VERSION = 4; private static SharedPreferences sharedPreferences; public static void init(Context context) { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); int savedVersion = sharedPreferences.getInt(Key.PREFS_VERSION_KEY, VERSION); if (savedVersion != VERSION) { Timber.d("Shared Prefs Key Mismatch! Clearing Prefs!"); sharedPreferences.edit() .clear() .apply(); } } public static void registerPrefsChangedListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { sharedPreferences.registerOnSharedPreferenceChangeListener(listener); } public static void unregisterPrefsChangedListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); } public static boolean isFirstRunProcessComplete() { return sharedPreferences.getBoolean(Key.PREF_WELCOME_DONE, false); } public static void setIsFirstRunProcessComplete(boolean isFirstRunProcessComplete) { sharedPreferences.edit() .putBoolean(Key.PREF_WELCOME_DONE, isFirstRunProcessComplete) .apply(); } public static boolean isAnalyticsDisabled() { return sharedPreferences.getBoolean(Key.PREF_ANALYTICS_TRACKING, false); } public static boolean isFirstRun() { return sharedPreferences.getBoolean(Key.PREF_FIRST_RUN, Default.PREF_FIRST_RUN_DEFAULT); } public static void setIsFirstRun(boolean isFirstRun) { sharedPreferences.edit() .putBoolean(Key.PREF_FIRST_RUN, isFirstRun) .apply(); } public static int getContentSortOrder() { return sharedPreferences.getInt(Key.PREF_ORDER_CONTENT_LISTS, Default.PREF_ORDER_CONTENT_DEFAULT); } public static void setContentSortOrder(int sortOrder) { sharedPreferences.edit() .putInt(Key.PREF_ORDER_CONTENT_LISTS, sortOrder) .apply(); } public static int getAttributesSortOrder() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_ORDER_ATTRIBUTE_LISTS, Default.PREF_ORDER_ATTRIBUTES_DEFAULT + "")); } public static int getContentPageQuantity() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_QUANTITY_PER_PAGE_LISTS, Default.PREF_QUANTITY_PER_PAGE_DEFAULT + "")); } public static String getAppLockPin() { return sharedPreferences.getString(Key.PREF_APP_LOCK, ""); } public static void setAppLockPin(String pin) { sharedPreferences.edit() .putString(Key.PREF_APP_LOCK, pin) .apply(); } public static boolean getEndlessScroll() { return sharedPreferences.getBoolean(Key.PREF_ENDLESS_SCROLL, Default.PREF_ENDLESS_SCROLL_DEFAULT); } public static boolean getRecentVisibility() { return sharedPreferences.getBoolean(Key.PREF_HIDE_RECENT, Default.PREF_HIDE_RECENT_DEFAULT); } static String getSdStorageUri() { return sharedPreferences.getString(Key.PREF_SD_STORAGE_URI, ""); } static void setSdStorageUri(String uri) { sharedPreferences.edit() .putString(Key.PREF_SD_STORAGE_URI, uri) .apply(); } static int getFolderNameFormat() { return Integer.parseInt( sharedPreferences.getString(Key.PREF_FOLDER_NAMING_CONTENT_LISTS, Default.PREF_FOLDER_NAMING_CONTENT_DEFAULT + "")); } public static String getRootFolderName() { return sharedPreferences.getString(Key.PREF_SETTINGS_FOLDER, ""); } static boolean setRootFolderName(String rootFolderName) { return sharedPreferences.edit() .putString(Key.PREF_SETTINGS_FOLDER, rootFolderName) .commit(); } public static int getWebViewInitialZoom() { return Integer.parseInt( sharedPreferences.getString( Key.PREF_WEBVIEW_INITIAL_ZOOM_LISTS, Default.PREF_WEBVIEW_INITIAL_ZOOM_DEFAULT + "")); } public static boolean getWebViewOverview() { return sharedPreferences.getBoolean( Key.PREF_WEBVIEW_OVERRIDE_OVERVIEW_LISTS, Default.PREF_WEBVIEW_OVERRIDE_OVERVIEW_DEFAULT); } public static int getDownloadThreadCount() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_DL_THREADS_QUANTITY_LISTS, Default.PREF_DL_THREADS_QUANTITY_DEFAULT + "")); } static int getFolderTruncationNbChars() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_FOLDER_TRUNCATION_LISTS, Default.PREF_FOLDER_TRUNCATION_DEFAULT + "")); } public static boolean isViewerResumeLastLeft() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_RESUME_LAST_LEFT, Default.PREF_VIEWER_RESUME_LAST_LEFT); } public static void setViewerResumeLastLeft(boolean resumeLastLeft) { sharedPreferences.edit() .putBoolean(Key.PREF_VIEWER_RESUME_LAST_LEFT, resumeLastLeft) .apply(); } public static boolean isViewerKeepScreenOn() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_KEEP_SCREEN_ON, Default.PREF_VIEWER_KEEP_SCREEN_ON); } public static void setViewerKeepScreenOn(boolean keepScreenOn) { sharedPreferences.edit() .putBoolean(Key.PREF_VIEWER_KEEP_SCREEN_ON, keepScreenOn) .apply(); } public static int getViewerResizeMode() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_IMAGE_DISPLAY, Integer.toString(Default.PREF_VIEWER_IMAGE_DISPLAY))); } public static void setViewerResizeMode(int resizeMode) { sharedPreferences.edit() .putString(Key.PREF_VIEWER_IMAGE_DISPLAY, Integer.toString(resizeMode)) .apply(); } public static int getViewerBrowseMode() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_BROWSE_MODE, Integer.toString(Default.PREF_VIEWER_BROWSE_MODE))); } public static int getViewerDirection() { return (getViewerBrowseMode() == Constant.PREF_VIEWER_BROWSE_RTL) ? Constant.PREF_VIEWER_DIRECTION_RTL : Constant.PREF_VIEWER_DIRECTION_LTR; } public static int getViewerOrientation() { return (getViewerBrowseMode() == Constant.PREF_VIEWER_BROWSE_TTB) ? Constant.PREF_VIEWER_ORIENTATION_VERTICAL : Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL; } public static void setViewerBrowseMode(int browseMode) { sharedPreferences.edit() .putString(Key.PREF_VIEWER_BROWSE_MODE, Integer.toString(browseMode)) .apply(); } public static int getViewerFlingFactor() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_FLING_FACTOR, Integer.toString(Default.PREF_VIEWER_FLING_FACTOR))); } public static void setViewerFlingFactor(int flingFactor) { sharedPreferences.edit() .putString(Key.PREF_VIEWER_FLING_FACTOR, Integer.toString(flingFactor)) .apply(); } public static boolean isViewerDisplayPageNum() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_DISPLAY_PAGENUM, Default.PREF_VIEWER_DISPLAY_PAGENUM); } public static void setViewerDisplayPageNum(boolean displayPageNum) { sharedPreferences.edit() .putBoolean(Key.PREF_VIEWER_DISPLAY_PAGENUM, displayPageNum) .apply(); } public static boolean isViewerTapTransitions() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_TAP_TRANSITIONS, Default.PREF_VIEWER_TAP_TRANSITIONS); } public static void setViewerTapTransitions(boolean tapTransitions) { sharedPreferences.edit() .putBoolean(Key.PREF_VIEWER_TAP_TRANSITIONS, tapTransitions) .apply(); } public static boolean isOpenBookInGalleryMode() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_OPEN_GALLERY, Default.PREF_VIEWER_OPEN_GALLERY); } public static void setOpenBookInGalleryMode(boolean openBookInGalleryMode) { sharedPreferences.edit() .putBoolean(Key.PREF_VIEWER_OPEN_GALLERY, openBookInGalleryMode) .apply(); } public static int getLastKnownAppVersionCode() { return Integer.parseInt(sharedPreferences.getString(Key.LAST_KNOWN_APP_VERSION_CODE, "0")); } public static void setLastKnownAppVersionCode(int versionCode) { sharedPreferences.edit() .putString(Key.LAST_KNOWN_APP_VERSION_CODE, Integer.toString(versionCode)) .apply(); } public static int getDarkMode() { return Integer.parseInt(sharedPreferences.getString(Key.DARK_MODE, Integer.toString(Default.PREF_VIEWER_DARK_MODE))); } public static void setDarkMode(int darkMode) { sharedPreferences.edit() .putString(Key.DARK_MODE, Integer.toString(darkMode)) .apply(); } public static final class Key { public static final String PREF_APP_LOCK = "pref_app_lock"; public static final String PREF_HIDE_RECENT = "pref_hide_recent"; public static final String PREF_ADD_NO_MEDIA_FILE = "pref_add_no_media_file"; public static final String PREF_CHECK_UPDATE_MANUAL = "pref_check_updates_manual"; public static final String PREF_REFRESH_LIBRARY = "pref_refresh_bookshelf"; public static final String PREF_ANALYTICS_TRACKING = "pref_analytics_tracking"; static final String PREF_WELCOME_DONE = "pref_welcome_done"; static final String PREFS_VERSION_KEY = "prefs_version"; static final String PREF_QUANTITY_PER_PAGE_LISTS = "pref_quantity_per_page_lists"; static final String PREF_ORDER_CONTENT_LISTS = "pref_order_content_lists"; static final String PREF_ORDER_ATTRIBUTE_LISTS = "pref_order_attribute_lists"; static final String PREF_FIRST_RUN = "pref_first_run"; static final String PREF_ENDLESS_SCROLL = "pref_endless_scroll"; static final String PREF_SD_STORAGE_URI = "pref_sd_storage_uri"; static final String PREF_FOLDER_NAMING_CONTENT_LISTS = "pref_folder_naming_content_lists"; static final String PREF_SETTINGS_FOLDER = "folder"; static final String PREF_WEBVIEW_OVERRIDE_OVERVIEW_LISTS = "pref_webview_override_overview_lists"; static final String PREF_WEBVIEW_INITIAL_ZOOM_LISTS = "pref_webview_initial_zoom_lists"; public static final String PREF_DL_THREADS_QUANTITY_LISTS = "pref_dl_threads_quantity_lists"; static final String PREF_FOLDER_TRUNCATION_LISTS = "pref_folder_trunc_lists"; static final String PREF_VIEWER_RESUME_LAST_LEFT = "pref_viewer_resume_last_left"; public static final String PREF_VIEWER_KEEP_SCREEN_ON = "pref_viewer_keep_screen_on"; public static final String PREF_VIEWER_IMAGE_DISPLAY = "pref_viewer_image_display"; public static final String PREF_VIEWER_BROWSE_MODE = "pref_viewer_browse_mode"; public static final String PREF_VIEWER_FLING_FACTOR = "pref_viewer_fling_factor"; public static final String PREF_VIEWER_DISPLAY_PAGENUM = "pref_viewer_display_pagenum"; static final String PREF_VIEWER_TAP_TRANSITIONS = "pref_viewer_tap_transitions"; static final String PREF_VIEWER_OPEN_GALLERY = "pref_viewer_open_gallery"; static final String LAST_KNOWN_APP_VERSION_CODE = "last_known_app_version_code"; public static final String DARK_MODE = "pref_dark_mode"; } // IMPORTANT : Any default value change must be mirrored in res/values/strings_settings.xml public static final class Default { public static final int PREF_QUANTITY_PER_PAGE_DEFAULT = 20; public static final int PREF_WEBVIEW_INITIAL_ZOOM_DEFAULT = 20; static final int PREF_ORDER_CONTENT_DEFAULT = Constant.ORDER_CONTENT_TITLE_ALPHA; static final int PREF_ORDER_ATTRIBUTES_DEFAULT = Constant.ORDER_ATTRIBUTES_COUNT; static final boolean PREF_FIRST_RUN_DEFAULT = true; static final boolean PREF_ENDLESS_SCROLL_DEFAULT = true; static final boolean PREF_HIDE_RECENT_DEFAULT = (!BuildConfig.DEBUG); // Debug apps always visible to facilitate video capture static final int PREF_FOLDER_NAMING_CONTENT_DEFAULT = Constant.PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID; static final boolean PREF_WEBVIEW_OVERRIDE_OVERVIEW_DEFAULT = false; static final int PREF_DL_THREADS_QUANTITY_DEFAULT = Constant.DOWNLOAD_THREAD_COUNT_AUTO; static final int PREF_FOLDER_TRUNCATION_DEFAULT = Constant.TRUNCATE_FOLDER_NONE; static final boolean PREF_VIEWER_RESUME_LAST_LEFT = true; static final boolean PREF_VIEWER_KEEP_SCREEN_ON = true; static final int PREF_VIEWER_IMAGE_DISPLAY = Constant.PREF_VIEWER_DISPLAY_FIT; static final int PREF_VIEWER_BROWSE_MODE = Constant.PREF_VIEWER_BROWSE_NONE; static final boolean PREF_VIEWER_DISPLAY_PAGENUM = false; static final boolean PREF_VIEWER_TAP_TRANSITIONS = true; static final boolean PREF_VIEWER_OPEN_GALLERY = false; static final int PREF_VIEWER_FLING_FACTOR = 0; static final int PREF_VIEWER_DARK_MODE = (Build.VERSION.SDK_INT > P) ? Constant.DARK_MODE_DEVICE : Constant.DARK_MODE_OFF; } // IMPORTANT : Any value change must be mirrored in res/values/array_preferences.xml public static final class Constant { public static final int DOWNLOAD_THREAD_COUNT_AUTO = 0; public static final int ORDER_CONTENT_NONE = -1; public static final int ORDER_CONTENT_TITLE_ALPHA = 0; public static final int ORDER_CONTENT_LAST_DL_DATE_FIRST = 1; public static final int ORDER_CONTENT_TITLE_ALPHA_INVERTED = 2; public static final int ORDER_CONTENT_LAST_DL_DATE_LAST = 3; public static final int ORDER_CONTENT_RANDOM = 4; public static final int ORDER_CONTENT_LAST_UL_DATE_FIRST = 5; public static final int ORDER_CONTENT_LEAST_READ = 6; public static final int ORDER_CONTENT_MOST_READ = 7; public static final int ORDER_CONTENT_LAST_READ = 8; public static final int ORDER_ATTRIBUTES_ALPHABETIC = 0; static final int ORDER_ATTRIBUTES_COUNT = 1; static final int PREF_FOLDER_NAMING_CONTENT_ID = 0; static final int PREF_FOLDER_NAMING_CONTENT_TITLE_ID = 1; static final int PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID = 2; static final int TRUNCATE_FOLDER_NONE = 0; public static final int PREF_VIEWER_DISPLAY_FIT = 0; public static final int PREF_VIEWER_DISPLAY_FILL = 1; public static final int PREF_VIEWER_BROWSE_NONE = -1; public static final int PREF_VIEWER_BROWSE_LTR = 0; public static final int PREF_VIEWER_BROWSE_RTL = 1; public static final int PREF_VIEWER_BROWSE_TTB = 2; public static final int PREF_VIEWER_DIRECTION_LTR = 0; public static final int PREF_VIEWER_DIRECTION_RTL = 1; public static final int PREF_VIEWER_ORIENTATION_HORIZONTAL = 0; public static final int PREF_VIEWER_ORIENTATION_VERTICAL = 1; public static final int DARK_MODE_DEVICE = 0; public static final int DARK_MODE_ON = 1; public static final int DARK_MODE_OFF = 2; public static final int DARK_MODE_BATTERY = 3; } }
package me.grada.io.task; import android.app.Application; import android.location.Address; import android.location.Geocoder; import android.os.AsyncTask; import com.google.android.gms.maps.model.LatLng; import com.squareup.otto.Bus; import java.io.IOException; import java.util.List; import javax.inject.Inject; import me.grada.di.Injector; import me.grada.io.event.ReverseGeocodingEvent; public class ReverseGeocodeTask extends AsyncTask<LatLng, Void, Address> { @Inject Application application; @Inject Bus bus; private final Geocoder geocoder; public ReverseGeocodeTask() { Injector.INSTANCE.getAppComponent().inject(this); geocoder = new Geocoder(application); } @Override protected Address doInBackground(LatLng... params) { LatLng latLng = params[0]; List<Address> results = null; try { results = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 10); } catch (IOException e) { e.printStackTrace(); } if (results != null && results.size() > 0) { return results.get(0); } return null; } @Override protected void onPostExecute(Address address) { super.onPostExecute(address); if (address != null) { bus.post(new ReverseGeocodingEvent(address.getAddressLine(0))); } } }
package org.commcare.android.models; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import org.commcare.android.database.user.models.User; import org.commcare.android.util.SessionUnavailableException; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DetailField; import org.commcare.suite.model.Text; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.expr.XPathFuncExpr; import org.javarosa.xpath.parser.XPathSyntaxException; /** * @author ctsims * */ public class NodeEntityFactory { protected EvaluationContext ec; protected Detail detail; protected FormInstance instance; protected User current; private boolean mEntitySetInitialized = false; private Object mPreparationLock = new Object(); public Detail getDetail() { return detail; } public NodeEntityFactory(Detail d, EvaluationContext ec) { this.detail = d; this.ec = ec; } public Entity<TreeReference> getEntity(TreeReference data) throws SessionUnavailableException { EvaluationContext nodeContext = new EvaluationContext(ec, data); Hashtable<String, XPathExpression> variables = getDetail().getVariableDeclarations(); //These are actually in an ordered hashtable, so we can't just get the keyset, since it's //in a 1.3 hashtable equivalent for(Enumeration<String> en = variables.keys(); en.hasMoreElements();) { String key = en.nextElement(); nodeContext.setVariable(key, XPathFuncExpr.unpack(variables.get(key).eval(nodeContext))); } //return new AsyncEntity<TreeReference>(detail.getFields(), nodeContext, data); int length = detail.getHeaderForms().length; Object[] details = new Object[length]; String[] sortDetails = new String[length]; String[] backgroundDetails = new String[length]; boolean[] relevancyDetails = new boolean[length]; int count = 0; for(DetailField f : this.getDetail().getFields()) { try { details[count] = f.getTemplate().evaluate(nodeContext); Text sortText = f.getSort(); Text backgroundText = f.getBackground(); if(sortText == null) { sortDetails[count] = null; } else { sortDetails[count] = sortText.evaluate(nodeContext); } if(backgroundText == null) { backgroundDetails[count] = ""; } else { backgroundDetails[count] = backgroundText.evaluate(nodeContext); } relevancyDetails[count] = f.isRelevant(nodeContext); } catch(XPathException xpe) { xpe.printStackTrace(); details[count] = "<invalid xpath: " + xpe.getMessage() + ">"; backgroundDetails[count] = ""; // assume that if there's an error, user should see it relevancyDetails[count] = true; } catch (XPathSyntaxException e) { e.printStackTrace(); details[count] = "<invalid xpath: " + e.getMessage() + ">"; backgroundDetails[count] = ""; // assume that if there's an error, user should see it relevancyDetails[count] = true; } count++; } return new Entity<TreeReference>(details, sortDetails, backgroundDetails, relevancyDetails, data); } public List<TreeReference> expandReferenceList(TreeReference treeReference) { List<TreeReference> references = ec.expandReference(treeReference); return references; } /** * Performs the underlying work to prepare the entity set * (see prepareEntities()). Separated out to enforce timing * related to preparing and utilizing results */ protected void prepareEntitiesInternal() { //No implementation in normal factory } /** * Optional: Allows the factory to make all of the entities that it has * returned "Ready" by performing any lazy evaluation needed for optimum * usage. This preparation occurs asynchronously, and the returned entity * set should not be manipulated until it has completed. */ public final void prepareEntities() { synchronized(mPreparationLock) { prepareEntitiesInternal(); mEntitySetInitialized = true; } } /** * Performs the underlying work to check on the entitySet preparation * (see isEntitySetReady()). Separated out to enforce timing * related to preparing and utilizing results */ protected boolean isEntitySetReadyInternal() { return true; } /** * Called only after a call to prepareEntities, this signals whether * the entities returned are ready for bulk operations. * * @return True if entities returned from the factory are again ready * for use. False otherwise. */ public final boolean isEntitySetReady() { synchronized(mPreparationLock) { if(!mEntitySetInitialized) { throw new RuntimeException("A Node Entity Factory was not prepared before usage. prepareEntities() must be called before a call to isEntitySetReady()"); } return isEntitySetReadyInternal(); } } }
package org.commcare.dalvik.activities; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import org.commcare.android.framework.CommCareActivity; import org.commcare.android.resource.AppInstallStatus; import org.commcare.android.resource.ResourceInstallUtils; import org.commcare.android.tasks.InstallStagedUpdateTask; import org.commcare.android.tasks.TaskListener; import org.commcare.android.tasks.TaskListenerRegistrationException; import org.commcare.android.tasks.UpdateTask; import org.commcare.dalvik.dialogs.CustomProgressDialog; import org.commcare.dalvik.utils.ConnectivityStatus; import org.javarosa.core.services.locale.Localization; /** * Allow user to manage app updating: * - Check and download the latest update * - Stop a downloading update * - Apply a downloaded update * * @author Phillip Mates (pmates@dimagi.com) */ public class UpdateActivity extends CommCareActivity<UpdateActivity> implements TaskListener<Integer, AppInstallStatus> { private static final String TAG = UpdateActivity.class.getSimpleName(); private static final String TASK_CANCELLING_KEY = "update_task_cancelling"; private static final int DIALOG_UPGRADE_INSTALL = 6; private boolean taskIsCancelling; private UpdateTask updateTask; private UpdateUIState uiState; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiState = new UpdateUIState(this); loadSaveInstanceState(savedInstanceState); setupUpdateTask(); } private void loadSaveInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null) { taskIsCancelling = savedInstanceState.getBoolean(TASK_CANCELLING_KEY, false); } } private void setupUpdateTask() { updateTask = UpdateTask.getRunningInstance(); try { if (updateTask != null) { updateTask.registerTaskListener(this); } } catch (TaskListenerRegistrationException e) { Log.e(TAG, "Attempting to register a TaskListener to an already " + "registered task."); uiState.errorUiState(); } } @Override protected void onResume() { super.onResume(); if (!ConnectivityStatus.isNetworkAvailable(this) && ConnectivityStatus.isAirplaneModeOn(this)) { uiState.noConnectivityUiState(); return; } setUiFromTask(); } private void setUiFromTask() { int currentProgress = 0; int maxProgress = 0; if (updateTask != null) { currentProgress = updateTask.getProgress(); maxProgress = updateTask.getMaxProgress(); if (taskIsCancelling) { uiState.cancellingUiState(); } else { setUiStateFromTaskStatus(updateTask.getStatus()); } } else { pendingUpdateOrIdle(); } uiState.updateProgressBar(currentProgress, maxProgress); uiState.refreshStatusText(); } private void setUiStateFromTaskStatus(AsyncTask.Status taskStatus) { switch (taskStatus) { case RUNNING: uiState.downloadingUiState(); break; case PENDING: pendingUpdateOrIdle(); break; case FINISHED: uiState.errorUiState(); break; default: uiState.errorUiState(); } } private void pendingUpdateOrIdle() { if (ResourceInstallUtils.isUpdateReadyToInstall()) { uiState.unappliedUpdateAvailableUiState(); } else { uiState.idleUiState(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterTask(); } private void unregisterTask() { if (updateTask != null) { try { updateTask.unregisterTaskListener(this); } catch (TaskListenerRegistrationException e) { Log.e(TAG, "Attempting to unregister a not previously " + "registered TaskListener."); } updateTask = null; } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(TASK_CANCELLING_KEY, taskIsCancelling); } @Override public void handleTaskUpdate(Integer... vals) { int progress = vals[0]; int max = vals[1]; uiState.updateProgressBar(progress, max); String msg = Localization.get("updates.found", new String[]{"" + progress, "" + max}); uiState.updateProgressText(msg); } @Override public void handleTaskCompletion(AppInstallStatus result) { if (result == AppInstallStatus.UpdateStaged) { uiState.unappliedUpdateAvailableUiState(); } else { uiState.upToDateUiState(); } unregisterTask(); uiState.refreshStatusText(); } @Override public void handleTaskCancellation(AppInstallStatus result) { unregisterTask(); uiState.idleUiState(); } protected void startUpdateCheck() { try { updateTask = UpdateTask.getNewInstance(); updateTask.startPinnedNotification(this); updateTask.registerTaskListener(this); } catch (IllegalStateException e) { connectToRunningTask(); return; } catch (TaskListenerRegistrationException e) { enterErrorState("Attempting to register a TaskListener to an " + "already registered task."); return; } String ref = ResourceInstallUtils.getDefaultProfileRef(); updateTask.execute(ref); uiState.downloadingUiState(); } private void connectToRunningTask() { setupUpdateTask(); setUiFromTask(); } private void enterErrorState(String errorMsg) { Log.e(TAG, errorMsg); uiState.errorUiState(); } public void stopUpdateCheck() { if (updateTask != null) { updateTask.cancel(true); taskIsCancelling = true; uiState.cancellingUiState(); } else { uiState.idleUiState(); } } /** * Block the user with a dialog while the update is finalized. */ protected void lauchUpdateInstallTask() { InstallStagedUpdateTask<UpdateActivity> task = new InstallStagedUpdateTask<UpdateActivity>(DIALOG_UPGRADE_INSTALL) { @Override protected void deliverResult(UpdateActivity receiver, AppInstallStatus result) { if (result == AppInstallStatus.Installed) { receiver.uiState.updateInstalledUiState(); } else { receiver.uiState.errorUiState(); } } @Override protected void deliverUpdate(UpdateActivity receiver, int[]... update) { } @Override protected void deliverError(UpdateActivity receiver, Exception e) { receiver.uiState.errorUiState(); } }; task.connect(this); task.execute(); } @Override public CustomProgressDialog generateProgressDialog(int taskId) { if (taskId != DIALOG_UPGRADE_INSTALL) { Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in CommCareSetupActivity"); return null; } String title = Localization.get("updates.installing.title"); String message = Localization.get("updates.installing.message"); CustomProgressDialog dialog = CustomProgressDialog.newInstance(title, message, taskId); dialog.setCancelable(false); return dialog; } }
package com.mapswithme.maps; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.provider.Settings; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.mapswithme.maps.MapStorage.Index; import com.mapswithme.util.ConnectionState; public class DownloadUI extends ListActivity implements MapStorage.Listener { private static String TAG = "DownloadUI"; /// ListView adapter private static class DownloadAdapter extends BaseAdapter { /// @name Different row types. private static final int TYPE_GROUP = 0; private static final int TYPE_COUNTRY_GROUP = 1; private static final int TYPE_COUNTRY_IN_PROCESS = 2; private static final int TYPE_COUNTRY_READY = 3; private static final int TYPES_COUNT = 4; private LayoutInflater m_inflater; private Activity m_context; private int m_slotID = 0; private MapStorage m_storage; private String m_packageName; private static class CountryItem { public String m_name; public String m_flag; /// @see constants in MapStorage public int m_status; public CountryItem(MapStorage storage, Index idx) { m_name = storage.countryName(idx); m_flag = storage.countryFlag(idx); // The aapt can't process resources with name "do". Hack with renaming. if (m_flag.equals("do")) m_flag = "do_hack"; updateStatus(storage, idx); } public void updateStatus(MapStorage storage, Index idx) { if (idx.mCountry == -1 || (idx.mRegion == -1 && m_flag.length() == 0)) { // group and not a country m_status = MapStorage.GROUP; } else if (idx.mRegion == -1 && storage.countriesCount(idx) > 0) { // country with grouping m_status = MapStorage.COUNTRY; } else { // country or region without grouping m_status = storage.countryStatus(idx); } } public int getTextColor() { switch (m_status) { case MapStorage.ON_DISK: return 0xFF00A144; case MapStorage.ON_DISK_OUT_OF_DATE: return 0xFFFF69B4; case MapStorage.NOT_DOWNLOADED: return 0xFFFFFFFF; case MapStorage.DOWNLOAD_FAILED: return 0xFFFF0000; case MapStorage.DOWNLOADING: return 0xFF342BB6; case MapStorage.IN_QUEUE: return 0xFF5B94DE; default: return 0xFFFFFFFF; } } /// Get item type for list view representation; public int getType() { switch (m_status) { case MapStorage.GROUP: return TYPE_GROUP; case MapStorage.COUNTRY: return TYPE_COUNTRY_GROUP; case MapStorage.ON_DISK: case MapStorage.ON_DISK_OUT_OF_DATE: return TYPE_COUNTRY_READY; default : return TYPE_COUNTRY_IN_PROCESS; } } } private Index m_idx = new Index(); private CountryItem[] m_items = null; private String m_kb; private String m_mb; private AlertDialog.Builder m_alert; private DialogInterface.OnClickListener m_alertCancelHandler = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); } }; public DownloadAdapter(Activity context) { MWMApplication app = (MWMApplication) context.getApplication(); m_storage = app.getMapStorage(); m_packageName = app.getPackageName(); m_context = context; m_inflater = (LayoutInflater) m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); m_kb = context.getString(R.string.kb); m_mb = context.getString(R.string.mb); m_alert = new AlertDialog.Builder(m_context); fillList(); } private final long MB = 1024 * 1024; private String getSizeString(long size) { if (size > MB) { // do the correct rounding of MB return (size + 512 * 1024) / MB + " " + m_mb; } else { // get upper bound size for Kb return (size + 1023) / 1024 + " " + m_kb; } } /// Fill list for current m_group and m_country. private void fillList() { final int count = m_storage.countriesCount(m_idx); if (count > 0) { m_items = new CountryItem[count]; for (int i = 0; i < count; ++i) m_items[i] = new CountryItem(m_storage, m_idx.getChild(i)); } notifyDataSetChanged(); } /// Process list item click. public boolean onItemClick(int position) { if (m_items[position].m_status < 0) { // expand next level m_idx = m_idx.getChild(position); fillList(); return true; } else { processCountry(position); return false; } } private void showNotEnoughFreeSpaceDialog(String spaceNeeded, String countryName) { new AlertDialog.Builder(m_context) .setMessage(String.format(m_context.getString(R.string.free_space_for_country), spaceNeeded, countryName)) .setNegativeButton(m_context.getString(R.string.close), m_alertCancelHandler) .create() .show(); } static private long getFreeSpace() { StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); return (long)stat.getAvailableBlocks() * (long)stat.getBlockSize(); } private void processCountry(int position) { final Index idx = m_idx.getChild(position); final String name = m_items[position].m_name; // Get actual status here switch (m_storage.countryStatus(idx)) { case MapStorage.ON_DISK: // Confirm deleting m_alert .setTitle(name) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { m_storage.deleteCountry(idx); dlg.dismiss(); } }) .setNegativeButton(R.string.cancel, m_alertCancelHandler) .create() .show(); break; case MapStorage.ON_DISK_OUT_OF_DATE: final long remoteSize = m_storage.countryRemoteSizeInBytes(idx); // Update or delete new AlertDialog.Builder(m_context) .setTitle(name) .setPositiveButton(m_context.getString(R.string.update_mb_or_kb, getSizeString(remoteSize)), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { if (remoteSize + MB > getFreeSpace()) showNotEnoughFreeSpaceDialog(getSizeString(remoteSize), name); else m_storage.downloadCountry(idx); dlg.dismiss(); } }) .setNeutralButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { m_storage.deleteCountry(idx); dlg.dismiss(); } }) .setNegativeButton(R.string.cancel, m_alertCancelHandler) .create() .show(); break; case MapStorage.NOT_DOWNLOADED: // Check for available free space final long size = m_storage.countryRemoteSizeInBytes(idx); if (size + MB > getFreeSpace()) { showNotEnoughFreeSpaceDialog(getSizeString(size), name); } else { // Confirm downloading m_alert .setTitle(name) .setPositiveButton(m_context.getString(R.string.download_mb_or_kb, getSizeString(size)), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { m_storage.downloadCountry(idx); dlg.dismiss(); } }) .setNegativeButton(R.string.cancel, m_alertCancelHandler) .create() .show(); } break; case MapStorage.DOWNLOAD_FAILED: // Do not confirm downloading if status is failed, just start it m_storage.downloadCountry(idx); break; case MapStorage.DOWNLOADING: // Confirm canceling m_alert .setTitle(name) .setPositiveButton(R.string.cancel_download, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { m_storage.deleteCountry(idx); dlg.dismiss(); } }) .setNegativeButton(R.string.do_nothing, m_alertCancelHandler) .create() .show(); break; case MapStorage.IN_QUEUE: // Silently discard country from the queue m_storage.deleteCountry(idx); break; } // Actual status will be updated in "updateStatus" callback. } private void updateStatuses() { for (int i = 0; i < m_items.length; ++i) { final Index idx = m_idx.getChild(i); assert(idx.isValid()); if (idx.isValid()) m_items[i].updateStatus(m_storage, idx); } } /// @name Process routine from parent Activity. /// @return true If "back" was processed. public boolean onBackPressed() { // we are on the root level already - return if (m_idx.isRoot()) return false; // go to the parent level m_idx = m_idx.getParent(); fillList(); return true; } public void onResume(MapStorage.Listener listener) { if (m_slotID == 0) m_slotID = m_storage.subscribe(listener); // update actual statuses for items after resuming activity updateStatuses(); notifyDataSetChanged(); } public void onPause() { if (m_slotID != 0) { m_storage.unsubscribe(m_slotID); m_slotID = 0; } } @Override public int getItemViewType(int position) { return m_items[position].getType(); } @Override public int getViewTypeCount() { return TYPES_COUNT; } @Override public int getCount() { return (m_items != null ? m_items.length : 0); } @Override public CountryItem getItem(int position) { return m_items[position]; } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public TextView m_name = null; public TextView m_summary = null; public ImageView m_flag = null; public ImageView m_map = null; void initFromView(View v) { m_name = (TextView) v.findViewById(R.id.title); m_summary = (TextView) v.findViewById(R.id.summary); m_flag = (ImageView) v.findViewById(R.id.country_flag); m_map = (ImageView) v.findViewById(R.id.show_country); } } /// Process "Map" button click in list view. private class MapClickListener implements OnClickListener { private int m_position; public MapClickListener(int position) { m_position = position; } @Override public void onClick(View v) { m_storage.showCountry(m_idx.getChild(m_position)); // close parent activity m_context.finish(); } } private String formatStringWithSize(int strID, int position) { return m_context.getString(strID, getSizeString(m_storage.countryLocalSizeInBytes(m_idx.getChild(position)))); } private String getSummary(int position) { int res = 0; switch (m_items[position].m_status) { case MapStorage.ON_DISK: return formatStringWithSize(R.string.downloaded_touch_to_delete, position); case MapStorage.ON_DISK_OUT_OF_DATE: return formatStringWithSize(R.string.downloaded_touch_to_update, position); case MapStorage.NOT_DOWNLOADED: res = R.string.touch_to_download; break; case MapStorage.DOWNLOAD_FAILED: res = R.string.download_has_failed; break; case MapStorage.DOWNLOADING: res = R.string.downloading; break; case MapStorage.IN_QUEUE: res = R.string.marked_for_downloading; break; default: return "An unknown error occured!"; } return m_context.getString(res); } private void setFlag(int position, ImageView v) { Resources res = m_context.getResources(); final int id = res.getIdentifier(m_items[position].m_flag, "drawable", m_packageName); if (id > 0) v.setImageDrawable(res.getDrawable(id)); else Log.e(TAG, "Failed to get resource id from: " + m_items[position].m_flag); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); switch (getItemViewType(position)) { case TYPE_GROUP: convertView = m_inflater.inflate(R.layout.download_item_group, null); holder.initFromView(convertView); break; case TYPE_COUNTRY_GROUP: convertView = m_inflater.inflate(R.layout.download_item_country_group, null); holder.initFromView(convertView); break; case TYPE_COUNTRY_IN_PROCESS: convertView = m_inflater.inflate(R.layout.download_item_country, null); holder.initFromView(convertView); holder.m_map.setVisibility(Button.INVISIBLE); break; case TYPE_COUNTRY_READY: convertView = m_inflater.inflate(R.layout.download_item_country, null); holder.initFromView(convertView); break; } convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // set texts holder.m_name.setText(m_items[position].m_name); holder.m_name.setTextColor(m_items[position].getTextColor()); if (holder.m_summary != null) holder.m_summary.setText(getSummary(position)); // attach to "Map" button if needed if (holder.m_map != null && holder.m_map.getVisibility() == Button.VISIBLE) holder.m_map.setOnClickListener(new MapClickListener(position)); // show flag if needed if (holder.m_flag != null && holder.m_flag.getVisibility() == ImageView.VISIBLE) setFlag(position, holder.m_flag); return convertView; } /// Get list item position by index(g, c, r). /// @return -1 If no such item in display list. private int getItemPosition(Index idx) { if (m_idx.isChild(idx)) { final int position = idx.getPosition(); if (position >= 0 && position < m_items.length) return position; else Log.e(TAG, "Incorrect item position for: " + idx.toString()); } return -1; } /// @return Current country status (@see MapStorage). public int onCountryStatusChanged(Index idx) { Log.d(TAG, "onCountryStatusChanged for index: " + idx.toString()); final int position = getItemPosition(idx); if (position != -1) { m_items[position].updateStatus(m_storage, idx); // use this hard reset, because of caching different ViewHolders according to item's type notifyDataSetChanged(); return m_items[position].m_status; } return MapStorage.UNKNOWN; } public void onCountryProgress(ListView list, Index idx, long current, long total) { final int position = getItemPosition(idx); if (position != -1) { assert(m_items[position].m_status == 3); // do update only one item's view; don't call notifyDataSetChanged View v = list.getChildAt(position - list.getFirstVisiblePosition()); if (v != null) { final ViewHolder holder = (ViewHolder) v.getTag(); // This function actually is a callback from downloading engine and // when using cached views and holders, summary may be null // because of different ListView context. if (holder != null && holder.m_summary != null) { holder.m_summary.setText(String.format(m_context.getString(R.string.downloading_touch_to_cancel), current * 100 / total)); v.invalidate(); } } } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.downloader_list_view); setListAdapter(new DownloadAdapter(this)); } private DownloadAdapter getDA() { return (DownloadAdapter) getListView().getAdapter(); } @Override protected void onResume() { super.onResume(); getDA().onResume(this); } @Override protected void onPause() { super.onPause(); getDA().onPause(); } @Override public void onBackPressed() { if (getDA().onBackPressed()) { // scroll list view to the top setSelection(0); } else super.onBackPressed(); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); if (getDA().onItemClick(position)) { // scroll list view to the top setSelection(0); } } @Override public void onCountryStatusChanged(final Index idx) { if (getDA().onCountryStatusChanged(idx) == MapStorage.DOWNLOAD_FAILED) { // Show wireless settings page if no connection found. if (ConnectionState.getState(this) == ConnectionState.NOT_CONNECTED) { final DownloadUI activity = this; final String country = getDA().m_storage.countryName(idx); runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(activity) .setCancelable(false) .setMessage(String.format(getString(R.string.download_country_failed), country)) .setPositiveButton(getString(R.string.connection_settings), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); dlg.dismiss(); } }) .setNegativeButton(getString(R.string.close), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); } }) .create() .show(); } }); } } } @Override public void onCountryProgress(Index idx, long current, long total) { getDA().onCountryProgress(getListView(), idx, current, total); } }
package it.innove; import android.annotation.TargetApi; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothManager; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.os.Bundle; import android.os.ParcelUuid; import android.support.annotation.Nullable; import android.util.Base64; import android.util.Log; import com.facebook.react.bridge.*; import com.facebook.react.modules.core.RCTNativeAppEventEmitter; import org.json.JSONException; import java.util.*; import static android.app.Activity.RESULT_OK; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread; class BleManager extends ReactContextBaseJavaModule implements ActivityEventListener { private static final String LOG_TAG = "logs"; static final int ENABLE_REQUEST = 1; private BluetoothAdapter bluetoothAdapter; private Context context; private ReactContext reactContext; private Callback enableBluetoothCallback; // key is the MAC Address private Map<String, Peripheral> peripherals = new LinkedHashMap<>(); public BleManager(ReactApplicationContext reactContext) { super(reactContext); context = reactContext; this.reactContext = reactContext; reactContext.addActivityEventListener(this); Log.d(LOG_TAG, "BleManager created"); } @Override public String getName() { return "BleManager"; } private BluetoothAdapter getBluetoothAdapter() { if (bluetoothAdapter == null) { BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = manager.getAdapter(); } return bluetoothAdapter; } private void sendEvent(String eventName, @Nullable WritableMap params) { getReactApplicationContext() .getJSModule(RCTNativeAppEventEmitter.class) .emit(eventName, params); } @ReactMethod public void start(ReadableMap options, Callback callback) { Log.d(LOG_TAG, "start"); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); context.registerReceiver(mReceiver, filter); callback.invoke(); Log.d(LOG_TAG, "BleManager initialized"); } @ReactMethod public void enableBluetooth(Callback callback) { if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } if (!getBluetoothAdapter().isEnabled()) { enableBluetoothCallback = callback; Intent intentEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); getCurrentActivity().startActivityForResult(intentEnable, ENABLE_REQUEST); } else callback.invoke(); } @ReactMethod public void scan(ReadableArray serviceUUIDs, final int scanSeconds, boolean allowDuplicates, Callback callback) { Log.d(LOG_TAG, "scan"); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } if (!getBluetoothAdapter().isEnabled()) return; for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, Peripheral> entry = iterator.next(); if (!entry.getValue().isConnected()) { iterator.remove(); } } if (Build.VERSION.SDK_INT >= LOLLIPOP) { scan21(serviceUUIDs, scanSeconds, callback); } else { scan19(serviceUUIDs, scanSeconds, callback); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void scan21(ReadableArray serviceUUIDs, final int scanSeconds, Callback callback) { ScanSettings settings = new ScanSettings.Builder().build(); List<ScanFilter> filters = new ArrayList<>(); if (serviceUUIDs.size() > 0) { for(int i = 0; i < serviceUUIDs.size(); i++){ ScanFilter.Builder builder = new ScanFilter.Builder(); builder.setServiceUuid(new ParcelUuid(UUIDHelper.uuidFromString(serviceUUIDs.getString(i)))); filters.add(builder.build()); Log.d(LOG_TAG, "Filter service: " + serviceUUIDs.getString(i)); } } final ScanCallback mScanCallback = new ScanCallback() { @Override public void onScanResult(final int callbackType, final ScanResult result) { runOnUiThread(new Runnable() { @Override public void run() { Log.i(LOG_TAG, "DiscoverPeripheral: " + result.getDevice().getName()); String address = result.getDevice().getAddress(); if (!peripherals.containsKey(address)) { Peripheral peripheral = new Peripheral(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes(), reactContext); peripherals.put(address, peripheral); BundleJSONConverter bjc = new BundleJSONConverter(); try { Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject()); WritableMap map = Arguments.fromBundle(bundle); sendEvent("BleManagerDiscoverPeripheral", map); } catch (JSONException ignored) { } } else { // this isn't necessary Peripheral peripheral = peripherals.get(address); peripheral.updateRssi(result.getRssi()); } } }); } @Override public void onBatchScanResults(final List<ScanResult> results) { } @Override public void onScanFailed(final int errorCode) { } }; getBluetoothAdapter().getBluetoothLeScanner().startScan(filters, settings, mScanCallback); if (scanSeconds > 0) { Thread thread = new Thread() { @Override public void run() { try { Thread.sleep(scanSeconds * 1000); } catch (InterruptedException ignored) { } runOnUiThread(new Runnable() { @Override public void run() { getBluetoothAdapter().getBluetoothLeScanner().stopScan(mScanCallback); WritableMap map = Arguments.createMap(); sendEvent("BleManagerStopScan", map); } }); } }; thread.start(); } callback.invoke(); } private void scan19(ReadableArray serviceUUIDs, final int scanSeconds, Callback callback) { getBluetoothAdapter().startLeScan(mLeScanCallback); if (scanSeconds > 0) { Thread thread = new Thread() { @Override public void run() { try { Thread.sleep(scanSeconds * 1000); } catch (InterruptedException ignored) { } runOnUiThread(new Runnable() { @Override public void run() { getBluetoothAdapter().stopLeScan(mLeScanCallback); WritableMap map = Arguments.createMap(); sendEvent("BleManagerStopScan", map); } }); } }; thread.start(); } callback.invoke(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void stopScan21(Callback callback) { final ScanCallback mScanCallback = new ScanCallback() { @Override public void onScanResult(final int callbackType, final ScanResult result) { } }; getBluetoothAdapter().getBluetoothLeScanner().stopScan(mScanCallback); callback.invoke(); } private void stopScan19(Callback callback) { getBluetoothAdapter().stopLeScan(mLeScanCallback); callback.invoke(); } @ReactMethod public void stopScan(Callback callback) { Log.d(LOG_TAG, "Stop scan"); if (getBluetoothAdapter() == null) { Log.d(LOG_TAG, "No bluetooth support"); callback.invoke("No bluetooth support"); return; } if (!getBluetoothAdapter().isEnabled()) { callback.invoke("Bluetooth not enabled"); return; } if (Build.VERSION.SDK_INT >= LOLLIPOP) { stopScan21(callback); } else { stopScan19(callback); } } @ReactMethod public void connect(String peripheralUUID, Callback callback) { Log.d(LOG_TAG, "Connect to: " + peripheralUUID ); Peripheral peripheral = peripherals.get(peripheralUUID); if (peripheral == null) { if (peripheralUUID != null) { peripheralUUID = peripheralUUID.toUpperCase(); } if (bluetoothAdapter.checkBluetoothAddress(peripheralUUID)) { BluetoothDevice device = bluetoothAdapter.getRemoteDevice(peripheralUUID); peripheral = new Peripheral(device, reactContext); peripherals.put(peripheralUUID, peripheral); } else { callback.invoke("Invalid peripheral uuid"); return; } } peripheral.connect(callback, getCurrentActivity()); } @ReactMethod public void disconnect(String peripheralUUID, Callback callback) { Log.d(LOG_TAG, "Disconnect from: " + peripheralUUID); Peripheral peripheral = peripherals.get(peripheralUUID); if (peripheral != null){ peripheral.disconnect(); callback.invoke(); } else callback.invoke("Peripheral not found"); } @ReactMethod public void startNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) { Log.d(LOG_TAG, "startNotification"); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ peripheral.registerNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback); } else callback.invoke("Peripheral not found"); } @ReactMethod public void stopNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) { Log.d(LOG_TAG, "stopNotification"); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ peripheral.removeNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback); } else callback.invoke("Peripheral not found"); } @ReactMethod public void write(String deviceUUID, String serviceUUID, String characteristicUUID, String message, Integer maxByteSize, Callback callback) { Log.d(LOG_TAG, "Write to: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ byte[] decoded = Base64.decode(message.getBytes(), Base64.DEFAULT); Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded)); peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, null, callback, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); } else callback.invoke("Peripheral not found"); } @ReactMethod public void writeWithoutResponse(String deviceUUID, String serviceUUID, String characteristicUUID, String message, Integer maxByteSize, Integer queueSleepTime, Callback callback) { Log.d(LOG_TAG, "Write without response to: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ byte[] decoded = Base64.decode(message.getBytes(), Base64.DEFAULT); Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded)); peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, queueSleepTime, callback, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); } else callback.invoke("Peripheral not found"); } @ReactMethod public void read(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) { Log.d(LOG_TAG, "Read from: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ peripheral.read(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback); } else callback.invoke("Peripheral not found", null); } @ReactMethod public void readRSSI(String deviceUUID, Callback callback) { Log.d(LOG_TAG, "Read RSSI from: " + deviceUUID); Peripheral peripheral = peripherals.get(deviceUUID); if (peripheral != null){ peripheral.readRSSI(callback); } else callback.invoke("Peripheral not found", null); } private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { Log.i(LOG_TAG, "DiscoverPeripheral: " + device.getName()); String address = device.getAddress(); if (!peripherals.containsKey(address)) { Peripheral peripheral = new Peripheral(device, rssi, scanRecord, reactContext); peripherals.put(device.getAddress(), peripheral); BundleJSONConverter bjc = new BundleJSONConverter(); try { Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject()); WritableMap map = Arguments.fromBundle(bundle); sendEvent("BleManagerDiscoverPeripheral", map); } catch (JSONException ignored) { } } else { // this isn't necessary Peripheral peripheral = peripherals.get(address); peripheral.updateRssi(rssi); } } }); } }; @ReactMethod public void checkState(){ Log.d(LOG_TAG, "checkState"); BluetoothAdapter adapter = getBluetoothAdapter(); String state = "off"; if (adapter != null) { switch (adapter.getState()){ case BluetoothAdapter.STATE_ON: state = "on"; break; case BluetoothAdapter.STATE_OFF: state = "off"; } } WritableMap map = Arguments.createMap(); map.putString("state", state); Log.d(LOG_TAG, "state:" + state); sendEvent("BleManagerDidUpdateState", map); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(LOG_TAG, "onReceive"); final String action = intent.getAction(); String stringState = ""; if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (state) { case BluetoothAdapter.STATE_OFF: stringState = "off"; break; case BluetoothAdapter.STATE_TURNING_OFF: stringState = "turning_off"; break; case BluetoothAdapter.STATE_ON: stringState = "on"; break; case BluetoothAdapter.STATE_TURNING_ON: stringState = "turning_on"; break; } } WritableMap map = Arguments.createMap(); map.putString("state", stringState); Log.d(LOG_TAG, "state: " + stringState); sendEvent("BleManagerDidUpdateState", map); } }; @ReactMethod public void getDiscoveredPeripherals(Callback callback) { Log.d(LOG_TAG, "Get discovered peripherals"); WritableArray map = Arguments.createArray(); BundleJSONConverter bjc = new BundleJSONConverter(); for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, Peripheral> entry = iterator.next(); Peripheral peripheral = entry.getValue(); try { Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject()); WritableMap jsonBundle = Arguments.fromBundle(bundle); map.pushMap(jsonBundle); } catch (JSONException ignored) { callback.invoke("Peripheral json conversion error", null); } } callback.invoke(null, map); } @ReactMethod public void getConnectedPeripherals(ReadableArray serviceUUIDs, Callback callback) { Log.d(LOG_TAG, "Get connected peripherals"); WritableArray map = Arguments.createArray(); BundleJSONConverter bjc = new BundleJSONConverter(); for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, Peripheral> entry = iterator.next(); Peripheral peripheral = entry.getValue(); Boolean accept = false; if (serviceUUIDs.size() > 0) { for (int i = 0; i < serviceUUIDs.size(); i++) { accept = peripheral.hasService(UUIDHelper.uuidFromString(serviceUUIDs.getString(i))); } } else { accept = true; } if (peripheral.isConnected() && accept) { try { Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject()); WritableMap jsonBundle = Arguments.fromBundle(bundle); map.pushMap(jsonBundle); } catch (JSONException ignored) { callback.invoke("Peripheral json conversion error", null); } } } callback.invoke(null, map); } private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { Log.d(LOG_TAG, "onActivityResult"); if (requestCode == ENABLE_REQUEST && enableBluetoothCallback != null) { if (resultCode == RESULT_OK) { enableBluetoothCallback.invoke(); } else { enableBluetoothCallback.invoke("User refused to enable"); } enableBluetoothCallback = null; } } @Override public void onNewIntent(Intent intent) { } }
package com.axelor.meta; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.function.Supplier; import java.util.stream.Collectors; import org.eclipse.birt.core.framework.URLClassLoader; import com.axelor.common.ClassUtils; import com.axelor.common.StringUtils; import com.axelor.common.reflections.ClassFinder; import com.axelor.common.reflections.Reflections; /** * This class provides some utility methods to scan class path for * resources/classes. * */ public final class MetaScanner { private static final String MODULE_PROPERTIES = "module.properties"; private static final String SCHEME_JAR = "jar"; private static final String BUILD_CLASSES = "build/classes/main"; private static final String BUILD_RESOURCES = "build/resources/main"; private MetaScanner() { } /** * Find module properties files within the class path. * * @return list of properties file urls */ private static List<URL> findModuleFiles() { final List<URL> paths = new ArrayList<>(); final ClassLoader loader = ClassUtils.getDefaultClassLoader(); try { Enumeration<URL> found = loader.getResources(MODULE_PROPERTIES); while (found.hasMoreElements()) { paths.add(found.nextElement()); } } catch (IOException e) { } return paths; } /** * Find the properties from the given module properties file. * * @param file * the properties file url * @return module properties */ private static Properties findProperties(URL file) { final Properties properties = new Properties(); try (InputStream stream = file.openStream()) { properties.load(stream); } catch (IOException e) { } return properties; } /** * Find class path for the given module represented by the module file. * * <p> * If the module file found in a jar, it will return jar url only. If the * module file found in a gradle build directory and a resource build * directory exits, it will return list of classes and resources build dir * urls. Otherwise, the directory url only. * </p> * * @param moduleFile * the module properties file * @return list of class path urls for the module */ private static List<URL> findClassPath(URL moduleFile) { final List<URL> paths = new ArrayList<>(); final String scheme = moduleFile.getProtocol(); final boolean isJar = SCHEME_JAR.equals(scheme); String fileName = isJar ? moduleFile.getFile() : moduleFile.toString(); fileName = fileName.substring(0, fileName.length() - MODULE_PROPERTIES.length() - (isJar ? 2 : 1)); final Path file; try { file = Paths.get(new URI(fileName)); } catch (URISyntaxException e) { // this should never happen throw new RuntimeException(e); } if (fileName.endsWith(".jar")) { try { paths.add(file.toUri().toURL()); } catch (MalformedURLException e) { // this should never happen } return paths; } final Path next; if (file.endsWith(Paths.get(BUILD_CLASSES))) { next = file.resolve("../../..").resolve(BUILD_RESOURCES).normalize(); } else if (file.endsWith(Paths.get(BUILD_RESOURCES))) { next = file.resolve("../../..").resolve(BUILD_CLASSES).normalize(); } else { next = null; } try { paths.add(file.toUri().toURL()); if (next != null && Files.exists(next)) { paths.add(next.toUri().toURL()); } } catch (MalformedURLException e) { // this should never happen } return paths; } /** * Find class path entries of modules excluding library paths. * * @return list of class path entry urls of the modules. */ private static List<URL> findClassPath() { return findModuleFiles() .stream() .flatMap(file -> findClassPath(file).stream()) .collect(Collectors.toList()); } /** * Run scanner task within module only class path. This will greatly speed * up scanning process. * * @param task * the scanning task * @return scan result */ private static <T> T findWithinModules(Supplier<T> task) { final List<URL> urls = findClassPath(); return findWithinModules(urls.toArray(new URL[] {}), task); } /** * Run scanner task within the given module's class path. * * @param module * the module to scan * @param task * the scanning task * @return scan result */ private static <T> T findWithin(String module, Supplier<T> task) { final List<URL> urls = new ArrayList<>(); for (URL file : findModuleFiles()) { Properties info = findProperties(file); if (module.equals(info.getProperty("name"))) { urls.addAll(findClassPath(file)); break; } } return findWithinModules(urls.toArray(new URL[]{}), task); } private static <T> T findWithinModules(URL[] paths, Supplier<T> task) { final ClassLoader context = ClassUtils.getContextClassLoader(); final ClassLoader wrapper = new URLClassLoader(paths, null) { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return context.loadClass(name); } }; try { ClassUtils.setContextClassLoader(wrapper); return task.get(); } finally { ClassUtils.setContextClassLoader(context); } } /** * Find module properties within the class paths. * * @return list of module properties */ public static List<Properties> findModuleProperties() { return findModuleFiles().stream() .map(file -> findProperties(file)) .filter(p -> StringUtils.notBlank(p.getProperty("name"))) .collect(Collectors.toList()); } /** * Find all resources matched by the given pattern. * * @param pattern * the resource name pattern to match * @return list of resources matched */ public static List<URL> findAll(String pattern) { return findWithinModules(() -> Reflections.findResources().byName(pattern).find()); } /** * Find all resources within a directory of the given module matching the * given pattern. * * @param module * the module name * @param directory * the resource directory name * @param pattern * the resource name pattern to match * @return list of resources matched */ public static List<URL> findAll(String module, String directory, String pattern) { final String namePattern = directory + "(/|\\\\)" + pattern; return findWithin(module, () -> Reflections.findResources().byName(namePattern).find()); } /** * Delegates to {@link Reflections#findSubTypesOf(Class)} but searches * within module paths only. * * @see Reflections#findSubTypesOf(Class) */ public static <T> ClassFinder<T> findSubTypesOf(Class<T> type) { return findWithinModules(() -> Reflections.findSubTypesOf(type)); } /** * Same as {@link #findSubTypesOf(Class)} but searches only within given * module. * * @see #findSubTypesOf(Class) */ public static <T> ClassFinder<T> findSubTypesOf(String module, Class<T> type) { return findWithin(module, () -> Reflections.findSubTypesOf(type)); } }
// 2010-2011, Dermot Cochran, IT University of Copenhagen package ie.votail.uilioch; import ie.votail.model.ElectoralScenario; import ie.votail.model.Method; import ie.votail.model.data.ElectionData; import ie.votail.model.factory.BallotBoxFactory; import ie.votail.model.factory.ScenarioFactory; import ie.votail.model.factory.ScenarioList; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.logging.FileHandler; import java.util.logging.Logger; public class UniversalTestGenerator { protected static final String FILENAME_PREFIX = "testdata/"; protected static final String DATA_FILENAME_SUFFIX = "_election.data"; protected static final String LOGFILENAME = "logs/uilioch/generator.log"; protected BallotBoxFactory ballotBoxFactory; protected ScenarioFactory scenarioFactory; protected Logger logger; protected Channel<AlloyTask> taskQueue; protected AlloyPool taskPool; protected String dataFilename; protected String existingDataFilename; /** * Prepare for test generation * * @param workers The number of tasks than run in parallel * @param width The expected maximum queue length per task */ /*@ requires 0 < workers; @ requires 0 < width; */ public UniversalTestGenerator(int workers, int width) { ballotBoxFactory = new BallotBoxFactory(); scenarioFactory = new ScenarioFactory(); logger = Logger.getLogger(this.getClass().getName()); try { final String logFilename = UniversalTestGenerator.LOGFILENAME + "." + System.currentTimeMillis(); FileHandler handler = new FileHandler(logFilename); logger.addHandler(handler); } catch (SecurityException e1) { logger.info("not allowed to attach logfile " + e1.getMessage()); } catch (IOException e1) { logger.info("not able to find logfile " + e1.getMessage()); } taskQueue = new ChannelQueue<AlloyTask>(workers*width); taskPool = new AlloyPool(taskQueue, workers); dataFilename = getFilename(); existingDataFilename = dataFilename + System.currentTimeMillis(); } /** * @return */ public String getFilename() { return getFilename(Method.STV, DATA_FILENAME_SUFFIX); } /** * Generate ballot box data for an election for the required number of seats, * candidates and voting scheme. * * @param numberOfSeats * The number of seats to be filled * @param numberOfCandidates * The number of candidates for election * @param method * The voting scheme * @param scope * Maximum scope for Alloy solution */ public void generateTests(final int numberOfSeats, final int numberOfCandidates, final Method method) { // If file already exists then rename it final boolean existingData = checkAndRename(dataFilename, existingDataFilename); try { FileOutputStream fos = new FileOutputStream(dataFilename, true); ObjectOutputStream out = new ObjectOutputStream(fos); for (int seats = 1; seats <= numberOfSeats; seats++) { for (int candidates = 1 + seats; candidates <= numberOfCandidates; candidates++) { createBallotBoxes(seats, candidates, method, out, existingDataFilename, existingData); } } out.close(); fos.close(); } catch (FileNotFoundException e) { logger.severe(e.toString()); } catch (IOException e) { logger.severe(e.toString()); } finally { } logger.info("Finished."); } /** * Check if file already exists and rename it if it does. * * @param oldName * The filename to check * @param newName * The new filename */ protected boolean checkAndRename(/*@ non_null*/String oldName, /*@ non_null*/String newName) { File file = new File(oldName); if (file.exists()) { File newFile = new File(newName); file.renameTo(newFile); return true; } return false; } /** * Simulate test data or universal testing of an election * * @param seats * The number of seats to be filled * @param candidates * The number of candidates * @param method * The voting scheme and method of election * @param in * @param out * Output file stream for generated data * @param scope * Maximum scope for Alloy solution */ protected void createBallotBoxes(final int seats, final int candidates, final Method method, ObjectOutputStream out, final String filename, final boolean existingData) { ScenarioList scenarioList = scenarioFactory.find(candidates, seats, method); logger.fine("Scenarios: " + scenarioList.toString()); int count = 0; for (ElectoralScenario scenario : scenarioList) { logger.info(scenario.toString()); // Check if this scenario already generated if (!existingData || !alreadyExists(scenario, filename, out)) { try { taskQueue.put(new AlloyTask(out,scenario)); count++; } catch (InterruptedException ioe) { logger.severe(ioe.toString()); } } } logger.info("Generated " + count + " scenarios for " + method.toString() + " with " + candidates + " candidates for " + seats + " seats."); } /** * Check if data for this scenario already exists * * @param scenario * The scenario to check * @param out * @param in * The file input stream containing existing test data * @return <code>false></code> if scenario is found in the data */ protected boolean alreadyExists(ElectoralScenario scenario, String filename, ObjectOutputStream out) { // Open a new reader try { FileInputStream fis = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(fis); ElectionData testData = getTestData(in); while (testData != null) { if (testData.getScenario().equivalentTo(scenario)) { // Copy existing data into new data file logger.info("Copying existing data: " + testData); out.writeObject(testData); return true; } } in.close(); fis.close(); } catch (IOException e) { logger.severe(e.getMessage()); } return false; } /** * Deserialization of Test Data * * @param in * The Object Input Stream which contains the test data * @return The Test Data (or null) */ public ElectionData getTestData(ObjectInputStream in) { ElectionData electionData = null; try { electionData = (ElectionData) in.readObject(); } catch (IOException ioe) { logger.severe(ioe.toString()); } catch (ClassNotFoundException cnfe) { logger.severe(cnfe.toString()); } return electionData; } /** * Get name of the file which contains testdata for this method. * * @param method * The type of voting scheme * @return The filename */ protected /*@ pure @*/String getFilename(final Method method, final String suffix) { return FILENAME_PREFIX + method.toString() + suffix; } /** * Generate enough test data for 100% path coverage */ public static void main(String[] args) { UniversalTestGenerator uilioch = new UniversalTestGenerator(15, 10); uilioch.generateTests(1, 5, Method.STV); // IRV 1-seat uilioch.generateTests(3, 7, Method.STV); // PR-STV 3-seat uilioch.generateTests(4, 9, Method.STV); // PR-STV 4-seat uilioch.generateTests(5, 11, Method.STV); // PR-STV 5-seat uilioch.generateTests(1, 11, Method.Plurality); // First-past-the-post } }
import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; @SuppressWarnings("all") public class BAS_Sample { private final Map<String, String> m = new HashMap<>(); private long value = 0; public void testIfScope(String s) { Object o = new Object(); if (s.equals("Foo")) { s = o.toString(); } } public String testFPForScope(String s) { Object o = new Object(); while (s.length() > 0) { o = s.substring(0, 1); s = s.substring(1); } return s; } public String testFP2Scopes(String s) { Object o = new Object(); if (s.equals("Boo")) { s = o.toString(); } else if (s.equals("Hoo")) { s = o.toString(); } return s; } public String test2InnerScopes(String s) { Object o = new Object(); if (s != null) { if (s.equals("Boo")) { s = o.toString(); } else if (s.equals("Hoo")) { s = o.toString(); } } return s; } public String testFPLoopCond(List<String> in) { StringBuilder sb = new StringBuilder(); for (String s : in) { sb.append(s); } return sb.toString(); } public List<String> getList() { return null; } public String testSwitch(int a) { String v = "Test"; switch (a) { case 1: v = "Testa"; break; case 2: v = "Tesseract"; break; case 3: v = "Testy"; break; default: v = "Rossa"; break; } return null; } public void testFPSync(Set<String> a, Set<String> b) { String c, d; synchronized (this) { c = a.iterator().next(); d = b.iterator().next(); } if (d.length() > 0) { d = c; } } public int testFPObjChange(Calendar c, boolean b) { int hour = c.get(Calendar.HOUR_OF_DAY); c.set(2000, Calendar.JANUARY, 1); if (b) { return hour; } return 0; } public void tstFPThisRefChange(long v, boolean b) { long oldValue = this.value; this.value = v; if (b) { if (oldValue < 0) { System.out.println("Negative"); } } } public void tstFPRefChange(Holder h1, Holder h2, boolean b) { int h = h1.member; h1 = h2; if (b) { System.out.println(h); } } public void tstFPRefChangeThruMethodChain(Holder h1, Holder h2, boolean b) { String h = h1.toString().trim(); h1 = h2; if (b) { System.out.println(h); } } public void testFPSrcOverwrite(int src, boolean b) { int d = src; src = 0; if (b) { System.out.println(d); } } public void testFPRiskies1(boolean b) { long start = System.currentTimeMillis(); if (b) { long delta = System.currentTimeMillis() - start; System.out.println(delta); } } public String testFPIteratorNext(Collection<String> c, boolean b) { Iterator<String> it = c.iterator(); String s = it.next(); if (b) { if (s == null) { return "yay"; } } return it.next(); } public List<String> testFPSynchronized(String s, String p) { List<String> l = new ArrayList<>(); String x = s; synchronized (s) { if (p != null) { l.add(p); return l; } } return null; } public void testFPNestedIfs(Map<String, String> x, int i, boolean b) { String s = x.get("hello"); if (i == 0) { if (b) { System.out.println(s); } } else if (i == 1) { System.out.println(s); } else if (i == 2) { System.out.println(s); } } public boolean testFPFuture(boolean b) { ExecutorService s = new ForkJoinPool(); Future f = s.submit(new Runnable() { @Override public void run() { } }); if (b) { if (f.isDone()) { return true; } } return false; } public int testFPTwoCatches(List<Integer> x) throws Exception { String msg = "This is a test"; try { return x.size() * x.get(0); } catch (NullPointerException e) { throw new Exception(msg + "NPE", e); } catch (IndexOutOfBoundsException e) { throw new Exception(msg + "IIOBE", e); } } static class Holder { int member; } }
package me.openphoto.android.app; import java.util.List; import me.openphoto.android.app.SyncImageSelectionFragment.NextStepFlow; import me.openphoto.android.app.SyncUploadFragment.PreviousStepFlow; import me.openphoto.android.app.provider.UploadsUtils.UploadsClearedHandler; import me.openphoto.android.app.util.CommonUtils; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.ViewGroup; import com.WazaBe.HoloEverywhere.LayoutInflater; import com.WazaBe.HoloEverywhere.app.Activity; public class SyncFragment extends CommonFragment implements NextStepFlow, PreviousStepFlow, Refreshable, UploadsClearedHandler { static final String FIRST_STEP_TAG = "firstStepSync"; static final String SECOND_STEP_TAG = "secondStepSync"; static final String ACTIVE_STEP = "SyncFragmentActiveStep"; Fragment activeFragment; SyncImageSelectionFragment firstStepFragment; SyncUploadFragment secondStepFragment; SyncHandler syncHandler; boolean instanceSaved = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initInnerFragments(savedInstanceState); } public void initInnerFragments(Bundle savedInstanceState) { String activeStep = savedInstanceState == null ? FIRST_STEP_TAG : savedInstanceState.getString(ACTIVE_STEP); firstStepFragment = (SyncImageSelectionFragment) getActivity() .getSupportFragmentManager().findFragmentByTag(FIRST_STEP_TAG); if (!activeStep.equals(FIRST_STEP_TAG)) { detachFragmentIfNecessary(firstStepFragment); } if (firstStepFragment != null) { CommonUtils.debug(TAG, "First step fragment is not null. Setting next step flow..."); firstStepFragment.setNextStepFlow(this); } secondStepFragment = (SyncUploadFragment) getActivity().getSupportFragmentManager() .findFragmentByTag(SECOND_STEP_TAG); if (!activeStep.equals(SECOND_STEP_TAG)) { detachFragmentIfNecessary(secondStepFragment); } if (secondStepFragment != null) { CommonUtils.debug(TAG, "Second step fragment is not null. Setting previous step flow..."); secondStepFragment.setPreviousStepFlow(this); } CommonUtils.debug(TAG, "Active step: " + activeStep); if (activeStep.equals(FIRST_STEP_TAG)) { activeFragment = firstStepFragment; } else { activeFragment = secondStepFragment; } } @Override public void onDetach() { super.onDetach(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (activeFragment != null) { outState.putString(ACTIVE_STEP, getTagForFragment(activeFragment)); } instanceSaved = true; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View v = inflater.inflate(R.layout.fragment_sync_switch, container, false); init(v); // fix for the issue #216 instanceSaved = false; return v; } @Override public void onAttach(Activity activity) { super.onAttach(activity); syncHandler = (SyncHandler) activity; } void init(View view) { if (activeFragment != null) { selectFragment(activeFragment, true); } else { activatePreviousStep(); } } void selectFragment(Fragment fragment, boolean attachOnly) { CommonUtils.debug(TAG, "Selecting fragment: " + fragment + "; attachOnly: " + attachOnly); FragmentTransaction transaction = getActivity() .getSupportFragmentManager().beginTransaction(); if (activeFragment != null && !activeFragment.isDetached()) { transaction.detach(activeFragment); } if (attachOnly) { transaction.attach(fragment); } else { transaction.replace(R.id.fragment_container, fragment, getTagForFragment(fragment)); } transaction.commit(); activeFragment = fragment; } String getTagForFragment(Fragment fragment) { if (fragment == firstStepFragment) { return FIRST_STEP_TAG; } else { return SECOND_STEP_TAG; } } @Override public void onDestroyView() { super.onDestroyView(); detachActiveFragment(); } public void detachActiveFragment() { if (activeFragment != null && !instanceSaved && !getActivity().isFinishing()) { FragmentTransaction transaction = getActivity() .getSupportFragmentManager().beginTransaction(); transaction.detach(activeFragment); transaction.commit(); // activeFragment = null; } }; public void detachFragmentIfNecessary(Fragment fragment) { if (fragment != null && !fragment.isDetached()) { CommonUtils.debug(TAG, "Detaching fragment: " + fragment); getActivity().getSupportFragmentManager().beginTransaction() .detach(fragment) .commit(); } } @Override public void activatePreviousStep() { if (getActivity() == null || getActivity().isFinishing() || instanceSaved) { CommonUtils .debug(TAG, "Skipping previous step activation because of finishing activity or saved instance state."); return; } if (firstStepFragment == null) { firstStepFragment = (SyncImageSelectionFragment) getActivity() .getSupportFragmentManager().findFragmentByTag(FIRST_STEP_TAG); detachFragmentIfNecessary(firstStepFragment); boolean attachOnly = true; if (firstStepFragment == null) { firstStepFragment = new SyncImageSelectionFragment(); attachOnly = false; } firstStepFragment.setNextStepFlow(this); selectFragment(firstStepFragment, attachOnly); } else { selectFragment(firstStepFragment, true); } } @Override public void activateNextStep() { if (secondStepFragment == null) { secondStepFragment = (SyncUploadFragment) getActivity().getSupportFragmentManager() .findFragmentByTag(SECOND_STEP_TAG); detachFragmentIfNecessary(secondStepFragment); boolean attachOnly = true; if (secondStepFragment == null) { secondStepFragment = new SyncUploadFragment(); attachOnly = false; } secondStepFragment.setPreviousStepFlow(this); selectFragment(secondStepFragment, attachOnly); } else { selectFragment(secondStepFragment, true); } } @Override public void refresh() { if (activeFragment == firstStepFragment) { firstStepFragment.refresh(); } } @Override public List<String> getSelectedFileNames() { return firstStepFragment.getSelectedFileNames(); } @Override public void uploadStarted(List<String> processedFileNames) { // detachActiveFragment(); firstStepFragment.clear(); firstStepFragment.addProcessedValues(processedFileNames); secondStepFragment.clear(); activatePreviousStep(); if (syncHandler != null) { syncHandler.syncStarted(); } } static interface SyncHandler { void syncStarted(); } @Override public void uploadsCleared() { firstStepFragment.uploadsCleared(); } }
package de.unipaderborn.visuflow.ui.view; import java.util.Dictionary; import java.util.Hashtable; import java.util.List; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import de.unipaderborn.visuflow.model.DataModel; import de.unipaderborn.visuflow.model.VFClass; import de.unipaderborn.visuflow.model.VFMethod; import de.unipaderborn.visuflow.model.VFUnit; import de.unipaderborn.visuflow.util.ServiceUtil; import soot.jimple.internal.JAssignStmt; public class UnitView extends ViewPart implements EventHandler { DataModel dataModel; Tree tree; Combo classCombo,methodCombo; Button checkBox; String classSelection, methodSelection; private List<VFUnit> listUnits; GridData gridUnitTable; class ViewLabelProvider extends LabelProvider implements ILabelProvider{ public String getColumnText(Object obj, int index){ return getText(obj); } public Image getColumnImage(Object obj, int index){ return getImage(obj); } @Override public Image getImage(Object obj){ return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT); } } @Override public void createPartControl(Composite parent){ GridLayout layout = new GridLayout(3, true); parent.setLayout(layout); GridData gridVFClass = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); gridVFClass.widthHint = SWT.DEFAULT; gridVFClass.heightHint = SWT.DEFAULT; classCombo = new Combo(parent, SWT.DROP_DOWN); classCombo.setLayout(layout); classCombo.setLayoutData(gridVFClass); GridData gridVFMethod = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); gridVFMethod.widthHint = SWT.DEFAULT; gridVFMethod.heightHint = SWT.DEFAULT; methodCombo = new Combo(parent, SWT.DROP_DOWN); methodCombo.setLayout(layout); methodCombo.setLayoutData(gridVFMethod); GridData gridCheck = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); gridCheck.widthHint = SWT.DEFAULT; gridCheck.heightHint = SWT.DEFAULT; checkBox = new Button(parent, SWT.CHECK); checkBox.setText("Sync with Graph View"); checkBox.setLayoutData(gridCheck); gridUnitTable = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); gridUnitTable.widthHint = SWT.DEFAULT; gridUnitTable.heightHint = SWT.DEFAULT; tree = new Tree(parent, SWT.FILL| SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BACKGROUND | SWT.MULTI | SWT.BACKGROUND); tree.setHeaderVisible(true); tree.setLayout(layout); tree.setLayoutData(gridUnitTable); //methodCombo.select(0); classCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { String selectedClass = classCombo.getText(); for (VFClass vfclass : dataModel.listClasses()) { if(vfclass.getSootClass().getName().toString().equals(selectedClass)) { methodCombo.removeAll(); for (VFMethod vfmethod : dataModel.listMethods(vfclass)) { methodCombo.add(vfmethod.getSootMethod().getDeclaration()); } } } methodCombo.select(0); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); methodCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { String selectMethod = methodCombo.getText(); String selectedClass = classCombo.getText(); for (VFClass vfclass : dataModel.listClasses()) { if(vfclass.getSootClass().getName().toString().equals(selectedClass)) { for (VFMethod vfmethod : dataModel.listMethods(vfclass)) { if(vfmethod.getSootMethod().getDeclaration().toString().equals(selectMethod)) { tree.removeAll(); listUnits = vfmethod.getUnits(); for (VFUnit unit : listUnits) { TreeItem treeItem= new TreeItem(tree, SWT.NONE | SWT.BORDER); treeItem.setText(unit.getUnit().toString()); if (unit.getUnit() instanceof JAssignStmt) { JAssignStmt stmt = (JAssignStmt)unit.getUnit(); TreeItem treeLeft = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER); treeLeft.setText(new String[] {"Left"}); TreeItem treeLeftValue= new TreeItem(treeLeft, SWT.LEFT | SWT.BORDER); treeLeftValue.setText(new String[] {"Value : "+stmt.leftBox.getValue().toString()}); TreeItem treeLeftClass= new TreeItem(treeLeft, SWT.LEFT | SWT.BORDER); treeLeftClass.setText(new String[] {"Class : "+stmt.leftBox.getValue().getClass().toString()}); TreeItem treeRight = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER); treeRight.setText(new String[] {"Right"}); TreeItem treeRightValue= new TreeItem(treeRight, SWT.LEFT | SWT.BORDER); treeRightValue.setText(new String[] {"Value : "+stmt.leftBox.getValue().toString()}); TreeItem treeRightClass= new TreeItem(treeRight, SWT.LEFT | SWT.BORDER); treeRightClass.setText(new String[] {"Class : "+stmt.leftBox.getValue().getClass().toString()}); } } } } } } } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); checkBox.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if(!listUnits.isEmpty()) { tree.removeAll(); for (VFUnit unit : listUnits) { TreeItem treeItem= new TreeItem(tree, SWT.NONE | SWT.BORDER); treeItem.setText(unit.getUnit().toString()); if (unit.getUnit() instanceof JAssignStmt) { JAssignStmt stmt = (JAssignStmt)unit.getUnit(); TreeItem treeLeft = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER); treeLeft.setText(new String[] {"Left"}); TreeItem treeLeftValue= new TreeItem(treeLeft, SWT.LEFT | SWT.BORDER); treeLeftValue.setText(new String[] {"Value : "+stmt.leftBox.getValue().toString()}); TreeItem treeLeftClass= new TreeItem(treeLeft, SWT.LEFT | SWT.BORDER); treeLeftClass.setText(new String[] {"Class : "+stmt.leftBox.getValue().getClass().toString()}); TreeItem treeRight = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER); treeRight.setText(new String[] {"Right"}); TreeItem treeRightValue= new TreeItem(treeRight, SWT.LEFT | SWT.BORDER); treeRightValue.setText(new String[] {"Value : "+stmt.leftBox.getValue().toString()}); TreeItem treeRightClass= new TreeItem(treeRight, SWT.LEFT | SWT.BORDER); treeRightClass.setText(new String[] {"Class : "+stmt.leftBox.getValue().getClass().toString()}); } } } } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); Dictionary<String, Object> properties = new Hashtable<>(); //properties.put(EventConstants.EVENT_TOPIC, new String[]{DataModel.EA_TOPIC_DATA_MODEL_CHANGED,DataModel.EA_TOPIC_DATA_SELECTION});
package us.kbase.common.service; import us.kbase.auth.AuthConfig; import us.kbase.auth.AuthException; import us.kbase.auth.AuthToken; import us.kbase.auth.ConfigurableAuthService; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.ini4j.Ini; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Helper class used as ancestor of generated server side servlets for JSON RPC calling. * @author rsutormin */ public class JsonServerServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String APP_JSON = "application/json"; private static final String DONT_TRUST_X_IP_HEADERS = "dont_trust_x_ip_headers"; private static final String DONT_TRUST_X_IP_HEADERS2 = "dont-trust-x-ip-headers"; private static final String STRING_TRUE = "true"; private static final String X_FORWARDED_FOR = "X-Forwarded-For"; private static final String X_REAL_IP = "X-Real-IP"; private ObjectMapper mapper; private Map<String, Method> rpcCache; public static final int LOG_LEVEL_ERR = JsonServerSyslog.LOG_LEVEL_ERR; public static final int LOG_LEVEL_INFO = JsonServerSyslog.LOG_LEVEL_INFO; public static final int LOG_LEVEL_DEBUG = JsonServerSyslog.LOG_LEVEL_DEBUG; public static final int LOG_LEVEL_DEBUG2 = JsonServerSyslog.LOG_LEVEL_DEBUG + 1; public static final int LOG_LEVEL_DEBUG3 = JsonServerSyslog.LOG_LEVEL_DEBUG + 2; private JsonServerSyslog sysLogger; private JsonServerSyslog userLogger; /** The key for the environment variable or JVM variable with the value of * the server config file location. */ public static final String KB_DEP = "KB_DEPLOYMENT_CONFIG"; /** The key for the environment variable or JVM variable with the value of * the server name. */ public static final String KB_SERVNAME = "KB_SERVICE_NAME"; private static final String CONFIG_AUTH_SERVICE_URL_PARAM = "auth-service-url"; private static final String KB_JOB_SERVICE_URL = "KB_JOB_SERVICE_URL"; private static final String CONFIG_JOB_SERVICE_URL_PARAM = "job-service-url"; private final ConfigurableAuthService auth; protected Map<String, String> config = new HashMap<String, String>(); private Server jettyServer = null; private Integer jettyPort = null; private boolean startupFailed = false; private Long maxRPCPackageSize = null; private int maxRpcMemoryCacheSize = 16 * 1024 * 1024; private File rpcDiskCacheTempDir = null; private final String specServiceName; private String serviceVersion = null; private final static DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC(); /** * Starts a test jetty server on an OS-determined port. Blocks until the * server is terminated. * @throws Exception if the server couldn't be started. */ public void startupServer() throws Exception { startupServer(0); } /** * Starts a test jetty server. Blocks until the * server is terminated. * @param port the port to which the server will connect. * @throws Exception if the server couldn't be started. */ public void startupServer(int port) throws Exception { jettyServer = new Server(port); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); jettyServer.setHandler(context); /** * Get the jetty test server port. Returns null if the server is not running or starting up. * @return the port */ public Integer getServerPort() { return jettyPort; } /** * Stops the test jetty server. * @throws Exception if there was an error stopping the server. */ public void stopServer() throws Exception { jettyServer.stop(); jettyServer = null; jettyPort = null; } /** Sets the server to failed mode. All API calls will return an error. */ public void startupFailed() { this.startupFailed = true; } /** Create a new Servlet. * @param specServiceName the name of this server. */ public JsonServerServlet(String specServiceName) { this.specServiceName = specServiceName; this.mapper = new ObjectMapper().registerModule(new JacksonTupleModule()); this.rpcCache = new HashMap<String, Method>(); for (Method m : getClass().getMethods()) { if (m.isAnnotationPresent(JsonServerMethod.class)) { JsonServerMethod ann = m.getAnnotation(JsonServerMethod.class); rpcCache.put(ann.rpc(), m); if (ann.async()) { rpcCache.put(ann.rpc() + "_async", m); rpcCache.put(ann.rpc() + "_check", m); } } } sysLogger = new JsonServerSyslog(getServiceName(specServiceName), KB_DEP, LOG_LEVEL_INFO, false); userLogger = new JsonServerSyslog(sysLogger, true); config = getConfig(specServiceName, sysLogger); auth = getAuth(config); } private ConfigurableAuthService getAuth(final Map<String, String> config) { final String authURL = config.get(CONFIG_AUTH_SERVICE_URL_PARAM); final AuthConfig c; if (authURL == null || authURL.isEmpty()) { c = new AuthConfig(); } else { try { c = new AuthConfig().withKBaseAuthServerURL(new URL(authURL)); } catch (URISyntaxException | MalformedURLException e) { startupFailed(); sysLogger.logErr(String.format( "Authentication url %s is invalid", authURL)); return null; } } try { return new ConfigurableAuthService(c); } catch (IOException e) { startupFailed(); sysLogger.logErr("Couldn't connect to authentication service at " + c.getAuthServerURL() + " : " + e.getLocalizedMessage()); return null; } } /** * Returns the configuration from the KBase deploy.cfg config file. * Returns an empty map if no config file is specified, if the file * can't be read, or if there is no section of the config file matching * serviceName. * @param defaultServiceName the default name of the service to use if it * can't be found in the environment, and the section of the config file * where the service's configuration exists * @param logger a logger for logging errors * @return the server config from the deploy.cfg file */ public static Map<String, String> getConfig( final String defaultServiceName, final JsonServerSyslog logger) { if (logger == null) { throw new NullPointerException("logger cannot be null"); } final String serviceName = getServiceName(defaultServiceName); final String file = System.getProperty(KB_DEP) == null ? System.getenv(KB_DEP) : System.getProperty(KB_DEP); if (file == null) { return new HashMap<String, String>(); } final File deploy = new File(file); final Ini ini; try { ini = new Ini(deploy); } catch (IOException ioe) { logger.log(LOG_LEVEL_ERR, JsonServerServlet.class.getName(), "There was an IO Error reading the deploy file " + deploy + ". Traceback:\n" + ioe); return new HashMap<String, String>(); } Map<String, String> config = ini.get(serviceName); if (config == null) { config = new HashMap<String, String>(); logger.log(LOG_LEVEL_ERR, JsonServerServlet.class.getName(), "The configuration file " + deploy + " has no section " + serviceName); } return config; } protected String getDefaultServiceName() { return specServiceName; } protected static String getServiceName(final String defaultServiceName) { if (defaultServiceName == null) { throw new NullPointerException("service name cannot be null"); } String serviceName = System.getProperty(KB_SERVNAME) == null ? System.getenv(KB_SERVNAME) : System.getProperty(KB_SERVNAME); if (serviceName == null) { serviceName = defaultServiceName; if (serviceName.contains(":")) serviceName = serviceName.substring( 0, serviceName.indexOf(':')).trim(); } return serviceName; } /** * WARNING! Please use this method for testing purposes only. * @param output */ public void changeSyslogOutput(JsonServerSyslog.SyslogOutput output) { sysLogger.changeOutput(output); userLogger.changeOutput(output); } public void logErr(String message) { userLogger.logErr(message); } public void logErr(Throwable err) { userLogger.logErr(err); } public void logInfo(String message) { userLogger.logInfo(message); } public void logDebug(String message) { userLogger.logDebug(message); } public void logDebug(String message, int debugLevelFrom1to3) { userLogger.logDebug(message, debugLevelFrom1to3); } public int getLogLevel() { return userLogger.getLogLevel(); } public void setLogLevel(int level) { userLogger.setLogLevel(level); } public void clearLogLevel() { userLogger.clearLogLevel(); } public boolean isLogDebugEnabled() { return userLogger.getLogLevel() >= LOG_LEVEL_DEBUG; } @Override protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { setupResponseHeaders(request, response); response.setContentLength(0); response.getOutputStream().print(""); response.getOutputStream().flush(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonServerSyslog.RpcInfo info = JsonServerSyslog.getCurrentRpcInfo().reset(); info.setIp(getIpAddress(request, config)); response.setContentType(APP_JSON); OutputStream output = response.getOutputStream(); JsonServerSyslog.getCurrentRpcInfo().reset(); if (startupFailed) { writeError(wrap(response), -32603, "The server did not start up properly. Please check the log files for the cause.", output); return; } writeError(wrap(response), -32300, "HTTP GET not allowed.", output); } /** Set up server response headers. * Sets Access-Control-Allow-Origin: * * Sets HTTP_ACCESS_CONTROL_REQUEST_HEADERS to the contents of the * request Access-Control-Allow-Headers, or a minimum of "authorization" * Sets the content type to application/json * @param request the HTTP request * @param response the HTTP response */ public static void setupResponseHeaders(HttpServletRequest request, HttpServletResponse response) { response.setHeader("Access-Control-Allow-Origin", "*"); String allowedHeaders = request.getHeader("HTTP_ACCESS_CONTROL_REQUEST_HEADERS"); response.setHeader("Access-Control-Allow-Headers", allowedHeaders == null ? "authorization" : allowedHeaders); response.setContentType(APP_JSON); } @Override protected void doPost(HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { checkMemoryForRpc(); String remoteIp = getIpAddress(request, config); setupResponseHeaders(request, response); OutputStream output = response.getOutputStream(); ResponseStatusSetter respStatus = new ResponseStatusSetter() { @Override public void setStatus(int status) { response.setStatus(status); } }; JsonServerSyslog.RpcInfo info = JsonServerSyslog.getCurrentRpcInfo().reset(); info.setIp(remoteIp); JsonTokenStream jts = null; File tempFile = null; try { InputStream input = request.getInputStream(); byte[] buffer = new byte[100000]; ByteArrayOutputStream bufferOs = new ByteArrayOutputStream(); long rpcSize = 0; while (rpcSize < maxRpcMemoryCacheSize) { int count = input.read(buffer, 0, Math.min(buffer.length, maxRpcMemoryCacheSize - (int)rpcSize)); if (count < 0) break; bufferOs.write(buffer, 0, count); rpcSize += count; } if (rpcSize >= maxRpcMemoryCacheSize) { OutputStream os; if (rpcDiskCacheTempDir == null) { os = bufferOs; } else { tempFile = generateTempFile(); os = new BufferedOutputStream(new FileOutputStream(tempFile)); bufferOs.close(); os.write(bufferOs.toByteArray()); bufferOs = null; } while (true) { int count = input.read(buffer, 0, buffer.length); if (count < 0) break; os.write(buffer, 0, count); rpcSize += count; if (maxRPCPackageSize != null && rpcSize > maxRPCPackageSize) { writeError(respStatus, -32700, "Object is too big, length is more than " + maxRPCPackageSize + " bytes", output); os.close(); input.close(); return; } } os.close(); if (tempFile == null) { jts = new JsonTokenStream(((ByteArrayOutputStream)os).toByteArray()); bufferOs = null; } else { jts = new JsonTokenStream(tempFile); } } else { bufferOs.close(); jts = new JsonTokenStream(bufferOs.toByteArray()); } bufferOs = null; String token = request.getHeader("Authorization"); String requestHeaderXFF = request.getHeader(X_FORWARDED_FOR); RpcCallData rpcCallData; try { rpcCallData = mapper.readValue(jts, RpcCallData.class); } catch (Exception ex) { writeError(respStatus, -32700, "Parse error (" + ex.getMessage() + ")", ex, output); return; } finally { jts.close(); } Object idNode = rpcCallData.getId(); try { info.setId(idNode == null ? null : "" + idNode); } catch (Exception ex) {} String rpcName = rpcCallData.getMethod(); if (rpcName == null) { writeError(respStatus, -32601, "JSON RPC method property is not defined", output); return; } rpcName = correctRpcMethod(rpcName); List<UObject> paramsList = rpcCallData.getParams(); if (paramsList == null) { writeError(respStatus, -32601, "JSON RPC params property is not defined", output); return; } if (!rpcName.contains(".")) { rpcName = specServiceName + "." + rpcName; rpcCallData.setMethod(rpcName); } RpcContext context = rpcCallData.getContext(); if (context == null) { context = new RpcContext(); rpcCallData.setContext(context); } if (context.getCallStack() == null) context.setCallStack(new ArrayList<MethodCall>()); context.getCallStack().add(new MethodCall().withMethod(rpcName) .withTime(DATE_FORMATTER.print(new DateTime()))); processRpcCall(rpcCallData, token, info, requestHeaderXFF, respStatus, output, false); } catch (Exception ex) { writeError(respStatus, -32400, "Unexpected internal error (" + ex.getMessage() + ")", ex, output); } finally { if (jts != null) { try { jts.close(); } catch (Exception ignore) {} if (tempFile != null) { try { tempFile.delete(); } catch (Exception ignore) {} } } } } protected int processRpcCall(File input, File output, String token) { JsonServerSyslog.RpcInfo info = JsonServerSyslog.getCurrentRpcInfo().reset(); final int[] responseCode = {0}; ResponseStatusSetter response = new ResponseStatusSetter() { @Override public void setStatus(int status) { responseCode[0] = status; } }; OutputStream os = null; try { File tokenFile = new File(token); if (tokenFile.exists()) { BufferedReader br = new BufferedReader(new FileReader(tokenFile)); token = br.readLine(); br.close(); } os = new FileOutputStream(output); RpcCallData rpcCallData = mapper.readValue(input, RpcCallData.class); processRpcCall(rpcCallData, token, info, null, response, os, true); } catch (Throwable ex) { writeError(response, -32400, "Unexpected internal error (" + ex.getMessage() + ")", ex, os); } finally { if (os != null) try { os.close(); } catch (Exception ignore) {} } return responseCode[0]; } protected void processRpcCall(RpcCallData rpcCallData, String token, JsonServerSyslog.RpcInfo info, String requestHeaderXForwardedFor, ResponseStatusSetter response, OutputStream output, boolean commandLine) { RpcContext context = rpcCallData.getContext(); String rpcName = rpcCallData.getMethod(); String[] serviceAndMethod = rpcName.split("\\."); info.setModule(serviceAndMethod[0]); info.setMethod(serviceAndMethod[1]); List<UObject> paramsList = rpcCallData.getParams(); AuthToken userProfile = null; try { Method rpcMethod = rpcCache.get(rpcName); if (rpcMethod == null) { writeError(response, -32601, "Can not find method [" + rpcName + "] in server class " + getClass().getName(), output); return; } String origRpcName = rpcMethod.getAnnotation(JsonServerMethod.class).rpc(); if (origRpcName.equals(rpcName)) { if (!(commandLine || rpcMethod.getAnnotation(JsonServerMethod.class).sync())) { writeError(response, -32601, "Method " + rpcName + " cannot be run synchronously", output); return; } int rpcArgCount = rpcMethod.getGenericParameterTypes().length; Object[] methodValues = new Object[rpcArgCount]; boolean lastParamRpcContext = rpcArgCount > 0 && rpcMethod.getParameterTypes()[rpcArgCount - 1].equals(RpcContext.class); boolean lastParamRpcContextArr = rpcArgCount > 0 && rpcMethod.getParameterTypes()[rpcArgCount - 1].isArray() && rpcMethod.getParameterTypes()[rpcArgCount - 1].getComponentType().equals(RpcContext.class); if (lastParamRpcContext || lastParamRpcContextArr) { if (prepareProvenanceAutomatically()) { try { Class<?> paType = Class.forName("us.kbase.workspace.ProvenanceAction"); Object pa = paType.newInstance(); paType.getMethod("setService", String.class).invoke(pa, info.getModule()); paType.getMethod("setMethod", String.class).invoke(pa, info.getMethod()); paType.getMethod("setMethodParams", List.class).invoke(pa, paramsList); List<Object> provenance = new ArrayList<Object>(); provenance.add(pa); if (context == null) context = new RpcContext(); context.setProvenance(provenance); } catch (ClassNotFoundException ignore) {} } rpcArgCount if (lastParamRpcContext) { methodValues[rpcArgCount] = context; } else { methodValues[rpcArgCount] = new RpcContext[] {context}; } } if (rpcArgCount > 0 && rpcMethod.getParameterTypes()[rpcArgCount - 1].equals(AuthToken.class)) { if (token != null || !rpcMethod.getAnnotation(JsonServerMethod.class).authOptional()) { try { userProfile = validateToken(token); if (userProfile != null) info.setUser(userProfile.getUserName()); } catch (Throwable ex) { writeError(response, -32400, "Token validation failed: " + ex.getMessage(), ex, output); return; } } rpcArgCount methodValues[rpcArgCount] = userProfile; } if (startupFailed) { writeError(response, -32603, "The server did not start up properly. Please check the log files for the cause.", output); return; } if (paramsList.size() != rpcArgCount) { writeError(response, -32602, "Wrong parameter count for method " + rpcName, output); return; } for (int typePos = 0; typePos < paramsList.size(); typePos++) { UObject jsonData = paramsList.get(typePos); Type paramType = rpcMethod.getGenericParameterTypes()[typePos]; PlainTypeRef paramJavaType = new PlainTypeRef(paramType); try { Object obj; if (jsonData == null) { obj = null; } else if (paramType instanceof Class && paramType.equals(UObject.class)) { obj = jsonData; } else { try { obj = mapper.readValue(jsonData.getPlacedStream(), paramJavaType); } finally { if (jsonData.isTokenStream()) ((JsonTokenStream)jsonData.getUserObject()).close(); } } methodValues[typePos] = obj; } catch (Exception ex) { writeError(response, -32602, "Wrong type of parameter " + typePos + " for method " + rpcName + " (" + ex.getMessage() + ")", ex, output); return; } } Object result; try { logHeaders(requestHeaderXForwardedFor); sysLogger.log(LOG_LEVEL_INFO, getClass().getName(), "start method"); result = rpcMethod.invoke(this, methodValues); sysLogger.log(LOG_LEVEL_INFO, getClass().getName(), "end method"); } catch (Throwable ex) { if (ex instanceof InvocationTargetException && ex.getCause() != null) { ex = ex.getCause(); } writeError(response, -32500, ex, output); onRpcMethodDone(); return; } try { boolean notVoid = !rpcMethod.getReturnType().equals(Void.TYPE); boolean isTuple = rpcMethod.getAnnotation(JsonServerMethod.class).tuple(); if (notVoid && !isTuple) { result = Arrays.asList(result); } Map<String, Object> ret = new LinkedHashMap<String, Object>(); ret.put("version", "1.1"); ret.put("result", result); mapper.writeValue(new UnclosableOutputStream(output), ret); output.flush(); } finally { try { onRpcMethodDone(); } catch (Exception ignore) {} } } else { if (token == null) { writeError(response, -32400, "Authentication is required for using job service", output); return; } try { userProfile = validateToken(token); if (userProfile != null) info.setUser(userProfile.getUserName()); } catch (Throwable ex) { writeError(response, -32400, "Token validation failed: " + ex.getMessage(), ex, output); return; } JsonClientCaller jobService = getJobServiceClient(userProfile); List<Object> result = null; if (rpcName.equals(origRpcName + "_async")) { List<Object> runJobParams = new ArrayList<Object>(); Map<String, Object> paramMap = new LinkedHashMap<String, Object>(); runJobParams.add(paramMap); paramMap.put("service_ver", getServiceVersion()); paramMap.put("method", origRpcName); paramMap.put("params", paramsList); paramMap.put("rpc_context", context); TypeReference<List<Object>> retType = new TypeReference<List<Object>>() {}; result = jobService.jsonrpcCall("KBaseJobService.run_job", runJobParams, retType, true, true); } else if (rpcName.equals(origRpcName + "_check")) { TypeReference<List<JobState<UObject>>> retType = new TypeReference<List<JobState<UObject>>>() {}; List<JobState<UObject>> jobStateList = jobService.jsonrpcCall("KBaseJobService.check_job", paramsList, retType, true, true); JobState<UObject> jobState = jobStateList.get(0); Long finished = jobState.getFinished(); if (finished != 0L) { Object error = jobState.getAdditionalProperties().get("error"); if (error != null) { Map<String, Object> ret = new LinkedHashMap<String, Object>(); ret.put("version", "1.1"); ret.put("error", error); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); mapper.writeValue(new UnclosableOutputStream(output), ret); output.flush(); return; } } result = new ArrayList<Object>(); result.add(jobState); } else { writeError(response, -32601, "Can not find method [" + rpcName + "] in server class " + getClass().getName(), output); return; } Map<String, Object> ret = new LinkedHashMap<String, Object>(); ret.put("version", "1.1"); ret.put("result", result); mapper.writeValue(new UnclosableOutputStream(output), ret); output.flush(); } } catch (Exception ex) { writeError(response, -32400, "Unexpected internal error (" + ex.getMessage() + ")", ex, output); } } private AuthToken validateToken(final String token) throws AuthException, IOException { if (token == null || token.isEmpty()) { throw new AuthException( "Authorization is required for this method but no " + "credentials were provided"); } return auth.validateToken(token); } protected void logHeaders(final String xFF) { if (xFF != null && !xFF.isEmpty()) { sysLogger.log(LOG_LEVEL_INFO, getClass().getName(), X_FORWARDED_FOR + ": " + xFF); } } /** Get the IP address of the client. In order of precedence: * 1. The first address in X-Forwarded-For * 2. X-Real-IP * 3. The remote address. * If dont_trust_x_ip_headers or dont-trust-x-ip-headers is set to "true" * in the configuration, the remote address is returned. * @param request the HTTP request * @param config the server configuration as returned by getConfig(). * @return the IP address of the client. */ public static String getIpAddress( final HttpServletRequest request, final Map<String, String> config) { final String xFF = request.getHeader(X_FORWARDED_FOR); final String realIP = request.getHeader(X_REAL_IP); final boolean trustXHeaders = !STRING_TRUE.equals(config.get(DONT_TRUST_X_IP_HEADERS)) && !STRING_TRUE.equals(config.get(DONT_TRUST_X_IP_HEADERS2)); if (trustXHeaders) { if (xFF != null && !xFF.isEmpty()) { return xFF.split(",")[0].trim(); } if (realIP != null && !realIP.isEmpty()) { return realIP.trim(); } } return request.getRemoteAddr(); } protected String correctRpcMethod(String methodWithModule) { // Do nothing. Inherited classes can use for method/module name correction. return methodWithModule; } protected void checkMemoryForRpc() { // Do nothing. Inherited classes could define proper implementation. } protected void onRpcMethodDone() { // Do nothing. Inherited classes could define proper implementation. } protected File generateTempFile() { File tempFile = null; long suffix = System.currentTimeMillis(); while (true) { tempFile = new File(rpcDiskCacheTempDir, "rpc" + suffix + ".json"); if (!tempFile.exists()) break; suffix++; } return tempFile; } protected Long getMaxRPCPackageSize() { return this.maxRPCPackageSize; } protected void setMaxRPCPackageSize(Long maxRPCPackageSize) { this.maxRPCPackageSize = maxRPCPackageSize; } protected void writeError(ResponseStatusSetter response, int code, String message, OutputStream output) { writeError(response, code, message, null, output); } protected void writeError(ResponseStatusSetter response, int code, Throwable ex, OutputStream output) { writeError(response, code, ex.getMessage(), ex, output); } protected void writeError(ResponseStatusSetter response, int code, String message, Throwable ex, OutputStream output) { //new Exception(message, ex).printStackTrace(); String data = null; if (ex != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); pw.close(); data = sw.toString(); sysLogger.logErr(ex, getClass().getName()); } else { sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), message); } response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ObjectNode ret = mapper.createObjectNode(); ObjectNode error = mapper.createObjectNode(); error.put("name", "JSONRPCError"); error.put("code", code); error.put("message", message); error.put("error", data); ret.put("version", "1.1"); ret.put("error", error); String id = JsonServerSyslog.getCurrentRpcInfo().getId(); if (id != null) ret.put("id", id); try { ByteArrayOutputStream bais = new ByteArrayOutputStream(); mapper.writeValue(bais, ret); bais.close(); //String logMessage = new String(bytes); //sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), logMessage); output.write(bais.toByteArray()); output.flush(); } catch (Exception e) { System.err.println( "Unable to write error to output - current exception:"); e.printStackTrace(); System.err.println("original exception:"); ex.printStackTrace(); } } public int getMaxRpcMemoryCacheSize() { return maxRpcMemoryCacheSize; } public void setMaxRpcMemoryCacheSize(int maxRpcMemoryCacheSize) { this.maxRpcMemoryCacheSize = maxRpcMemoryCacheSize; } public File getRpcDiskCacheTempDir() { return rpcDiskCacheTempDir; } public void setRpcDiskCacheTempDir(File rpcDiskCacheTempDir) { this.rpcDiskCacheTempDir = rpcDiskCacheTempDir; } protected ResponseStatusSetter wrap(final HttpServletResponse response) { return new ResponseStatusSetter() { @Override public void setStatus(int status) { response.setStatus(status); } }; } protected JsonClientCaller getJobServiceClient(AuthToken token) throws Exception { String url = System.getProperty(KB_JOB_SERVICE_URL); if (url == null) url = System.getenv(KB_JOB_SERVICE_URL); if (url == null) url = config.get(CONFIG_JOB_SERVICE_URL_PARAM); if (url == null) throw new IllegalStateException("Neither '" + CONFIG_JOB_SERVICE_URL_PARAM + "' " + "parameter is defined in configuration nor '" + KB_JOB_SERVICE_URL + "' " + "variable is defined in system"); JsonClientCaller ret = new JsonClientCaller(new URL(url), token); ret.setInsecureHttpConnectionAllowed(true); return ret; } public String getServiceVersion() { return serviceVersion; } public void setServiceVersion(String serviceVersion) { this.serviceVersion = serviceVersion; } protected boolean prepareProvenanceAutomatically() { return true; } public static class RpcCallData { private Object id; private String method; private List<UObject> params; private Object version; private RpcContext context; public Object getId() { return id; } public void setId(Object id) { this.id = id; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public List<UObject> getParams() { return params; } public void setParams(List<UObject> params) { this.params = params; } public Object getVersion() { return version; } public void setVersion(Object version) { this.version = version; } public RpcContext getContext() { return context; } public void setContext(RpcContext context) { this.context = context; } } protected static class PlainTypeRef extends TypeReference<Object> { Type type; PlainTypeRef(Type type) { this.type = type; } @Override public Type getType() { return type; } } protected static class UnclosableOutputStream extends OutputStream { OutputStream inner; boolean isClosed = false; public UnclosableOutputStream(OutputStream inner) { this.inner = inner; } @Override public void write(int b) throws IOException { if (isClosed) return; inner.write(b); } @Override public void close() throws IOException { isClosed = true; } @Override public void flush() throws IOException { inner.flush(); } @Override public void write(byte[] b) throws IOException { if (isClosed) return; inner.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { if (isClosed) return; inner.write(b, off, len); } } public static interface ResponseStatusSetter { public void setStatus(int status); } }
package dr.evomodel.operators; import dr.evolution.tree.NodeRef; import dr.evomodel.tree.TreeModel; import dr.inference.operators.MCMCOperator; import dr.inference.operators.OperatorFailedException; import dr.inference.operators.SimpleMCMCOperator; import dr.math.MathUtils; import dr.xml.*; import java.util.ArrayList; import java.util.List; /** * A generic operator swaps a randomly selected rate change from parent to offspring or vice versa. * * @author Alexei Drummond * @version $Id$ */ public class TreeBitMoveOperator extends SimpleMCMCOperator { public static final String BIT_MOVE_OPERATOR = "treeBitMoveOperator"; public TreeBitMoveOperator(TreeModel tree, double weight) { this.tree = tree; setWeight(weight); } /** * Pick a parent-child node pair involving a single rate change and swap the rate change location * and corresponding rate parameters. */ public final double doOperation() throws OperatorFailedException { NodeRef root = tree.getRoot(); // 1. collect nodes that form a pair with parent such that // one of them has a one and one has a zero List<NodeRef> candidates = new ArrayList<NodeRef>(); for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); if (node != root && tree.getParent(node) != root) { NodeRef parent = tree.getParent(node); int sum = rateChange(tree, node) + rateChange(tree, parent); if (sum == 1) candidates.add(node); } } if (candidates.size() == 0) throw new OperatorFailedException("No suitable pairs!"); NodeRef node = candidates.get(MathUtils.nextInt(candidates.size())); NodeRef parent = tree.getParent(node); double nodeRate = tree.getNodeRate(node); double parentRate = tree.getNodeRate(parent); double nodeTrait = tree.getNodeTrait(node, "trait"); double parentTrait = tree.getNodeTrait(parent, "trait"); tree.setNodeRate(node, parentRate); tree.setNodeRate(parent, nodeRate); tree.setNodeTrait(node, "trait", parentTrait); tree.setNodeTrait(parent, "trait", nodeTrait); return 0.0; } public final int rateChange(TreeModel tree, NodeRef node) { return (int) Math.round(tree.getNodeTrait(node, "trait")); } // Interface MCMCOperator public final String getOperatorName() { return "treeBitMove()"; } public final String getPerformanceSuggestion() { return "no performance suggestion"; } public String toString() { return getOperatorName(); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return BIT_MOVE_OPERATOR; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { double weight = xo.getDoubleAttribute(WEIGHT); TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); return new TreeBitMoveOperator(treeModel, weight); }
package edu.rpi.cct.misc.indexing; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Store; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Searcher; import org.apache.lucene.store.Directory; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.log4j.Logger; /** This class implements indexing using Lucene. * There is an abstract method to create a Lucene Document from an object. * Also an abstract method to create the Key object. */ public abstract class IndexLuceneImpl implements Index { private boolean debug; private boolean writeable; private String basePath; private String defaultFieldName; /** We append this to basePath to reach the indexes. */ private final static String indexDir = "/indexes"; private boolean updatedIndex; private boolean isOpen; private boolean cleanLocks; private transient Logger log; /** We try to keep readers and writers open if batchMode is true. */ //private boolean batchMode; IndexReader rdr; IndexWriter wtr; Searcher sch; Analyzer defaultAnalyzer; QueryParser queryParser; Hits lastResult; private String[] stopWords; /** Simple representation of field options */ public static class FieldInfo { /** lucene name for field. */ String name; /** Do w store it? */ boolean store; /** Do we tokenize it? */ boolean tokenized; /** boost value for this field */ float boost; /* Initialised in constructor from store. */ Store howStore; /* Initialised in constructor from tokenized. */ Field.Index howIndexed; /** Constructor for unstored, unboosted field * * @param name * @param tokenized */ public FieldInfo(String name, boolean tokenized) { this(name, false, tokenized, 1); } /** Constructor for unstored field * * @param name * @param tokenized * @param boost */ public FieldInfo(String name, boolean tokenized, float boost) { this(name, false, tokenized, boost); } /** Constructor allowing full specification * * @param name * @param store * @param tokenized * @param boost */ public FieldInfo(String name, boolean store, boolean tokenized, float boost) { this.name = name; this.store = store; this.tokenized = tokenized; this.boost = boost; if (store) { howStore = Store.YES; } else { howStore = Store.NO; } if (tokenized) { howIndexed = Field.Index.TOKENIZED; } else { howIndexed = Field.Index.UN_TOKENIZED; } } Field makeField(String val) { Field f = new Field(name, val, howStore, howIndexed); f.setBoost(boost); return f; } /** * @return String field name */ public String getName() { return name; } } /** Create an indexer with the default set of stop words. * * @param basePath String path to where we should read/write indexes * @param defaultFieldName default name for searches * @param writeable true if the caller can update the index * @param debug true if we want to see what's going on * @throws IndexException */ public IndexLuceneImpl(String basePath, String defaultFieldName, boolean writeable, boolean debug) throws IndexException { this(basePath, defaultFieldName, writeable, null, debug); } /** Create an indexer with the given set of stop words. * * @param basePath String path to where we should read/write indexes * @param defaultFieldName default name for searches * @param writeable true if the caller can update the index * @param stopWords set of stop words, null for default. * @param debug true if we want to see what's going on * @throws IndexException */ public IndexLuceneImpl(String basePath, String defaultFieldName, boolean writeable, String[] stopWords, boolean debug) throws IndexException { setDebug(debug); this.writeable = writeable; this.basePath = basePath; this.defaultFieldName = defaultFieldName; this.stopWords = stopWords; } /** * @return boolean debugging flag */ public boolean getDebug() { return debug; } /** Indicate if we shoudkl try to clean locks. * * @param val */ public void setCleanLocks(boolean val) { cleanLocks = val; } /** String appended to basePath * @return String */ public static String getPathSuffix() { return indexDir; } /** Called to make or fill in a Key object. * * @param key Possible Index.Key object for reuse * @param doc The retrieved Document * @param score The rating for this entry * @return Index.Key new or reused object * @throws IndexException */ public abstract Index.Key makeKey(Index.Key key, Document doc, float score) throws IndexException; /** Called to make a key term for a record. * * @param rec The record * @return Term Lucene term which uniquely identifies the record * @throws IndexException */ public abstract Term makeKeyTerm(Object rec) throws IndexException; /** Called to make the primary key name for a record. * * @param rec The record * @return String Name for the field/term * @throws IndexException */ public abstract String makeKeyName(Object rec) throws IndexException; /** Called to fill in a Document from an object. * * @param doc The =Document * @param rec The record * @throws IndexException */ public abstract void addFields(Document doc, Object rec) throws IndexException; /** Called to return an array of valid term names. * * @return String[] term names */ public abstract String[] getTermNames(); public void setDebug(boolean val) { debug = val; } /** This can be called to open the index in the appropriate manner * probably determined by information passed to the constructor. * * <p>For a first time call a new analyzer will be created. */ public void open() throws IndexException { close(); if (defaultAnalyzer == null) { if (stopWords == null) { defaultAnalyzer = new StandardAnalyzer(); } else { defaultAnalyzer = new StandardAnalyzer(stopWords); } queryParser = new QueryParser(defaultFieldName, defaultAnalyzer); } updatedIndex = false; isOpen = true; } /** This can be called to (re)create the index. It will destroy any * previously existing index. */ public void create() throws IndexException { try { if (!writeable) { throw new IndexException(IndexException.noIdxCreateAccess); } close(); if (basePath == null) { throw new IndexException(IndexException.noBasePath); } IndexWriter iw = new IndexWriter(basePath + indexDir, defaultAnalyzer, true); iw.optimize(); iw.close(); iw = null; open(); } catch (IOException e) { throw new IndexException(e); } catch (Throwable t) { throw new IndexException(t); } } /** See if we need to call open */ public boolean getIsOpen() { return isOpen; } /** This gives a single keyword to identify the implementation. * * @return String An identifying key. */ public String id() { return "LUCENE"; } /** This can be called to obtain some information about the index * implementation. id gives a single keyword whereas this gives a more * detailed description. * * @return String A descrptive string. */ public String info() { return "An implementation of an indexer using jakarta Lucene."; } /** Called to index a record * * @param rec The record to index */ public void indexRec(Object rec) throws IndexException { unindexRec(rec); intIndexRec(rec); closeWtr(); } /** Called to unindex a record * * @param rec The record to unindex */ public void unindexRec(Object rec) throws IndexException { try { checkOpen(); closeWtr(); intUnindexRec(rec); } catch (IndexException ie) { if (ie.getCause() instanceof FileNotFoundException) { // Assume not indexed yet throw new IndexException(IndexException.noFiles); } else { throw ie; } } finally { closeWtr(); // Just in case closeRdr(); } } /** Called to (re)index a batch of records * * @param recs The records to index */ public void indexRecs(Object[] recs) throws IndexException { if (recs == null) { return; } try { unindexRecs(recs); for (int i = 0; i < recs.length; i++) { if (recs[i] != null) { intIndexRec(recs[i]); } } } finally { closeWtr(); closeRdr(); // Just in case } } /** Called to index a batch of new records. More efficient way of * rebuilding the index. * * @param recs The records to index */ public void indexNewRecs(Object[] recs) throws IndexException { if (recs == null) { return; } try { closeRdr(); // Just in case for (int i = 0; i < recs.length; i++) { if (recs[i] != null) { intIndexRec(recs[i]); } } } finally { closeWtr(); } } /** Called to unindex a batch of records * * @param recs The records to unindex */ public void unindexRecs(Object[] recs) throws IndexException { if (recs == null) { return; } try { checkOpen(); closeWtr(); for (int i = 0; i < recs.length; i++) { if (recs[i] != null) { intUnindexRec(recs[i]); } } } finally { closeWtr(); // Just in case closeRdr(); } } /** Called to find entries that match the search string. This string may * be a simple sequence of keywords or some sort of query the syntax of * which is determined by the underlying implementation. * * @param query Query string * @return int Number found. 0 means none found, * -1 means indeterminate */ public int search(String query) throws IndexException { return search(query, null); } /** Called to find entries that match the search string. This string may * be a simple sequence of keywords or some sort of query the syntax of * which is determined by the underlying implementation. * * @param query Query string * @param filter Filter tro apply or null * @return int Number found. 0 means none found, * -1 means indeterminate * @throws IndexException */ public int search(String query, Filter filter) throws IndexException { checkOpen(); try { if (debug) { trace("About to search for " + query); } Query parsed = queryParser.parse(query); if (debug) { trace(" with parsed query " + parsed.toString(null)); } if (sch == null) { sch = new IndexSearcher(getRdr()); } lastResult = sch.search(parsed); if (debug) { trace(" found " + lastResult.length()); } return lastResult.length(); } catch (ParseException pe) { throw new IndexException(pe); } catch (IOException e) { throw new IndexException(e); } catch (Throwable t) { throw new IndexException(t); } } /** Called to retrieve record keys from the result. * * @param n Starting index * @param keys Array for the record keys * @return int Actual number of records */ public int retrieve(int n, Index.Key[] keys) throws IndexException { checkOpen(); if ((lastResult == null) || (keys == null) || (n >= lastResult.length())) { return 0; } int i; for (i = 0; i < keys.length; i++) { int hi = i + n; if (hi >= lastResult.length()) { break; } try { keys[i] = makeKey(keys[i], lastResult.doc(hi), lastResult.score(hi)); } catch (IOException e) { throw new IndexException(e); } catch (Throwable t) { throw new IndexException(t); } } return i; } /** Called if we intend to run a batch of updates. endBatch MUST be * called or manual intervention may be required to remove locks. */ public void startBatch() throws IndexException { //batchMode = true; } /** Called at the end of a batch of updates. */ public void endBatch() throws IndexException { //batchMode = false; close(); } /** Called to close at the end of a session. */ public synchronized void close() throws IndexException { closeWtr(); closeRdr(); isOpen = false; } /** Called if we need to close the writer * * @throws IndexException */ public synchronized void closeWtr() throws IndexException { try { if (wtr != null) { if (updatedIndex) { wtr.optimize(); updatedIndex = false; } wtr.close(); wtr = null; } } catch (IOException e) { throw new IndexException(e); } catch (Throwable t) { throw new IndexException(t); } } /** Called if we need to close the reader * * @throws IndexException */ public synchronized void closeRdr() throws IndexException { try { if (sch != null) { try { sch.close(); } catch (Exception e) {} sch = null; } if (rdr != null) { rdr.close(); rdr = null; } } catch (IOException e) { throw new IndexException(e); } catch (Throwable t) { throw new IndexException(t); } } /** Called to provide some debugging dump info. */ public void dump() { } /** Called to provide some statistics. */ public void stats() { } /** Ensure we're open * * @throws IndexException */ private void checkOpen() throws IndexException { if (isOpen) { return; } open(); } /* Called to obtain the current or a new writer. * * @return IndexWriter writer to our index */ private IndexWriter getWtr() throws IndexException { if (!writeable) { throw new IndexException(IndexException.noAccess); } String dirPath = basePath + indexDir; try { if (wtr == null) { wtr = new IndexWriter(dirPath, defaultAnalyzer, false); } return wtr; } catch (IOException e) { if (e instanceof FileNotFoundException) { // Assume not indexed yet throw new IndexException(IndexException.noFiles); } if (!cleanLocks) { error(e); throw new IndexException(e); } info("Had exception: " + e.getMessage()); info("Will try to clean lock"); try { // There should really be a lucene exception for this one if (IndexReader.isLocked(dirPath)) { Directory d = getRdr().directory(); IndexReader.unlock(d); } wtr = new IndexWriter(dirPath, defaultAnalyzer, false); info("Clean lock succeeded"); return wtr; } catch (Throwable t) { info("Clean lock failed"); throw new IndexException(t); } } catch (Throwable t) { throw new IndexException(t); } } /* Called to obtain the current or a new reader. * * @return IndexReader reader of our index */ private IndexReader getRdr() throws IndexException { if (basePath == null) { throw new IndexException(IndexException.noBasePath); } try { if (rdr == null) { rdr = IndexReader.open(basePath + indexDir); } return rdr; } catch (IOException e) { throw new IndexException(e); } catch (Throwable t) { throw new IndexException(t); } } /* Called to unindex a record. The reader will be left * open. The writer must be closed and will stay closed. * * @param rec The record to unindex */ private boolean intUnindexRec(Object rec) throws IndexException { try { Term t = makeKeyTerm(rec); int numDeleted = getRdr().deleteDocuments(t); if (numDeleted > 1) { throw new IndexException(IndexException.dupKey, t.toString()); } if (debug) { trace("removed " + numDeleted + " entries for " + t); } updatedIndex = true; return true; } catch (IndexException ie) { if (ie.getCause() instanceof FileNotFoundException) { // ignore return false; } throw ie; } catch (IOException e) { throw new IndexException(e); } catch (Throwable t) { throw new IndexException(t); } } /* Called to index a record. The writer will be left open and the reader * must be closed on entry and will stay closed. * * @param rec The record to index */ private void intIndexRec(Object rec) throws IndexException { Document doc = new Document(); addFields(doc, rec); try { closeRdr(); getWtr().addDocument(doc); updatedIndex = true; } catch (IndexException ie) { throw ie; } catch (IOException e) { throw new IndexException(e); } catch (Throwable t) { throw new IndexException(t); } } /** Called to add an array of objects to a document * * @param doc Document object * @param fld Field info * @param os Object array * @throws IndexException */ protected void addField(Document doc, FieldInfo fld, Object[] os) throws IndexException { if (os == null) { return; } for (Object o: os) { if (o != null) { doc.add(fld.makeField(String.valueOf(o))); } } } /** Called to add a String val to a document * * @param doc The document * @param fld Field info * @param val The value * @throws IndexException */ protected void addField(Document doc, FieldInfo fld, Object val) throws IndexException { if (val == null) { return; } doc.add(fld.makeField(String.valueOf(val))); } protected Logger getLog() { if (log == null) { log = Logger.getLogger(this.getClass()); } return log; } protected void error(Throwable e) { getLog().error(this, e); } protected void error(String msg) { getLog().error(msg); } protected void info(String msg) { getLog().info(msg); } protected void trace(String msg) { getLog().debug(msg); } }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.smartdashboard.*; import edu.wpi.first.wpilibj.DriverStationEnhancedIO; public class RobotMain extends SimpleRobot { Compressor compressor = new Compressor(1, 1); RobotDrive chassis; Joystick leftStick = new Joystick(1); Joystick rightStick = new Joystick(2); AxisCamera camera; Servo servoTest; DriverStation driverStation; Talon fl; Talon bl; Talon fr; Talon br; public RobotMain() { } public void robotInit() { driverStation = DriverStation.getInstance(); servoTest = new Servo(5); fl = new Talon(1); bl = new Talon(2); br = new Talon(3); fr = new Talon(4); compressor.start(); chassis = new RobotDrive(fl, bl, fr, br); chassis.setInvertedMotor(RobotDrive.MotorType.kFrontRight, true); chassis.setInvertedMotor(RobotDrive.MotorType.kRearRight, true); // camera = AxisCamera.getInstance(); } public void autonomous() { } public void operatorControl() { chassis.setSafetyEnabled(false); SmartDashboard.putString("Alliance", driverStation.getAlliance().name); while (this.isOperatorControl() && this.isEnabled()) { SmartDashboard.putNumber("Mecanum X", getMecX()); SmartDashboard.putNumber("Mecanum Y", getMecY()); SmartDashboard.putNumber("Mecanum Rotation", getMecRot()); SmartDashboard.putNumber("Front Left", fl.getSpeed()); SmartDashboard.putNumber("Front Right", fr.getSpeed()); SmartDashboard.putNumber("Back Left", bl.getSpeed()); SmartDashboard.putNumber("Back Right", br.getSpeed()); //System.out.println("Axies: "+getMecX()+", "+getMecY()+", "+getMecRot()); //System.out.println("Drive: fl:"+fl.getSpeed()+" bl:"+bl.getSpeed()+" fr:"+fr.getSpeed()+" br:"+br.getSpeed()); mecanumDrive(getMecX(), getMecY(), getMecRot()); //chassis.mecanumDrive_Cartesian(getMecX(), getMecY(), getMecRot(), 0); if (rightStick.getRawButton(3)) { servoTest.setAngle(-360); } else if (rightStick.getRawButton(2)) { //down servoTest.setAngle(360); } Timer.delay(.01); } } public void disabled() { } public void test() { } private double getMecX() { return deadZone(rightStick.getAxis(Joystick.AxisType.kX)); } private double getMecY() { return deadZone(rightStick.getAxis(Joystick.AxisType.kY)); } private double getMecRot() { return deadZone(leftStick.getAxis(Joystick.AxisType.kX)); } private double deadZone(double value) { return (abs(value) < .1) ? 0 : value; } private double abs(double value) { return value < 0 ? -value : value; } private void mecanumDrive(double x, double y, double r) { y = -y; double frn = 0; double fln = 0; double brn = 0; double bln = 0; frn *= 1; fln *= 1; brn *= 1; bln *= 1; fln = y + x + r; frn = y - x - r; bln = y - x + r; brn = y + x - r; fr.set(-maxAt1(frn)); fl.set(maxAt1(fln)); br.set(-maxAt1(brn)); bl.set(maxAt1(bln)); } private double maxAt1(double n) { return n < -1 ? -1 : (n > 1 ? 1 : n); } }
package nars.inference; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Objects; import nars.core.Memory; import nars.core.Parameters; import nars.entity.BudgetValue; import nars.entity.Concept; import nars.entity.Sentence; import nars.entity.Stamp; import nars.entity.Task; import nars.entity.TaskLink; import nars.entity.TermLink; import nars.entity.TruthValue; import nars.io.Symbols; import nars.language.CompoundTerm; import nars.language.Conjunction; import nars.language.Equivalence; import nars.language.Implication; import nars.language.Inheritance; import nars.language.Interval; import nars.language.Product; import nars.language.Similarity; import nars.language.Statement; import nars.language.Term; import nars.language.Terms; import nars.language.Variable; import nars.language.Variables; import nars.operator.Operation; /** * * @author peiwang */ public class TemporalRules { public static final int ORDER_NONE = 2; public static final int ORDER_FORWARD = 1; public static final int ORDER_CONCURRENT = 0; public static final int ORDER_BACKWARD = -1; public static final int ORDER_INVALID = -2; public final static int reverseOrder(final int order) { if (order == ORDER_NONE) { return ORDER_NONE; } else { return -order; } } public final static boolean matchingOrder(final Sentence a, final Sentence b) { return matchingOrder(a.getTemporalOrder(), b.getTemporalOrder()); } public final static boolean matchingOrder(final int order1, final int order2) { return (order1 == order2) || (order1 == ORDER_NONE) || (order2 == ORDER_NONE); } public final static int dedExeOrder(final int order1, final int order2) { int order = ORDER_INVALID; if ((order1 == order2) || (order2 == TemporalRules.ORDER_NONE)) { order = order1; } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = order2; } else if (order2 == TemporalRules.ORDER_CONCURRENT) { order = order1; } return order; } public final static int abdIndComOrder(final int order1, final int order2) { int order = ORDER_INVALID; if (order2 == TemporalRules.ORDER_NONE) { order = order1; } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = reverseOrder(order2); } else if ((order2 == TemporalRules.ORDER_CONCURRENT) || (order1 == -order2)) { order = order1; } return order; } public final static int analogyOrder(final int order1, final int order2, final int figure) { int order = ORDER_INVALID; if ((order2 == TemporalRules.ORDER_NONE) || (order2 == TemporalRules.ORDER_CONCURRENT)) { order = order1; } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = (figure < 20) ? order2 : reverseOrder(order2); } else if (order1 == order2) { if ((figure == 12) || (figure == 21)) { order = order1; } } else if ((order1 == -order2)) { if ((figure == 11) || (figure == 22)) { order = order1; } } return order; } public static final int resemblanceOrder(final int order1, final int order2, final int figure) { int order = ORDER_INVALID; int order1Reverse = reverseOrder(order1); if ((order2 == TemporalRules.ORDER_NONE)) { order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12 } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = (figure % 10 == 1) ? order2 : reverseOrder(order2); // switch when 12 or 22 } else if (order2 == TemporalRules.ORDER_CONCURRENT) { order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12 } else if (order1 == order2) { order = (figure == 21) ? order1 : -order1; } return order; } public static final int composeOrder(final int order1, final int order2) { int order = ORDER_INVALID; if (order2 == TemporalRules.ORDER_NONE) { order = order1; } else if (order1 == TemporalRules.ORDER_NONE) { order = order2; } else if (order1 == order2) { order = order1; } return order; } /** whether temporal induction can generate a task by avoiding producing wrong terms; only one temporal operator is allowed */ public final static boolean tooMuchTemporalStatements(final Term t) { return (t == null) || (t.containedTemporalRelations() > 1); } // { A =/> B, B =/> C } |- (&/,A,B) =/> C // { A =/> B, (&/,B,...) =/> C } |- (&/,A,B,...) =/> C public static boolean temporalInductionChain(final Sentence s1, final Sentence s2, final nars.core.control.NAL nal) { //prevent trying question sentences, causes NPE if ((s1.truth == null) || (s2.truth == null)) return false; //try if B1 unifies with B2, if yes, create new judgement Implication S1=(Implication) s1.term; Implication S2=(Implication) s2.term; Term A=S1.getSubject(); Term B1=S1.getPredicate(); Term B2=S2.getSubject(); Term C=S2.getPredicate(); ArrayList<Term> args=null; int beginoffset=0; if(B2 instanceof Conjunction) { Conjunction CB2=((Conjunction)B2); if(CB2.getTemporalOrder()==TemporalRules.ORDER_FORWARD) { if(A instanceof Conjunction && ((Conjunction)A).getTemporalOrder()==TemporalRules.ORDER_FORWARD) { Conjunction ConjA=(Conjunction) A; args=new ArrayList(CB2.term.length+ConjA.term.length); beginoffset=ConjA.size(); for(final Term t: ConjA.term) args.add(t); } else { args = new ArrayList(CB2.term.length + 1); args.add(A); beginoffset=1; } for (final Term t : CB2.term) args.add(t); } } else { args=Lists.newArrayList(A, B1); } if(args==null) return false; //ok we have our B2, no matter if packed as first argument of &/ or directly, lets see if it unifies Term[] term = args.toArray(new Term[args.size()]); Term realB2 = term[beginoffset]; HashMap<Term, Term> res1 = new HashMap<>(); HashMap<Term, Term> res2 = new HashMap<>(); if(Variables.findSubstitute(Symbols.VAR_INDEPENDENT, B1, realB2, res1,res2)) { //ok it unifies, so lets create a &/ term for(int i=0;i<term.length;i++) { if(term[i] instanceof CompoundTerm) { term[i]=((CompoundTerm) term[i]).applySubstitute(res1); if(term[i]==null) { //it resulted in invalid term for example <a --> a>, so wrong return false; } } } int order1=s1.getTemporalOrder(); int order2=s2.getTemporalOrder(); Term S = Conjunction.make(term,order1); //check if term has a element which is equal to C for(Term t : term) { if(Terms.equalSubTermsInRespectToImageAndProduct(t, C)) { return false; } for(Term u : term) { if(u!=t) { //important: checking reference here is as it should be! if(Terms.equalSubTermsInRespectToImageAndProduct(t, u)) { return false; } } } } Implication whole=Implication.make(S, C,order2); if(whole!=null) { TruthValue truth = TruthFunctions.deduction(s1.truth, s2.truth); BudgetValue budget = BudgetFunctions.forward(truth, nal); budget.setPriority((float) Math.min(0.99, budget.getPriority())); return nal.doublePremiseTask(whole, truth, budget, true)!=null; } } return false; } /** whether a term can be used in temoralInduction(,,) */ protected static boolean termForTemporalInduction(final Term t) { return (t instanceof Inheritance) || (t instanceof Similarity); } public static void applyExpectationOffset(Memory memory, Term temporalStatement, Stamp stamp) { if(temporalStatement!=null && temporalStatement instanceof Implication) { Implication imp=(Implication) temporalStatement; if(imp.getSubject() instanceof Conjunction && imp.getTemporalOrder()==TemporalRules.ORDER_FORWARD) { Conjunction conj=(Conjunction) imp.getSubject(); if(conj.term[conj.term.length-1] instanceof Interval) { Interval intv=(Interval) conj.term[conj.term.length-1]; long time_offset=intv.getTime(memory); stamp.setOccurrenceTime(stamp.getOccurrenceTime()+time_offset); } } } } public static List<Task> temporalInduction(final Sentence s1, final Sentence s2, final nars.core.control.NAL nal) { if ((s1.truth==null) || (s2.truth==null)) return Collections.EMPTY_LIST; Term t1 = s1.term; Term t2 = s2.term; if (Statement.invalidStatement(t1, t2)) return Collections.EMPTY_LIST; Term t11=null; Term t22=null; //if(t1 instanceof Operation && t2 instanceof Operation) { // return; //maybe too restrictive /*if(((t1 instanceof Implication || t1 instanceof Equivalence) && t1.getTemporalOrder()!=TemporalRules.ORDER_NONE) || ((t2 instanceof Implication || t2 instanceof Equivalence) && t2.getTemporalOrder()!=TemporalRules.ORDER_NONE)) { return; //better, if this is fullfilled, there would be more than one temporal operator in the statement, return }*/ //since induction shouldnt miss something trivial random is not good here ///ex: *Memory.randomNumber.nextDouble()>0.5 &&*/ if (termForTemporalInduction(t1) && termForTemporalInduction(t2)) { Statement ss1 = (Statement) t1; Statement ss2 = (Statement) t2; Variable var1 = new Variable("$0"); Variable var2 = var1; if (ss1.getSubject().equals(ss2.getSubject())) { t11 = Statement.make(ss1, var1, ss1.getPredicate()); t22 = Statement.make(ss2, var2, ss2.getPredicate()); } else if (ss1.getPredicate().equals(ss2.getPredicate())) { t11 = Statement.make(ss1, ss1.getSubject(), var1); t22 = Statement.make(ss2, ss2.getSubject(), var2); } //allow also temporal induction on operator arguments: if(ss2 instanceof Operation ^ ss1 instanceof Operation) { if(ss2 instanceof Operation && !(ss2.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term Term comp=ss1.getSubject(); Term ss2_term = ((Operation)ss2).getSubject(); boolean applicableVariableType = !(comp instanceof Variable && ((Variable)comp).hasVarIndep()); if(ss2_term instanceof Product) { Product ss2_prod=(Product) ss2_term; if(applicableVariableType && Terms.contains(ss2_prod.term, comp)) { //only if there is one and it isnt a variable already Term[] ars = ss2_prod.cloneTermsReplacing(comp, var1); t11 = Statement.make(ss1, var1, ss1.getPredicate()); Operation op=(Operation) Operation.make( new Product(ars), ss2.getPredicate() ); t22 = op; } } } if(ss1 instanceof Operation && !(ss1.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term Term comp=ss2.getSubject(); Term ss1_term = ((Operation)ss1).getSubject(); boolean applicableVariableType = !(comp instanceof Variable && ((Variable)comp).hasVarIndep()); if(ss1_term instanceof Product) { Product ss1_prod=(Product) ss1_term; if(applicableVariableType && Terms.contains(ss1_prod.term, comp)) { //only if there is one and it isnt a variable already Term[] ars = ss1_prod.cloneTermsReplacing(comp, var1); t22 = Statement.make(ss2, var1, ss2.getPredicate()); Operation op=(Operation) Operation.make( new Product(ars), ss1.getPredicate() ); t11 = op; } } } } } final Interval.AtomicDuration duration = nal.memory.param.duration; int durationCycles = duration.get(); long time1 = s1.getOccurenceTime(); long time2 = s2.getOccurenceTime(); long timeDiff = time2 - time1; List<Interval> interval; if (!concurrent(time1, time2, durationCycles)) { interval = Interval.intervalTimeSequence(Math.abs(timeDiff), Parameters.TEMPORAL_INTERVAL_PRECISION, nal.mem()); long st=interval.get(0).getTime(nal.memory); if (timeDiff > 0) { t1 = Conjunction.make(t1, interval, ORDER_CONCURRENT); if(t11!=null) { t11 = Conjunction.make(t11, interval, ORDER_CONCURRENT); } } else { t2 = Conjunction.make(t2, interval, ORDER_CONCURRENT); if(t22!=null) { t22 = Conjunction.make(t22, interval, ORDER_CONCURRENT); } } } int order = order(timeDiff, durationCycles); TruthValue givenTruth1 = s1.truth; TruthValue givenTruth2 = s2.truth; TruthValue truth1 = TruthFunctions.induction(givenTruth1, givenTruth2); TruthValue truth2 = TruthFunctions.induction(givenTruth2, givenTruth1); TruthValue truth3 = TruthFunctions.comparison(givenTruth1, givenTruth2); BudgetValue budget1 = BudgetFunctions.forward(truth1, nal); BudgetValue budget2 = BudgetFunctions.forward(truth2, nal); BudgetValue budget3 = BudgetFunctions.forward(truth3, nal); Statement statement1 = Implication.make(t1, t2, order); Statement statement2 = Implication.make(t2, t1, reverseOrder(order)); Statement statement3 = Equivalence.make(t1, t2, order); List<Task> success=new ArrayList<Task>(); if(t11!=null && t22!=null) { Statement statement11 = Implication.make(t11, t22, order); Statement statement22 = Implication.make(t22, t11, reverseOrder(order)); Statement statement33 = Equivalence.make(t11, t22, order); if(!tooMuchTemporalStatements(statement11)) { Task t=nal.doublePremiseTask(statement11, truth1, budget1,true); if(t!=null) { success.add(t); } } if(!tooMuchTemporalStatements(statement22)) { Task t=nal.doublePremiseTask(statement22, truth2, budget2,true); if(t!=null) { success.add(t); } } if(!tooMuchTemporalStatements(statement33)) { Task t=nal.doublePremiseTask(statement33, truth3, budget3,true); if(t!=null) { success.add(t); } } } if(!tooMuchTemporalStatements(statement1)) { Task t=nal.doublePremiseTask(statement1, truth1, budget1,true); if(t!=null) { success.add(t); } } if(!tooMuchTemporalStatements(statement2)) { Task t=nal.doublePremiseTask(statement2, truth2, budget2,true); //=/> only to keep graph simple for now if(t!=null) { success.add(t); } } if(!tooMuchTemporalStatements(statement3)) { Task t=nal.doublePremiseTask(statement3, truth3, budget3,true); if(t!=null) { success.add(t); } } return success; } /** * Evaluate the quality of the judgment as a solution to a problem * * @param problem A goal or question * @param solution The solution to be evaluated * @return The quality of the judgment as the solution */ public static float solutionQuality(final Sentence problem, final Sentence solution, Memory memory) { if (!matchingOrder(problem.getTemporalOrder(), solution.getTemporalOrder())) { return 0.0F; } TruthValue truth = solution.truth; if (problem.getOccurenceTime()!=solution.getOccurenceTime()) { truth = solution.projectionTruth(problem.getOccurenceTime(), memory.time()); } if (problem.containQueryVar()) { return truth.getExpectation() / solution.term.getComplexity(); } else { return truth.getConfidence(); } } /** * Evaluate the quality of a belief as a solution to a problem, then reward * the belief and de-prioritize the problem * * @param problem The problem (question or goal) to be solved * @param solution The belief as solution * @param task The task to be immediately processed, or null for continued * process * @return The budget for the new task which is the belief activated, if * necessary */ public static BudgetValue solutionEval(final Sentence problem, final Sentence solution, Task task, final nars.core.control.NAL nal) { BudgetValue budget = null; boolean feedbackToLinks = false; if (task == null) { task = nal.getCurrentTask(); feedbackToLinks = true; } boolean judgmentTask = task.sentence.isJudgment(); final float quality = TemporalRules.solutionQuality(problem, solution, nal.mem()); if (judgmentTask) { task.incPriority(quality); } else { float taskPriority = task.getPriority(); budget = new BudgetValue(UtilityFunctions.or(taskPriority, quality), task.getDurability(), BudgetFunctions.truthToQuality(solution.truth)); task.setPriority(Math.min(1 - quality, taskPriority)); } if (feedbackToLinks) { TaskLink tLink = nal.getCurrentTaskLink(); tLink.setPriority(Math.min(1 - quality, tLink.getPriority())); TermLink bLink = nal.getCurrentBeliefLink(); bLink.incPriority(quality); } return budget; } public static int order(final long timeDiff, final int durationCycles) { final int halfDuration = durationCycles/2; if (timeDiff > halfDuration) { return ORDER_FORWARD; } else if (timeDiff < -halfDuration) { return ORDER_BACKWARD; } else { return ORDER_CONCURRENT; } } /** if (relative) event B after (stationary) event A then order=forward; * event B before then order=backward * occur at the same time, relative to duration: order = concurrent */ public static int order(final long a, final long b, final int durationCycles) { if ((a == Stamp.ETERNAL) || (b == Stamp.ETERNAL)) throw new RuntimeException("order() does not compare ETERNAL times"); return order(b - a, durationCycles); } public static boolean concurrent(final long a, final long b, final int durationCycles) { //since Stamp.ETERNAL is Integer.MIN_VALUE, //avoid any overflow errors by checking eternal first if (a == Stamp.ETERNAL) { //if both are eternal, consider concurrent. this is consistent with the original //method of calculation which compared equivalent integer values only return (b == Stamp.ETERNAL); } else if (b == Stamp.ETERNAL) { return false; //a==b was compared above } else { return order(a, b, durationCycles) == ORDER_CONCURRENT; } } }
package io.spine.validate; import com.google.common.flogger.FluentLogger; import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; import io.spine.code.proto.FieldContext; import io.spine.code.proto.FieldDeclaration; import io.spine.validate.option.Distinct; import io.spine.validate.option.FieldValidatingOption; import io.spine.validate.option.Goes; import io.spine.validate.option.Required; import io.spine.validate.option.ValidatingOptionFactory; import java.util.Set; import java.util.function.Function; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkNotNull; final class FieldConstraints { private static final FluentLogger log = FluentLogger.forEnclosingClass(); /** * Prevents the utility class instantiation. */ private FieldConstraints() { } @SuppressWarnings("OverlyComplexMethod") // Assembles many options and option factories for all field types. static Stream<Constraint> of(FieldContext field) { checkNotNull(field); FieldDeclaration declaration = field.targetDeclaration(); JavaType type = declaration.javaType(); switch (type) { case INT: return primitive(ValidatingOptionFactory::forInt, field); case LONG: return primitive(ValidatingOptionFactory::forLong, field); case FLOAT: return primitive(ValidatingOptionFactory::forFloat, field); case DOUBLE: return primitive(ValidatingOptionFactory::forDouble, field); case BOOLEAN: return primitive(ValidatingOptionFactory::forBoolean, field); case STRING: return objectLike(ValidatingOptionFactory::forString, field); case BYTE_STRING: return objectLike(ValidatingOptionFactory::forByteString, field); case ENUM: return objectLike(ValidatingOptionFactory::forEnum, field); case MESSAGE: return objectLike(ValidatingOptionFactory::forMessage, field); default: log.atWarning().log("Unknown field type `%s` at `%s`.", type, declaration); return Stream.of(); } } private static Stream<Constraint> primitive(Function<ValidatingOptionFactory, Set<FieldValidatingOption<?>>> selector, FieldContext context) { return ConstraintsFrom .factories(selector) .andForCollections(Required.create(false), Goes.create(), Distinct.create()) .forField(context); } private static Stream<Constraint> objectLike(Function<ValidatingOptionFactory, Set<FieldValidatingOption<?>>> selector, FieldContext context) { return ConstraintsFrom .factories(selector) .and(Required.create(false), Goes.create()) .andForCollections(Distinct.create()) .forField(context); } }
package edu.wustl.query.domain; import java.util.Date; import java.util.List; import edu.wustl.common.actionForm.IValueObject; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.exception.AssignDataException; import edu.wustl.query.actionForm.WorkflowForm; public class Workflow extends AbstractDomainObject { private static final long serialVersionUID = 1L; private List<WorkflowItem> workflowItemList; private Long id; private String name; private Date createdOn; // private User createdBy; public Workflow() { super(); } public Workflow(final IValueObject object) throws AssignDataException { this(); setAllValues(object); } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setId(Long id) { this.id = id; } public Long getId() { return this.id; } public void setWorkflowItemList(List<WorkflowItem> workflowItemList) { this.workflowItemList = workflowItemList; } public List<WorkflowItem> getWorkflowItemList() { return this.workflowItemList; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } // public User getCreatedBy() // return createdBy; // public void setCreatedBy(User createdBy) // this.createdBy = createdBy; @Override public void setAllValues(IValueObject form) throws AssignDataException { WorkflowForm workFlowForm = (WorkflowForm)form; this.setName(workFlowForm.getName()); this.setName("Workflow1"); } public String getMessageLabel() { return this.getClass().toString(); } }
package org.basex.query.expr; import org.basex.query.*; import org.basex.query.iter.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.query.value.seq.*; import org.basex.query.var.*; import org.basex.util.*; import org.basex.util.hash.*; public final class IterMap extends SimpleMap { /** * Constructor. * @param info input info * @param exprs expressions */ IterMap(final InputInfo info, final Expr... exprs) { super(info, exprs); } @Override public Iter iter(final QueryContext qc) { final QueryFocus qf = qc.focus, focus = new QueryFocus(); final int el = exprs.length; final Iter[] iter = new Iter[el]; // choose item-based or iterative processing final boolean[] items = new boolean[exprs.length]; for(int e = 0; e < el; e++) items[e] = exprs[e].seqType().zeroOrOne(); // initial context values final Value[] values = new Value[el]; values[0] = qc.focus.value; return new Iter() { private int pos; @Override public Item next() throws QueryException { qc.focus = focus; try { do { focus.value = values[pos]; Iter ir = iter[pos]; if(items[pos]) { // item-based processing if(ir == Empty.ITER) { iter[pos--] = null; } else { final Item item = exprs[pos].item(qc, info); if(item == Empty.VALUE) { pos } else { iter[pos] = Empty.ITER; if(pos < el - 1) { values[++pos] = item; } else { return item; } } } } else { // iterative processing if(ir == null) { ir = exprs[pos].iter(qc); iter[pos] = ir; } final Item item = qc.next(ir); if(item == null) { iter[pos--] = null; } else if(pos < el - 1) { values[++pos] = item; } else { return item; } } } while(pos != -1); return null; } finally { qc.focus = qf; } } }; } @Override public Value value(final QueryContext qc) throws QueryException { return iter(qc).value(qc, this); } @Override public IterMap copy(final CompileContext cc, final IntObjMap<Var> vm) { return copyType(new IterMap(info, Arr.copyAll(cc, vm, exprs))); } @Override public String description() { return "iterative " + super.description(); } }
package org.onetwo.common.utils.list; import java.io.Serializable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.onetwo.common.utils.Assert; import org.onetwo.common.utils.LangUtils; import org.onetwo.common.utils.ReflectUtils; import org.onetwo.common.utils.SimpleBlock; import org.onetwo.common.utils.StringUtils; import org.onetwo.common.utils.map.ListMap; @SuppressWarnings("unchecked") public class JFishList<E> implements List<E>, Serializable { public static class EachContext { private int total; private int index; public boolean isFinished(){ return total == index; } public boolean isBreak(){ return total != index; } } public static <T> JFishList<T> wrap(Collection<T> list){ if(JFishList.class.isInstance(list)) return (JFishList<T>)list; if(list==null) return newList(); return new JFishList<T>(list); } public static <T> JFishList<T> wrap(Collection<?> list, SimpleBlock<Object, T> block){ if(list==null) return newList(); return new JFishList<T>(list, block); } public static <T> JFishList<T> wrap(T... e){ return new JFishList<T>(e); } public static <T> JFishList<T> wrapObject(Object e){ if(JFishList.class.isInstance(e)) return (JFishList<T>)e; List<T> list = LangUtils.asList(e); return new JFishList<T>(list); } public static <T> JFishList<T> create(){ return new JFishList<T>(); } public static <T> JFishList<T> newList(){ return new JFishList<T>(); } public static <T> JFishList<T> newList(int size){ return new JFishList<T>(size); } private static final long serialVersionUID = -3308735018101552664L; private ArrayList<E> list; public JFishList(){ super(); list = new ArrayList<E>(); } public JFishList(int size){ list = new ArrayList<E>(size); } public JFishList(E...objects){ if(LangUtils.isEmpty(objects)){ list = new ArrayList<E>(); }else{ list = new ArrayList<E>(objects.length+5); for(E e : objects){ list.add(e); } } } public void addArray(E...objects) { if(LangUtils.isEmpty(objects)) return ; for(E e : objects) add(e); } public void addArrayIgnoreNull(E...objects) { if(LangUtils.isEmpty(objects)) return ; for(E e : objects) if(e!=null) add(e); } public JFishList<E> addCollection(Collection<E> objects) { if(LangUtils.isEmpty(objects)) return this; for(E e : objects){ add(e); } return this; } public JFishList<E> addCollectionIgnoreNull(Collection<E> objects) { if(LangUtils.isEmpty(objects)) return this; for(E e : objects){ if(e!=null) add(e); } return this; } public JFishList(Collection<E> col){ Assert.notNull(col); list = new ArrayList<E>(col.size()+5); list.addAll(col); } public JFishList(Collection<?> col, SimpleBlock<Object, E> block){ Assert.notNull(col); Assert.notNull(block); list = new ArrayList<E>(col.size()+5); for(Object ele : col){ E e = block.execute(ele); if(e!=null) add(e); } } public JFishList<E> addWith(Object obj, SimpleBlock<Object, E> block){ E e = block.execute(obj); if(e!=null){ add(e); } return this; } public <T> T[] asArray(Class<T> arrayClass){ T[] arrays = (T[])Array.newInstance(arrayClass, size()); return toArray(arrays); } public String asString(String separator){ return StringUtils.join(this, separator); } public <T> List<T> getPropertyList(final String name){ final List<T> propValues = new ArrayList<T>(); this.each(new NoIndexIt<E>() { @Override protected void doIt(E element) { T val = (T)ReflectUtils.getExpr(element, name); if(val==null) return ; propValues.add(val); } }); return propValues; } public EachContext each(It<E> it){ EachContext c = new EachContext(); c.total = size(); c.index = 0; for(E e : list){ // try { if(!it.doIt(e, c.index)){ break; } /*} catch (Exception e2) { throw new BaseException("iterator has breaked. ", e2); }*/ c.index++; } return c; } public <K> Map<K, List<E>> groupBy(final SimpleBlock<E, K> block){ final ListMap<K, E> maps = ListMap.newLinkedListMap(); each(new NoIndexIt<E>() { @Override protected void doIt(E element) throws Exception { K rs = block.execute(element); maps.putElement(rs, element); } }); return maps; } /*public void doInResult(It<E> it, final List<?> result){ List<String> strs = new ArrayList<String>(); this.each(new It<E>(){ @Override public boolean doIt(E element, int index) throws Exception { // TODO Auto-generated method stub return false; } }); }*/ public boolean all(final PredicateBlock<E> block){ EachContext c = this.each(new It<E>() { @Override public boolean doIt(E element, int index) { return block.evaluate(element, index); } }); return c.isFinished(); } public boolean any(final PredicateBlock<E> block){ EachContext c = this.each(new It<E>() { @Override public boolean doIt(E element, int index) { if(block.evaluate(element, index)){ return false; } return true; } }); return c.isBreak(); } public void addEnumeration(Enumeration<E> enums){ if(enums==null) return ; while(enums.hasMoreElements()){ add(enums.nextElement()); } } public boolean isNotEmpty() { return !list.isEmpty(); } public void trimToSize() { list.trimToSize(); } public void ensureCapacity(int minCapacity) { list.ensureCapacity(minCapacity); } public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } public boolean contains(Object o) { return list.contains(o); } public int indexOf(Object o) { return list.indexOf(o); } public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public Iterator<E> iterator() { return list.iterator(); } public boolean containsAll(Collection<?> c) { return list.containsAll(c); } public Object clone() { return list.clone(); } public ListIterator<E> listIterator() { return list.listIterator(); } public Object[] toArray() { return list.toArray(); } public ListIterator<E> listIterator(int index) { return list.listIterator(index); } public <T> T[] toArray(T[] a) { return list.toArray(a); } public boolean removeAll(Collection<?> c) { return list.removeAll(c); } public boolean retainAll(Collection<?> c) { return list.retainAll(c); } public E get(int index) { return list.get(index); } public E set(int index, E element) { return list.set(index, element); } public boolean add(E e) { return list.add(e); } public void add(int index, E element) { list.add(index, element); } public String toString() { return list.toString(); } public List<E> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } public E remove(int index) { return list.remove(index); } public boolean remove(Object o) { return list.remove(o); } public boolean equals(Object o) { return list.equals(o); } public void clear() { list.clear(); } public boolean addAll(Collection<? extends E> c) { return list.addAll(c); } public boolean addAll(int index, Collection<? extends E> c) { return list.addAll(index, c); } public int hashCode() { return list.hashCode(); } }
package at.ggjg.evg.screens; import at.ggjg.evg.AudioManager; import at.ggjg.evg.State; import at.ggjg.evg.gestures.Sequence; import at.ggjg.evg.gestures.SequenceFactory; import at.ggjg.evg.gestures.SequenceHolder; import at.ggjg.evg.mechanic.World; import at.ggjg.evg.mechanic.WorldRenderer; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.input.GestureDetector; import com.badlogic.gdx.math.Vector3; import java.util.ArrayList; public class GameplayScreen extends Screen { World world; WorldRenderer renderer; AudioManager audio; int lvl; SequenceHolder sequenceHolder; public GameplayScreen(ScreenManager manager, int lvl) { super(manager); audio = new AudioManager(); audio.setNewState(State.IDLE); this.lvl = lvl; switch (lvl) { case 0: world = new World("levels/testMap.tmx"); break; case 1: world = new World("levels/level_1.tmx"); break; case 2: world = new World("levels/level_2.tmx"); break; case 100: world = new World("levels/oneBunnyLevel.tmx"); } world.level = lvl; renderer = new WorldRenderer(world); audio = new AudioManager(); world.setRenderer(renderer); world.setAudio(audio); world.setManager(manager); initGestures(); Gdx.input.setInputProcessor(new GestureDetector(new at.ggjg.evg.gestures.SequenceGestureListener(world, sequenceHolder, Gdx.graphics.getHeight(), Gdx.graphics.getWidth()))); } private void initGestures() { ArrayList<Sequence> sequenceList = new ArrayList<Sequence>(); //define sequences .. item which first matches wins sequenceList.add(SequenceFactory.createSquare(6, 7, 8, 13, 18, 17, 16, 11, 6)); //sequenceList.add(SequenceFactory.createHeart(7, 1, 0, 5, 10, 16, 22, 18, 14, 9, 3, 7)); sequenceList.add(SequenceFactory.createHorizontalLine(0, 1, 2, 3, 4)); sequenceList.add(SequenceFactory.createVerticalLine(2, 7, 12, 17, 22)); sequenceHolder = new SequenceHolder(24, sequenceList); } @Override public void render() { float delta = Gdx.graphics.getDeltaTime(); Sequence match = sequenceHolder.getMatch(); if (match != null) { System.out.println("sequence was a " + match.getSequenceName()); if (world.currentClickedObj != null) { world.currentClickedObj.onGestureDrawn(match.getSequenceName()); } sequenceHolder.clearLastArea(); } renderer.render(delta); audio.update(delta); world.update(delta); } @Override public void resize(int width, int height) { super.resize(width, height); renderer.resize(width, height); } @Override public void dispose() { renderer.dispose(); audio.dispose(); // world.dispose(); } }
package fi.bittiraha.walletd; import org.bitcoinj.core.*; import org.bitcoinj.kits.WalletAppKit; import net.minidev.json.*; import com.google.common.collect.ImmutableList; import java.util.*; import java.io.File; /** * This class extends WalletAppKit to add ability to tag individual addresses * with account names to emulate bitcoind's accounts. However, emulation in * this version is incomplete and only useful in searching for incoming txs. */ public class WalletAccountManager extends WalletAppKit { AccountManager manager; public WalletAccountManager(NetworkParameters params, File directory, String filePrefix) { super(params,directory,filePrefix); manager = new AccountManager(); } protected class AccountManager extends JSONObject implements WalletExtension { public void deserializeWalletExtension(Wallet containingWallet, byte[] data) { Object parsed = JSONValue.parse(data); if (parsed instanceof JSONObject) { this.merge((JSONObject)parsed); } } public String getWalletExtensionID() { return "fi.bittiraha.walletd.WalletAccountManager"; } public boolean isWalletExtensionMandatory() { return true; } public byte[] serializeWalletExtension() { return this.toJSONString(JSONStyle.MAX_COMPRESS).getBytes(); } } protected List<WalletExtension> provideWalletExtensions() throws Exception { return ImmutableList.of((WalletExtension)manager); } public Map<String,Object> getAccountMap() { return manager; } }
package org.eclipse.birt.core.archive; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; 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.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.eclipse.birt.core.archive.compound.ArchiveFileFactory; import org.eclipse.birt.core.archive.compound.ArchiveFileV3; import org.eclipse.birt.core.archive.compound.ArchiveReader; import org.eclipse.birt.core.archive.compound.ArchiveWriter; import org.eclipse.birt.core.archive.compound.IArchiveFile; import org.eclipse.birt.core.archive.compound.IArchiveFileFactory; import org.eclipse.birt.core.i18n.CoreMessages; import org.eclipse.birt.core.i18n.ResourceConstants; import org.eclipse.birt.core.util.IOUtil; public class ArchiveUtil { protected static Logger logger = Logger.getLogger( ArchiveUtil.class.getName( ) ); // We need this because the report document should be platform neutual. Here // we define the neutual is the unix seperator. public static String UNIX_SEPERATOR = "/"; public final static String CONTNET_SUFFIX = ".content"; /** * @param rootPath - * the absolute path of the root folder. The path is seperated by * system's File seperator. * @param relativePath - * the relative path. The path is either seperated by system's * File seperator or seperated by Unix seperator "/". * @return the absolute path which concats rootPath and relativePath. The * full path is seperated by system's File seperator. The returned * absolute path can be used directly to locate the file. */ public static String generateFullPath( String rootPath, String relativePath ) { relativePath = convertToSystemString( relativePath ); if ( rootPath != null ) { if ( !rootPath.endsWith( File.separator ) ) rootPath += File.separator; if ( relativePath.startsWith( File.separator ) ) relativePath = relativePath.substring( 1 ); return rootPath + relativePath; } return relativePath; } public static String generateFullContentPath( String rootPath, String relativePath ) { return generateFullPath( rootPath, relativePath + CONTNET_SUFFIX ); } /** * @param rootPath - * the absolute path of the root folder. The path is seperated by * system's File seperator. * @param fullString - * the absolute path of the stream. The path is seperated by * system's File seperator. * @return the relative path string. The path is based on Unix syntax and * starts with "/". */ public static String generateRelativePath( String rootPath, String fullPath ) { String relativePath = null; if ( ( rootPath != null ) && fullPath.startsWith( rootPath ) ) { relativePath = fullPath.substring( rootPath.length( ) ); } else relativePath = fullPath; relativePath = convertToUnixString( relativePath ); if ( !relativePath.startsWith( UNIX_SEPERATOR ) ) relativePath = UNIX_SEPERATOR + relativePath; return relativePath; } public static String generateRelativeContentPath( String rootPath, String fullPath ) { String path = generateRelativePath(rootPath, fullPath); if(path.endsWith( CONTNET_SUFFIX )) { return path.substring( 0, path.length( ) - CONTNET_SUFFIX.length( ) ); } return path; } /** * @param path - * the path that could be in system format (seperated by * File.seperator) or Unix format (seperated by "/"). * @return the path that is in Unix format. */ private static String convertToUnixString( String path ) { if ( path == null ) return null; return path.replace( File.separator.charAt( 0 ), UNIX_SEPERATOR .charAt( 0 ) ); } /** * @param path - * the path that could be in system format (seperated by * File.seperator) or Unix format (seperated by "/"). * @return the path that is in the system format. */ private static String convertToSystemString( String path ) { if ( path == null ) return null; return path.replace( UNIX_SEPERATOR.charAt( 0 ), File.separator .charAt( 0 ) ); } /** * Generate a unique file or folder name which is in the same folder as the * originalName * * @param originalName - * the original Name. For example, it could be the name of the * file archive * @return a unique file or folder name which is in the same folder as the * originalName */ synchronized public static String generateUniqueFileFolderName( String originalName ) { SimpleDateFormat df = new SimpleDateFormat( "yyyy_MM_dd_HH_mm_ss" ); //$NON-NLS-1$ String dateTimeString = df.format( new Date( ) ); StringBuffer folderName = new StringBuffer( originalName ); folderName.append( '_' ); folderName.append( dateTimeString ); Random generator = new Random( ); File folder = new File( folderName.toString( ) ); while ( folder.exists( ) ) { folderName.append( generator.nextInt( ) ); folder = new File( folderName.toString( ) ); } return folderName.toString( ); } /** * If the parent folder of the file doesn't exsit, create the parent folder. */ public static void createParentFolder( File fd ) { if ( fd != null && fd.getParentFile( ) != null && fd.getParentFile( ).exists( ) == false ) { fd.getParentFile( ).mkdirs( ); } } /** * Recursively delete all the files and folders under dirOrFile * * @param dirOrFile - * the File object which could be either a folder or a file. */ public static void deleteAllFiles( File dirOrFile ) { if ( !dirOrFile.exists( ) ) return; if ( dirOrFile.isFile( ) ) { dirOrFile.delete( ); } else // dirOrFile is directory { if ( ( dirOrFile.listFiles( ) != null ) && ( dirOrFile.listFiles( ).length > 0 ) ) { File[] fileList = dirOrFile.listFiles( ); for ( int i = 0; i < fileList.length; i++ ) deleteAllFiles( fileList[i] ); } // Directory can only be deleted when it is empty. dirOrFile.delete( ); } } public static void zipFolderToStream( String tempFolderPath, OutputStream ostream ) { ZipOutputStream zipOutput = new ZipOutputStream( ostream ); File rootDir = new File( tempFolderPath ); File[] files = rootDir.listFiles( ); try { zipFiles( zipOutput, files, tempFolderPath ); zipOutput.close( ); } catch ( FileNotFoundException e ) { logger.log( Level.WARNING, e.getMessage( ) ); } catch ( IOException e ) { logger.log( Level.WARNING, e.getMessage( ) ); } } /** * Utility funtion to write files/directories to a ZipOutputStream. For * directories, all the files and subfolders are written recursively. */ private static void zipFiles( ZipOutputStream zipOut, File[] files, String tempFolderPath ) throws FileNotFoundException, IOException { if ( files == null ) return; for ( int i = 0; i < files.length; i++ ) { File file = files[i]; if ( file.isDirectory( ) ) { // if file is a directory, get child files and recursively call // this method File[] dirFiles = file.listFiles( ); zipFiles( zipOut, dirFiles, tempFolderPath ); } else { // if file is a file, create a new ZipEntry and write out the // file. BufferedInputStream in = new BufferedInputStream( new FileInputStream( file ) ); try { String relativePath = generateRelativePath( tempFolderPath, file.getPath( ) ); ZipEntry entry = new ZipEntry( relativePath ); try { entry.setTime( file.lastModified( ) ); zipOut.putNextEntry( entry ); // Create a new zipEntry int len; byte[] buf = new byte[1024 * 5]; while ( ( len = in.read( buf ) ) > 0 ) { zipOut.write( buf, 0, len ); } } finally { zipOut.closeEntry( ); } } finally { in.close( ); } } } // end of for ( int i = 0; i < files.length; i++ ) } public static void unzipArchive( File zipArchive, String tempFolderPath ) { try { ZipFile zipFile = new ZipFile( zipArchive ); Enumeration<? extends ZipEntry> entries = zipFile.entries( ); while ( entries.hasMoreElements( ) ) { ZipEntry entry = (ZipEntry) entries.nextElement( ); if ( entry.isDirectory( ) ) { // Assume directories are stored parents first then // children. String dirName = generateFullPath( tempFolderPath, entry .getName( ) ); // TODO: handle the error case where the folder can not be // created! File dir = new File( dirName ); dir.mkdirs( ); } else { InputStream in = null; try { in = zipFile.getInputStream( entry ); File file = new File( generateFullPath( tempFolderPath, entry.getName( ) ) ); File dir = new File( file.getParent( ) ); if ( dir.exists( ) ) { assert ( dir.isDirectory( ) ); } else { dir.mkdirs( ); } BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream( file ) ); int len; byte[] buf = new byte[1024 * 5]; try { while ( ( len = in.read( buf ) ) > 0 ) { out.write( buf, 0, len ); } } finally { out.close( ); } } finally { if ( in != null ) { in.close( ); } } } } zipFile.close( ); } catch ( ZipException e ) { logger.log( Level.WARNING, e.getMessage( ) ); } catch ( IOException e ) { logger.log( Level.WARNING, e.getMessage( ) ); } } public static void copy( IArchiveFile inArchive, IArchiveFile outArchive ) throws IOException { if ( inArchive == null || outArchive == null ) { throw new IOException( CoreMessages.getString( ResourceConstants.NULL_SOURCE ) ); } copy( new ArchiveReader( inArchive ), new ArchiveWriter( outArchive ) ); } static public void copy( IDocArchiveReader reader, IDocArchiveWriter writer ) throws IOException { List<String> streamList = reader.listAllStreams( ); for ( int i = 0; i < streamList.size( ); i++ ) { String streamPath = streamList.get( i ); RAInputStream in = reader.getStream( streamPath ); try { RAOutputStream out = writer .createRandomAccessStream( streamPath ); try { copyStream( in, out ); } finally { out.close( ); } } finally { in.close( ); } } } static private void copyStream( RAInputStream in, RAOutputStream out ) throws IOException { byte[] buf = new byte[4096]; int readSize = in.read( buf ); while ( readSize != -1 ) { out.write( buf, 0, readSize ); readSize = in.read( buf ); } } static public void archive( String folder, String file ) throws IOException { archive( folder, null, file ); } static public void convertFolderArchive(String folder, String file) throws IOException { FolderArchiveReader reader = null; InputStream inputStream = null; DataInputStream dataInput = null; try { archive( folder, null, file ); String folderName = new File( folder ).getCanonicalPath( ); reader = new FolderArchiveReader( folderName ); if ( reader.exists( FolderArchiveFile.METEDATA ) ) { inputStream = reader.getInputStream( FolderArchiveFile.METEDATA ); dataInput = new DataInputStream( inputStream ); Map properties = IOUtil.readMap( dataInput ); IArchiveFileFactory factory = new ArchiveFileFactory( ); ArchiveFileV3 archive = new ArchiveFileV3( file, "rw+" ); if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { archive.setDependId( properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ).toString( ) ); } if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { archive.setDependId( properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ).toString( ) ); } archive.removeEntry( FolderArchiveFile.METEDATA ); archive.close( ); } } finally { if(reader!=null) { reader.close( ); } if(inputStream!=null) { inputStream.close( ); } if(dataInput!=null) { dataInput.close( ); } } } /** * Compound File Format: <br> * 1long(stream section position) + 1long(entry number in lookup map) + * lookup map section + stream data section <br> * The Lookup map is a hash map. The key is the relative path of the stram. * The entry contains two long number. The first long is the start postion. * The second long is the length of the stream. <br> * * @param tempFolder * @param fileArchiveName - * the file archive name * @return Whether the compound file was created successfully. */ static public void archive( String folderName, IStreamSorter sorter, String fileName ) throws IOException { // Delete existing file or folder that has the same // name of the file archive. folderName = new File( folderName ).getCanonicalPath( ); FolderArchiveReader reader = new FolderArchiveReader( folderName ); try { reader.open( ); File file = new File( fileName ); if ( file.exists( ) ) { if ( file.isFile( ) ) { file.delete( ); } } FileArchiveWriter writer = new FileArchiveWriter( fileName ); try { writer.initialize( ); copy( reader, writer ); } finally { writer.finish( ); } } finally { reader.close( ); } } /** * files used to record the reader count reference. */ static final String READER_COUNT_FILE_NAME = "/.reader.count"; /** * files which should not be copy into the archives */ static final String[] SKIP_FILES = new String[]{READER_COUNT_FILE_NAME}; static boolean needSkip( String file ) { for ( int i = 0; i < SKIP_FILES.length; i++ ) { if ( SKIP_FILES[i].equals( file ) ) { return true; } } return false; } /** * Get all the files under the specified folder (including all the files * under sub-folders) * * @param dir - * the folder to look into * @param fileList - * the fileList to be returned */ public static void listAllFiles( File dir, ArrayList<? super File> fileList ) { if ( dir.exists( ) && dir.isDirectory( ) ) { File[] files = dir.listFiles( ); if ( files == null ) return; for ( int i = 0; i < files.length; i++ ) { File file = files[i]; if ( file.isFile( ) ) { fileList.add( file ); } else if ( file.isDirectory( ) ) { listAllFiles( file, fileList ); } } } } static public void expand( String file, String folder ) throws IOException { FileArchiveReader reader = new FileArchiveReader( file ); try { reader.open( ); reader.expandFileArchive( folder ); } finally { reader.close( ); } } /** * Assemble four bytes to an int value, make sure that the passed bytes * length is larger than 4. * * @param bytes * @return int value of bytes */ public final static int bytesToInteger( byte[] b ) { assert b.length >= 4; return ( ( b[0] & 0xFF ) << 24 ) + ( ( b[1] & 0xFF ) << 16 ) + ( ( b[2] & 0xFF ) << 8 ) + ( ( b[3] & 0xFF ) << 0 ); } public final static int bytesToInteger( byte[] b, int off ) { assert b.length - off >= 4; return ( ( b[off++] & 0xFF ) << 24 ) + ( ( b[off++] & 0xFF ) << 16 ) + ( ( b[off++] & 0xFF ) << 8 ) + ( ( b[off] & 0xFF ) << 0 ); } /** * Assemble eight bytes to an long value, make sure that the passed bytes * length larger than 8. * * @param bytes * @return int value of bytes */ public final static long bytesToLong( byte[] b ) { assert b.length >= 8; return ( ( b[0] & 0xFFL ) << 56 ) + ( ( b[1] & 0xFFL ) << 48 ) + ( ( b[2] & 0xFFL ) << 40 ) + ( ( b[3] & 0xFFL ) << 32 ) + ( ( b[4] & 0xFFL ) << 24 ) + ( ( b[5] & 0xFFL ) << 16 ) + ( ( b[6] & 0xFFL ) << 8 ) + ( ( b[7] & 0xFFL ) << 0 ); } public final static long bytesToLong( byte[] b, int off ) { assert b.length - off >= 8; return ( ( b[off++] & 0xFFL ) << 56 ) + ( ( b[off++] & 0xFFL ) << 48 ) + ( ( b[off++] & 0xFFL ) << 40 ) + ( ( b[off++] & 0xFFL ) << 32 ) + ( ( b[off++] & 0xFFL ) << 24 ) + ( ( b[off++] & 0xFFL ) << 16 ) + ( ( b[off++] & 0xFFL ) << 8 ) + ( ( b[off] & 0xFFL ) << 0 ); } public final static void integerToBytes( int v, byte[] b ) { assert b.length >= 4; b[0] = (byte) ( ( v >>> 24 ) & 0xFF ); b[1] = (byte) ( ( v >>> 16 ) & 0xFF ); b[2] = (byte) ( ( v >>> 8 ) & 0xFF ); b[3] = (byte) ( ( v >>> 0 ) & 0xFF ); } public final static void integerToBytes( int v, byte[] b, int off ) { assert b.length - off >= 4; b[off++] = (byte) ( ( v >>> 24 ) & 0xFF ); b[off++] = (byte) ( ( v >>> 16 ) & 0xFF ); b[off++] = (byte) ( ( v >>> 8 ) & 0xFF ); b[off] = (byte) ( ( v >>> 0 ) & 0xFF ); } public final static void longToBytes( long v, byte[] b ) { assert b.length >= 8; b[0] = (byte) ( ( v >>> 56 ) & 0xFF ); b[1] = (byte) ( ( v >>> 48 ) & 0xFF ); b[2] = (byte) ( ( v >>> 40 ) & 0xFF ); b[3] = (byte) ( ( v >>> 32 ) & 0xFF ); b[4] = (byte) ( ( v >>> 24 ) & 0xFF ); b[5] = (byte) ( ( v >>> 16 ) & 0xFF ); b[6] = (byte) ( ( v >>> 8 ) & 0xFF ); b[7] = (byte) ( ( v >>> 0 ) & 0xFF ); } public final static void longToBytes( long v, byte[] b, int off ) { assert b.length - off >= 8; b[off++] = (byte) ( ( v >>> 56 ) & 0xFF ); b[off++] = (byte) ( ( v >>> 48 ) & 0xFF ); b[off++] = (byte) ( ( v >>> 40 ) & 0xFF ); b[off++] = (byte) ( ( v >>> 32 ) & 0xFF ); b[off++] = (byte) ( ( v >>> 24 ) & 0xFF ); b[off++] = (byte) ( ( v >>> 16 ) & 0xFF ); b[off++] = (byte) ( ( v >>> 8 ) & 0xFF ); b[off] = (byte) ( ( v >>> 0 ) & 0xFF ); } public static boolean removeFileAndFolder( File file ) { assert ( file != null ); if ( file.isDirectory( ) ) { File[] children = file.listFiles( ); if ( children != null ) { for ( int i = 0; i < children.length; i++ ) { removeFileAndFolder( children[i] ); } } } if ( file.exists( ) ) { return file.delete( ); } return true; } }
// Clirr: compares two versions of a java library for binary compatibility // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sf.clirr.core; import org.apache.bcel.classfile.JavaClass; /** * A filter for Java classes. * <p> * Instances of this interface are passed to the * {@link Checker#reportDiffs} method of the {@link Checker} class. * </p> * * @see Checker#reportDiffs * @see java.io.FileFilter * @author lkuehne */ public interface ClassFilter { /** * Tests whether or not a given java class is considered when reporting the API * differences between jar files. * * @param clazz a Java class * @return true if clazz should be considered by the Checker * in this object. */ boolean isSelected(JavaClass clazz); }
package org.eclipse.birt.core.data; import java.util.ArrayList; import java.util.List; import org.eclipse.birt.core.exception.BirtException; /** * This class help to manipulate expressions. * */ public final class ExpressionUtil { /** prefix for row */ private static final String ROW_INDICATOR = "row"; /** * Return a row expression text according to given row name. * * @param rowName * @return */ public static String createRowExpression( String rowName ) { return ROW_INDICATOR + "[\"" + rowName + "\"]"; } /** * Return a row expression text according to given row index, which * is 1-based. * * @param index * @return */ public static String createRowExpression( int index ) { return ROW_INDICATOR + "[" + index + "]"; } /** * @param oldExpression * @return * @throws BirtException */ public static List extractColumnExpressions( String oldExpression ) throws BirtException { if ( oldExpression == null ) return new ArrayList( ); return ExpressionParserUtility.compileColumnExpression( oldExpression ); } /** * Translate the old expression with "row" as indicator to new expression * using "dataSetRow" as indicator in xml file. * * NOTE: "&quot;" will not be parse as '"' * * @param xmlString * @return */ public static List extractColumnNamesFromXML( String xmlString ) { List result = new ArrayList( ); if ( xmlString == null ) return null; char[] chars = xmlString.toCharArray( ); int retrieveSize = 0; for ( int i = 0; i < chars.length; i++ ) { retrieveSize = 0; if ( chars[i] == '-' ) { if ( i > 1 && chars[i - 1] == '!' && chars[i - 2] == '<' ) { i++; retrieveSize = retrieveSize + 3; while ( i < chars.length ) { i++; retrieveSize++; if ( chars[i - 2] == '-' && chars[i - 1] == '-' && chars[i] == '>' ) { break; } } retrieveSize++; i++; } } if ( i >= retrieveSize + 3 ) { if ( chars[i - retrieveSize - 3] == 'r' && chars[i - retrieveSize - 2] == 'o' && chars[i - retrieveSize - 1] == 'w' ) { if ( i - retrieveSize - 4 <= 0 || isValidProceeding( chars[i - retrieveSize - 4] ) ) { if ( chars[i] == '.' ) { i++; int j = i; while ( chars[i] != ' ' && chars[i] != '<' && chars[i] != '>' ) { i++; if ( i >= chars.length ) return result; } result.add( xmlString.substring( j, i ) ); } else if ( chars[i] == '[' ) { i++; int j = i; boolean push = true; while ( chars[i] != ']' || chars[i - 1] == '\\' ) { i++; if ( i >= chars.length ) return result; if ( chars[i] == '<' || chars[i] == '>' ) { push = false; break; } } if ( push ) { addCandidateColumnToList( xmlString, result, i, j ); } } } } } } return result; } /** * @param xmlString * @param result * @param i * @param j */ private static void addCandidateColumnToList( String xmlString, List result, int i, int j ) { Object candidate = xmlString.substring( j,i ).trim( ); if ( candidate.toString( ).startsWith( "\"" ) && candidate.toString( ).endsWith( "\"" ) ) candidate = candidate.toString( ).substring( 1, candidate.toString( ).length( ) - 1 ); else { try{ candidate = new Integer( candidate.toString( ) ); }catch (Exception e) { candidate = null; } } if( candidate!= null ) result.add( candidate ); } /** * Test whether the char immediately before the candidate "row" key is * valid. * * @param operator * @return */ private static boolean isValidProceeding( char operator ) { if ( (operator >= 'A' && operator <= 'Z') || (operator >='a' && operator <= 'z') || operator == '_') return false; return true; } }
package brooklyn.util; import java.util.LinkedHashMap; import java.util.Map; import com.google.common.collect.ImmutableMap; /** Map impl, exposing simple builder operations (add) in a fluent-style API, * where the final map is mutable. You can also toImmutable. */ public class MutableMap<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = -2463168443382874384L; public static <K,V> MutableMap<K,V> of(K k1, V v1) { MutableMap<K,V> result = new MutableMap<K,V>(); result.put(k1, v1); return result; } public static <K,V> MutableMap<K,V> of(K k1, V v1, K k2, V v2) { MutableMap<K,V> result = new MutableMap<K,V>(); result.put(k1, v1); result.put(k2, v2); return result; } public static <K,V> MutableMap<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3) { MutableMap<K,V> result = new MutableMap<K,V>(); result.put(k1, v1); result.put(k2, v2); result.put(k3, v3); return result; } public MutableMap<K,V> add(K key, V value) { put(key, value); return this; } public MutableMap<K,V> add(Map<K,V> m) { putAll(m); return this; } public ImmutableMap<K,V> toImmutable() { return ImmutableMap.<K,V>builder().putAll(this).build(); } }
package com.emistoolbox.server.renderer.pdfreport.html; import info.joriki.io.Util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.emistoolbox.common.renderer.ChartConfig; import com.emistoolbox.common.renderer.pdfreport.PdfText; import com.emistoolbox.common.renderer.pdfreport.TextSet; import com.emistoolbox.common.results.ReportMetaResult; import com.emistoolbox.common.util.Rectangle; import com.emistoolbox.server.renderer.pdfreport.EmisPageGroup; import com.emistoolbox.server.renderer.pdfreport.EmisPdfPage; import com.emistoolbox.server.renderer.pdfreport.PdfChartContent; import com.emistoolbox.server.renderer.pdfreport.PdfContent; import com.emistoolbox.server.renderer.pdfreport.PdfContentVisitor; import com.emistoolbox.server.renderer.pdfreport.PdfImageContent; import com.emistoolbox.server.renderer.pdfreport.PdfPriorityListContent; import com.emistoolbox.server.renderer.pdfreport.PdfReport; import com.emistoolbox.server.renderer.pdfreport.PdfTableContent; import com.emistoolbox.server.renderer.pdfreport.impl.PDFAdvancedReportWriter; import com.emistoolbox.server.renderer.pdfreport.impl.PdfTextContent; import com.emistoolbox.server.renderer.pdfreport.impl.PdfVariableContent; import com.emistoolbox.server.renderer.pdfreport.layout.LayoutFrame; import com.emistoolbox.server.renderer.pdfreport.layout.LayoutPage; import com.emistoolbox.server.util.ZipArchiver; import es.jbauer.lib.io.IOInput; import es.jbauer.lib.io.IOOutput; import es.jbauer.lib.io.impl.IOInputStreamInput; import es.jbauer.lib.io.impl.IOOutputStreamOutput; public class HTMLReportWriter extends PDFAdvancedReportWriter { final static String zipSuffix = ".zip"; private boolean showIds = true; public boolean isShowIds () { return showIds; } public void setShowIds (boolean showIds) { this.showIds = showIds; } static interface HTMLNode { void print (PrintStream ps); } static class TextNode implements HTMLNode { String text; public TextNode (String text) { this.text = text; } public void print (PrintStream ps) { ps.print (text); } } static class HTMLTag implements HTMLNode { String name; Map<String,String> attributes = new HashMap<String,String> (); List<HTMLNode> children = new ArrayList<HTMLNode> (); public HTMLTag (String name) { int dot = name.indexOf ('.'); if (dot != -1) { attributes.put ("class",name.substring (dot + 1)); name = name.substring (0,dot); } this.name = name; } public HTMLTag (String name,String content) { this (name,new TextNode (content)); } public HTMLTag (String name,HTMLNode node) { this (name); add (node); } public void print (PrintStream ps) { ps.print ('<' + name); for (Entry<String,String> entry : attributes.entrySet ()) ps.print (' ' + entry.getKey () + "='" + entry.getValue () + "'"); ps.print ('>'); for (HTMLNode child : children) child.print (ps); if (!children.isEmpty ()) ps.print ("</" + name + '>'); } public void add (HTMLNode child) { children.add (child); } public boolean isEmpty () { return children.isEmpty (); } public void removeLastChild () { children.remove (children.size () - 1); } } static class HTMLDocument { HTMLTag html = new HTMLTag ("html"); HTMLTag head = new HTMLTag ("head"); HTMLTag body = new HTMLTag ("body"); public HTMLDocument () { html.add (head); html.add (body); } public void print (File file) throws FileNotFoundException { PrintStream ps = new PrintStream (file); ps.println ("<!DOCTYPE HTML>"); html.print (ps); ps.close (); } public void add (HTMLNode node) { body.add (node); } } private File indexDirectory; private int imageCount; private int labelCount; private String reportName; private HTMLTag linkTag; private HTMLTag getReportNameTag () { return new HTMLTag ("div.report-name",reportName); } public void writeReport (PdfReport report,File out) throws IOException { reportName = report.getReportConfig ().getName (); String filename = out.getName (); if (!filename.endsWith (zipSuffix)) throw new Error ("trying to write HTML ZIP archive to file without " + zipSuffix + " suffix"); indexDirectory = new File (out.getParentFile (),filename.substring (0,filename.length () - zipSuffix.length ())); indexDirectory.mkdir (); HTMLDocument indexDocument = new HTMLDocument (); indexDocument.add (getReportNameTag ()); linkTag = new HTMLTag ("div.emis-links"); // this gets reused on every page, and is added to each page twice renderPageGroup (report.getPageGroup (),indexDocument.body,1,null,null,true); indexDocument.head.add (new HTMLTag ("style",".smaller{font-size:20px}.hierarchy-lowest{margin:0px}")); indexDocument.print (new File (indexDirectory,"index.html")); ZipArchiver.archive (indexDirectory,out,false); } private void renderPageGroup (EmisPageGroup pageGroup,HTMLTag container,int headingLevel,String linkPrefix,String titlePrefix,boolean condensing) throws IOException { List<EmisPageGroup> pageGroups = pageGroup.getPageGroups (); List<EmisPdfPage> pages = pageGroup.getPages (); if (getListSize (pageGroups) != 0 && getListSize (pages) != 0) throw new Error ("HTML rendering for page group containing both subgroups and pages not implemented"); String level = pageGroup.getLevel (); String name = pageGroup.getName (); Integer id = pageGroup.getId (); boolean isLeaf = showIds && pageGroups.isEmpty (); String fullName = isLeaf ? level + " " + name + " (" + id + ")" : name; linkPrefix = newPrefix (linkPrefix,fullName); if (condensing && getListSize (pageGroups) == 1) renderPageGroup (pageGroups.get (0),container,headingLevel,linkPrefix,newPrefix (titlePrefix,fullName),true); else { HTMLTag heading = new HTMLTag ("h" + Math.min (headingLevel,4)); HTMLNode nameNode = new TextNode (fullName); HTMLTag link = new HTMLTag ("a",linkPrefix); String anchor = level + id; link.attributes.put ("href","../index.html#" + anchor); heading.attributes.put ("id",anchor); if (!linkTag.isEmpty ()) linkTag.add (new TextNode (" / ")); linkTag.add (link); if (!pages.isEmpty ()) { HTMLTag a = new HTMLTag ("a",nameNode); String groupDirectoryName = id + "-" + sanitize (name); a.attributes.put ("href",groupDirectoryName + "/index.html"); nameNode = a; final File groupDirectory = new File (indexDirectory,groupDirectoryName); groupDirectory.mkdir (); imageCount = 0; HTMLDocument groupDocument = new HTMLDocument (); groupDocument.add (linkTag); groupDocument.add (getReportNameTag ()); groupDocument.add (new HTMLTag ("h1",fullName)); heading.attributes.put ("class","hierarchy-lowest"); final HTMLTag toc = new HTMLTag ("div.emis-toc"); groupDocument.add (toc); groupDocument.add (new HTMLTag ("hr")); for (EmisPdfPage page : pages) { lastTitle = null; HTMLTag pageTag = new HTMLTag ("div.emis-page"); groupDocument.add (pageTag); if (!(page instanceof LayoutPage)) throw new Error ("can only handle layout pages"); renderTitles (page,pageTag,false); for (final LayoutFrame frame : ((LayoutPage) page).getFrames ()) { final HTMLTag frameTag = new HTMLTag ("div.emis-frame"); pageTag.add (frameTag); PdfContent content = frame.getContent (); final String title = content.getTitle (); if (content instanceof PdfTextContent || content instanceof PdfChartContent) updateFrameTitle (frame,title); renderTitles (frame,frameTag,true); content.accept (new PdfContentVisitor<Void> () { public Void visit (PdfChartContent content) { Rectangle position = frame.getFrameConfig ().getPosition (); try { renderImage (renderChart (content, position.getWidth (), position.getHeight ())); } catch (IOException e) { e.printStackTrace (); throw new Error (); } return null; } public Void visit (PdfImageContent content) { try { renderImage (content.getFile ()); } catch (IOException e) { e.printStackTrace (); throw new Error (); } return null; } public Void visit (PdfPriorityListContent content) { throw new Error ("html rendering for priority list content not implemented"); } public Void visit (PdfTableContent content) { int rows = content.getRows (); int cols = content.getColumns (); HTMLTag table = new HTMLTag ("table"); for (int row = 0;row < rows;row++) { HTMLTag tableRow = new HTMLTag ("tr"); for (int col = 0;col < cols;col++) { HTMLTag tableItem = new HTMLTag ("td"); tableItem.add (new TextNode (content.getText (row,col))); tableRow.add (tableItem); } table.add (tableRow); } frameTag.add (table); return null; } public Void visit (PdfTextContent content) { if (content.getText () != null) frameTag.add (new HTMLTag ("p",content.getText ())); return null; } public Void visit (PdfVariableContent content) { throw new Error ("html rendering for variable content not implemented"); } private void renderImage (IOInput input) throws IOException { String filename = "image-" + ++imageCount + ".png"; Util.copy (input.getInputStream (),new File (groupDirectory,filename)); String label = "a" + ++labelCount; HTMLTag link = new HTMLTag ("a",title); link.attributes.put ("href",'#' + label); toc.add (link); HTMLTag h2 = new HTMLTag ("h2",title); h2.attributes.put ("id",label); frameTag.add (h2); HTMLTag img = new HTMLTag ("img"); img.attributes.put ("src",filename); frameTag.add (img); } }); renderFooter (frame,frameTag); } renderFooter (page,pageTag); } groupDocument.add (linkTag); groupDocument.print (new File (groupDirectory,"index.html")); } if (titlePrefix == null) heading.add (nameNode); else { HTMLTag div1 = new HTMLTag ("div.smaller",titlePrefix); HTMLTag div2 = new HTMLTag ("div"); div2.add (nameNode); heading.add (div1); heading.add (div2); } HTMLTag target; if (container.name.equals ("ul")) { target = new HTMLTag ("li"); container.add (target); } else target = container; target.add (heading); if (!isLeaf) { HTMLTag ul = new HTMLTag ("ul"); for (EmisPageGroup childGroup : pageGroups) renderPageGroup (childGroup,ul,headingLevel + 1,null,null,false); target.add (ul); } linkTag.removeLastChild (); if (!linkTag.isEmpty ()) linkTag.removeLastChild (); } } private String lastTitle; private void renderTitles (TextSet textSet,HTMLTag target,boolean dontRepeat) { String title = textSet.getText (PdfText.TEXT_TITLE); if (title != null && !(dontRepeat && title.equals (lastTitle))) target.add (new HTMLTag ("h1.emis-title",title)); lastTitle = title; String subtitle = textSet.getText (PdfText.TEXT_SUBTITLE); if (subtitle != null) target.add (new HTMLTag ("h2.emis-subtitle",subtitle)); } private void renderFooter (TextSet textSet,HTMLTag target) { String footer = textSet.getText (PdfText.TEXT_FOOTER); if (footer != null) target.add (new HTMLTag ("h2.emis-footer",footer)); } private IOInput renderChart(PdfChartContent content, double width, double height) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOOutput out = new IOOutputStreamOutput(buffer, "chart.png", "image/png", null); ChartConfig chartConfig = content.getChartConfig (); chartConfig.setChartSize (800,400); getChartRenderer ().render (content.getType (),content.getResult (),chartConfig, out); IOInput in = new IOInputStreamInput (new ByteArrayInputStream (buffer.toByteArray ()),out.getName (),out.getContentType (),null); if (in.getContentType ().equals ("image/png")) return in; throw new IllegalArgumentException("Unsupported chart output format"); } private static String sanitize (String s) { StringBuilder builder = new StringBuilder (); for (char c : s.toCharArray ()) if (Character.isLetter (c)) builder.append (c); return builder.toString (); } private static String newPrefix (String oldPrefix,String newSegment) { return oldPrefix == null ? newSegment : oldPrefix + " / " + newSegment; } private static <T> int getListSize (List<T> list) { return list == null ? 0 : list.size (); } public void setDateInfo (ReportMetaResult metaInfo) { } @Override public String getExtension() { return zipSuffix; } }
package com.ctrip.xpipe.netty; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.channel.FileRegion; import io.netty.util.CharsetUtil; import io.netty.util.concurrent.ScheduledFuture; import java.net.SocketAddress; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * @author leoliang * * 201731 */ public abstract class ChannelTrafficStatisticsHandler extends AbstractNettyHandler { private final long reportIntervalMillis; private volatile ScheduledFuture<?> nextCheck; private String ip = ""; private int port = -1; private AtomicLong writtenBytes = new AtomicLong(0L); private AtomicLong readBytes = new AtomicLong(0L); private volatile int state = 0; // 0 - none, 1 - initialized, 2 - destroyed public ChannelTrafficStatisticsHandler(long reportIntervalMillis) { if (reportIntervalMillis <= 0) { throw new IllegalArgumentException(String.format("Invalid reportIntervalMillis %s", reportIntervalMillis)); } this.reportIntervalMillis = reportIntervalMillis; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (ctx.channel().isActive() && ctx.channel().isRegistered()) { // channelActvie() event has been fired already, which means this.channelActive() will // not be invoked. We have to initialize here instead. initialize(ctx); } else { // channelActive() event has not been fired yet. this.channelActive() will be invoked // and initialization will occur there. } super.handlerAdded(ctx); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { destroy(); super.handlerRemoved(ctx); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { // Initialize early if channel is active already. if (ctx.channel().isActive()) { initialize(ctx); } super.channelRegistered(ctx); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // This method will be invoked only if this handler was added // before channelActive() event is fired. If a user adds this handler // after the channelActive() event, initialize() will be called by beforeAdd(). initialize(ctx); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { destroy(); super.channelInactive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { readBytes.addAndGet(((ByteBuf) msg).readableBytes()); } doChannelRead(ctx, msg); super.channelRead(ctx, msg); } protected abstract void doChannelRead(ChannelHandlerContext ctx, Object msg) throws Exception; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof ByteBuf) { logger.debug("[write]{}", ((ByteBuf) msg).toString(CharsetUtil.UTF_8)); writtenBytes.addAndGet(((ByteBuf) msg).readableBytes()); } else if (msg instanceof FileRegion) { writtenBytes.addAndGet(((FileRegion) msg).count()); } doWrite(ctx, msg, promise); super.write(ctx, msg, promise); } protected abstract void doWrite(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception; protected void initialize(ChannelHandlerContext ctx) { // Avoid the case where destroy() is called before scheduling timeouts. switch (state) { case 1: case 2: return; } state = 1; parseIpPort(ctx.channel()); nextCheck = ctx.executor().schedule(new ReportingTask(ctx), reportIntervalMillis, TimeUnit.MILLISECONDS); } protected void destroy() { state = 2; if (nextCheck != null) { nextCheck.cancel(false); nextCheck = null; } } protected void reportTraffic() { doReportTraffic(readBytes.getAndSet(0), writtenBytes.getAndSet(0), ip, port); } protected abstract void doReportTraffic(long readBytes, long writtenBytes, String remoteIp, int remotePort); protected void parseIpPort(final Channel channel) { if (null == channel) { return; } final SocketAddress remote = channel.remoteAddress(); final String addr = remote != null ? remote.toString() : ""; if (addr.length() > 0) { int index = addr.lastIndexOf("/"); if (index >= 0) { String ipPort = addr.substring(index + 1); String[] splits = ipPort.split(":"); if (splits != null && splits.length == 2) { ip = splits[0]; try { port = Integer.parseInt(splits[1]); } catch (NumberFormatException e) { // ignore } } } } } protected final class ReportingTask implements Runnable { private final ChannelHandlerContext ctx; public ReportingTask(ChannelHandlerContext ctx) { this.ctx = ctx; } @Override public void run() { if (!ctx.channel().isOpen()) { return; } try { reportTraffic(); } catch (Throwable t) { ctx.fireExceptionCaught(t); } finally { nextCheck = ctx.executor().schedule(this, reportIntervalMillis, TimeUnit.MILLISECONDS); } } } protected long getWrittenBytes() { return writtenBytes.get(); } protected long getReadBytes() { return readBytes.get(); } }
package com.novoda.merlin; import com.novoda.merlin.registerable.Registerer; import com.novoda.merlin.registerable.bind.Bindable; import com.novoda.merlin.registerable.connection.Connectable; import com.novoda.merlin.registerable.disconnection.Disconnectable; import com.novoda.merlin.service.MerlinServiceBinder; public class Merlin { public static final String DEFAULT_ENDPOINT = "http: private final MerlinServiceBinder merlinServiceBinder; private final Registerer registerer; Merlin(MerlinServiceBinder merlinServiceBinder, Registerer registerer) { this.merlinServiceBinder = merlinServiceBinder; this.registerer = registerer; } public void setEndpoint(String endpoint) { merlinServiceBinder.setEndpoint(endpoint); } public void bind() { merlinServiceBinder.bindService(); } public void unbind() { merlinServiceBinder.unbind(); } public void registerConnectable(Connectable connectable) { registerer.registerConnectable(connectable); } public void registerDisconnectable(Disconnectable disconnectable) { registerer.registerDisconnectable(disconnectable); } public void registerBindable(Bindable bindable) { registerer.registerBindable(bindable); } public static class Builder extends MerlinBuilder { } }
package hudson.model; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.converters.collections.CollectionConverter; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import hudson.Util; import hudson.XmlFile; import hudson.util.HexBinaryConverter; import hudson.util.Iterators; import hudson.util.XStream2; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; /** * A file being tracked by Hudson. * * @author Kohsuke Kawaguchi */ @ExportedBean public class Fingerprint implements ModelObject { /** * Pointer to a {@link Build}. */ @ExportedBean(defaultVisibility=2) public static class BuildPtr { final String name; final int number; public BuildPtr(String name, int number) { this.name = name; this.number = number; } public BuildPtr(Run run) { this( run.getParent().getFullName(), run.getNumber() ); } /** * Gets {@link Job#getFullName() the full name of the job}. * <p> * Such job could be since then removed, * so there might not be a corresponding * {@link Job}. */ @Exported public String getName() { return name; } /** * Gets the {@link Job} that this pointer points to, * or null if such a job no longer exists. */ public AbstractProject getJob() { return Hudson.getInstance().getItemByFullName(name,AbstractProject.class); } /** * Gets the project build number. * <p> * Such {@link Run} could be since then * discarded. */ @Exported public int getNumber() { return number; } /** * Gets the {@link Job} that this pointer points to, * or null if such a job no longer exists. */ public Run getRun() { Job j = getJob(); if(j==null) return null; return j.getBuildByNumber(number); } private boolean isAlive() { return getRun()!=null; } /** * Returns true if {@link BuildPtr} points to the given run. */ public boolean is(Run r) { return r.getNumber()==number && r.getParent().getFullName().equals(name); } /** * Returns true if {@link BuildPtr} points to the given job. */ public boolean is(Job job) { return job.getFullName().equals(name); } } /** * Range of build numbers [start,end). Immutable. */ @ExportedBean(defaultVisibility=4) public static final class Range { final int start; final int end; public Range(int start, int end) { assert start<end; this.start = start; this.end = end; } @Exported public int getStart() { return start; } @Exported public int getEnd() { return end; } public boolean isSmallerThan(int i) { return end<=i; } public boolean isBiggerThan(int i) { return i<start; } public boolean includes(int i) { return start<=i && i<end; } public Range expandRight() { return new Range(start,end+1); } public Range expandLeft() { return new Range(start-1,end); } public boolean isAdjacentTo(Range that) { return this.end==that.start; } public String toString() { return "["+start+","+end+")"; } /** * Returns true if two {@link Range}s can't be combined into a single range. */ public boolean isIndependent(Range that) { return this.end<that.start ||that.end<this.start; } /** * Returns the {@link Range} that combines two ranges. */ public Range combine(Range that) { assert !isIndependent(that); return new Range( Math.min(this.start,that.start), Math.max(this.end ,that.end )); } } /** * Set of {@link Range}s. */ @ExportedBean(defaultVisibility=3) public static final class RangeSet { // sorted private final List<Range> ranges; public RangeSet() { this(new ArrayList<Range>()); } private RangeSet(List<Range> data) { this.ranges = data; } /** * List all numbers in this range set. */ public Iterable<Integer> listNumbers() { final List<Range> ranges = getRanges(); return new Iterable<Integer>() { public Iterator<Integer> iterator() { return new Iterators.FlattenIterator<Integer,Range>(ranges) { protected Iterator<Integer> expand(Range range) { return Iterators.sequence(range.start,range.end).iterator(); } }; } }; } /** * List all numbers in this range set in the descending order. */ public Iterable<Integer> listNumbersReverse() { final List<Range> ranges = getRanges(); return new Iterable<Integer>() { public Iterator<Integer> iterator() { return new Iterators.FlattenIterator<Integer,Range>(Iterators.reverse(ranges)) { protected Iterator<Integer> expand(Range range) { return Iterators.reverseSequence(range.start,range.end).iterator(); } }; } }; } /** * Gets all the ranges. */ @Exported public synchronized List<Range> getRanges() { return new ArrayList<Range>(ranges); } /** * Expands the range set to include the given value. * If the set already includes this number, this will be a no-op. */ public synchronized void add(int n) { for( int i=0; i<ranges.size(); i++ ) { Range r = ranges.get(i); if(r.includes(n)) return; // already included if(r.end==n) { ranges.set(i,r.expandRight()); checkCollapse(i); return; } if(r.start==n+1) { ranges.set(i,r.expandLeft()); checkCollapse(i-1); return; } if(r.isBiggerThan(n)) { // needs to insert a single-value Range ranges.add(i,new Range(n,n+1)); return; } } ranges.add(new Range(n,n+1)); } private void checkCollapse(int i) { if(i<0 || i==ranges.size()-1) return; Range lhs = ranges.get(i); Range rhs = ranges.get(i+1); if(lhs.isAdjacentTo(rhs)) { // collapsed Range r = new Range(lhs.start,rhs.end); ranges.set(i,r); ranges.remove(i+1); } } public synchronized boolean includes(int i) { for (Range r : ranges) { if(r.includes(i)) return true; } return false; } public synchronized void add(RangeSet that) { int lhs=0,rhs=0; while(lhs<this.ranges.size() && rhs<that.ranges.size()) { Range lr = this.ranges.get(lhs); Range rr = that.ranges.get(rhs); // no overlap if(lr.end<rr.start) { lhs++; continue; } if(rr.end<lr.start) { ranges.add(lhs,rr); lhs++; rhs++; continue; } // overlap. merge two Range m = lr.combine(rr); rhs++; // since ranges[lhs] is expanded, it might overlap with others in this.ranges while(lhs+1<this.ranges.size() && !m.isIndependent(this.ranges.get(lhs+1))) { m = m.combine(this.ranges.get(lhs+1)); this.ranges.remove(lhs+1); } this.ranges.set(lhs,m); } // if anything is left in that.ranges, add them all this.ranges.addAll(that.ranges.subList(rhs,that.ranges.size())); } public synchronized String toString() { StringBuffer buf = new StringBuffer(); for (Range r : ranges) { if(buf.length()>0) buf.append(','); buf.append(r); } return buf.toString(); } public synchronized boolean isEmpty() { return ranges.isEmpty(); } /** * Returns true if all the integers logically in this {@link RangeSet} * is smaller than the given integer. For example, {[1,3)} is smaller than 3, * but {[1,3),[100,105)} is not smaller than anything less than 105. * * Note that {} is smaller than any n. */ public synchronized boolean isSmallerThan(int n) { if(ranges.isEmpty()) return true; return ranges.get(ranges.size() - 1).isSmallerThan(n); } static final class ConverterImpl implements Converter { private final Converter collectionConv; // used to convert ArrayList in it public ConverterImpl(Converter collectionConv) { this.collectionConv = collectionConv; } public boolean canConvert(Class type) { return type==RangeSet.class; } public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { collectionConv.marshal( ((RangeSet)source).getRanges(), writer, context ); } public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) { return new RangeSet((List<Range>)(collectionConv.unmarshal(reader,context))); } } } private final Date timestamp; /** * Null if this fingerprint is for a file that's * apparently produced outside. */ private final BuildPtr original; private final byte[] md5sum; private final String fileName; /** * Range of builds that use this file keyed by a job full name. */ private final Hashtable<String,RangeSet> usages = new Hashtable<String,RangeSet>(); public Fingerprint(Run build, String fileName, byte[] md5sum) throws IOException { this.original = build==null ? null : new BuildPtr(build); this.md5sum = md5sum; this.fileName = fileName; this.timestamp = new Date(); save(); } /** * The first build in which this file showed up, * if the file looked like it's created there. * <p> * This is considered as the "source" of this file, * or the owner, in the sense that this project "owns" * this file. * * @return null * if the file is apparently created outside Hudson. */ @Exported public BuildPtr getOriginal() { return original; } public String getDisplayName() { return fileName; } /** * The file name (like "foo.jar" without path). */ @Exported public String getFileName() { return fileName; } /** * Gets the MD5 hash string. */ @Exported(name="hash") public String getHashString() { return Util.toHexString(md5sum); } /** * Gets the timestamp when this record is created. */ @Exported public Date getTimestamp() { return timestamp; } /** * Gets the string that says how long since this build has scheduled. * * @return * string like "3 minutes" "1 day" etc. */ public String getTimestampString() { long duration = System.currentTimeMillis()-timestamp.getTime(); return Util.getPastTimeString(duration); } /** * Gets the build range set for the given job name. * * <p> * These builds of this job has used this file. */ public RangeSet getRangeSet(String jobFullName) { RangeSet r = usages.get(jobFullName); if(r==null) r = new RangeSet(); return r; } public RangeSet getRangeSet(Job job) { return getRangeSet(job.getFullName()); } /** * Gets the sorted list of job names where this jar is used. */ public List<String> getJobs() { List<String> r = new ArrayList<String>(); r.addAll(usages.keySet()); Collections.sort(r); return r; } public Hashtable<String,RangeSet> getUsages() { return usages; } @ExportedBean(defaultVisibility=2) public static final class RangeItem { @Exported public final String name; @Exported public final RangeSet ranges; public RangeItem(String name, RangeSet ranges) { this.name = name; this.ranges = ranges; } } // this is for remote API @Exported(name="usage") public List<RangeItem> _getUsages() { List<RangeItem> r = new ArrayList<RangeItem>(); for (Entry<String, RangeSet> e : usages.entrySet()) r.add(new RangeItem(e.getKey(),e.getValue())); return r; } public synchronized void add(AbstractBuild b) throws IOException { add(b.getParent().getFullName(),b.getNumber()); } /** * Records that a build of a job has used this file. */ public synchronized void add(String jobFullName, int n) throws IOException { synchronized(usages) { RangeSet r = usages.get(jobFullName); if(r==null) { r = new RangeSet(); usages.put(jobFullName,r); } r.add(n); } save(); } /** * Returns true if any of the builds recorded in this fingerprint * is still retained. * * <p> * This is used to find out old fingerprint records that can be removed * without losing too much information. */ public synchronized boolean isAlive() { if(original!=null && original.isAlive()) return true; for (Entry<String,RangeSet> e : usages.entrySet()) { Job j = Hudson.getInstance().getItemByFullName(e.getKey(),Job.class); if(j==null) continue; int oldest = j.getFirstBuild().getNumber(); if(!e.getValue().isSmallerThan(oldest)) return true; } return false; } /** * Save the settings to a file. */ public synchronized void save() throws IOException { long start=0; if(logger.isLoggable(Level.FINE)) start = System.currentTimeMillis(); File file = getFingerprintFile(md5sum); getConfigFile(file).write(this); if(logger.isLoggable(Level.FINE)) logger.fine("Saving fingerprint "+file+" took "+(System.currentTimeMillis()-start)+"ms"); } public Api getApi() { return new Api(this); } /** * The file we save our configuration. */ private static XmlFile getConfigFile(File file) { return new XmlFile(XSTREAM,file); } /** * Determines the file name from md5sum. */ private static File getFingerprintFile(byte[] md5sum) { assert md5sum.length==16; return new File( Hudson.getInstance().getRootDir(), "fingerprints/"+ Util.toHexString(md5sum,0,1)+'/'+Util.toHexString(md5sum,1,1)+'/'+Util.toHexString(md5sum,2,md5sum.length-2)+".xml"); } /** * Loads a {@link Fingerprint} from a file in the image. */ /*package*/ static Fingerprint load(byte[] md5sum) throws IOException { return load(getFingerprintFile(md5sum)); } /*package*/ static Fingerprint load(File file) throws IOException { XmlFile configFile = getConfigFile(file); if(!configFile.exists()) return null; long start=0; if(logger.isLoggable(Level.FINE)) start = System.currentTimeMillis(); try { Fingerprint f = (Fingerprint) configFile.read(); if(logger.isLoggable(Level.FINE)) logger.fine("Loading fingerprint "+file+" took "+(System.currentTimeMillis()-start)+"ms"); return f; } catch (IOException e) { logger.log(Level.WARNING, "Failed to load "+configFile,e); throw e; } } private static final XStream XSTREAM = new XStream2(); static { XSTREAM.alias("fingerprint",Fingerprint.class); XSTREAM.alias("range",Range.class); XSTREAM.alias("ranges",RangeSet.class); XSTREAM.registerConverter(new HexBinaryConverter(),10); XSTREAM.registerConverter(new RangeSet.ConverterImpl( new CollectionConverter(XSTREAM.getClassMapper()) { protected Object createCollection(Class type) { return new ArrayList(); } } ),10); } private static final Logger logger = Logger.getLogger(Fingerprint.class.getName()); }
package com.twitter.elephantbird.mapreduce.io; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.IOException; import java.util.List; import com.google.protobuf.ByteString; import com.google.protobuf.CodedInputStream; import com.google.protobuf.DescriptorProtos; import com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type; import com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Label; import com.google.protobuf.Descriptors; import com.google.protobuf.DynamicMessage; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.twitter.elephantbird.util.Protobufs; import org.apache.hadoop.io.IOUtils; /** * This is a {@link DynamicMessage} equivalent of following protobuf : <pre> * * message SerializedBlock { * optional int32 version = 1; * optional string proto_class_name = 2; * repeated bytes proto_blobs = 3; * }; </pre> * * This protobuf is required for BinaryBlock format used to store to binary records. * See {@link BinaryBlockReader} and {@link BinaryBlockWriter}. The file layout * is described in a comment at the bottom of this file. The format is an alternative * to a SequenceFile. <p> * * The primary purpose of DynamicMessage is to avoid any dependence on * pre-generated protobuf classes, since generated files are not compatible between * protobuf versions (2.4.1 and 2.5.0).This class works with either of these * versions at runtime.<p> * * Developer Note: More documentation on protobuf fields and file format * is included at the bottom of this file. */ public class SerializedBlock { private final Message message; // use newInstance() to create a new message private SerializedBlock(Message message) { this.message = message; } public Message getMessage() { return message; } public int getVersion() { return (Integer) message.getField(versionDesc); } public String getProtoClassName() { return (String) message.getField(protoClassNameDesc); } public List<ByteString> getProtoBlobs() { return (List<ByteString>) message.getField(protoBlobsDesc); } public static SerializedBlock newInstance(String protoClassName, List<ByteString> protoBlobs) { return new SerializedBlock( DynamicMessage.newBuilder(messageDescriptor) .setField(versionDesc, Integer.valueOf(1)) .setField(protoClassNameDesc, protoClassName) .setField(protoBlobsDesc, protoBlobs) .build()); } public static SerializedBlock parseFrom(InputStream in, int maxSize) throws InvalidProtocolBufferException, IOException { // create a CodedInputStream so that protobuf can enforce the configured max size // instead of using the default which may not be large enough for this data CodedInputStream codedInput = CodedInputStream.newInstance(in); codedInput.setSizeLimit(maxSize); DynamicMessage.Builder messageBuilder = DynamicMessage.newBuilder(messageDescriptor) .mergeFrom(codedInput); // verify we've read to the end codedInput.checkLastTagWas(0); return new SerializedBlock(messageBuilder.build()); } public static SerializedBlock parseFrom(byte[] messageBuffer) throws InvalidProtocolBufferException { return new SerializedBlock( DynamicMessage.newBuilder(messageDescriptor) .mergeFrom(messageBuffer) .build()); } private static final Descriptors.Descriptor messageDescriptor; private static final Descriptors.FieldDescriptor versionDesc; private static final Descriptors.FieldDescriptor protoClassNameDesc; private static final Descriptors.FieldDescriptor protoBlobsDesc; static { // initialize messageDescriptor and the three field descriptors DescriptorProtos.FieldDescriptorProto version = DescriptorProtos.FieldDescriptorProto.newBuilder() .setName("version") .setNumber(1) .setType(Type.TYPE_INT32) .setLabel(Label.LABEL_OPTIONAL) .build(); DescriptorProtos.FieldDescriptorProto protoClassName = DescriptorProtos.FieldDescriptorProto.newBuilder() .setName("proto_class_name") .setNumber(2) .setType(Type.TYPE_STRING) .setLabel(Label.LABEL_OPTIONAL) .build(); DescriptorProtos.FieldDescriptorProto protoBlobs = DescriptorProtos.FieldDescriptorProto.newBuilder() .setName("proto_blobs") .setNumber(3) .setType(Type.TYPE_BYTES) .setLabel(Label.LABEL_REPEATED) .build(); try { messageDescriptor = Protobufs.makeMessageDescriptor( DescriptorProtos.DescriptorProto.newBuilder() .setName("SerializedBlock") .addField(version) .addField(protoClassName) .addField(protoBlobs) .build()); } catch (Descriptors.DescriptorValidationException e) { throw new RuntimeException(e); } versionDesc = messageDescriptor.findFieldByName("version"); protoClassNameDesc = messageDescriptor.findFieldByName("proto_class_name"); protoBlobsDesc = messageDescriptor.findFieldByName("proto_blobs"); } } /* Contents of old protobuf spec file block_storage.proto which included detailed documentation : package com.twitter.data.proto; message SerializedBlock { // The version of the block format we are writing. Always set to 1. optional int32 version = 1; // The class_name of the message, e.g. "com.twitter.data.proto.Tables.Status" optional string proto_class_name = 2; // A list of serialized byte blobs of the contained protocol buffers. // Generally there should be no more than 1000 or so blobs per block, // because all of them get parsed into memory at once during analysis. // The number of blobs per block can vary arbitrarily, and can even be // just 1 if necessary (somewhat space-inefficient). repeated bytes proto_blobs = 3; }; // The serialization format for all protobuf data consists of repeated sequences that look like // 16-byte GUID | 4-byte size, little-endian | that many bytes of a serialized SerializedBlock data structure // 16-byte GUID | 4-byte size, little-endian | that many bytes of a serialized SerializedBlock data structure // ... // 16-byte GUID | 4-byte size, little-endian | that many bytes of a serialized SerializedBlock data structure // The 16-byte GUID is ALWAYS the following: // 0x29, 0xd8, 0xd5, 0x06, 0x58, 0xcd, 0x4c, 0x29, 0xb2, 0xbc, 0x57, 0x99, 0x21, 0x71, 0xbd, 0xff // // Pseudocode for serializing the block is the following (approximately in Java): // SerializedBlock block = SerializedBlock.newBuilder().setVersion(1) // .setProtoClassName(Status.class.getName()) // .addProtoBlobs(status1.toByteString()) // .addProtoBlobs(status2.toByteString()) // .build(); // Now write to disk, with os being an OutputStream: // os.write(<bytes of the guid above>) // os.write(<raw little endian of block.getSerializedSize()) // os.write(block.toByteArray()); // // and repeat. // Note that the description above implies that all files start with the GUID. */
package org.lemurproject.galago.core.retrieval; import org.lemurproject.galago.core.index.Index; import org.lemurproject.galago.core.index.disk.DiskIndex; import org.lemurproject.galago.core.index.stats.*; import org.lemurproject.galago.core.parse.Document; import org.lemurproject.galago.core.parse.Document.DocumentComponents; import org.lemurproject.galago.core.retrieval.iterator.*; import org.lemurproject.galago.core.retrieval.processing.ProcessingModel; import org.lemurproject.galago.core.retrieval.processing.ScoringContext; import org.lemurproject.galago.core.retrieval.query.Node; import org.lemurproject.galago.core.retrieval.query.NodeType; import org.lemurproject.galago.core.retrieval.query.QueryType; import org.lemurproject.galago.core.retrieval.query.StructuredQuery; import org.lemurproject.galago.core.retrieval.traversal.Traversal; import org.lemurproject.galago.utility.CmpUtil; import org.lemurproject.galago.utility.Parameters; import java.io.IOException; import java.util.*; import java.util.logging.Logger; /** * The responsibility of the LocalRetrieval object is to provide a simpler * interface on top of the DiskIndex. Therefore, given a query or text string * representing a query, this object will perform the necessary transformations * to make it an executable object. * * 10/7/2010 - Modified for asynchronous execution * * @author trevor * @author irmarc * @author sjh */ public class LocalRetrieval implements Retrieval { protected final Logger logger = Logger.getLogger(this.getClass().getName()); protected Index index; protected FeatureFactory features; protected Parameters globalParameters; protected CachedRetrieval cache; protected List<Traversal> defaultTraversals; /** * One retrieval interacts with one index. Parameters dictate the behavior * during retrieval time, and selection of the appropriate feature factory. * Additionally, the supplied parameters will be passed forward to the * chosen feature factory. */ public LocalRetrieval(Index index) throws Exception { this(index, Parameters.create()); } public LocalRetrieval(String filename) throws Exception { this(filename, Parameters.create()); } public LocalRetrieval(String filename, Parameters parameters) throws Exception { this(new DiskIndex(filename), parameters); } public LocalRetrieval(Index index, Parameters parameters) throws Exception { this.globalParameters = parameters; setIndex(index); } protected void setIndex(Index indx) throws Exception { this.index = indx; features = new FeatureFactory(globalParameters); defaultTraversals = features.getTraversals(this); cache = null; if (this.globalParameters.get("cache", false)) { cache = new CachedRetrieval(this.globalParameters); } } /** * Closes the underlying index */ @Override public void close() throws IOException { index.close(); } /** * Returns some statistics about a particular index part -- vocab size, * number of entries, maximumDocCount of any indexed term, etc */ @Override public IndexPartStatistics getIndexPartStatistics(String partName) throws IOException { return index.getIndexPartStatistics(partName); } @Override public Parameters getGlobalParameters() { return this.globalParameters; } /* * { * <partName> : { <nodeName> : <iteratorClass>, stemming : false, ... }, * <partName> : { <nodeName> : <iteratorClass>, ... }, ... } */ @Override public Parameters getAvailableParts() throws IOException { Parameters p = Parameters.create(); for (String partName : index.getPartNames()) { Parameters inner = Parameters.create(); Map<String, NodeType> nodeTypes = index.getPartNodeTypes(partName); for (String nodeName : nodeTypes.keySet()) { inner.set(nodeName, nodeTypes.get(nodeName).getIteratorClass().getName()); } p.set(partName, inner); } return p; } public Index getIndex() { return index; } @Override public Document getDocument(String identifier, DocumentComponents p) throws IOException { return this.index.getDocument(identifier, p); } @Override public Map<String, Document> getDocuments(List<String> identifier, DocumentComponents p) throws IOException { return this.index.getDocuments(identifier, p); } /* * getArrayResults annotates a queue of scored documents returns an array * */ protected <T extends ScoredDocument> T[] getArrayResults(T[] results, String indexId) throws IOException { assert (results != null); // unfortunately, we can't make an array of type T in java if (results.length == 0) { return results; } for (int i = 0; i < results.length; i++) { results[i].source = indexId; results[i].rank = i + 1; } // this is to assign proper document names T[] byID = Arrays.copyOf(results, results.length); Arrays.sort(byID, new Comparator<T>() { @Override public int compare(T o1, T o2) { return CmpUtil.compare(o1.document, o2.document); } }); DataIterator<String> namesIterator = index.getNamesIterator(); ScoringContext sc = new ScoringContext(); for (T doc : byID) { namesIterator.syncTo(doc.document); sc.document = doc.document; if (doc.document == namesIterator.currentCandidate()) { doc.documentName = namesIterator.data(sc); } else { logger.warning("NAMES ITERATOR FAILED TO FIND DOCUMENT " + doc.document); doc.documentName = null; } } return results; } @Override public Results executeQuery(Node queryTree) throws Exception { return executeQuery(queryTree, Parameters.create()); } /** * Simple method to avoid boilerplate, but with some configuration. */ public Results transformAndExecuteQuery(Node queryTree, Parameters qp) { try { return executeQuery(transformQuery(queryTree, qp), qp); } catch (Exception e) { throw new RuntimeException(e); } } /** * Simple method to avoid boilerplate. */ public Results transformAndExecuteQuery(Node queryTree) { return transformAndExecuteQuery(queryTree, Parameters.create()); } // Based on the root of the tree, that dictates how we execute. @Override public Results executeQuery(Node queryTree, Parameters queryParams) throws Exception { ScoredDocument[] results; if (globalParameters.containsKey("processingModel")) { queryParams.set("processingModel", globalParameters.getString("processingModel")); } ProcessingModel pm = ProcessingModel.create(this, queryTree, queryParams); // get some results results = pm.execute(queryTree, queryParams); if (results == null) { results = new ScoredDocument[0]; } // Format and get names String indexId = this.globalParameters.get("indexId", "0"); List<ScoredDocument> rankedList = Arrays.asList(getArrayResults(results, indexId)); Results r = new Results(); r.inputQuery = queryTree; r.processingModel = pm.getClass(); r.scoredDocuments = rankedList; return r; } public BaseIterator createIterator(Parameters queryParameters, Node node) throws Exception { if (queryParameters.get("shareNodes", globalParameters.get("shareNodes", true))) { return createNodeMergedIterator(node, new HashMap<String, BaseIterator>()); } return createNodeMergedIterator(node, null); } public BaseIterator createNodeMergedIterator(Node node, Map<String, BaseIterator> queryIteratorCache) throws Exception { ArrayList<BaseIterator> internalIterators = new ArrayList<>(); BaseIterator iterator; // first check if this is a repeated node in this tree: if (queryIteratorCache != null && queryIteratorCache.containsKey(node.toString())) { iterator = queryIteratorCache.get(node.toString()); return iterator; } // second check if this node is cached if (cache != null && cache.isCached(node)) { iterator = cache.getCachedIterator(node); } else { // otherwise we need to create a new iterator // start by recursively creating children for (Node internalNode : node.getInternalNodes()) { BaseIterator internalIterator = createNodeMergedIterator(internalNode, queryIteratorCache); internalIterators.add(internalIterator); } iterator = index.getIterator(node); if (iterator == null) { iterator = features.getIterator(node, internalIterators); } } // we've created a new iterator - add to the cache for future nodes if (queryIteratorCache != null) { queryIteratorCache.put(node.toString(), iterator); } return iterator; } @Override public Node transformQuery(Node queryTree, Parameters queryParams) throws Exception { return transformQuery(defaultTraversals, queryTree, queryParams); } private Node transformQuery(List<Traversal> traversals, Node queryTree, Parameters queryParams) throws Exception { for (Traversal traversal : traversals) { //System.out.println("Before:"+traversal.getClass()); //System.out.println("Before:"+queryTree); queryTree = traversal.traverse(queryTree, queryParams); //System.out.println("After:"+traversal.getClass()); //System.out.println("After:"+queryTree); } return queryTree; } @Override public FieldStatistics getCollectionStatistics(String nodeString) throws Exception { // first parse the node Node root = StructuredQuery.parse(nodeString); return getCollectionStatistics(root); } @Override public FieldStatistics getCollectionStatistics(Node root) throws Exception { String rootString = root.toString(); if (cache != null && cache.cacheStats) { AggregateStatistic stat = cache.getCachedStatistic(rootString); if (stat != null && stat instanceof FieldStatistics) { return (FieldStatistics) stat; } } FieldStatistics s; // if you want passage statistics, you'll need a manual solution for now. ScoringContext sc = new ScoringContext(); BaseIterator structIterator = createIterator(Parameters.create(), root); // first check if this iterator is an aggregate iterator (has direct access to stats) if (CollectionAggregateIterator.class.isInstance(structIterator)) { s = ((CollectionAggregateIterator) structIterator).getStatistics(); } else if (structIterator instanceof LengthsIterator) { LengthsIterator iterator = (LengthsIterator) structIterator; s = new FieldStatistics(); s.fieldName = root.toString(); s.minLength = Integer.MAX_VALUE; while (!iterator.isDone()) { sc.document = iterator.currentCandidate(); if (iterator.hasMatch(sc)) { int len = iterator.length(sc); s.collectionLength += len; s.documentCount += 1; s.nonZeroLenDocCount += (len > 0) ? 1 : 0; s.maxLength = Math.max(s.maxLength, len); s.minLength = Math.min(s.minLength, len); } iterator.movePast(sc.document); } s.avgLength = (s.documentCount > 0) ? (double) s.collectionLength / (double) s.documentCount : 0; s.minLength = (s.documentCount > 0) ? s.minLength : 0; return s; } else { throw new IllegalArgumentException("Node " + root.toString() + " is not a lengths iterator."); } if (cache != null && cache.cacheStats) { cache.addToCache(rootString, s); } return s; } @Override public NodeStatistics getNodeStatistics(String nodeString) throws Exception { // first parse the node Node root = StructuredQuery.parse(nodeString); return getNodeStatistics(root); } @Override public NodeStatistics getNodeStatistics(Node root) throws Exception { String rootString = root.toString(); if (cache != null && cache.cacheStats) { AggregateStatistic stat = cache.getCachedStatistic(rootString); if (stat != null && stat instanceof NodeStatistics) { return (NodeStatistics) stat; } } NodeStatistics s; // if you want passage statistics, you'll need a manual solution for now. ScoringContext sc = new ScoringContext(); BaseIterator structIterator = createIterator(Parameters.create(), root); if (NodeAggregateIterator.class.isInstance(structIterator)) { s = ((NodeAggregateIterator) structIterator).getStatistics(); } else if (structIterator instanceof CountIterator) { s = new NodeStatistics(); // set up initial values s.node = root.toString(); s.nodeDocumentCount = 0; s.nodeFrequency = 0; s.maximumCount = 0; CountIterator iterator = (CountIterator) structIterator; while (!iterator.isDone()) { sc.document = iterator.currentCandidate(); if (iterator.hasMatch(sc)) { int c = iterator.count(sc); s.nodeFrequency += iterator.count(sc); s.maximumCount = Math.max(iterator.count(sc), s.maximumCount); s.nodeDocumentCount += (c > 0) ? 1 : 0; // positive counting } iterator.movePast(iterator.currentCandidate()); } return s; } else { // otherwise : throw new IllegalArgumentException("Node " + root.toString() + " is not a count iterator."); } if (cache != null && cache.cacheStats) { cache.addToCache(rootString, s); } return s; } @Override public NodeType getNodeType(Node node) throws Exception { NodeType nodeType = index.getNodeType(node); if (nodeType == null) { nodeType = features.getNodeType(node); } return nodeType; } @Override public QueryType getQueryType(Node node) throws Exception { if (node.getOperator().equals("text")) { return QueryType.UNKNOWN; } NodeType nodeType = getNodeType(node); Class outputClass = nodeType.getIteratorClass(); if (ScoreIterator.class.isAssignableFrom(outputClass) || ScoringFunctionIterator.class.isAssignableFrom(outputClass)) { return QueryType.RANKED; } else if (IndicatorIterator.class.isAssignableFrom(outputClass)) { return QueryType.BOOLEAN; } else if (CountIterator.class.isAssignableFrom(outputClass)) { return QueryType.COUNT; // } else if (LengthsIterator.class.isAssignableFrom(outputClass)) { // return QueryType.LENGTH; } else { return QueryType.RANKED; } } @Override public Integer getDocumentLength(Integer docid) throws IOException { return index.getLength(docid); } @Override public Integer getDocumentLength(String docname) throws IOException { return index.getLength(index.getIdentifier(docname)); } @Override public String getDocumentName(Integer docid) throws IOException { return index.getName(docid); } @Override public Long getDocumentId(String docname) throws IOException { return index.getIdentifier(docname); } public LengthsIterator getDocumentLengthsIterator() throws IOException { return index.getLengthsIterator(); } public List<Long> getDocumentIds(List<String> docnames) throws IOException { List<Long> internalDocBuffer = new ArrayList<>(); for (String name : docnames) { try { internalDocBuffer.add(index.getIdentifier(name)); } catch (Exception e) { // arrays NEED to be aligned for good error detection internalDocBuffer.add(-1L); } } return internalDocBuffer; } @Override public void addNodeToCache(Node node) throws Exception { if (cache != null) { cache.addToCache(node, this.createIterator(Parameters.create(), node)); } } @Override public void addAllNodesToCache(Node node) throws Exception { if (cache != null) { // recursivly add all nodes for (Node child : node.getInternalNodes()) { addAllNodesToCache(child); } cache.addToCache(node, this.createIterator(Parameters.create(), node)); } } @Override public String toString() { return "LocalRetrieval(" + index.getIndexPath() + ")"; } }
package info.tregmine.listeners; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.text.SimpleDateFormat; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.block.BlockState; import org.bukkit.block.DoubleChest; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryCreativeEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.inventory.InventoryInteractEvent; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryPickupItemEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.api.InventoryAccess; import info.tregmine.api.lore.Created; import info.tregmine.database.DAOException; import info.tregmine.database.IContext; import info.tregmine.database.IInventoryDAO; import static info.tregmine.database.IInventoryDAO.InventoryType; import static info.tregmine.database.IInventoryDAO.ChangeType; public class InventoryListener implements Listener { private Tregmine plugin; private Map<Location, ItemStack[]> openInventories; public InventoryListener(Tregmine instance) { this.plugin = instance; this.openInventories = new HashMap<>(); } @EventHandler public void onInventoryOpen(InventoryOpenEvent event) { if (!(event.getPlayer() instanceof Player)) { return; } TregminePlayer player = plugin.getPlayer((Player)event.getPlayer()); Inventory inv = event.getInventory(); InventoryHolder holder = inv.getHolder(); Location loc = null; if (holder instanceof BlockState) { BlockState block = (BlockState)holder; loc = block.getLocation(); } else if (holder instanceof DoubleChest) { DoubleChest block = (DoubleChest)holder; loc = block.getLocation(); } else { return; } ItemStack[] contents = inv.getContents(); ItemStack[] copy = new ItemStack[contents.length]; for (int i = 0; i < contents.length; i++) { if (contents[i] != null) { copy[i] = contents[i].clone(); } } openInventories.put(loc, contents); try (IContext ctx = plugin.createContext()) { IInventoryDAO invDAO = ctx.getInventoryDAO(); // Find inventory id, or create a new row if none exists int id = invDAO.getInventoryId(loc); if (id == -1) { id = invDAO.insertInventory(player, loc, InventoryType.BLOCK); } else { List<InventoryAccess> accessLog = invDAO.getAccessLog(id, 10); int others = 0; for (InventoryAccess access : accessLog) { if (access.getPlayerId() != player.getId()) { others++; } } if (others > 0 && player.hasFlag(TregminePlayer.Flags.CHEST_LOG)) { player.sendMessage(ChatColor.YELLOW + "Last accessed by:"); SimpleDateFormat dfm = new SimpleDateFormat("dd/MM/yy hh:mm:ss a"); int i = 0; for (InventoryAccess access : accessLog) { if (access.getPlayerId() != player.getId()) { if (i > 2) { break; } TregminePlayer p = plugin.getPlayerOffline(access.getPlayerId()); player.sendMessage(p.getChatName() + ChatColor.YELLOW + " on " + dfm.format(access.getTimestamp()) + "."); i++; } } } } // Insert into access log invDAO.insertAccessLog(player, id); } catch (DAOException e) { throw new RuntimeException(e); } } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { if (!(event.getPlayer() instanceof Player)) { return; } TregminePlayer player = plugin.getPlayer((Player)event.getPlayer()); Inventory inv = event.getInventory(); InventoryHolder holder = inv.getHolder(); Location loc = null; if (holder instanceof BlockState) { BlockState block = (BlockState)holder; loc = block.getLocation(); } else if (holder instanceof DoubleChest) { DoubleChest block = (DoubleChest)holder; loc = block.getLocation(); } else { return; } if (!openInventories.containsKey(loc)) { Tregmine.LOGGER.info("Inventory location not found."); return; } Tregmine.LOGGER.info(player.getRealName() + " closed inventory: " + "x=" + loc.getBlockX() + " " + "y=" + loc.getBlockY() + " " + "z=" + loc.getBlockZ()); ItemStack[] oldContents = openInventories.get(loc); ItemStack[] currentContents = inv.getContents(); assert oldContents.length == currentContents.length; try (IContext ctx = plugin.createContext()) { IInventoryDAO invDAO = ctx.getInventoryDAO(); // Find inventory id, or create a new row if none exists int id = invDAO.getInventoryId(loc); if (id == -1) { Tregmine.LOGGER.warning("Inventory id " + id + " not found!"); return; } // Store all changes for (int i = 0; i < oldContents.length; i++) { ItemStack a = oldContents[i]; ItemStack b = currentContents[i]; if (a == null && b == null) { continue; } if (a == null || b == null || !a.equals(b)) { Tregmine.LOGGER.info("Slot " + i + " changed. Was " + a + " and is " + b); // Removed if (a != null) { invDAO.insertChangeLog(player, id, i, a, ChangeType.REMOVE); } // Added if (b != null) { invDAO.insertChangeLog(player, id, i, b, ChangeType.ADD); } } } // Store contents invDAO.insertStacks(id, currentContents); } catch (DAOException e) { throw new RuntimeException(e); } openInventories.remove(loc); /*Player player = (Player) event.getPlayer(); if (player.getGameMode() == GameMode.CREATIVE) { for (ItemStack item : player.getInventory().getContents()) { if (item != null) { ItemMeta meta = item.getItemMeta(); List<String> lore = new ArrayList<String>(); lore.add(Created.CREATIVE.toColorString()); TregminePlayer p = this.plugin.getPlayer(player); lore.add(ChatColor.WHITE + "by: " + p.getChatName()); lore.add(ChatColor.WHITE + "Value: " + ChatColor.MAGIC + "0000" + ChatColor.RESET + ChatColor.WHITE + " Treg"); meta.setLore(lore); item.setItemMeta(meta); } } }*/ } /*@EventHandler public void onInventoryCreative(InventoryCreativeEvent event) { Tregmine.LOGGER.info("InventoryCreative"); Tregmine.LOGGER.info(event.getInventory().getHolder().toString()); }*/ }
package lucee.runtime.db; import java.sql.Connection; import java.sql.SQLException; import lucee.commons.lang.SystemOut; class DCStack { private Item item; private DataSource datasource; DCStack(DataSource datasource, String user, String pass) { this.datasource=datasource; } public void add(DatasourceConnection dc){ // make sure the connection is not already in stack, this can happen when the conn is released twice Item test = item; while(test!=null){ if(test.dc==dc) { SystemOut.print("a datasource connection was released twice!"); return; } test=test.prev; } item=new Item(item,dc); } public DatasourceConnection get(){ if(item==null) return null; DatasourceConnection rtn = item.dc; item=item.prev; try { if(!rtn.getConnection().isClosed()){ return rtn; } return get(); } catch (SQLException e) {} return null; } public boolean isEmpty(){ return item==null; } public int size(){ int count=0; Item i = item; while(i!=null){ count++; i=i.prev; } return count; } public int openConnections(){ int count=0; Item i = item; while(i!=null){ try { if(!i.dc.getConnection().isClosed())count++; } catch (SQLException e) {} i=i.prev; } return count; } class Item { private DatasourceConnection dc; private Item prev; private int count=1; public Item(Item item,DatasourceConnection dc) { this.prev=item; this.dc=dc; if(prev!=null)count=prev.count+1; } @Override public String toString(){ return "("+prev+")<-"+count; } } public synchronized void clear() { clear(item,null); } /** * * @param current * @param next * @param timeout timeout in seconds used to validate existing connections * @throws SQLException */ private void clear(Item current,Item next) { if(current==null) return; // timeout or closed if( current.dc.isTimeout() || current.dc.isLifecycleTimeout() || isClosedEL(current.dc.getConnection()) || Boolean.FALSE.equals(isValidEL(current.dc.getConnection()))) { // when timeout was reached but it is still open, close it if(!isClosedEL(current.dc.getConnection())){ try { current.dc.close(); } catch (SQLException e) {} } // remove this connection from chain if(next==null)item=current.prev; else { next.prev=current.prev; } clear(current.prev,next); } else clear(current.prev,current); } private boolean isClosedEL(Connection conn) { try { return conn.isClosed(); } catch (SQLException se) { datasource.getLog().error("Connection Pool", se); // in case of a exception we see this conn as useless and close the connection try { conn.close(); } catch (SQLException e) { datasource.getLog().error("Connection Pool", e); } return true; } } private Boolean isValidEL(Connection conn) { try { return conn.isValid(datasource.getNetworkTimeout())?Boolean.TRUE:Boolean.FALSE; } catch (Throwable t) { return null; } } }
/** * This is only generated once! It will never be overwritten. * You can (and have to!) safely modify it by hand. * TEMPLATE: SpringServiceImpl.vsl in andromda-spring cartridge * MODEL CLASS: AndroMDAModel::ctsms::org.phoenixctms.ctsms::service::shared::ToolsService * STEREOTYPE: Service */ package org.phoenixctms.ctsms.service.shared; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.TimeZone; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.hibernate.Cache; import org.hibernate.LockMode; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.phoenixctms.ctsms.adapt.ReminderEntityAdapter; import org.phoenixctms.ctsms.compare.EntityIDComparator; import org.phoenixctms.ctsms.domain.AlphaIdDao; import org.phoenixctms.ctsms.domain.Announcement; import org.phoenixctms.ctsms.domain.AnnouncementDao; import org.phoenixctms.ctsms.domain.AspDao; import org.phoenixctms.ctsms.domain.AspSubstanceDao; import org.phoenixctms.ctsms.domain.ContactDetailType; import org.phoenixctms.ctsms.domain.Course; import org.phoenixctms.ctsms.domain.CourseParticipationStatusEntry; import org.phoenixctms.ctsms.domain.Department; import org.phoenixctms.ctsms.domain.DepartmentDao; import org.phoenixctms.ctsms.domain.ECRFFieldDao; import org.phoenixctms.ctsms.domain.File; import org.phoenixctms.ctsms.domain.FileDao; import org.phoenixctms.ctsms.domain.InputField; import org.phoenixctms.ctsms.domain.InputFieldDao; import org.phoenixctms.ctsms.domain.InputFieldSelectionSetValueDao; import org.phoenixctms.ctsms.domain.InquiryDao; import org.phoenixctms.ctsms.domain.InventoryStatusEntry; import org.phoenixctms.ctsms.domain.JournalEntryDao; import org.phoenixctms.ctsms.domain.KeyPairDao; import org.phoenixctms.ctsms.domain.MaintenanceScheduleItem; import org.phoenixctms.ctsms.domain.MassMailRecipient; import org.phoenixctms.ctsms.domain.MassMailRecipientDao; import org.phoenixctms.ctsms.domain.Notification; import org.phoenixctms.ctsms.domain.NotificationDao; import org.phoenixctms.ctsms.domain.NotificationRecipient; import org.phoenixctms.ctsms.domain.NotificationRecipientDao; import org.phoenixctms.ctsms.domain.NotificationType; import org.phoenixctms.ctsms.domain.OpsCodeDao; import org.phoenixctms.ctsms.domain.Password; import org.phoenixctms.ctsms.domain.PasswordDao; import org.phoenixctms.ctsms.domain.Proband; import org.phoenixctms.ctsms.domain.ProbandContactDetailValue; import org.phoenixctms.ctsms.domain.ProbandContactDetailValueDao; import org.phoenixctms.ctsms.domain.ProbandDao; import org.phoenixctms.ctsms.domain.ProbandGroupDao; import org.phoenixctms.ctsms.domain.ProbandListEntryTagDao; import org.phoenixctms.ctsms.domain.ProbandStatusEntry; import org.phoenixctms.ctsms.domain.Staff; import org.phoenixctms.ctsms.domain.StaffCategory; import org.phoenixctms.ctsms.domain.StaffStatusEntry; import org.phoenixctms.ctsms.domain.TimelineEvent; import org.phoenixctms.ctsms.domain.TimelineEventDao; import org.phoenixctms.ctsms.domain.User; import org.phoenixctms.ctsms.domain.UserDao; import org.phoenixctms.ctsms.domain.VisitDao; import org.phoenixctms.ctsms.domain.VisitScheduleItem; import org.phoenixctms.ctsms.email.NotificationEmailSender; import org.phoenixctms.ctsms.email.NotificationMessageTemplateParameters; import org.phoenixctms.ctsms.enumeration.AuthenticationType; import org.phoenixctms.ctsms.enumeration.DBModule; import org.phoenixctms.ctsms.enumeration.EventImportance; import org.phoenixctms.ctsms.enumeration.FileModule; import org.phoenixctms.ctsms.enumeration.InputFieldType; import org.phoenixctms.ctsms.enumeration.JournalModule; import org.phoenixctms.ctsms.enumeration.RandomizationMode; import org.phoenixctms.ctsms.enumeration.RangePeriod; import org.phoenixctms.ctsms.enumeration.Sex; import org.phoenixctms.ctsms.enumeration.VariablePeriod; import org.phoenixctms.ctsms.exception.AuthenticationException; import org.phoenixctms.ctsms.exception.ServiceException; import org.phoenixctms.ctsms.security.Authenticator; import org.phoenixctms.ctsms.security.CryptoUtil; import org.phoenixctms.ctsms.security.PasswordPolicy; import org.phoenixctms.ctsms.util.AuthorisationExceptionCodes; import org.phoenixctms.ctsms.util.CheckIDUtil; import org.phoenixctms.ctsms.util.CommonUtil; import org.phoenixctms.ctsms.util.Compile; import org.phoenixctms.ctsms.util.CoreUtil; import org.phoenixctms.ctsms.util.DefaultSettings; import org.phoenixctms.ctsms.util.L10nUtil; import org.phoenixctms.ctsms.util.L10nUtil.Locales; import org.phoenixctms.ctsms.util.ServiceExceptionCodes; import org.phoenixctms.ctsms.util.ServiceUtil; import org.phoenixctms.ctsms.util.SettingCodes; import org.phoenixctms.ctsms.util.Settings; import org.phoenixctms.ctsms.util.Settings.Bundle; import org.phoenixctms.ctsms.util.SystemMessageCodes; import org.phoenixctms.ctsms.util.date.DateCalc; import org.phoenixctms.ctsms.util.date.DateInterval; import org.phoenixctms.ctsms.vo.AlphaIdVO; import org.phoenixctms.ctsms.vo.AnnouncementVO; import org.phoenixctms.ctsms.vo.AspSubstanceVO; import org.phoenixctms.ctsms.vo.AspVO; import org.phoenixctms.ctsms.vo.AuthenticationTypeVO; import org.phoenixctms.ctsms.vo.AuthenticationVO; import org.phoenixctms.ctsms.vo.CalendarWeekVO; import org.phoenixctms.ctsms.vo.DBModuleVO; import org.phoenixctms.ctsms.vo.EventImportanceVO; import org.phoenixctms.ctsms.vo.FileStreamOutVO; import org.phoenixctms.ctsms.vo.HolidayVO; import org.phoenixctms.ctsms.vo.InputFieldImageVO; import org.phoenixctms.ctsms.vo.InputFieldOutVO; import org.phoenixctms.ctsms.vo.InputFieldSelectionSetValueOutVO; import org.phoenixctms.ctsms.vo.InputFieldTypeVO; import org.phoenixctms.ctsms.vo.JournalModuleVO; import org.phoenixctms.ctsms.vo.LdapEntryVO; import org.phoenixctms.ctsms.vo.LightECRFFieldOutVO; import org.phoenixctms.ctsms.vo.LightInputFieldSelectionSetValueOutVO; import org.phoenixctms.ctsms.vo.LightInquiryOutVO; import org.phoenixctms.ctsms.vo.LightProbandListEntryTagOutVO; import org.phoenixctms.ctsms.vo.OpsCodeVO; import org.phoenixctms.ctsms.vo.PSFVO; import org.phoenixctms.ctsms.vo.PasswordInVO; import org.phoenixctms.ctsms.vo.PasswordOutVO; import org.phoenixctms.ctsms.vo.PasswordPolicyVO; import org.phoenixctms.ctsms.vo.ProbandGroupOutVO; import org.phoenixctms.ctsms.vo.RandomizationModeVO; import org.phoenixctms.ctsms.vo.RangeIntervalVO; import org.phoenixctms.ctsms.vo.SexVO; import org.phoenixctms.ctsms.vo.TimeZoneVO; import org.phoenixctms.ctsms.vo.TimelineEventOutVO; import org.phoenixctms.ctsms.vo.UserInVO; import org.phoenixctms.ctsms.vo.UserInheritedVO; import org.phoenixctms.ctsms.vo.UserOutVO; import org.phoenixctms.ctsms.vo.VariablePeriodVO; import org.phoenixctms.ctsms.vo.VisitOutVO; /** * @see org.phoenixctms.ctsms.service.shared.ToolsService */ public class ToolsServiceImpl extends ToolsServiceBase { private static HashSet<Long> createSendDepartmentStaffCategorySet(NotificationType notificationType) { Collection<StaffCategory> sendDepartmentStaffCategories = notificationType.getSendDepartmentStaffCategories(); HashSet<Long> result = new HashSet<Long>(sendDepartmentStaffCategories.size()); Iterator<StaffCategory> it = sendDepartmentStaffCategories.iterator(); while (it.hasNext()) { result.add(it.next().getId()); } return result; } private static ArrayList<Notification> filterNotifications(Collection<Notification> notifications, org.phoenixctms.ctsms.enumeration.NotificationType notificationType, Boolean obsolete) throws Exception { ArrayList<Notification> result = new ArrayList<Notification>(notifications); Iterator<Notification> notificationsIt = notifications.iterator(); while (notificationsIt.hasNext()) { Notification notification = notificationsIt.next(); if ((obsolete == null || notification.isObsolete() == obsolete) && notification.getType().getType().equals(notificationType)) { result.add(notification); } } return result; } // private static JournalEntry logSystemMessage(User user, UserOutVO userVO, Timestamp now, User modified, String systemMessageCode, Object result, Object original, // JournalEntryDao journalEntryDao) throws Exception { // if (user == null) { // return null; // return journalEntryDao.addSystemMessage(user, now, modified, systemMessageCode, new Object[] { CommonUtil.userOutVOToString(userVO) }, // new Object[] { CoreUtil.getSystemMessageCommentContent(result, original, !CommonUtil.getUseJournalEncryption(JournalModule.USER_JOURNAL, null)) }); private NotificationEmailSender notificationEmailSender; private Authenticator authenticator; private SessionFactory sessionFactory; private Collection<LdapEntryVO> completeLdapEntry(String nameInfix, AuthenticationType authMethod, Integer limit) throws Exception { if (!CommonUtil.isEmptyString(nameInfix) && authMethod != null) { try { return authenticator.search(authMethod, limit, nameInfix); } catch (Exception e) { throw new ServiceException(e.getMessage()); } } return new ArrayList<LdapEntryVO>(); } private LdapEntryVO getLdapEntry(AuthenticationVO auth, String username, AuthenticationType authMethod) throws Exception { if (username != null && username.length() > 0 && authMethod != null) { CoreUtil.setUser(auth, this.getUserDao()); // exception message localization List<LdapEntryVO> ldapEntries = null; try { ldapEntries = authenticator.searchAuth(authMethod, username); } catch (Exception e) { throw new ServiceException(e.getMessage()); } if (ldapEntries.size() == 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.ZERO_LDAP_USERS, username); } else if (ldapEntries.size() > 1) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MULTIPLE_LDAP_USERS, username, ldapEntries.size()); } return ldapEntries.get(0); } return null; } @Override protected Date handleAddIntervals(Date date, VariablePeriod period, Long explicitDays, int n) throws Exception { return DateCalc.addIntervals(date, period, explicitDays, n); } @Override protected RangeIntervalVO handleGetRangeInterval(Date date, RangePeriod period) throws Exception { DateInterval range = new DateInterval(date, period); RangeIntervalVO result = new RangeIntervalVO(); result.setStart(range.getStart()); result.setStop(range.getStop()); return result; } @Override protected UserOutVO handleAddUser(UserInVO newUser, PasswordInVO newPassword, String plainDepartmentPassword) throws Exception { UserDao userDao = this.getUserDao(); ServiceUtil.checkUsernameExists(newUser.getName(), userDao); ServiceUtil.checkUserInput(newUser, null, plainDepartmentPassword, this.getDepartmentDao(), this.getStaffDao(), this.getUserDao()); if (!PasswordPolicy.USER.isAdminIgnorePolicy()) { PasswordPolicy.USER.checkStrength(newPassword.getPassword()); } ServiceUtil.checkLogonLimitations(newPassword); PasswordDao passwordDao = this.getPasswordDao(); User user = userDao.userInVOToEntity(newUser); Timestamp now = new Timestamp(System.currentTimeMillis()); User modified = null; CoreUtil.modifyVersion(user, now, modified); ServiceUtil.createKeyPair(user, plainDepartmentPassword, this.getKeyPairDao()); user = userDao.create(user); ServiceUtil.createPassword(true, passwordDao.passwordInVOToEntity(newPassword), user, now, null, newPassword.getPassword(), plainDepartmentPassword, passwordDao, this.getJournalEntryDao()); UserOutVO result = userDao.toUserOutVO(user); ServiceUtil.logSystemMessage(user, result, now, modified, SystemMessageCodes.USER_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected void handleChangeDepartmentPassword(Long departmentId, String plainNewDepartmentPassword, String plainOldDepartmentPassword) throws Exception { Department department = CheckIDUtil.checkDepartmentId(departmentId, this.getDepartmentDao()); PasswordPolicy.DEPARTMENT.checkStrength(plainNewDepartmentPassword); if (!CryptoUtil.checkDepartmentPassword(department, plainOldDepartmentPassword)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.OLD_DEPARTMENT_PASSWORD_WRONG); } CryptoUtil.encryptDepartmentKey(department, CryptoUtil.decryptDepartmentKey(department, plainOldDepartmentPassword), plainNewDepartmentPassword); this.getDepartmentDao().update(department); KeyPairDao keyPairDao = this.getKeyPairDao(); PasswordDao passwordDao = this.getPasswordDao(); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); UserDao userDao = this.getUserDao(); Timestamp now = new Timestamp(System.currentTimeMillis()); Iterator<User> usersIt = department.getUsers().iterator(); while (usersIt.hasNext()) { User user = usersIt.next(); userDao.lock(user, LockMode.PESSIMISTIC_WRITE); ServiceUtil.updateUserDepartmentPassword(user, plainNewDepartmentPassword, plainOldDepartmentPassword, keyPairDao, passwordDao); ServiceUtil.logSystemMessage(user, userDao.toUserOutVO(user), now, null, SystemMessageCodes.DEPARTMENT_PASSWORD_CHANGED, null, null, journalEntryDao); } } @Override protected void handleClearHibernateCache() throws Exception { Session session = sessionFactory.getCurrentSession(); if (session != null) { session.clear(); // internal cache clear } Cache cache = sessionFactory.getCache(); if (cache != null) { cache.evictCollectionRegions(); cache.evictDefaultQueryRegion(); cache.evictEntityRegions(); cache.evictQueryRegions(); } } @Override protected void handleClearResourceBundleCache() throws Exception { ResourceBundle.clearCache(); Compile.clearResourceBundleCache(); } @Override protected void handleCleanJavaClasses() throws Exception { Compile.reset(); } @Override protected Collection<AlphaIdVO> handleCompleteAlphaId(AuthenticationVO auth, String textInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); AlphaIdDao alphaIdDao = this.getAlphaIdDao(); Collection alphaIds = alphaIdDao.findAlphaIds(textInfix, limit); alphaIdDao.toAlphaIdVOCollection(alphaIds); return alphaIds; } @Override protected Collection<String> handleCompleteAlphaIdCode(AuthenticationVO auth, String codePrefix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getAlphaIdDao().findAlphaIdCodes(codePrefix, limit); } @Override protected Collection<String> handleCompleteAlphaIdText(AuthenticationVO auth, String textInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getAlphaIdDao().findAlphaIdTexts(textInfix, limit); } @Override protected Collection<AspVO> handleCompleteAsp(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); AspDao aspDao = this.getAspDao(); Collection asps = aspDao.findAsps(nameInfix, limit); aspDao.toAspVOCollection(asps); return asps; } @Override protected Collection<String> handleCompleteAspAtcCodeCode(AuthenticationVO auth, String codePrefix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getAspAtcCodeDao().findAspAtcCodeCodes(codePrefix, limit); } @Override protected Collection<String> handleCompleteAspName(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getAspDao().findAspNames(nameInfix, limit); } @Override protected Collection<AspSubstanceVO> handleCompleteAspSubstance(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); AspSubstanceDao aspSubstanceDao = this.getAspSubstanceDao(); Collection substances = aspSubstanceDao.findAspSubstances(nameInfix, limit); aspSubstanceDao.toAspSubstanceVOCollection(substances); return substances; } @Override protected Collection<String> handleCompleteAspSubstanceName(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getAspSubstanceDao().findAspSubstanceNames(nameInfix, limit); } @Override protected Collection<String> handleCompleteBankCodeNumber(AuthenticationVO auth, String bankCodeNumberPrefix, String bicPrefix, String bankNameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getBankIdentificationDao().findBankCodeNumbers(bankCodeNumberPrefix, bicPrefix, bankNameInfix, limit); } @Override protected Collection<String> handleCompleteBankName(AuthenticationVO auth, String bankNameInfix, String bankCodeNumberPrefix, String bicPrefix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getBankIdentificationDao().findBankNames(bankCodeNumberPrefix, bicPrefix, bankNameInfix, limit); } @Override protected Collection<String> handleCompleteBic(AuthenticationVO auth, String bicPrefix, String bankCodeNumberPrefix, String bankNameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getBankIdentificationDao().findBics(bankCodeNumberPrefix, bicPrefix, bankNameInfix, limit); } @Override protected Collection<String> handleCompleteCityName(AuthenticationVO auth, String cityNameInfix, String countryNameInfix, String zipCodePrefix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getZipDao().findCityNames(countryNameInfix, zipCodePrefix, cityNameInfix, limit); } @Override protected Collection<String> handleCompleteCountryName(AuthenticationVO auth, String countryNameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getCountryDao().findCountryNames(countryNameInfix, limit); } @Override protected Collection<LightECRFFieldOutVO> handleCompleteEcrfField(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); ECRFFieldDao ecrfFieldDao = this.getECRFFieldDao(); Collection ecrfFields = ecrfFieldDao.findAllSorted(nameInfix, limit); ecrfFieldDao.toLightECRFFieldOutVOCollection(ecrfFields); return ecrfFields; } @Override protected Collection<InputFieldOutVO> handleCompleteEcrfFieldInputField(AuthenticationVO auth, String fieldNameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); InputFieldDao inputFieldDao = this.getInputFieldDao(); Collection inputFields = inputFieldDao.findUsedByEcrfFieldsSorted(fieldNameInfix, limit); inputFieldDao.toInputFieldOutVOCollection(inputFields); return inputFields; } @Override protected Collection<LightInputFieldSelectionSetValueOutVO> handleCompleteEcrfFieldInputFieldSelectionSetValue(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); InputFieldSelectionSetValueDao selectionSetValueDao = this.getInputFieldSelectionSetValueDao(); Collection selectionSetValues = selectionSetValueDao.findUsedByEcrfFieldsSorted(nameInfix, limit); selectionSetValueDao.toLightInputFieldSelectionSetValueOutVOCollection(selectionSetValues); return selectionSetValues; } @Override protected Collection<String> handleCompleteIcdSystBlockPreferredRubricLabel( AuthenticationVO auth, String preferredRubricLabelInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getIcdSystBlockDao().findBlockPreferredRubricLabels(preferredRubricLabelInfix, limit); } @Override protected Collection<String> handleCompleteIcdSystCategoryPreferredRubricLabel( AuthenticationVO auth, String preferredRubricLabelInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getIcdSystCategoryDao().findCategoryPreferredRubricLabels(preferredRubricLabelInfix, limit); } @Override protected Collection<InputFieldSelectionSetValueOutVO> handleCompleteInputFieldSelectionSetValue(AuthenticationVO auth, String nameInfix, Long inputFieldId, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); // no check for inputFieldId for performance reasons... InputFieldSelectionSetValueDao inputFieldSelectionSetValueDao = this.getInputFieldSelectionSetValueDao(); Collection selectionSetValues = inputFieldSelectionSetValueDao.findSelectionSetValues(inputFieldId, nameInfix, limit); inputFieldSelectionSetValueDao.toInputFieldSelectionSetValueOutVOCollection(selectionSetValues); return selectionSetValues; } @Override protected Collection<String> handleCompleteInputFieldSelectionSetValueValue(AuthenticationVO auth, String valueInfix, Long inputFieldId, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); // no check for inputFieldId for performance reasons... return this.getInputFieldSelectionSetValueDao().findValues(inputFieldId, valueInfix, limit); } @Override protected Collection<String> handleCompleteInputFieldTextValue( AuthenticationVO auth, String textValueInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getInputFieldValueDao().findTextValues(textValueInfix, limit); } @Override protected Collection<LightInquiryOutVO> handleCompleteInquiry(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); InquiryDao inquiryDao = this.getInquiryDao(); Collection inquiries = inquiryDao.findAllSorted(nameInfix, limit); inquiryDao.toLightInquiryOutVOCollection(inquiries); return inquiries; } @Override protected Collection<InputFieldOutVO> handleCompleteInquiryInputField(AuthenticationVO auth, String fieldNameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); InputFieldDao inputFieldDao = this.getInputFieldDao(); Collection inputFields = inputFieldDao.findUsedByInquiriesSorted(fieldNameInfix, limit); inputFieldDao.toInputFieldOutVOCollection(inputFields); return inputFields; } @Override protected Collection<TimelineEventOutVO> handleCompleteTimelineEvent(AuthenticationVO auth, String titleInfix, Long trialId, Integer maxInstances, Integer maxParentDepth, Integer maxChildrenDepth, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); // no check for trialId ... TimelineEventDao timelineEventDao = this.getTimelineEventDao(); Collection timelineEvents = timelineEventDao.findTimelineEvents(trialId, titleInfix, limit); ArrayList<TimelineEventOutVO> result = new ArrayList<TimelineEventOutVO>(timelineEvents.size()); Iterator<TimelineEvent> timelineEventsIt = timelineEvents.iterator(); while (timelineEventsIt.hasNext()) { result.add(timelineEventDao.toTimelineEventOutVO(timelineEventsIt.next(), maxInstances, maxParentDepth, maxChildrenDepth)); } return result; } @Override protected Collection<ProbandGroupOutVO> handleCompleteProbandGroup(AuthenticationVO auth, String tokenInfix, String titleInfix, Long trialId, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); // no check for trialId ... ProbandGroupDao probandGroupDao = this.getProbandGroupDao(); Collection probandGroups = probandGroupDao.findProbandGroups(trialId, tokenInfix, titleInfix, limit); probandGroupDao.toProbandGroupOutVOCollection(probandGroups); return probandGroups; } @Override protected Collection<VisitOutVO> handleCompleteVisit(AuthenticationVO auth, String tokenInfix, String titleInfix, Long trialId, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); // no check for trialId ... VisitDao visitDao = this.getVisitDao(); Collection visits = visitDao.findVisits(trialId, tokenInfix, titleInfix, limit); visitDao.toVisitOutVOCollection(visits); return visits; } @Override protected Collection<LightInputFieldSelectionSetValueOutVO> handleCompleteInquiryInputFieldSelectionSetValue(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); InputFieldSelectionSetValueDao selectionSetValueDao = this.getInputFieldSelectionSetValueDao(); Collection selectionSetValues = selectionSetValueDao.findUsedByInquiriesSorted(nameInfix, limit); selectionSetValueDao.toLightInputFieldSelectionSetValueOutVOCollection(selectionSetValues); return selectionSetValues; } @Override protected Collection<LdapEntryVO> handleCompleteLdapEntry1(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return completeLdapEntry(nameInfix, AuthenticationType.LDAP1, limit); } @Override protected Collection<LdapEntryVO> handleCompleteLdapEntry2(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return completeLdapEntry(nameInfix, AuthenticationType.LDAP2, limit); } @Override protected Collection<String> handleCompleteMedicationDoseUnit(AuthenticationVO auth, String doseUnitPrefix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getMedicationDao().findDoseUnits(doseUnitPrefix, limit); } @Override protected Collection<OpsCodeVO> handleCompleteOpsCode(AuthenticationVO auth, String textInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); OpsCodeDao opsCodeDao = this.getOpsCodeDao(); Collection opsCodes = opsCodeDao.findOpsCodes(textInfix, limit); opsCodeDao.toOpsCodeVOCollection(opsCodes); return opsCodes; } @Override protected Collection<String> handleCompleteOpsCodeCode(AuthenticationVO auth, String codePrefix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getOpsCodeDao().findOpsCodeCodes(codePrefix, limit); } @Override protected Collection<String> handleCompleteOpsCodeText(AuthenticationVO auth, String textInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getOpsCodeDao().findOpsCodeTexts(textInfix, limit); } @Override protected Collection<String> handleCompleteOpsSystBlockPreferredRubricLabel( AuthenticationVO auth, String preferredRubricLabelInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getOpsSystBlockDao().findBlockPreferredRubricLabels(preferredRubricLabelInfix, limit); } @Override protected Collection<String> handleCompleteOpsSystCategoryPreferredRubricLabel( AuthenticationVO auth, String preferredRubricLabelInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getOpsSystCategoryDao().findCategoryPreferredRubricLabels(preferredRubricLabelInfix, limit); } @Override protected Collection<LightProbandListEntryTagOutVO> handleCompleteProbandListEntryTag(AuthenticationVO auth, String nameInfix, Long trialId, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); // no check for trialId ... ProbandListEntryTagDao listEntryTagDao = this.getProbandListEntryTagDao(); Collection tags = listEntryTagDao.findListEntryTags(trialId, nameInfix, limit); listEntryTagDao.toLightProbandListEntryTagOutVOCollection(tags); return tags; } @Override protected Collection<InputFieldOutVO> handleCompleteProbandListEntryTagInputField(AuthenticationVO auth, String fieldNameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); InputFieldDao inputFieldDao = this.getInputFieldDao(); Collection inputFields = inputFieldDao.findUsedByListEntryTagsSorted(fieldNameInfix, limit); inputFieldDao.toInputFieldOutVOCollection(inputFields); return inputFields; } @Override protected Collection<LightInputFieldSelectionSetValueOutVO> handleCompleteProbandListEntryTagInputFieldSelectionSetValue(AuthenticationVO auth, String nameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); InputFieldSelectionSetValueDao selectionSetValueDao = this.getInputFieldSelectionSetValueDao(); Collection selectionSetValues = selectionSetValueDao.findUsedByListEntryTagsSorted(nameInfix, limit); selectionSetValueDao.toLightInputFieldSelectionSetValueOutVOCollection(selectionSetValues); return selectionSetValues; } @Override protected Collection<String> handleCompleteStreetName(AuthenticationVO auth, String streetNameInfix, String countryName, String zipCode, String cityName, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getStreetDao().findStreetNames(countryName, zipCode, cityName, streetNameInfix, limit); } @Override protected Collection<String> handleCompleteSystemMessageCode(AuthenticationVO auth, String systemMessageCodeInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); ArrayList<String> result = new ArrayList<String>(); if (limit == null) { limit = Settings.getIntNullable(SettingCodes.SYSTEM_MESSAGE_CODE_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS, DefaultSettings.SYSTEM_MESSAGE_CODE_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT); } Pattern systemMessageCodeRegex = null; if (!CommonUtil.isEmptyString(systemMessageCodeInfix)) { systemMessageCodeRegex = CommonUtil.createSqlLikeRegexp(CommonUtil.SQL_LIKE_PERCENT_WILDCARD + systemMessageCodeInfix + CommonUtil.SQL_LIKE_PERCENT_WILDCARD, true); } Iterator<String> codesIt = CoreUtil.SYSTEM_MESSAGE_CODES.iterator(); while (codesIt.hasNext() && (limit == null || result.size() < limit)) { // no trie for searching 300 entries String code = codesIt.next(); if (systemMessageCodeRegex == null || systemMessageCodeRegex.matcher(code).find()) { result.add(code); } } return result; } @Override protected Collection<TimeZoneVO> handleCompleteTimeZone(AuthenticationVO auth, String nameInfix, Integer limit) { CoreUtil.setUser(auth, this.getUserDao()); if (nameInfix != null) { nameInfix = nameInfix.toLowerCase(); } if (limit == null) { limit = Settings.getIntNullable(SettingCodes.TIMEZONE_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS, DefaultSettings.TIMEZONE_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT); } ArrayList<TimeZone> timeZones = CoreUtil.getTimeZones(); ArrayList<TimeZoneVO> result = new ArrayList<TimeZoneVO>(timeZones.size()); Iterator<TimeZone> it = timeZones.iterator(); Locale userLocale = L10nUtil.getLocale(Locales.USER); while (it.hasNext() && (limit == null || result.size() < limit)) { TimeZone timeZone = it.next(); TimeZoneVO timeZoneVO = new TimeZoneVO(); timeZoneVO.setTimeZoneID(CommonUtil.timeZoneToString(timeZone)); timeZoneVO.setName(CommonUtil.timeZoneToDisplayString(timeZone, userLocale)); if (CommonUtil.isEmptyString(nameInfix) || timeZoneVO.getName().toLowerCase().contains(nameInfix) || timeZoneVO.getTimeZoneID().toLowerCase().contains(nameInfix)) { timeZoneVO.setRawOffset(timeZone.getRawOffset()); result.add(timeZoneVO); } } return result; } @Override protected Collection<String> handleCompleteTitle(AuthenticationVO auth, String titlePrefix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getTitleDao().findTitles(titlePrefix, limit); } @Override protected Collection<String> handleCompleteZipCode(AuthenticationVO auth, String zipCodePrefix, String countryNameInfix, String cityNameInfix, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getZipDao().findZipCodes(countryNameInfix, zipCodePrefix, cityNameInfix, limit); } @Override protected Collection<String> handleCompleteZipCodeByStreetName(AuthenticationVO auth, String zipCodePrefix, String countryName, String cityName, String streetName, Integer limit) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return this.getStreetDao().findZipCodes(countryName, zipCodePrefix, cityName, streetName, limit); } @Override protected long handleDeleteProbands(Long departmentId, PSFVO psf) throws Exception { if (departmentId != null) { CheckIDUtil.checkDepartmentId(departmentId, this.getDepartmentDao()); } Date today = new Date(); ProbandDao probandDao = this.getProbandDao(); long count = 0; final HashMap<Long, Long> countMap = new HashMap<Long, Long>(); Iterator<Proband> toBeAutoDeletedIt = this.getProbandDao().findToBeAutoDeleted(today, departmentId, null, null, null, true, true, psf).iterator(); while (toBeAutoDeletedIt.hasNext()) { Proband proband = toBeAutoDeletedIt.next(); Long probandDepartmentId = proband.getDepartment().getId(); ServiceUtil.removeProband(proband, null, true, null, new Timestamp(System.currentTimeMillis()), probandDao, this.getProbandContactParticularsDao(), this.getAnimalContactParticularsDao(), this.getJournalEntryDao(), this.getNotificationDao(), this.getNotificationRecipientDao(), this.getProbandTagValueDao(), this.getProbandContactDetailValueDao(), this.getProbandAddressDao(), this.getProbandStatusEntryDao(), this.getDiagnosisDao(), this.getProcedureDao(), this.getMedicationDao(), this.getInventoryBookingDao(), this.getMoneyTransferDao(), this.getBankAccountDao(), this.getProbandListStatusEntryDao(), this.getProbandListEntryDao(), this.getProbandListEntryTagValueDao(), this.getInputFieldValueDao(), this.getInquiryValueDao(), this.getECRFFieldValueDao(), this.getECRFFieldStatusEntryDao(), this.getSignatureDao(), this.getECRFStatusEntryDao(), this.getMassMailRecipientDao(), this.getJobDao(), this.getFileDao()); if (countMap.containsKey(probandDepartmentId)) { countMap.put(probandDepartmentId, countMap.get(probandDepartmentId) + 1l); } else { countMap.put(probandDepartmentId, 1l); } count++; } if (count > 0) { NotificationDao notificationDao = this.getNotificationDao(); DepartmentDao departmentDao = this.getDepartmentDao(); Iterator<Long> departmentIt = countMap.keySet().iterator(); while (departmentIt.hasNext()) { final Long probandDepartmentId = departmentIt.next(); Map messageParameters = CoreUtil.createEmptyTemplateModel(); messageParameters.put(NotificationMessageTemplateParameters.NUMBER_OF_PROBANDS_DELETED, countMap.get(probandDepartmentId).toString()); notificationDao.addNotification(departmentDao.load(probandDepartmentId), today, messageParameters); } } return count; } @Override protected String handleGetAllowedFileExtensionsPattern(FileModule module, Boolean image) throws Exception { Collection<String> fileNameExtensions = this.getMimeTypeDao().findFileNameExtensions(module, image); StringBuilder result = new StringBuilder(); String delimiter; if (CommonUtil.FILE_EXTENSION_REGEXP_MODE) { result.append("/(\\.|\\/)("); delimiter = "|"; } else { delimiter = ";"; } HashSet<String> dupeCheck = new HashSet<String>(); boolean first = true; Iterator<String> it = fileNameExtensions.iterator(); while (it.hasNext()) { String fileNameExtensionsString = it.next(); if (fileNameExtensionsString != null && fileNameExtensionsString.length() > 0) { if (CommonUtil.FILE_EXTENSION_REGEXP_MODE) { if (dupeCheck.add(fileNameExtensionsString)) { if (first) { first = false; } else { result.append(delimiter); } result.append("("); result.append(fileNameExtensionsString); result.append(")"); try { Pattern.compile(result.toString() + ")$/"); } catch (PatternSyntaxException e) { throw L10nUtil.initServiceException(ServiceExceptionCodes.INVALID_REGEXP_PATTERN_FROM_FILE_EXTENSION, fileNameExtensionsString, e.getMessage()); } } } else { String[] fileNameExtensionsArray = fileNameExtensionsString.split(java.util.regex.Pattern.quote(delimiter), -1); for (int i = 0; i < fileNameExtensionsArray.length; i++) { if (fileNameExtensionsArray[i].length() == 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.FILE_EXTENSION_ZERO_LENGTH); } else if (!CommonUtil.FILE_EXTENSION_PATTERN_REGEXP.matcher(fileNameExtensionsArray[i]).find()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.INVALID_FILE_EXTENSION, fileNameExtensionsArray[i]); } else if (dupeCheck.add(fileNameExtensionsArray[i])) { if (first) { first = false; } else { result.append(delimiter); } result.append(fileNameExtensionsArray[i]); } } } } else { throw L10nUtil.initServiceException(ServiceExceptionCodes.FILE_EXTENSIONS_REQUIRED); } } if (dupeCheck.size() == 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.NO_MIME_TYPES_OR_FILE_EXTENSIONS); } if (CommonUtil.FILE_EXTENSION_REGEXP_MODE) { result.append(")$/"); } return result.toString(); } @Override protected AnnouncementVO handleGetAnnouncement() throws Exception { AnnouncementDao announcementDao = this.getAnnouncementDao(); Announcement announcement = announcementDao.getAnnouncement(); if (announcement != null) { return announcementDao.toAnnouncementVO(announcement); } return null; } @Override protected CalendarWeekVO handleGetCalendarWeek(Date date) throws Exception { return DateCalc.getCalendarWeek(date); } @Override protected String handleGetCurrencySymbol() throws Exception { return Settings.getString(SettingCodes.CURRENCY_SYMBOL, Bundle.SETTINGS, DefaultSettings.CURRENCY_SYMBOL); } @Override protected String handleGetDefaultLocale() throws Exception { return CommonUtil.localeToString(Locale.getDefault()); } @Override protected String handleGetDefaultTimeZone() throws Exception { return CommonUtil.timeZoneToString(TimeZone.getDefault()); } @Override protected String handleGetEmailDomainName() throws Exception { return Settings.getEmailDomainName(); } @Override protected Collection<HolidayVO> handleGetHolidays(AuthenticationVO auth, Date from, Date to, Boolean holiday) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return DateCalc.getHolidays(from, to, holiday, this.getHolidayDao()); } @Override protected String handleGetHttpBaseUrl() throws Exception { return Settings.getHttpBaseUrl(); } @Override protected String handleGetHttpDomainName() throws Exception { return Settings.getHttpDomainName(); } @Override protected String handleGetHttpHost() throws Exception { return Settings.getHttpHost(); } @Override protected String handleGetHttpScheme() throws Exception { return Settings.getHttpScheme(); } @Override protected InputFieldImageVO handleGetInputFieldImage(Long inputFieldId) throws Exception { InputFieldDao inputFieldDao = this.getInputFieldDao(); InputField inputField = CheckIDUtil.checkInputFieldId(inputFieldId, inputFieldDao); return inputFieldDao.toInputFieldImageVO(inputField); } @Override protected Integer handleGetInputFieldImageUploadSizeLimit() throws Exception { return Settings.getIntNullable(SettingCodes.INPUT_FIELD_IMAGE_SIZE_LIMIT, Bundle.SETTINGS, DefaultSettings.INPUT_FIELD_IMAGE_SIZE_LIMIT); } @Override protected String handleGetInstanceName() throws Exception { return Settings.getInstanceName(); } @Override protected LdapEntryVO handleGetLdapEntry1(AuthenticationVO auth, String username) throws Exception { return getLdapEntry(auth, username, AuthenticationType.LDAP1); } @Override protected LdapEntryVO handleGetLdapEntry2(AuthenticationVO auth, String username) throws Exception { return getLdapEntry(auth, username, AuthenticationType.LDAP2); } @Override protected DBModuleVO handleGetLocalizedDBModule(AuthenticationVO auth, DBModule module) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return L10nUtil.createDBModuleVO(Locales.USER, module); } @Override protected EventImportanceVO handleGetLocalizedEventImportance(AuthenticationVO auth, EventImportance importance) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return L10nUtil.createEventImportanceVO(Locales.USER, importance); } @Override protected AuthenticationTypeVO handleGetLocalizedAuthenticationType(AuthenticationVO auth, AuthenticationType authMethod) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return L10nUtil.createAuthenticationTypeVO(Locales.USER, authMethod); } @Override protected InputFieldTypeVO handleGetLocalizedInputFieldType(AuthenticationVO auth, InputFieldType fieldType) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return L10nUtil.createInputFieldTypeVO(Locales.USER, fieldType); } @Override protected JournalModuleVO handleGetLocalizedJournalModule(AuthenticationVO auth, JournalModule module) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return L10nUtil.createJournalModuleVO(Locales.USER, module); } @Override protected RandomizationModeVO handleGetLocalizedRandomizationMode(AuthenticationVO auth, RandomizationMode mode) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return L10nUtil.createRandomizationModeVO(Locales.USER, mode); } @Override protected SexVO handleGetLocalizedSex(AuthenticationVO auth, Sex sex) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return L10nUtil.createSexVO(Locales.USER, sex); } @Override protected VariablePeriodVO handleGetLocalizedVariablePeriod(AuthenticationVO auth, VariablePeriod period) throws Exception { CoreUtil.setUser(auth, this.getUserDao()); return L10nUtil.createVariablePeriodVO(Locales.USER, period); } @Override protected PasswordInVO handleGetNewPassword(AuthenticationVO auth) throws Exception { authenticator.authenticate(auth, false); PasswordInVO newPassword = new PasswordInVO(); ServiceUtil.applyLogonLimitations(newPassword); newPassword.setPassword(PasswordPolicy.USER.getDummyPassword()); return newPassword; } @Override protected PasswordPolicyVO handleGetPasswordPolicy(AuthenticationVO auth) throws Exception { authenticator.authenticate(auth, false); return PasswordPolicy.USER.getPasswordPolicyVO(); } @Override protected Integer handleGetProbandImageUploadSizeLimit() throws Exception { return Settings.getIntNullable(SettingCodes.PROBAND_IMAGE_SIZE_LIMIT, Bundle.SETTINGS, DefaultSettings.PROBAND_IMAGE_SIZE_LIMIT); } @Override protected FileStreamOutVO handleGetPublicFileStream(Long fileId) throws Exception { FileDao fileDao = this.getFileDao(); File file = CheckIDUtil.checkFileId(fileId, fileDao); if (CommonUtil.getUseFileEncryption(file.getModule())) { throw L10nUtil.initAuthorisationException(AuthorisationExceptionCodes.ENCRYPTED_FILE, fileId.toString()); } if (!file.isPublicFile()) { throw L10nUtil.initAuthorisationException(AuthorisationExceptionCodes.FILE_NOT_PUBLIC, fileId.toString()); } FileStreamOutVO result = fileDao.toFileStreamOutVO(file); return result; } @Override protected Integer handleGetStaffImageUploadSizeLimit() throws Exception { return Settings.getIntNullable(SettingCodes.STAFF_IMAGE_SIZE_LIMIT, Bundle.SETTINGS, DefaultSettings.STAFF_IMAGE_SIZE_LIMIT); } @Override protected Integer handleGetUploadSizeLimit() throws Exception { if (Settings.getBoolean(SettingCodes.USE_EXTERNAL_FILE_DATA_DIR, Bundle.SETTINGS, DefaultSettings.USE_EXTERNAL_FILE_DATA_DIR)) { return Settings.getIntNullable(SettingCodes.EXTERNAL_FILE_SIZE_LIMIT, Bundle.SETTINGS, DefaultSettings.EXTERNAL_FILE_SIZE_LIMIT); } else { return Settings.getIntNullable(SettingCodes.EXTERNAL_FILE_CONTENT_SIZE_LIMIT, Bundle.SETTINGS, DefaultSettings.EXTERNAL_FILE_CONTENT_SIZE_LIMIT); } } @Override protected boolean handleIsHoliday(Date date) throws Exception { return DateCalc.isHoliday(date, this.getHolidayDao()); } @Override protected boolean handleIsStreamUploadEnabled() throws Exception { return Settings.getBoolean(SettingCodes.USE_EXTERNAL_FILE_DATA_DIR, Bundle.SETTINGS, DefaultSettings.USE_EXTERNAL_FILE_DATA_DIR); } @Override protected boolean handleIsTrustedHost(String host) throws Exception { return CoreUtil.checkHostIp(host); } @Override protected PasswordOutVO handleLogon(AuthenticationVO auth) throws Exception { Password lastPassword = null; User user = null; Timestamp now = null; PasswordDao passwordDao = this.getPasswordDao(); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); PasswordOutVO lastPasswordVO; UserInheritedVO userVO; try { lastPassword = authenticator.authenticate(auth, true); user = lastPassword.getUser(); now = lastPassword.getLastSuccessfulLogonTimestamp(); lastPasswordVO = passwordDao.toPasswordOutVO(lastPassword); userVO = lastPasswordVO.getUser(); ServiceUtil.logSystemMessage(user, userVO, now, user, SystemMessageCodes.SUCCESSFUL_LOGON, lastPasswordVO, null, journalEntryDao); } catch (AuthenticationException e) { lastPassword = CoreUtil.getLastPassword(); user = CoreUtil.getUser(); if (user != null) { now = new Timestamp(System.currentTimeMillis()); lastPasswordVO = lastPassword != null ? passwordDao.toPasswordOutVO(lastPassword) : null; userVO = lastPasswordVO != null ? lastPasswordVO.getUser() : this.getUserDao().toUserInheritedVO(user); ServiceUtil.logSystemMessage(user, userVO, now, user, SystemMessageCodes.FAILED_LOGON, lastPasswordVO, null, journalEntryDao); } throw e; } finally { if (lastPassword != null) { passwordDao.update(lastPassword); } } return passwordDao.toPasswordOutVO(lastPassword); } @Override protected void handleMarkMassMailRead(String beacon) throws Exception { CommonUtil.parseUUID(beacon); MassMailRecipientDao massMailRecipientDao = this.getMassMailRecipientDao(); MassMailRecipient recipient = massMailRecipientDao.searchUniqueBeacon(beacon); if (recipient == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MASS_MAIL_RECIPIENT_BEACON_NOT_FOUND, beacon); } massMailRecipientDao.refresh(recipient, LockMode.PESSIMISTIC_WRITE); Timestamp now = new Timestamp(System.currentTimeMillis()); recipient.setRead(recipient.getRead() + 1l); recipient.setReadTimestamp(now); CoreUtil.modifyVersion(recipient, recipient.getVersion(), recipient.getModifiedTimestamp(), recipient.getModifiedUser()); massMailRecipientDao.update(recipient); } @Override protected void handleNoOp() throws Exception { } @Override protected long handlePrepareNotifications(Long departmentId) throws Exception { if (departmentId != null) { CheckIDUtil.checkDepartmentId(departmentId, this.getDepartmentDao()); } Date today = new Date(); NotificationDao notificationDao = this.getNotificationDao(); long count = 0; Iterator<MaintenanceScheduleItem> maintenanceScheduleIt = this.getMaintenanceScheduleItemDao() .findMaintenanceSchedule(today, null, departmentId, null, null, null, true, false, null) .iterator(); while (maintenanceScheduleIt.hasNext()) { MaintenanceScheduleItem maintenanceScheduleItem = maintenanceScheduleIt.next(); Collection<Notification> notifications = filterNotifications(maintenanceScheduleItem.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.MAINTENANCE_REMINDER, false); if (notifications.size() == 0) { if (notificationDao.addNotification(maintenanceScheduleItem, today, null) != null) { count++; } } else if (maintenanceScheduleItem.isRecurring()) { if (ReminderEntityAdapter.getInstance(maintenanceScheduleItem).getReminderStart(today, false, null, null) .compareTo(Collections.max(notifications, new EntityIDComparator<Notification>(false)).getDate()) > 0) { if (notificationDao.addNotification(maintenanceScheduleItem, today, null) != null) { count++; } } } } Iterator<InventoryStatusEntry> inventoryStatusIt = this.getInventoryStatusEntryDao() .findInventoryStatus(CommonUtil.dateToTimestamp(today), null, departmentId, null, false, null, null).iterator(); while (inventoryStatusIt.hasNext()) { InventoryStatusEntry inventoryStatusEntry = inventoryStatusIt.next(); if (!ServiceUtil.testNotificationExists(inventoryStatusEntry.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.INVENTORY_INACTIVE, false)) { if (notificationDao.addNotification(inventoryStatusEntry, today, null) != null) { count++; } } } Iterator<StaffStatusEntry> staffStatusIt = this.getStaffStatusEntryDao().findStaffStatus(CommonUtil.dateToTimestamp(today), null, departmentId, null, false, null, null) .iterator(); while (staffStatusIt.hasNext()) { StaffStatusEntry staffStatusEntry = staffStatusIt.next(); if (!ServiceUtil.testNotificationExists(staffStatusEntry.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.STAFF_INACTIVE, false)) { if (notificationDao.addNotification(staffStatusEntry, today, null) != null) { count++; } } } Iterator<ProbandStatusEntry> probandStatusIt = this.getProbandStatusEntryDao() .findProbandStatus(CommonUtil.dateToTimestamp(today), null, departmentId, null, false, null, null).iterator(); while (probandStatusIt.hasNext()) { ProbandStatusEntry probandStatusEntry = probandStatusIt.next(); if (!ServiceUtil.testNotificationExists(probandStatusEntry.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.PROBAND_INACTIVE, false)) { if (notificationDao.addNotification(probandStatusEntry, today, null) != null) { count++; } } } VariablePeriod expiringCourseReminderPeriod = Settings.getVariablePeriod(SettingCodes.NOTIFICATION_EXPIRING_COURSE_REMINDER_PERIOD, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_EXPIRING_COURSE_REMINDER_PERIOD); Long expiringCourseReminderPeriodDays = Settings.getLongNullable(SettingCodes.NOTIFICATION_EXPIRING_COURSE_REMINDER_PERIOD_DAYS, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_EXPIRING_COURSE_REMINDER_PERIOD_DAYS); Iterator<Course> expiringCourseIt = this.getCourseDao().findExpiring(today, departmentId, null, expiringCourseReminderPeriod, expiringCourseReminderPeriodDays, false, null) .iterator(); while (expiringCourseIt.hasNext()) { Course course = expiringCourseIt.next(); if (!ServiceUtil.testNotificationExists(course.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.EXPIRING_COURSE, false)) { Map messageParameters = CoreUtil.createEmptyTemplateModel(); messageParameters.put(NotificationMessageTemplateParameters.COURSE_EXPIRATION_DAYS_LEFT, DateCalc.dateDeltaDays(today, DateCalc.addInterval(course.getStop(), course.getValidityPeriod(), course.getValidityPeriodDays()))); notificationDao.addExpiringCourseNotification(course, today, messageParameters); count++; } } VariablePeriod expiringCourseParticipationReminderPeriod = Settings.getVariablePeriod(SettingCodes.NOTIFICATION_EXPIRING_COURSE_PARTICIPATION_REMINDER_PERIOD, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_EXPIRING_COURSE_PARTICIPATION_REMINDER_PERIOD); Long expiringCourseParticipationReminderPeriodDays = Settings.getLongNullable(SettingCodes.NOTIFICATION_EXPIRING_COURSE_PARTICIPATION_REMINDER_PERIOD_DAYS, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_EXPIRING_COURSE_PARTICIPATION_REMINDER_PERIOD_DAYS); Iterator<CourseParticipationStatusEntry> courseParticipationStatusEntryIt = this.getCourseParticipationStatusEntryDao() .findExpiring(today, null, null, departmentId, null, null, true, expiringCourseParticipationReminderPeriod, expiringCourseParticipationReminderPeriodDays, false, null) .iterator(); while (courseParticipationStatusEntryIt.hasNext()) { CourseParticipationStatusEntry courseParticipationStatusEntry = courseParticipationStatusEntryIt.next(); if (!ServiceUtil.testNotificationExists(courseParticipationStatusEntry.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.EXPIRING_COURSE_PARTICIPATION, false)) { Course course = courseParticipationStatusEntry.getCourse(); Map messageParameters = CoreUtil.createEmptyTemplateModel(); messageParameters.put(NotificationMessageTemplateParameters.COURSE_EXPIRATION_DAYS_LEFT, DateCalc.dateDeltaDays(today, DateCalc.addInterval(course.getStop(), course.getValidityPeriod(), course.getValidityPeriodDays()))); if (notificationDao.addNotification(courseParticipationStatusEntry, true, false, today, messageParameters) != null) { count++; } } } Iterator<TimelineEvent> timelineScheduleIt = this.getTimelineEventDao().findTimelineSchedule(today, null, departmentId, null, true, false, false, null).iterator(); while (timelineScheduleIt.hasNext()) { TimelineEvent timelineEvent = timelineScheduleIt.next(); if (!ServiceUtil.testNotificationExists(timelineEvent.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.TIMELINE_EVENT_REMINDER, false)) { if (notificationDao.addNotification(timelineEvent, today, null) != null) { count++; } } } VariablePeriod visitScheduleItemReminderPeriod = Settings.getVariablePeriod(SettingCodes.NOTIFICATION_VISIT_SCHEDULE_ITEM_REMINDER_PERIOD, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_VISIT_SCHEDULE_ITEM_REMINDER_PERIOD); Long visitScheduleItemReminderPeriodDays = Settings.getLongNullable(SettingCodes.NOTIFICATION_VISIT_SCHEDULE_ITEM_REMINDER_PERIOD_DAYS, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_VISIT_SCHEDULE_ITEM_REMINDER_PERIOD_DAYS); Iterator<Map.Entry> visitScheduleItemScheduleIt = this.getVisitScheduleItemDao() .findVisitScheduleItemSchedule(today, null, null, null, departmentId, true, false, visitScheduleItemReminderPeriod, visitScheduleItemReminderPeriodDays, false) .entrySet().iterator(); while (visitScheduleItemScheduleIt.hasNext()) { Entry visitScheduleItemSchedule = visitScheduleItemScheduleIt.next(); Long probandId = (Long) visitScheduleItemSchedule.getKey(); Proband proband = probandId != null ? this.getProbandDao().load(probandId) : null; Iterator<VisitScheduleItem> visitScheduleItemsIt = ((List<VisitScheduleItem>) visitScheduleItemSchedule.getValue()).iterator(); while (visitScheduleItemsIt.hasNext()) { VisitScheduleItem visitScheduleItem = visitScheduleItemsIt.next(); if (!ServiceUtil.testNotificationExists(visitScheduleItem.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.VISIT_SCHEDULE_ITEM_REMINDER, false)) { if (notificationDao.addNotification(visitScheduleItem, proband, today, null) != null) { count++; } } } } VariablePeriod expiringProbandAutoDeleteReminderPeriod = Settings.getVariablePeriod(SettingCodes.NOTIFICATION_EXPIRING_PROBAND_AUTO_DELETE_REMINDER_PERIOD, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_EXPIRING_PROBAND_AUTO_DELETE_REMINDER_PERIOD); Long expiringProbandAutoDeleteReminderPeriodDays = Settings.getLongNullable(SettingCodes.NOTIFICATION_EXPIRING_PROBAND_AUTO_DELETE_REMINDER_PERIOD_DAYS, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_EXPIRING_PROBAND_AUTO_DELETE_REMINDER_PERIOD_DAYS); Iterator<Proband> toBeAutoDeletedIt = this.getProbandDao() .findToBeAutoDeleted(today, departmentId, null, expiringProbandAutoDeleteReminderPeriod, expiringProbandAutoDeleteReminderPeriodDays, true, false, null).iterator(); while (toBeAutoDeletedIt.hasNext()) { Proband proband = toBeAutoDeletedIt.next(); if (!ServiceUtil.testNotificationExists(proband.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.EXPIRING_PROBAND_AUTO_DELETE, false)) { Map messageParameters = CoreUtil.createEmptyTemplateModel(); messageParameters.put(NotificationMessageTemplateParameters.PROBAND_AUTO_DELETE_DAYS_LEFT, DateCalc.dateDeltaDays(today, proband.getAutoDeleteDeadline())); if (notificationDao.addNotification(proband, today, messageParameters) != null) { count++; } } } VariablePeriod expiringPasswordReminderPeriod = Settings.getVariablePeriod(SettingCodes.NOTIFICATION_EXPIRING_PASSWORD_REMINDER_PERIOD, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_EXPIRING_PASSWORD_REMINDER_PERIOD); Long expiringPasswordReminderPeriodDays = Settings.getLongNullable(SettingCodes.NOTIFICATION_EXPIRING_PASSWORD_REMINDER_PERIOD_DAYS, Settings.Bundle.SETTINGS, DefaultSettings.NOTIFICATION_EXPIRING_PASSWORD_REMINDER_PERIOD_DAYS); Iterator<Password> expiringPasswordIt = this.getPasswordDao() .findExpiring(today, departmentId, AuthenticationType.LOCAL, expiringPasswordReminderPeriod, expiringPasswordReminderPeriodDays, true, false, null).iterator(); while (expiringPasswordIt.hasNext()) { Password password = expiringPasswordIt.next(); if (!ServiceUtil.testNotificationExists(password.getNotifications(), org.phoenixctms.ctsms.enumeration.NotificationType.EXPIRING_PASSWORD, false)) { Map messageParameters = CoreUtil.createEmptyTemplateModel(); messageParameters.put(NotificationMessageTemplateParameters.PASSWORD_EXPIRATION_DAYS_LEFT, DateCalc.dateDeltaDays(today, ServiceUtil.getLogonExpirationDate(password))); if (notificationDao.addNotification(password, today, messageParameters) != null) { count++; } } } return count; } @Override protected long handleProcessNotifications(Long departmentId, PSFVO psf) throws Exception { if (departmentId != null) { CheckIDUtil.checkDepartmentId(departmentId, this.getDepartmentDao()); } long totalEmailCount = 0; int delayMillis = Settings.getInt(SettingCodes.EMAIL_PROCESS_NOTIFICATIONS_DELAY_MILLIS, Bundle.SETTINGS, DefaultSettings.EMAIL_PROCESS_NOTIFICATIONS_DELAY_MILLIS); NotificationRecipientDao notificationRecipientDao = this.getNotificationRecipientDao(); Iterator<NotificationRecipient> recipientsIt = notificationRecipientDao.findPending(null, departmentId, psf).iterator(); while (recipientsIt.hasNext()) { NotificationRecipient recipient = recipientsIt.next(); Notification notification = recipient.getNotification(); NotificationType notificationType = notification.getType(); Staff recipientStaff = recipient.getStaff(); HashSet<Long> sendDepartmentStaffCategoryIds = createSendDepartmentStaffCategorySet(notificationType); boolean sent = false; boolean dropped = false; int toCount = 0; if (sendDepartmentStaffCategoryIds.contains(recipientStaff.getCategory().getId())) { try { toCount = notificationEmailSender.prepareAndSend(notification, recipientStaff); if (toCount > 0) { sent = true; if (delayMillis > 0) { Thread.sleep(delayMillis); } } else { dropped = true; } } catch (Throwable t) { recipient.setErrorMessage(t.getMessage()); if (delayMillis > 0) { Thread.sleep(delayMillis); } } } else { dropped = true; } recipient.setTimesProcessed(recipient.getTimesProcessed() + 1l); recipient.setTimestamp(new Timestamp(System.currentTimeMillis())); recipient.setSent(sent); recipient.setDropped(dropped); notificationRecipientDao.update(recipient); notificationRecipientDao.commitAndResumeTransaction(); totalEmailCount += toCount; } return totalEmailCount; } @Override protected Date handleSubIntervals(Date date, VariablePeriod period, Long explicitDays, int n) throws Exception { return DateCalc.subIntervals(date, period, explicitDays, n); } @Override protected void handleUnsubscribeProbandEmail(String beacon) throws Exception { CommonUtil.parseUUID(beacon); MassMailRecipientDao massMailRecipientDao = this.getMassMailRecipientDao(); Timestamp now = new Timestamp(System.currentTimeMillis()); Proband proband = this.getProbandDao().searchUniqueBeacon(beacon); if (proband == null) { MassMailRecipient recipient = massMailRecipientDao.searchUniqueBeacon(beacon); if (recipient != null) { massMailRecipientDao.refresh(recipient, LockMode.PESSIMISTIC_WRITE); recipient.setUnsubscribed(recipient.getUnsubscribed() + 1l); recipient.setUnsubscribedTimestamp(now); CoreUtil.modifyVersion(recipient, recipient.getVersion(), recipient.getModifiedTimestamp(), recipient.getModifiedUser()); massMailRecipientDao.update(recipient); proband = recipient.getProband(); } else { throw L10nUtil.initServiceException(ServiceExceptionCodes.MASS_MAIL_RECIPIENT_BEACON_NOT_FOUND, beacon); } } ProbandContactDetailValueDao probandContactDetailValueDao = this.getProbandContactDetailValueDao(); if (proband != null) { this.getProbandDao().lock(proband, LockMode.PESSIMISTIC_WRITE); Iterator<ProbandContactDetailValue> contactsIt = proband.getContactDetailValues().iterator(); while (contactsIt.hasNext()) { ProbandContactDetailValue contact = contactsIt.next(); ContactDetailType contactType; if (!contact.isNa() && contact.isNotify() && (contactType = contact.getType()).isEmail()) { contact.setNotify(false); CoreUtil.modifyVersion(contact, contact.getVersion(), now, contact.getModifiedUser()); probandContactDetailValueDao.update(contact); } } } } @Override protected Integer handleGetJobFileUploadSizeLimit() throws Exception { return Settings.getIntNullable(SettingCodes.JOB_FILE_SIZE_LIMIT, Bundle.SETTINGS, DefaultSettings.JOB_FILE_SIZE_LIMIT); } @Override protected boolean handleIsDecryptFromUntrustedHosts() throws Exception { return Settings.getBoolean(SettingCodes.DECRYPT_FROM_UNTRUSTED_HOSTS, Bundle.SETTINGS, DefaultSettings.DECRYPT_FROM_UNTRUSTED_HOSTS); } public void setAuthenticator(Authenticator authenticator) { this.authenticator = authenticator; } public void setNotificationEmailSender(NotificationEmailSender notificationEmailSender) { this.notificationEmailSender = notificationEmailSender; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override protected Integer handleGetCourseParticipationFileUploadSizeLimit() throws Exception { return Settings.getIntNullable(SettingCodes.COURSE_PARTICIPATION_FILE_SIZE_LIMIT, Bundle.SETTINGS, DefaultSettings.COURSE_PARTICIPATION_FILE_SIZE_LIMIT); } @Override protected String handleIssueJwt(AuthenticationVO auth, String realm, Long validityPeriodSecs) throws Exception { return authenticator.issueJwt(auth, realm, validityPeriodSecs); } @Override protected String[] handleVerifyJwt(String jwt) throws Exception { return authenticator.verifyJwt(jwt); } }
package io.zonk.jbomberman.game.server; import io.zonk.jbomberman.game.Action; import io.zonk.jbomberman.game.ActionDispatcher; import io.zonk.jbomberman.game.ActionQueue; import io.zonk.jbomberman.game.ActionType; import io.zonk.jbomberman.game.GameLoop; import io.zonk.jbomberman.game.GameObjectType; import io.zonk.jbomberman.game.Party; import io.zonk.jbomberman.game.Player; import io.zonk.jbomberman.game.PowerUpType; import io.zonk.jbomberman.network.NetworkFacade; import io.zonk.jbomberman.time.Timer; import io.zonk.jbomberman.utils.ActionSerializer; import io.zonk.jbomberman.utils.IDGenerator; import io.zonk.jbomberman.utils.Position; import java.util.Observable; import java.util.Random; public class ServerGame extends Observable implements GameLoop { private NetworkFacade network; private ActionQueue queue; private GameObjectManager manager; private Party party; private boolean initmap; public ServerGame(NetworkFacade network, Party party) { this.network = network; this.party = party; manager = new GameObjectManager(); /* for(Player player : party.getPlayers().values()) { player.setBomberman(new GBomberman(null, player.getId()));//Position }*/ queue = new ActionQueue(); ActionDispatcher dispatcher = new ActionDispatcher(network, queue); dispatcher.start(); Timer timer = new Timer(1000/30, this); timer.start(); } @Override public void loop() { if(!initmap) initMap(); //while(true) { //game running? //System.out.println("loop"); //handle all available Actions while(!queue.isEmpty()) { Action action = queue.take(); switch(action.getActionType()) { case PLAYER_INPUT: int id = (int) action.getProperty(0); party.get(id).getBomberman().update(action); break; case CREATE_BOMB: manager.add(new GBomb((Position)action.getProperty(0), (int)action.getProperty(1), (int)action.getProperty(2), (int)action.getProperty(3))); network.sendMessage(ActionSerializer.serialize(action)); break; case CREATE_POWERUP: manager.add(new GPowerUp((Position)action.getProperty(0),(int)action.getProperty(1), (PowerUpType)action.getProperty(2))); network.sendMessage(ActionSerializer.serialize(action)); break; case DESTROY_BOMB: manager.remove((int)action.getProperty(0)); network.sendMessage(ActionSerializer.serialize(action)); break; case CREATE_EXPLOSION: GExplosion explosion = new GExplosion((Position)action.getProperty(0), (int)action.getProperty(1), (int)action.getProperty(2), (GExplosion.Direction)action.getProperty(3)); boolean collision = false; for(GameObject object : manager.getByType(GameObjectType.SOLID_BLOCK, GameObjectType.DESTROYBALE_BLOCK)) { if(explosion.checkCollisionWith(object)) { if(object instanceof GDestroyableBlock) { explosion.setPower(0); } if(object instanceof GSolidBlock) { collision = true; } break; } } if(!collision) { manager.add(explosion); network.sendMessage(ActionSerializer.serialize(action)); } break; case DESTROY: manager.remove((int)action.getProperty(0)); network.sendMessage(ActionSerializer.serialize(action)); break; default: break; } } //Tick all Objects for(GameObject object : manager.getAll()) { object.tick(queue, manager); } for(Player player : party.getPlayers().values()) { if(player == null) continue; player.getBomberman().tick(manager, queue); player.getBomberman().sendUpdates(network); } } private void initMap() { Random rnd = new Random(); Map map = new StandardMap(); for(int y = 0; y < 13; ++y) for(int x = 0; x < 13; ++x) { Position position = new Position(x*64, y*64); Integer id; Action action; switch(map.get(x, y)) { case ' id = IDGenerator.getId(); manager.add(new GSolidBlock(position, id)); action = new Action(ActionType.CREATE_SOLIDBLOCK, new Object[]{position, id}); network.sendMessage(ActionSerializer.serialize(action)); break; case ' ': if(rnd.nextInt(100) > 70) break; id = IDGenerator.getId(); manager.add(new GDestroyableBlock(position, id)); action = new Action(ActionType.CREATE_DESTROYABLEBLOCK, new Object[]{position, id}); network.sendMessage(ActionSerializer.serialize(action)); break; case '1': if (party.get(1) != null) { party.get(1).setBomberman(new GBomberman(position, 1)); action = new Action(ActionType.CREATE_BOMBERMAN, new Object[]{position, 1}); network.sendMessage(ActionSerializer.serialize(action)); } break; case '2': if (party.get(2) != null) { party.get(2).setBomberman(new GBomberman(position, 2)); action = new Action(ActionType.CREATE_BOMBERMAN, new Object[]{position, 2}); network.sendMessage(ActionSerializer.serialize(action)); } break; case '3': if (party.get(3) != null) { party.get(3).setBomberman(new GBomberman(position, 3)); action = new Action(ActionType.CREATE_BOMBERMAN, new Object[]{position, 3}); network.sendMessage(ActionSerializer.serialize(action)); } break; case '4': if (party.get(4) != null) { party.get(4).setBomberman(new GBomberman(position, 4)); action = new Action(ActionType.CREATE_BOMBERMAN, new Object[]{position, 4}); network.sendMessage(ActionSerializer.serialize(action)); } break; default: break; } } initmap = true; } }
package net.liutikas.mrsad.entities; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.TimeUtils; import com.badlogic.gdx.utils.viewport.Viewport; import net.liutikas.mrsad.Constants; import net.liutikas.mrsad.utils.Assets; /** * The main game character the the player will be controlling. */ public class Player { private static final int FACING_LEFT = 0; private static final int FACING_RIGHT = 1; private static final int STANDING = 0; private static final int WALKING = 1; private final Viewport mViewport; private Vector2 mLastFramePosition; // Position of the middle of player's feet. private Vector2 mPosition; private Vector2 mVelocity; private JumpState mJumpState; private int mDirection; private int mWalkingState; private long mWalkStartTime; private long mJumpStartTime; public Player(Viewport viewport) { mViewport = viewport; } public void init() { mLastFramePosition = new Vector2(0, 0); mPosition = new Vector2(mViewport.getWorldWidth() / 2, 40); mVelocity = new Vector2(0, 0); mJumpState = JumpState.FALLING; mDirection = FACING_RIGHT; mWalkingState = STANDING; } public void update(float delta, Array<Platform> platforms) { mLastFramePosition.set(mPosition); if (Gdx.input.isTouched()) { if (Gdx.input.getX() < mViewport.getScreenWidth() / 2) { moveLeft(delta); } else { moveRight(delta); } } else if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) { moveLeft(delta); } else if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) { moveRight(delta); } else { mWalkingState = STANDING; } if (Gdx.input.isKeyPressed(Input.Keys.SPACE)) { if (mJumpState == JumpState.GROUNDED) { mJumpState = JumpState.JUMPING; mJumpStartTime = TimeUtils.nanoTime(); } float jumpDuration = MathUtils.nanoToSec * (TimeUtils.nanoTime() - mJumpStartTime); if (jumpDuration < Constants.PLAYER_MAX_JUMP_DURATION && mJumpState == JumpState.JUMPING) { mPosition.y += delta * Constants.PLAYER_JUMP_SPEED; } else { continueFalling(delta, platforms); } } else if (mPosition.y > 0) { continueFalling(delta, platforms); } } public void render(SpriteBatch batch) { TextureRegion region; if (mDirection == FACING_LEFT) { if (mJumpState == JumpState.GROUNDED) { if (mWalkingState == STANDING) { region = Assets.instance.playerAssets.standingLeft; } else { float walkTimeSeconds = MathUtils.nanoToSec * (TimeUtils.nanoTime() - mWalkStartTime); region = Assets.instance.playerAssets.walkingLeftAnimation.getKeyFrame( walkTimeSeconds); } } else { region = Assets.instance.playerAssets.jumpingLeft; } } else { if (mJumpState == JumpState.GROUNDED) { if (mWalkingState == STANDING) { region = Assets.instance.playerAssets.standingRight; } else { float walkTimeSeconds = MathUtils.nanoToSec * (TimeUtils.nanoTime() - mWalkStartTime); region = Assets.instance.playerAssets.walkingRightAnimation.getKeyFrame( walkTimeSeconds); } } else { region = Assets.instance.playerAssets.jumpingRight; } } batch.draw( region.getTexture(), mPosition.x - Constants.PLAYER_TEXTURE_WIDTH / 2, mPosition.y, 0, 0, region.getRegionWidth(), region.getRegionHeight(), 1, 1, 0, region.getRegionX(), region.getRegionY(), region.getRegionWidth(), region.getRegionHeight(), false, false); } public float getPositionX() { return mPosition.x; } public float getPositionY() { return mPosition.y; } private void moveLeft(float delta) { mDirection = FACING_LEFT; if (mJumpState == JumpState.GROUNDED && mWalkingState == STANDING) { mWalkStartTime = TimeUtils.nanoTime(); mWalkingState = WALKING; } mPosition.x -= delta * Constants.PLAYER_WALK_SPEED; } private void moveRight(float delta) { mDirection = FACING_RIGHT; if (mJumpState == JumpState.GROUNDED && mWalkingState == STANDING) { mWalkStartTime = TimeUtils.nanoTime(); mWalkingState = WALKING; } mPosition.x += delta * Constants.PLAYER_WALK_SPEED; } private void continueFalling(float delta, Array<Platform> platforms) { if (mJumpState == JumpState.JUMPING) { mJumpState = JumpState.FALLING; } mVelocity.y -= delta * Constants.GRAVITY_ACCELERATION; mPosition.y += delta * mVelocity.y; if (mPosition.y <= 0) { mPosition.y = 0f; mVelocity.y = 0f; mJumpState = JumpState.GROUNDED; } for (int i = 0; i < platforms.size; i++) { Platform platform = platforms.get(i); if (mLastFramePosition.y >= platform.top && mPosition.y <= platform.top) { float leftFoot = mPosition.x - Constants.PLAYER_FEET_WIDTH / 2; float rightFoot = mPosition.x + Constants.PLAYER_FEET_WIDTH / 2; boolean leftFootIn = leftFoot > platform.left && leftFoot < platform.right; boolean rightFootIn = rightFoot > platform.left && rightFoot < platform.right; if (leftFootIn || rightFootIn) { mPosition.y = platform.top; mVelocity.y = 0f; mJumpState = JumpState.GROUNDED; break; } } } } enum JumpState { GROUNDED, // No vertical velocity. Player is on a ground. JUMPING, // Positive up velocity. Can stay in this state for up to PLAYER_MAX_JUMP_DURATION. FALLING // Negative vertical velocity. Changes to GROUNDED when player reaches ground. } }
package org.xins.server; import java.io.File; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TimeZone; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.Utils; import org.xins.common.collections.BasicPropertyReader; import org.xins.common.collections.InvalidPropertyValueException; import org.xins.common.collections.MissingRequiredPropertyException; import org.xins.common.collections.PropertyReader; import org.xins.common.io.FastStringWriter; import org.xins.common.manageable.BootstrapException; import org.xins.common.manageable.DeinitializationException; import org.xins.common.manageable.InitializationException; import org.xins.common.manageable.Manageable; import org.xins.common.net.IPAddressUtils; import org.xins.common.spec.APISpec; import org.xins.common.spec.InvalidSpecificationException; import org.xins.common.text.DateConverter; import org.xins.common.text.ParseException; import org.xins.common.xml.Element; import org.xins.common.xml.ElementBuilder; import org.xins.logdoc.LogdocSerializable; /** * Base class for API implementation classes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * @author Anthony Goubard (<a href="mailto:anthony.goubard@nl.wanadoo.com">anthony.goubard@nl.wanadoo.com</a>) * @author Tauseef Rehman (<a href="mailto:tauseef.rehman@nl.wanadoo.com">tauseef.rehman@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ public abstract class API extends Manageable implements DefaultResultCodes { // Class fields /** * Fully-qualified name of this class. */ private static final String CLASSNAME = API.class.getName(); /** * Successful empty call result. */ private static final FunctionResult SUCCESSFUL_RESULT = new FunctionResult(); /** * The runtime (initialization) property that defines the ACL (access * control list) rules. */ private static final String ACL_PROPERTY = "org.xins.server.acl"; /** * The name of the build property that specifies the version of the API. */ static final String API_VERSION_PROPERTY = "org.xins.api.version"; /** * The name of the build property that specifies the hostname of the * machine the package was built on. */ private static final String BUILD_HOST_PROPERTY = "org.xins.api.build.host"; /** * The name of the build property that specifies the time the package was * built. */ private static final String BUILD_TIME_PROPERTY = "org.xins.api.build.time"; /** * The name of the build property that specifies which version of XINS was * used to build the package. */ private static final String BUILD_XINS_VERSION_PROPERTY = "org.xins.api.build.version"; // Constructors protected API(String name) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name); if (name.length() < 1) { String message = "name.length() == " + name.length(); throw new IllegalArgumentException(message); } // Initialize fields _name = name; _startupTimestamp = System.currentTimeMillis(); _lastStatisticsReset = _startupTimestamp; _manageableObjects = new ArrayList(20); _functionsByName = new HashMap(89); _functionList = new ArrayList(80); _resultCodesByName = new HashMap(89); _resultCodeList = new ArrayList(80); _emptyProperties = new RuntimeProperties(); _timeZone = TimeZone.getDefault(); _localIPAddress = IPAddressUtils.getLocalHostIPAddress(); // Initialize mapping from meta-function to call ID _metaFunctionCallIDs = new HashMap(89); _metaFunctionCallIDs.put("_NoOp", new Counter()); _metaFunctionCallIDs.put("_GetFunctionList", new Counter()); _metaFunctionCallIDs.put("_GetStatistics", new Counter()); _metaFunctionCallIDs.put("_GetVersion", new Counter()); _metaFunctionCallIDs.put("_CheckLinks", new Counter()); _metaFunctionCallIDs.put("_GetSettings", new Counter()); _metaFunctionCallIDs.put("_DisableFunction", new Counter()); _metaFunctionCallIDs.put("_EnableFunction", new Counter()); _metaFunctionCallIDs.put("_ResetStatistics", new Counter()); _metaFunctionCallIDs.put("_ReloadProperties", new Counter()); } // Fields /** * The engine that owns this <code>API</code> object. */ private Engine _engine; /** * The name of this API. Cannot be <code>null</code> and cannot be an empty * string. */ private final String _name; /** * List of registered manageable objects. See {@link #add(Manageable)}. * * <p />This field is initialized to a non-<code>null</code> value by the * constructor. */ private final List _manageableObjects; /** * Map that maps function names to <code>Function</code> instances. * Contains all functions associated with this API. * * <p />This field is initialized to a non-<code>null</code> value by the * constructor. */ private final Map _functionsByName; /** * List of all functions. This field cannot be <code>null</code>. */ private final List _functionList; /** * Map that maps result code names to <code>ResultCode</code> instances. * Contains all result codes associated with this API. * * <p />This field is initialized to a non-<code>null</code> value by the * constructor. */ private final Map _resultCodesByName; /** * List of all result codes. This field cannot be <code>null</code>. */ private final List _resultCodeList; /** * The build-time settings. This field is initialized exactly once by * {@link #bootstrap(PropertyReader)}. It can be <code>null</code> before * that. */ private PropertyReader _buildSettings; /** * The {@link RuntimeProperties} containing the method to verify and access * the defined runtime properties. */ private RuntimeProperties _emptyProperties; /** * The runtime-time settings. This field is initialized by * {@link #init(PropertyReader)}. It can be <code>null</code> before that. */ private PropertyReader _runtimeSettings; /** * Timestamp indicating when this API instance was created. */ private final long _startupTimestamp; /** * Last time the statistics were reset. Initially the startup timestamp. */ private long _lastStatisticsReset; /** * Host name for the machine that was used for this build. */ private String _buildHost; /** * Time stamp that indicates when this build was done. */ private String _buildTime; /** * XINS version used to build the web application package. */ private String _buildVersion; /** * The time zone used when generating dates for output. */ private final TimeZone _timeZone; /** * Version of the API. */ private String _apiVersion; /** * The API specific access rule list. */ private AccessRuleList _apiAccessRuleList; /** * The general access rule list. */ private AccessRuleList _accessRuleList; /** * The API specification. */ private APISpec _apiSpecification; /** * The local IP address. */ private String _localIPAddress; /** * Mapping from function name to the call ID for all meta-functions. This * field is never <code>null</code>. */ private final HashMap _metaFunctionCallIDs; // Methods /** * Gets the name of this API. * * @return * the name of this API, never <code>null</code> and never an empty * string. */ public final String getName() { return _name; } /** * Gets the list of the functions of this API. * * @return * the function of this API as a list of {@link Function}, never <code>null</code>. */ final List getFunctionList() { return _functionList; } /** * Gets the bootstrap properties specified for the API. * * @return * the bootstrap properties, cannot be <code>null</code>. * * @since XINS 1.5.0. */ public PropertyReader getBootstrapProperties() { return _buildSettings; } /** * Gets the API runtime properties. * * @return * the bootstrap properties, cannot be <code>null</code>. */ PropertyReader getRuntimeProperties() { return _runtimeSettings; } /** * Gets the runtime properties specified in the implementation. * * @return * the runtime properties for the API, cannot be <code>null</code>. */ public RuntimeProperties getProperties() { // This method is overridden by the APIImpl to return the generated // RuntimeProperties class which contains the runtime properties. return _emptyProperties; } /** * Gets the timestamp that indicates when this <code>API</code> instance * was created. * * @return * the time this instance was constructed, as a number of milliseconds * since midnight January 1, 1970. */ public final long getStartupTimestamp() { return _startupTimestamp; } /** * Returns the applicable time zone. * * @return * the time zone, never <code>null</code>. */ public final TimeZone getTimeZone() { return _timeZone; } protected final void bootstrapImpl(PropertyReader buildSettings) throws IllegalStateException, MissingRequiredPropertyException, InvalidPropertyValueException, BootstrapException { // Check state Manageable.State state = getState(); if (state != BOOTSTRAPPING) { String message = "State is " + state + " instead of " + BOOTSTRAPPING + '.'; Utils.logProgrammingError(message); throw new IllegalStateException(message); } // Log the time zone String tzShortName = _timeZone.getDisplayName(false, TimeZone.SHORT); String tzLongName = _timeZone.getDisplayName(false, TimeZone.LONG); Log.log_3404(tzShortName, tzLongName); // Store the build-time settings _buildSettings = buildSettings; // Get build-time properties _apiVersion = _buildSettings.get(API_VERSION_PROPERTY ); _buildHost = _buildSettings.get(BUILD_HOST_PROPERTY ); _buildTime = _buildSettings.get(BUILD_TIME_PROPERTY ); _buildVersion = _buildSettings.get(BUILD_XINS_VERSION_PROPERTY); Log.log_3212(_buildHost, _buildTime, _buildVersion, _name, _apiVersion); // Skip check if build version is not set if (_buildVersion == null) { // fall through // Check if build version identifies a production release of XINS } else if (! Library.isProductionRelease(_buildVersion)) { Log.log_3228(_buildVersion); } // Let the subclass perform initialization // TODO: What if bootstrapImpl2 throws an unexpected exception? bootstrapImpl2(buildSettings); // Bootstrap all instances int count = _manageableObjects.size(); for (int i = 0; i < count; i++) { Manageable m = (Manageable) _manageableObjects.get(i); String className = m.getClass().getName(); Log.log_3213(_name, className); try { m.bootstrap(_buildSettings); Log.log_3214(_name, className); // Missing property } catch (MissingRequiredPropertyException exception) { Log.log_3215(_name, className, exception.getPropertyName(), exception.getDetail()); throw exception; // Invalid property } catch (InvalidPropertyValueException exception) { Log.log_3216(_name, className, exception.getPropertyName(), exception.getPropertyValue(), exception.getReason()); throw exception; // Catch BootstrapException and any other exceptions not caught // by previous catch statements } catch (Throwable exception) { // Log event Log.log_3217(exception, _name, className); // Throw a BootstrapException. If necessary, wrap around the // caught exception if (exception instanceof BootstrapException) { throw (BootstrapException) exception; } else { throw new BootstrapException(exception); } } } // Bootstrap all functions count = _functionList.size(); for (int i = 0; i < count; i++) { Function f = (Function) _functionList.get(i); String functionName = f.getName(); Log.log_3220(_name, functionName); try { f.bootstrap(_buildSettings); Log.log_3221(_name, functionName); // Missing required property } catch (MissingRequiredPropertyException exception) { Log.log_3222(_name, functionName, exception.getPropertyName(), exception.getDetail()); throw exception; // Invalid property value } catch (InvalidPropertyValueException exception) { Log.log_3223(_name, functionName, exception.getPropertyName(), exception.getPropertyValue(), exception.getReason()); throw exception; // Catch BootstrapException and any other exceptions not caught // by previous catch statements } catch (Throwable exception) { // Log this event Log.log_3224(exception, _name, functionName); // Throw a BootstrapException. If necessary, wrap around the // caught exception if (exception instanceof BootstrapException) { throw (BootstrapException) exception; } else { throw new BootstrapException(exception); } } } } /** * Bootstraps this API (implementation method). * * <p />The implementation of this method in class {@link API} is empty. * Custom subclasses can perform any necessary bootstrapping in this * class. * * <p />Note that bootstrapping and initialization are different. Bootstrap * includes only the one-time configuration of the API based on the * build-time settings, while the initialization * * <p />The {@link #add(Manageable)} may be called from this method, * and from this method <em>only</em>. * * @param buildSettings * the build-time properties, guaranteed not to be <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if a property has an invalid value. * * @throws BootstrapException * if the bootstrap fails. */ protected void bootstrapImpl2(PropertyReader buildSettings) throws MissingRequiredPropertyException, InvalidPropertyValueException, BootstrapException { // empty } /** * Stores a reference to the <code>Engine</code> that owns this * <code>API</code> object. * * @param engine * the {@link Engine} instance, should not be <code>null</code>. */ void setEngine(Engine engine) { _engine = engine; } /** * Triggers re-initialization of this API. This method is meant to be * called by API function implementations when it is anticipated that the * API should be re-initialized. */ protected final void reinitializeImpl() { _engine.initAPI(); } protected final void initImpl(PropertyReader runtimeSettings) throws MissingRequiredPropertyException, InvalidPropertyValueException, InitializationException, IllegalStateException { Log.log_3405(_name); // Store runtime settings _runtimeSettings = runtimeSettings; // TODO: Investigate whether we can take the configuration file reload // interval from somewhere (ConfigManager? Engine?). String propName = APIServlet.CONFIG_RELOAD_INTERVAL_PROPERTY; String propValue = runtimeSettings.get(propName); int interval = APIServlet.DEFAULT_CONFIG_RELOAD_INTERVAL; if (propValue != null && propValue.trim().length() > 0) { try { interval = Integer.parseInt(propValue); } catch (NumberFormatException e) { String detail = "Invalid interval. Must be a non-negative integer" + " number (32-bit signed)."; throw new InvalidPropertyValueException(propName, propValue, detail); } if (interval < 0) { throw new InvalidPropertyValueException(propName, propValue, "Negative interval not allowed. Use 0 to disable reloading."); } } // Initialize ACL subsystem // First with the API specific access rule list if (_apiAccessRuleList != null) { _apiAccessRuleList.dispose(); } _apiAccessRuleList = createAccessRuleList(runtimeSettings, ACL_PROPERTY + '.' + _name, interval); // Then read the generic access rule list if (_accessRuleList != null) { _accessRuleList.dispose(); } _accessRuleList = createAccessRuleList(runtimeSettings, ACL_PROPERTY, interval); // Initialize the RuntimeProperties object. getProperties().init(runtimeSettings); // Initialize all instances int count = _manageableObjects.size(); for (int i = 0; i < count; i++) { Manageable m = (Manageable) _manageableObjects.get(i); String className = m.getClass().getName(); Log.log_3416(_name, className); try { m.init(runtimeSettings); Log.log_3417(_name, className); // Missing required property } catch (MissingRequiredPropertyException exception) { Log.log_3418(_name, className, exception.getPropertyName(), exception.getDetail()); throw exception; // Invalid property value } catch (InvalidPropertyValueException exception) { Log.log_3419(_name, className, exception.getPropertyName(), exception.getPropertyValue(), exception.getReason()); throw exception; // Catch InitializationException and any other exceptions not caught // by previous catch statements } catch (Throwable exception) { // Log this event Log.log_3420(exception, _name, className); if (exception instanceof InitializationException) { throw (InitializationException) exception; } else { throw new InitializationException(exception); } } } // Initialize all functions count = _functionList.size(); for (int i = 0; i < count; i++) { Function f = (Function) _functionList.get(i); String functionName = f.getName(); Log.log_3421(_name, functionName); try { f.init(runtimeSettings); Log.log_3422(_name, functionName); // Missing required property } catch (MissingRequiredPropertyException exception) { Log.log_3423(_name, functionName, exception.getPropertyName(), exception.getDetail()); throw exception; // Invalid property value } catch (InvalidPropertyValueException exception) { Log.log_3424(_name, functionName, exception.getPropertyName(), exception.getPropertyValue(), exception.getReason()); throw exception; // Catch InitializationException and any other exceptions not caught // by previous catch statements } catch (Throwable exception) { // Log this event Log.log_3425(exception, _name, functionName); // Throw an InitializationException. If necessary, wrap around the // caught exception if (exception instanceof InitializationException) { throw (InitializationException) exception; } else { throw new InitializationException(exception); } } } // TODO: Call initImpl2(PropertyReader) ? Log.log_3406(_name); } /** * Creates the access rule list for the given property. * * @param runtimeSettings * the runtime properties, never <code>null</code>. * * @param aclProperty * the ACL property, never <code>null</code> * * @param interval * the interval in seconds to chack if the ACL file has changed and * should be reloaded. * * @return * the access rule list created from the property value, never <code>null</code>. * * @throws InvalidPropertyValueException * if the value for the property is invalid. */ private AccessRuleList createAccessRuleList(PropertyReader runtimeSettings, String aclProperty, int interval) throws InvalidPropertyValueException { String acl = runtimeSettings.get(aclProperty); // New access control list is empty if (acl == null || acl.trim().length() < 1) { if (aclProperty.equals(ACL_PROPERTY)) { Log.log_3426(aclProperty); } return AccessRuleList.EMPTY; // New access control list is non-empty } else { // Parse the new ACL try { AccessRuleList accessRuleList = AccessRuleList.parseAccessRuleList(acl, interval); int ruleCount = accessRuleList.getRuleCount(); Log.log_3427(ruleCount); return accessRuleList; // Parsing failed } catch (ParseException exception) { String exceptionMessage = exception.getMessage(); Log.log_3428(aclProperty, acl, exceptionMessage); throw new InvalidPropertyValueException(aclProperty, acl, exceptionMessage); } } } protected final void add(Manageable m) throws IllegalStateException, IllegalArgumentException { // Check state Manageable.State state = getState(); if (state != BOOTSTRAPPING) { String message = "State is " + state + " instead of " + BOOTSTRAPPING + '.'; Utils.logProgrammingError(message); throw new IllegalStateException(message); } // Check preconditions MandatoryArgumentChecker.check("m", m); String className = m.getClass().getName(); Log.log_3218(_name, className); // Store the manageable object in the list _manageableObjects.add(m); } /** * Performs shutdown of this XINS API. This method will never throw any * exception. */ protected final void deinitImpl() { // Deinitialize instances int count = _manageableObjects.size(); for (int i = 0; i < count; i++) { Manageable m = (Manageable) _manageableObjects.get(i); String className = m.getClass().getName(); Log.log_3603(_name, className); try { m.deinit(); Log.log_3604(_name, className); } catch (DeinitializationException exception) { Log.log_3605(_name, className, exception.getMessage()); } catch (Throwable exception) { Log.log_3606(exception, _name, className); } } _manageableObjects.clear(); // Deinitialize functions count = _functionList.size(); for (int i = 0; i < count; i++) { Function f = (Function) _functionList.get(i); String functionName = f.getName(); Log.log_3607(_name, functionName); try { f.deinit(); Log.log_3608(_name, functionName); } catch (DeinitializationException exception) { Log.log_3609(_name, functionName, exception.getMessage()); } catch (Throwable exception) { Log.log_3610(exception, _name, functionName); } } } final void functionAdded(Function function) throws NullPointerException, IllegalStateException { // Check state Manageable.State state = getState(); if (state != UNUSABLE) { String message = "State is " + state + " instead of " + UNUSABLE + '.'; Utils.logProgrammingError(message); throw new IllegalStateException(message); } _functionsByName.put(function.getName(), function); _functionList.add(function); } /** * Callback method invoked when a result code is constructed. * * @param resultCode * the result code that is added, not <code>null</code>. * * @throws NullPointerException * if <code>resultCode == null</code>. */ final void resultCodeAdded(ResultCode resultCode) throws NullPointerException { _resultCodesByName.put(resultCode.getName(), resultCode); _resultCodeList.add(resultCode); } /** * Returns the function with the specified name. * * @param name * the name of the function, will not be checked if it is * <code>null</code>. * * @return * the function with the specified name, or <code>null</code> if there * is no match. */ final Function getFunction(String name) { return (Function) _functionsByName.get(name); } /** * Get the specification of the API. * * @return * the {@link APISpec} specification object, never <code>null</code>. * * @throws InvalidSpecificationException * if the specification cannot be found or is invalid. * * @since XINS 1.3.0 */ public final APISpec getAPISpecification() throws InvalidSpecificationException { if (_apiSpecification == null) { String baseURL = null; ServletConfig config = _engine.getServletConfig(); ServletContext context = config.getServletContext(); try { String realPath = context.getRealPath("specs/"); if (realPath != null) { baseURL = new File(realPath).toURL().toExternalForm(); } else { baseURL = context.getResource("specs/").toExternalForm(); } } catch (MalformedURLException muex) { // Let the base URL be null } _apiSpecification = new APISpec(getClass(), baseURL); } return _apiSpecification; } public boolean allow(String ip, String functionName) throws IllegalArgumentException { // If no property is defined only localhost is allowed if (_apiAccessRuleList == AccessRuleList.EMPTY && _accessRuleList == AccessRuleList.EMPTY && (ip.equals("127.0.0.1") || ip.equals(_localIPAddress))) { return true; } // Match an access rule Boolean allowed; try { // First check with the API specific one, then use the generic one. allowed = _apiAccessRuleList.isAllowed(ip, functionName); if (allowed == null) { allowed = _accessRuleList.isAllowed(ip, functionName); } // If the IP address cannot be parsed there is a programming error // somewhere } catch (ParseException exception) { String thisMethod = "allow(java.lang.String,java.lang.String)"; String subjectClass = _accessRuleList.getClass().getName(); String subjectMethod = "allow(java.lang.String,java.lang.String)"; String detail = "Malformed IP address: \"" + ip + "\"."; throw Utils.logProgrammingError(CLASSNAME, thisMethod, subjectClass, subjectMethod, detail, exception); } // If there is a match, return the allow-indication if (allowed != null) { return allowed.booleanValue(); } // No matching access rule match, do not allow Log.log_3553(ip, functionName); return false; } final FunctionResult handleCall(long start, FunctionRequest functionRequest, String ip) throws IllegalStateException, NullPointerException, NoSuchFunctionException, AccessDeniedException { // Check state first assertUsable(); // Determine the function name String functionName = functionRequest.getFunctionName(); // Check the access rule list boolean allow = allow(ip, functionName); if (! allow) { throw new AccessDeniedException(ip, functionName); } // Handle meta-functions FunctionResult result; if (functionName.charAt(0) == '_') { // Determine the call ID int callID; synchronized (_metaFunctionCallIDs) { Counter counter = (Counter) _metaFunctionCallIDs.get(functionName); if (counter == null) { throw new NoSuchFunctionException(functionName); } else { callID = counter.next(); } } // Call the meta-function try { result = callMetaFunction(functionName, functionRequest); } catch (Throwable exception) { result = handleFunctionException(start, functionRequest, ip, callID, exception); } // Determine duration long duration = System.currentTimeMillis() - start; // Determine error code, fallback is a zero character String code = result.getErrorCode(); if (code == null || code.length() < 1) { code = "0"; } // Prepare for transaction logging LogdocSerializable serStart = new FormattedDate(start); LogdocSerializable inParams = new FormattedParameters(functionRequest.getParameters(), functionRequest.getDataElement()); LogdocSerializable outParams = new FormattedParameters(result.getParameters(), result.getDataElement()); // Log transaction before returning the result Log.log_3540(serStart, ip, functionName, duration, code, inParams, outParams); Log.log_3541(serStart, ip, functionName, duration, code); // Handle normal functions } else { Function function = getFunction(functionName); if (function == null) { throw new NoSuchFunctionException(functionName); } result = function.handleCall(start, functionRequest, ip); } return result; } /** * Handles a call to a meta-function. * * @param functionName * the name of the meta-function, cannot be <code>null</code> and must * start with the underscore character <code>'_'</code>. * * @param functionRequest * the function request, never <code>null</code>. * * @return * the result of the function call, never <code>null</code>. * * @throws NoSuchFunctionException * if there is no meta-function by the specified name. */ private FunctionResult callMetaFunction(String functionName, FunctionRequest functionRequest) throws NoSuchFunctionException { // Check preconditions MandatoryArgumentChecker.check("functionName", functionName); if (functionName.length() < 1) { throw new IllegalArgumentException("functionName.length() < 1"); } else if (functionName.charAt(0) != '_') { throw new IllegalArgumentException("Function name \"" + functionName + "\" is not a meta-function."); } FunctionResult result; // No Operation if ("_NoOp".equals(functionName)) { result = SUCCESSFUL_RESULT; // Retrieve function list } else if ("_GetFunctionList".equals(functionName)) { result = doGetFunctionList(); // Get function call quantity and performance statistics } else if ("_GetStatistics".equals(functionName)) { // Determine value of 'detailed' argument String detailedArg = functionRequest.getParameters().get("detailed"); boolean detailed = "true".equals(detailedArg); // Get the statistics result = doGetStatistics(detailed); // Determine value of 'reset' argument String resetArg = functionRequest.getParameters().get("reset"); boolean reset = "true".equals(resetArg); if (reset) { doResetStatistics(); } // Get version information } else if ("_GetVersion".equals(functionName)) { result = doGetVersion(); // Check links to underlying systems } else if ("_CheckLinks".equals(functionName)) { result = doCheckLinks(); // Retrieve configuration settings } else if ("_GetSettings".equals(functionName)) { result = doGetSettings(); // Disable a function } else if ("_DisableFunction".equals(functionName)) { String disabledFunction = functionRequest.getParameters().get("functionName"); result = doDisableFunction(disabledFunction); // Enable a function } else if ("_EnableFunction".equals(functionName)) { String enabledFunction = functionRequest.getParameters().get("functionName"); result = doEnableFunction(enabledFunction); // Reset the statistics } else if ("_ResetStatistics".equals(functionName)) { result = doResetStatistics(); // Reload the runtime properties } else if ("_ReloadProperties".equals(functionName)) { _engine.reloadPropertiesIfChanged(); result = SUCCESSFUL_RESULT; // Meta-function does not exist } else { throw new NoSuchFunctionException(functionName); } return result; } /** * Handles an exception caught while a function was executed. * * @param start * the start time of the call, as milliseconds since midnight January 1, * 1970. * * @param functionRequest * the request, never <code>null</code>. * * @param ip * the IP address of the requester, never <code>null</code>. * * @param callID * the call identifier, never <code>null</code>. * * @param exception * the exception caught, never <code>null</code>. * * @return * the call result, never <code>null</code>. */ FunctionResult handleFunctionException(long start, FunctionRequest functionRequest, String ip, int callID, Throwable exception) { Log.log_3500(exception, _name, callID); // Create a set of parameters for the result BasicPropertyReader resultParams = new BasicPropertyReader(); // Add the exception class String exceptionClass = exception.getClass().getName(); resultParams.set("_exception.class", exceptionClass); // Add the exception message, if any String exceptionMessage = exception.getMessage(); if (exceptionMessage != null) { exceptionMessage = exceptionMessage.trim(); if (exceptionMessage.length() > 0) { resultParams.set("_exception.message", exceptionMessage); } } // Add the stack trace, if any FastStringWriter stWriter = new FastStringWriter(360); PrintWriter printWriter = new PrintWriter(stWriter); exception.printStackTrace(printWriter); String stackTrace = stWriter.toString(); if (stackTrace != null) { stackTrace = stackTrace.trim(); if (stackTrace.length() > 0) { resultParams.set("_exception.stacktrace", stackTrace); } } return new FunctionResult("_InternalError", resultParams); } /** * Returns a list of all functions in this API. Per function the name and * the version are returned. * * @return * the call result, never <code>null</code>. */ private final FunctionResult doGetFunctionList() { // Initialize a builder FunctionResult builder = new FunctionResult(); // Loop over all functions int count = _functionList.size(); for (int i = 0; i < count; i++) { // Get some details about the function Function function = (Function) _functionList.get(i); String name = function.getName(); String version = function.getVersion(); String enabled = function.isEnabled() ? "true" : "false"; // Add an element describing the function ElementBuilder functionElem = new ElementBuilder("function"); functionElem.setAttribute("name", name ); functionElem.setAttribute("version", version); functionElem.setAttribute("enabled", enabled); builder.add(functionElem.createElement()); } return builder; } /** * Returns the call statistics for all functions in this API. * * @param detailed * If <code>true</code>, the unsuccessful result will be returned sorted * per error code. Otherwise the unsuccessful result won't be displayed * by error code. * * @return * the call result, never <code>null</code>. */ private final FunctionResult doGetStatistics(boolean detailed) { // Initialize a builder FunctionResult builder = new FunctionResult(); builder.param("startup", DateConverter.toDateString(_timeZone, _startupTimestamp)); builder.param("lastReset", DateConverter.toDateString(_timeZone, _lastStatisticsReset)); builder.param("now", DateConverter.toDateString(_timeZone, System.currentTimeMillis())); // Currently available processors Runtime rt = Runtime.getRuntime(); try { builder.param("availableProcessors", String.valueOf(rt.availableProcessors())); } catch (NoSuchMethodError error) { // NOTE: Runtime.availableProcessors() is not available in Java 1.3 } // Heap memory statistics ElementBuilder heap = new ElementBuilder("heap"); long free = rt.freeMemory(); long total = rt.totalMemory(); heap.setAttribute("used", String.valueOf(total - free)); heap.setAttribute("free", String.valueOf(free)); heap.setAttribute("total", String.valueOf(total)); try { heap.setAttribute("max", String.valueOf(rt.maxMemory())); } catch (NoSuchMethodError error) { // NOTE: Runtime.maxMemory() is not available in Java 1.3 } builder.add(heap.createElement()); // Function-specific statistics int count = _functionList.size(); for (int i = 0; i < count; i++) { Function function = (Function) _functionList.get(i); FunctionStatistics stats = function.getStatistics(); ElementBuilder functionElem = new ElementBuilder("function"); functionElem.setAttribute("name", function.getName()); // Successful Element successful = stats.getSuccessfulElement(); functionElem.addChild(successful); // Unsuccessful Element[] unsuccessful = stats.getUnsuccessfulElement(detailed); for(int j = 0; j < unsuccessful.length; j++) { functionElem.addChild(unsuccessful[j]); } builder.add(functionElem.createElement()); } return builder; } /** * Returns the XINS version. * * @return * the call result, never <code>null</code>. */ private final FunctionResult doGetVersion() { FunctionResult builder = new FunctionResult(); builder.param("java.version", System.getProperty("java.version")); builder.param("xmlenc.version", org.znerd.xmlenc.Library.getVersion()); builder.param("xins.version", Library.getVersion()); builder.param("api.version", _apiVersion); return builder; } /** * Returns the links in linked system components. It uses the * {@link CheckLinks} to connect to each link and builds a * {@link FunctionResult} which will have the total link count and total * link failures. * * @return * the call result, never <code>null</code>. */ private final FunctionResult doCheckLinks() { return CheckLinks.checkLinks(getProperties().descriptors()); } /** * Returns the settings. * * @return * the call result, never <code>null</code>. */ private final FunctionResult doGetSettings() { FunctionResult builder = new FunctionResult(); // Build settings Iterator names = _buildSettings.getNames(); ElementBuilder build = new ElementBuilder("build"); while (names.hasNext()) { String key = (String) names.next(); String value = _buildSettings.get(key); ElementBuilder property = new ElementBuilder("property"); property.setAttribute("name", key); property.setText(value); build.addChild(property.createElement()); } builder.add(build.createElement()); // Runtime settings names = _runtimeSettings.getNames(); ElementBuilder runtime = new ElementBuilder("runtime"); while (names.hasNext()) { String key = (String) names.next(); String value = _runtimeSettings.get(key); ElementBuilder property = new ElementBuilder("property"); property.setAttribute("name", key); property.setText(value); runtime.addChild(property.createElement()); } builder.add(runtime.createElement()); // System properties Properties sysProps; try { sysProps = System.getProperties(); } catch (SecurityException ex) { final String THIS_METHOD = "doGetSettings()"; final String SUBJECT_CLASS = "java.lang.System"; final String SUBJECT_METHOD = "getProperties()"; Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, null, ex); sysProps = new Properties(); } Enumeration e = sysProps.propertyNames(); ElementBuilder system = new ElementBuilder("system"); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String value = sysProps.getProperty(key); if ( key != null && key.trim().length() > 0 && value != null && value.trim().length() > 0) { ElementBuilder property = new ElementBuilder("property"); property.setAttribute("name", key); property.setText(value); system.addChild(property.createElement()); } } builder.add(system.createElement()); return builder; } /** * Enables a function. * * @param functionName * the name of the function to disable, can be <code>null</code>. * * @return * the call result, never <code>null</code>. */ private final FunctionResult doEnableFunction(String functionName) { // Get the name of the function to enable if (functionName == null || functionName.length() < 1) { InvalidRequestResult invalidRequest = new InvalidRequestResult(); invalidRequest.addMissingParameter("functionName"); return invalidRequest; } // Get the Function object Function function = getFunction(functionName); if (function == null) { return new InvalidRequestResult(); } // Enable or disable the function function.setEnabled(true); return SUCCESSFUL_RESULT; } /** * Disables a function. * * @param functionName * the name of the function to disable, can be <code>null</code>. * * @return * the call result, never <code>null</code>. */ private final FunctionResult doDisableFunction(String functionName) { // Get the name of the function to disable if (functionName == null || functionName.length() < 1) { InvalidRequestResult invalidRequest = new InvalidRequestResult(); invalidRequest.addMissingParameter("functionName"); return invalidRequest; } // Get the Function object Function function = getFunction(functionName); if (function == null) { return new InvalidRequestResult(); } // Enable or disable the function function.setEnabled(false); return SUCCESSFUL_RESULT; } /** * Resets the statistics. * * @return * the call result, never <code>null</code>. */ private final FunctionResult doResetStatistics() { // Remember when we last reset the statistics _lastStatisticsReset = System.currentTimeMillis(); // Function-specific statistics int count = _functionList.size(); for (int i = 0; i < count; i++) { Function function = (Function) _functionList.get(i); function.getStatistics().resetStatistics(); } return SUCCESSFUL_RESULT; } // Inner classes /** * Thread-safe <code>int</code> counter. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) */ private static final class Counter extends Object { // Constructors /** * Constructs a new <code>Counter</code> that initially returns the * value <code>0</code>. */ private Counter() { // empty } // Fields /** * The wrapped <code>int</code> number. Initially <code>0</code>. */ private int _value; // Methods /** * Retrieves the next value. The first time <code>0</code> is returned, * the second time <code>1</code>, etc. * * @return * the next sequence number. */ private synchronized int next() { return _value++; } } }
package org.sql2o; import junit.framework.TestCase; import org.sql2o.quirks.NoQuirks; import javax.sql.DataSource; import java.sql.*; import java.sql.Connection; import static org.mockito.Mockito.*; public class ConnectionTest extends TestCase { public void test_createQueryWithParams() throws Throwable { DataSource dataSource = mock(DataSource.class); Connection jdbcConnection = mock(Connection.class); when(jdbcConnection.isClosed()).thenReturn(false); when(dataSource.getConnection()).thenReturn(jdbcConnection); PreparedStatement ps = mock(PreparedStatement.class); when(jdbcConnection.prepareStatement(anyString())).thenReturn(ps); Sql2o sql2o = new Sql2o(dataSource,new NoQuirks(){ @Override public boolean returnGeneratedKeysByDefault() { return false; } }); org.sql2o.Connection cn = new org.sql2o.Connection(sql2o,false); cn.createQueryWithParams("select :p1 name, :p2 age", "Dmitry Alexandrov", 35).buildPreparedStatement(); verify(dataSource,times(1)).getConnection(); verify(jdbcConnection).isClosed(); verify(jdbcConnection,times(1)).prepareStatement("select ? name, ? age"); verify(ps,times(1)).setString(1,"Dmitry Alexandrov"); verify(ps,times(1)).setInt(2,35); // check statement still alive verify(ps,never()).close(); } public class MyException extends RuntimeException{} public void test_createQueryWithParamsThrowingException() throws Throwable { DataSource dataSource = mock(DataSource.class); Connection jdbcConnection = mock(Connection.class); when(jdbcConnection.isClosed()).thenReturn(false); when(dataSource.getConnection()).thenReturn(jdbcConnection); PreparedStatement ps = mock(PreparedStatement.class); doThrow(MyException.class).when(ps).setInt(anyInt(),anyInt()); when(jdbcConnection.prepareStatement(anyString())).thenReturn(ps); Sql2o sql2o = new Sql2o(dataSource,new NoQuirks(){ @Override public boolean returnGeneratedKeysByDefault() { return false; } }); try(org.sql2o.Connection cn = sql2o.open()){ cn.createQueryWithParams("select :p1 name, :p2 age", "Dmitry Alexandrov", 35).buildPreparedStatement(); fail("exception not thrown"); } catch (MyException ex){ // as designed } verify(dataSource,times(1)).getConnection(); verify(jdbcConnection,atLeastOnce()).isClosed(); verify(jdbcConnection,times(1)).prepareStatement("select ? name, ? age"); verify(ps,times(1)).setInt(2,35); // check statement was closed verify(ps,times(1)).close(); } }
// Getdown - application installer, patcher and launcher // This program is free software; you can redistribute it and/or modify it // any later version. // This program is distributed in the hope that it will be useful, but WITHOUT // more details. // this program; if not, write to the: Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA package com.threerings.getdown.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import com.samskivert.io.StreamUtil; import org.apache.commons.io.IOUtils; import com.threerings.getdown.Log; /** * File related utilities. */ public class FileUtil { /** * Gets the specified source file to the specified destination file by hook or crook. Windows * has all sorts of problems which we work around in this method. * * @return true if we managed to get the job done, false otherwise. */ public static boolean renameTo (File source, File dest) { // if we're on a civilized operating system we may be able to simple rename it if (source.renameTo(dest)) { return true; } // fall back to trying to rename the old file out of the way, rename the new file into // place and then delete the old file if (dest.exists()) { File temp = new File(dest.getPath() + "_old"); if (temp.exists()) { if (!temp.delete()) { Log.warning("Failed to delete old intermediate file " + temp + "."); // the subsequent code will probably fail } } if (dest.renameTo(temp)) { if (source.renameTo(dest)) { if (temp.delete()) { Log.warning("Failed to delete intermediate file " + temp + "."); } return true; } } } // as a last resort, try copying the old data over the new FileInputStream fin = null; FileOutputStream fout = null; try { fin = new FileInputStream(source); fout = new FileOutputStream(dest); IOUtils.copy(fin, fout); if (!source.delete()) { Log.warning("Failed to delete " + source + " after brute force copy to " + dest + "."); } return true; } catch (IOException ioe) { Log.warning("Failed to copy " + source + " to " + dest + ": " + ioe); return false; } finally { StreamUtil.close(fin); StreamUtil.close(fout); } } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui; import playn.java.JavaPlatform; import org.junit.*; import static org.junit.Assert.*; /** * Tests aspects of the {@link Styles} class. */ public class StylesTest { static { JavaPlatform.Config config = new JavaPlatform.Config(); config.headless = true; JavaPlatform.register(config); } @Test public void testEmpty () { Styles s = Styles.none(); checkIsNull(s, Style.COLOR); } @Test public void testNonReceiverMod () { Styles s = Styles.none(); checkIsNull(s, Style.COLOR); Styles s1 = s.add(Style.COLOR.is(0xFFAABBCC)); checkIsNull(s, Style.COLOR); checkEquals(0xFFAABBCC, s1, Style.COLOR); } @Test public void testAddsGets () { Styles s = Styles.make(Style.COLOR.is(0xFFAABBCC), Style.SHADOW.is(0xFF333333), Style.HIGHLIGHT.is(0xFFAAAAAA)); checkEquals(0xFFAABBCC, s, Style.COLOR); checkEquals(0xFF333333, s, Style.SHADOW); checkEquals(0xFFAAAAAA, s, Style.HIGHLIGHT); } @Test public void testOverwrite () { Styles s = Styles.make(Style.COLOR.is(0xFFAABBCC), Style.SHADOW.is(0xFF333333)); checkEquals(0xFFAABBCC, s, Style.COLOR); checkEquals(0xFF333333, s, Style.SHADOW); Styles ns = s.add(Style.COLOR.is(0xFFBBAACC)); checkEquals(0xFFBBAACC, ns, Style.COLOR); ns = s.add(Style.COLOR.is(0xFFBBAACC), Style.HIGHLIGHT.is(0xFFAAAAAA)); checkEquals(0xFFBBAACC, ns, Style.COLOR); checkEquals(0xFFAAAAAA, ns, Style.HIGHLIGHT); ns = s.add(Style.HIGHLIGHT.is(0xFFAAAAAA), Style.COLOR.is(0xFFBBAACC)); checkEquals(0xFFBBAACC, ns, Style.COLOR); checkEquals(0xFFAAAAAA, ns, Style.HIGHLIGHT); } @Test public void testClear () { Styles s = Styles.make(Style.COLOR.is(0xFFAABBCC), Style.SHADOW.is(0xFF333333)); checkEquals(0xFFAABBCC, s, Style.COLOR); checkEquals(0xFF333333, s, Style.SHADOW); s = s.clear(Style.Mode.DEFAULT, Style.COLOR); checkEquals(null, s, Style.COLOR); } protected static <V> void checkIsNull (Styles s, Style<V> style) { assertNull(s.get(style, new Label())); } protected static <V> void checkEquals (V value, Styles s, Style<V> style) { assertEquals(value, s.get(style, new Label())); } }
package org.jaxen.dom; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.util.HashMap; import java.util.Iterator; import java.util.NoSuchElementException; import org.jaxen.DefaultNavigator; import org.jaxen.FunctionCallException; import org.jaxen.Navigator; import org.jaxen.XPath; import org.jaxen.JaxenConstants; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; /** Interface for navigating around the W3C DOM Level 2 object model. * * <p> * This class is not intended for direct usage, but is * used by the Jaxen engine during evaluation. * </p> * * <p>This class implements the org.jaxen.DefaultNavigator interface * for the Jaxen XPath library, version 1.0beta3 (it is not guaranteed * to work with subsequent releases). This adapter allows the Jaxen * library to be used to execute XPath queries against any object tree * that implements the DOM level 2 interfaces.</p> * * <p>Note: DOM level 2 does not include a node representing an XML * Namespace declaration. This navigator will return Namespace decls * as instantiations of the custom {@link NamespaceNode} class, and * users will have to check result sets to locate and isolate * these.</p> * * @author David Megginson * @author James Strachan * * @see XPath * @see NamespaceNode */ public class DocumentNavigator extends DefaultNavigator { // Constants. /** * Constant: singleton navigator. */ private final static DocumentNavigator SINGLETON = new DocumentNavigator(); // Constructor. /** * Default Constructor. */ public DocumentNavigator () { } /** * Get a singleton DocumentNavigator for efficiency. * * @return a singleton instance of a DocumentNavigator. */ public static Navigator getInstance () { return SINGLETON; } // Implementation of org.jaxen.DefaultNavigator. /** * Get an iterator over all of this node's children. * * @param contextNode the context node for the child axis. * @return a possibly-empty iterator (not null) */ public Iterator getChildAxisIterator (Object contextNode) { return new NodeIterator ((Node)contextNode) { protected Node getFirstNode (Node node) { return node.getFirstChild(); } protected Node getNextNode (Node node) { return node.getNextSibling(); } }; } /** * Get a (single-member) iterator over this node's parent. * * @param contextNode the context node for the parent axis. * @return a possibly-empty iterator (not null) */ public Iterator getParentAxisIterator (Object contextNode) { Node node = (Node)contextNode; if (node.getNodeType() == Node.ATTRIBUTE_NODE) { return new NodeIterator (node) { protected Node getFirstNode (Node n) { // FIXME: assumes castability. return ((Attr)n).getOwnerElement(); } protected Node getNextNode (Node n) { return null; } }; } else { return new NodeIterator (node) { protected Node getFirstNode (Node n) { return n.getParentNode(); } protected Node getNextNode (Node n) { return null; } }; } } /** * Get an iterator over all following siblings. * * @param contextNode the context node for the sibling iterator. * @return a possibly-empty iterator (not null) */ public Iterator getFollowingSiblingAxisIterator (Object contextNode) { return new NodeIterator ((Node)contextNode) { protected Node getFirstNode (Node node) { return getNextNode(node); } protected Node getNextNode (Node node) { return node.getNextSibling(); } }; } /** * Get an iterator over all preceding siblings. * * @param contextNode the context node for the preceding sibling axis. * @return a possibly-empty iterator (not null) */ public Iterator getPrecedingSiblingAxisIterator (Object contextNode) { return new NodeIterator ((Node)contextNode) { protected Node getFirstNode (Node node) { return getNextNode(node); } protected Node getNextNode (Node node) { return node.getPreviousSibling(); } }; } /** * Get an iterator over all following nodes, depth-first. * * @param contextNode the context node for the following axis. * @return a possibly-empty iterator (not null) */ public Iterator getFollowingAxisIterator (Object contextNode) { return new NodeIterator ((Node)contextNode) { protected Node getFirstNode (Node node) { if (node == null) return null; else { Node sibling = node.getNextSibling(); if (sibling == null) return getFirstNode(node.getParentNode()); else return sibling; } } protected Node getNextNode (Node node) { if (node == null) return null; else { Node n = node.getFirstChild(); if (n == null) n = node.getNextSibling(); if (n == null) return getFirstNode(node.getParentNode()); else return n; } } }; } /** * Get an iterator over all preceding nodes, depth-first. * * @param contextNode the context node for the preceding axis. * @return a possibly-empty iterator (not null) */ public Iterator getPrecedingAxisIterator (Object contextNode) { return new NodeIterator ((Node)contextNode) { protected Node getFirstNode (Node node) { if (node == null) return null; Node sibling = node.getPreviousSibling(); if (sibling == null) return getFirstNode(node.getParentNode()); while (sibling != null) { node = sibling; sibling = node.getLastChild(); } return node; } protected Node getNextNode (Node node) { if (node == null) return null; else { Node n = node.getLastChild(); if (n == null) n = node.getPreviousSibling(); if (n == null) return getFirstNode(node.getParentNode()); else return n; } } }; } /** * Get an iterator over all attributes. * * @param contextNode the context node for the attribute axis * @return a possibly-empty iterator (not null) */ public Iterator getAttributeAxisIterator (Object contextNode) { if (isElement(contextNode)) { return new AttributeIterator((Node)contextNode); } else { return JaxenConstants.EMPTY_ITERATOR; } } /** * Get an iterator over all declared Namespaces. * * <p>Note: this iterator is not live: it takes a snapshot * and that snapshot remains static during the life of * the iterator (i.e. it won't reflect subsequent changes * to the DOM).</p> * * @param contextNode the context node for the namespace axis * @return a possibly-empty iterator (not null) */ public Iterator getNamespaceAxisIterator (Object contextNode) { // Only elements have Namespace nodes if (isElement(contextNode)) { HashMap nsMap = new HashMap(); // Start at the current node at walk // up to the root, noting what Namespace // declarations are in force. // TODO: deal with empty URI for // cancelling Namespace scope for (Node n = (Node)contextNode; n != null; n = n.getParentNode()) { if (n.hasAttributes()) { NamedNodeMap atts = n.getAttributes(); int length = atts.getLength(); for (int i = 0; i < length; i++) { Node att = atts.item(i); if (att.getNodeName().startsWith("xmlns")) { NamespaceNode ns = new NamespaceNode((Node)contextNode, att); // Add only if there's not a closer // declaration in force. String name = ns.getNodeName(); if (!nsMap.containsKey(name)) nsMap.put(name, ns); } } } } // Section 5.4 of the XPath rec requires // this to be present. nsMap.put("xml", new NamespaceNode((Node)contextNode, "xml", "http: // An empty default Namespace cancels // any previous default. NamespaceNode defaultNS = (NamespaceNode)nsMap.get(""); if (defaultNS != null && defaultNS.getNodeValue().length() == 0) nsMap.remove(""); return nsMap.values().iterator(); } else { return JaxenConstants.EMPTY_ITERATOR; } } /** Returns a parsed form of the given XPath string, which will be suitable * for queries on DOM documents. */ public XPath parseXPath (String xpath) throws org.jaxen.saxpath.SAXPathException { return new DOMXPath(xpath); } /** * Get the top-level document node. * * @param contextNode any node in the document * @return the root node */ public Object getDocumentNode (Object contextNode) { if (isDocument(contextNode)) return contextNode; else return ((Node)contextNode).getOwnerDocument(); } /** * Get the Namespace URI of an element. * * @param object the target node * @return a string (possibly empty) if the node is an element, * and null otherwise */ public String getElementNamespaceUri (Object object) { String uri = ((Node)object).getNamespaceURI(); return uri; } /** * Get the local name of an element. * * @param object the target node * @return a string representing the unqualified local name * if the node is an element, or null otherwise */ public String getElementName (Object object) { String name = ((Node)object).getLocalName(); if (name == null) name = ((Node)object).getNodeName(); return name; } /** * Get the qualified name of an element. * * @param object the target node * @return a string representing the qualified (i.e. possibly * prefixed) name if the node is an element, or null otherwise */ public String getElementQName (Object object) { String qname = ((Node)object).getNodeName(); if (qname == null) qname = ((Node)object).getLocalName(); return qname; } /** * Get the Namespace URI of an attribute. * * @param object the target node */ public String getAttributeNamespaceUri (Object object) { String uri = ((Node)object).getNamespaceURI(); return uri; } /** * Get the local name of an attribute. * * @param object the target node * @return a string representing the unqualified local name * if the node is an attribute, or null otherwise */ public String getAttributeName (Object object) { String name = ((Node)object).getLocalName(); if (name == null) name = ((Node)object).getNodeName(); return name; } /** * Get the qualified name of an attribute. * * @param object the target node * @return a string representing the qualified (i.e. possibly * prefixed) name if the node is an attribute, or null otherwise */ public String getAttributeQName (Object object) { String qname = ((Node)object).getNodeName(); if (qname == null) qname = ((Node)object).getLocalName(); return qname; } /** * Test if a node is a top-level document. * * @param object the target node * @return true if the node is the document root, false otherwise */ public boolean isDocument (Object object) { return (object instanceof Node) && (((Node)object).getNodeType() == Node.DOCUMENT_NODE); } /** * Test if a node is a namespace. * * @param object the target node * @return true if the node is a namespace, false otherwise */ public boolean isNamespace (Object object) { return (object instanceof NamespaceNode); } /** * Test if a node is an element. * * @param object the target node * @return true if the node is an element, false otherwise */ public boolean isElement (Object object) { return (object instanceof Node) && (((Node)object).getNodeType() == Node.ELEMENT_NODE); } /** * Test if a node is an attribute. <code>xmlns</code> and * <code>xmlns:pre</code> attributes do not count as attributes * for the purposes of XPath. * * @param object the target node * @return true if the node is an attribute, false otherwise */ public boolean isAttribute (Object object) { return (object instanceof Node) && (((Node)object).getNodeType() == Node.ATTRIBUTE_NODE) && ! "http: } /** * Test if a node is a comment. * * @param object the target node * @return true if the node is a comment, false otherwise */ public boolean isComment (Object object) { return (object instanceof Node) && (((Node)object).getNodeType() == Node.COMMENT_NODE); } /** * Test if a node is plain text. * * @param object the target node * @return true if the node is a text node, false otherwise */ public boolean isText (Object object) { if (object instanceof Node) { switch (((Node)object).getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: return true; default: return false; } } else { return false; } } /** * Test if a node is a processing instruction. * * @param object the target node * @return true if the node is a processing instruction, false otherwise */ public boolean isProcessingInstruction (Object object) { return (object instanceof Node) && (((Node)object).getNodeType() == Node.PROCESSING_INSTRUCTION_NODE); } /** * Get the string value of an element node. * * @param object the target node * @return the text inside the node and its descendants if the node * is an element, null otherwise */ public String getElementStringValue (Object object) { if (isElement(object)) return getStringValue((Node)object, new StringBuffer()).toString(); else return null; } /** * Construct an element's string value recursively. * * @param node the current node * @param buffer the buffer for building the text * @return the buffer passed as a parameter (for convenience) */ private StringBuffer getStringValue (Node node, StringBuffer buffer) { if (isText(node)) { buffer.append(node.getNodeValue()); } else { NodeList children = node.getChildNodes(); int length = children.getLength(); for (int i = 0; i < length; i++) getStringValue(children.item(i), buffer); } return buffer; } /** * Get the string value of an attribute node. * * @param object the target node * @return the text of the attribute value if the node is an * attribute, null otherwise */ public String getAttributeStringValue (Object object) { if (isAttribute(object)) return ((Node)object).getNodeValue(); else return null; } /** * Get the string value of text. * * @param object the target node * @return the string of text if the node is text, null otherwise */ public String getTextStringValue (Object object) { if (isText(object)) return ((Node)object).getNodeValue(); else return null; } /** * Get the string value of a comment node. * * @param object the target node * @return the text of the comment if the node is a comment, * null otherwise */ public String getCommentStringValue (Object object) { if (isComment(object)) return ((Node)object).getNodeValue(); else return null; } /** * Get the string value of a namespace node. * * @param object the target node * @return the namespace URI as a (possibly empty) string if the * node is a namespace node, null otherwise */ public String getNamespaceStringValue (Object object) { if (isNamespace(object)) return ((NamespaceNode)object).getNodeValue(); else return null; } /** * Get the prefix value of a Namespace node. * * @param object the target node * @return the Namespace prefix a (possibly empty) string if the * node is a namespace node, null otherwise */ public String getNamespacePrefix (Object object) { if (isNamespace(object)) return ((NamespaceNode)object).getLocalName(); else return null; } /** * Translate a Namespace prefix to a URI. */ public String translateNamespacePrefixToUri (String prefix, Object element) { Iterator it = getNamespaceAxisIterator(element); while (it.hasNext()) { NamespaceNode ns = (NamespaceNode)it.next(); if (prefix.equals(ns.getNodeName())) return ns.getNodeValue(); } return null; } /** * Use JAXP to load a namespace aware document from a given URI * * @param uri is the URI of the document to load * @return the new W3C DOM Level 2 Document instance * @throws FunctionCallException containing a nested exception * if a problem occurs trying to parse the given document */ public Object getDocument(String uri) throws FunctionCallException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse( uri ); } catch (Exception e) { throw new FunctionCallException("Failed to parse document for URI: " + uri, e); } } public String getProcessingInstructionTarget(Object obj) { ProcessingInstruction pi = (ProcessingInstruction) obj; return pi.getTarget(); } public String getProcessingInstructionData(Object obj) { ProcessingInstruction pi = (ProcessingInstruction) obj; return pi.getData(); } // Inner class: iterate over DOM nodes. // FIXME: needs to recurse into // DocumentFragment and EntityReference // to use their children. /** * A generic iterator over DOM nodes. * * <p>Concrete subclasses must implement the {@link #getFirstNode} * and {@link #getNextNode} methods for a specific iteration * strategy.</p> */ abstract class NodeIterator implements Iterator { /** * Constructor. * * @param contextNode the starting node. */ public NodeIterator (Node contextNode) { node = getFirstNode(contextNode); while (!isXPathNode(node)) node = getNextNode(node); } /** * @see Iterator#hasNext */ public boolean hasNext () { return (node != null); } /** * @see Iterator#next */ public Object next () { if (node == null) throw new NoSuchElementException(); Node ret = node; node = getNextNode(node); while (!isXPathNode(node)) node = getNextNode(node); return ret; } /** * @see Iterator#remove */ public void remove () { throw new UnsupportedOperationException(); } /** * Get the first node for iteration. * * <p>This method must derive an initial node for iteration * from a context node.</p> * * @param contextNode the starting node * @return the first node in the iteration * @see #getNextNode */ protected abstract Node getFirstNode (Node contextNode); /** * Get the next node for iteration. * * <p>This method must locate a following node from the * current context node.</p> * * @param contextNode the current node in the iteration * @return the following node in the iteration, or null * if there is none * @see #getFirstNode */ protected abstract Node getNextNode (Node contextNode); /** * Test whether a DOM node is usable by XPath. * * @param node the DOM node to test * @return true if the node is usable, false if it should be * skipped */ private boolean isXPathNode (Node node) { // null is usable, because it means end if (node == null) return true; switch (node.getNodeType()) { case Node.DOCUMENT_FRAGMENT_NODE: case Node.DOCUMENT_TYPE_NODE: case Node.ENTITY_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.NOTATION_NODE: return false; default: return true; } } private Node node; } // Inner class: iterate over a DOM named node map. /** * An iterator over an attribute list. */ class AttributeIterator implements Iterator { /** * Constructor. * * @param parent The parent DOM element for the attributes. */ AttributeIterator (Node parent) { this.map = parent.getAttributes(); this.pos = 0; } /** * @see Iterator#hasNext */ public boolean hasNext () { return pos < map.getLength(); } /** * @see Iterator#next */ public Object next () { Node attr = map.item(pos++); if (attr == null) throw new NoSuchElementException(); else return attr; } /** * @see Iterator#remove */ public void remove () { throw new UnsupportedOperationException(); } private NamedNodeMap map; private int pos; } /** * Returns the element whose ID is given by elementId. * If no such element exists, returns null. * Attributes with the name "ID" are not of type ID unless so defined. * Atribute types are only known if when the parser understands DTD's or * schemas that declare attributes of type ID. When JAXP is used, you * must call <code>setValidating(true)</code> on the * DocumentBuilderFactory. * * @param object a node from the document in which to look for the id * @param elementId id to look for * * @return element whose ID is given by elementId, or null if no such * element exists in the document or if the implementation * does not know about attribute types * @see javax.xml.parsers.DocumentBuilderFactory */ public Object getElementById(Object object, String elementId) { Document doc = (Document)getDocumentNode(object); if (doc != null) return doc.getElementById(elementId); else return null; } } // end of DocumentNavigator.java
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.lang.english; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import opennlp.tools.parser.Constituent; import opennlp.tools.parser.GapLabeler; import opennlp.tools.parser.Parse; import opennlp.tools.parser.chunking.Parser; /** * Class for storing the English head rules associated with parsing. */ public class HeadRules implements opennlp.tools.parser.HeadRules, GapLabeler { private static class HeadRule { public boolean leftToRight; public String[] tags; public HeadRule(boolean l2r, String[] tags) { leftToRight = l2r; this.tags = tags; } } private Map<String, HeadRule> headRules; private Set<String> punctSet; /** * Creates a new set of head rules based on the specified head rules file. * * @param ruleFile the head rules file. * * @throws IOException if the head rules file can not be read. */ public HeadRules(String ruleFile) throws IOException { this(new BufferedReader(new FileReader(ruleFile))); } /** * Creates a new set of head rules based on the specified reader. * * @param rulesReader the head rules reader. * * @throws IOException if the head rules reader can not be read. */ public HeadRules(BufferedReader rulesReader) throws IOException { readHeadRules(rulesReader); punctSet = new HashSet<String>(); punctSet.add("."); punctSet.add(","); punctSet.add("``"); punctSet.add("''"); punctSet.add(":"); } public Set<String> getPunctuationTags() { return punctSet; } public Parse getHead(Parse[] constituents, String type) { if (constituents[0].getType() == Parser.TOK_NODE) { return null; } HeadRule hr; if (type.equals("NP") || type.equals("NX")) { String[] tags1 = { "NN", "NNP", "NNPS", "NNS", "NX", "JJR", "POS" }; for (int ci = constituents.length - 1; ci >= 0; ci for (int ti = tags1.length - 1; ti >= 0; ti if (constituents[ci].getType().equals(tags1[ti])) { return constituents[ci].getHead(); } } } for (int ci = 0; ci < constituents.length; ci++) { if (constituents[ci].getType().equals("NP")) { return constituents[ci].getHead(); } } String[] tags2 = { "$", "ADJP", "PRN" }; for (int ci = constituents.length - 1; ci >= 0; ci for (int ti = tags2.length - 1; ti >= 0; ti if (constituents[ci].getType().equals(tags2[ti])) { return constituents[ci].getHead(); } } } String[] tags3 = { "JJ", "JJS", "RB", "QP" }; for (int ci = constituents.length - 1; ci >= 0; ci for (int ti = tags3.length - 1; ti >= 0; ti if (constituents[ci].getType().equals(tags3[ti])) { return constituents[ci].getHead(); } } } return constituents[constituents.length - 1].getHead(); } else if ((hr = (HeadRule) headRules.get(type)) != null) { String[] tags = hr.tags; int cl = constituents.length; int tl = tags.length; if (hr.leftToRight) { for (int ti = 0; ti < tl; ti++) { for (int ci = 0; ci < cl; ci++) { if (constituents[ci].getType().equals(tags[ti])) { return constituents[ci].getHead(); } } } return constituents[0].getHead(); } else { for (int ti = 0; ti < tl; ti++) { for (int ci = cl - 1; ci >= 0; ci if (constituents[ci].getType().equals(tags[ti])) { return constituents[ci].getHead(); } } } return constituents[cl - 1].getHead(); } } return constituents[constituents.length - 1].getHead(); } private void readHeadRules(BufferedReader str) throws IOException { String line; headRules = new HashMap<String, HeadRule>(30); while ((line = str.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); String num = st.nextToken(); String type = st.nextToken(); String dir = st.nextToken(); String[] tags = new String[Integer.parseInt(num)]; int ti = 0; while (st.hasMoreTokens()) { tags[ti] = st.nextToken(); ti++; } headRules.put(type, new HeadRule(dir.equals("1"), tags)); } } public void labelGaps(Stack<Constituent> stack) { if (stack.size() > 4) { //Constituent con0 = (Constituent) stack.get(stack.size()-1); Constituent con1 = (Constituent) stack.get(stack.size()-2); Constituent con2 = (Constituent) stack.get(stack.size()-3); Constituent con3 = (Constituent) stack.get(stack.size()-4); Constituent con4 = (Constituent) stack.get(stack.size()-5); //System.err.println("con0="+con0.label+" con1="+con1.label+" con2="+con2.label+" con3="+con3.label+" con4="+con4.label); //subject extraction if (con1.getLabel().equals("NP") && con2.getLabel().equals("S") && con3.getLabel().equals("SBAR")) { con1.setLabel(con1.getLabel()+"-G"); con2.setLabel(con2.getLabel()+"-G"); con3.setLabel(con3.getLabel()+"-G"); } //object extraction else if (con1.getLabel().equals("NP") && con2.getLabel().equals("VP") && con3.getLabel().equals("S") && con4.getLabel().equals("SBAR")) { con1.setLabel(con1.getLabel()+"-G"); con2.setLabel(con2.getLabel()+"-G"); con3.setLabel(con3.getLabel()+"-G"); con4.setLabel(con4.getLabel()+"-G"); } } } public void serialize(Writer writer) throws IOException { for (String type : headRules.keySet()) { HeadRule headRule = headRules.get(type); // write num of tags writer.write(Integer.toString(headRule.tags.length)); writer.write(' '); // write type writer.write(type); writer.write(' '); // write l2r true == 1 if (headRule.leftToRight) writer.write("1"); else writer.write("0"); // write tags for (String tag : headRule.tags) { writer.write(' '); writer.write(tag); } writer.write('\n'); } } }
package com.bladecoder.engine.ink; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.Json.Serializable; import com.badlogic.gdx.utils.JsonValue; import com.badlogic.gdx.utils.reflect.ReflectionException; import com.bladecoder.engine.actions.Action; import com.bladecoder.engine.actions.ActionCallback; import com.bladecoder.engine.actions.ActionCallbackQueue; import com.bladecoder.engine.actions.ActionFactory; import com.bladecoder.engine.assets.EngineAssetManager; import com.bladecoder.engine.model.Text.Type; import com.bladecoder.engine.model.VerbRunner; import com.bladecoder.engine.model.World; import com.bladecoder.engine.util.ActionCallbackSerialization; import com.bladecoder.engine.util.ActionUtils; import com.bladecoder.engine.util.EngineLogger; import com.bladecoder.ink.runtime.Choice; import com.bladecoder.ink.runtime.InkList; import com.bladecoder.ink.runtime.Story; public class InkManager implements VerbRunner, Serializable { public final static char NAME_VALUE_TAG_SEPARATOR = ':'; public final static char NAME_VALUE_PARAM_SEPARATOR = '='; private final static String PARAM_SEPARATOR = ","; private final static char COMMAND_MARK = '>'; private Story story = null; private ExternalFunctions externalFunctions; private ActionCallback cb; private ArrayList<Action> actions; private boolean wasInCutmode; private String storyName; private int ip = -1; public InkManager() { externalFunctions = new ExternalFunctions(); actions = new ArrayList<Action>(); } public void newStory(InputStream is) throws Exception { String json = getJsonString(is); story = new Story(json); externalFunctions.bindExternalFunctions(this); } public void newStory(String storyName) throws Exception { FileHandle asset = EngineAssetManager.getInstance() .getAsset(EngineAssetManager.MODEL_DIR + storyName + EngineAssetManager.INK_EXT); try { long initTime = System.currentTimeMillis(); newStory(asset.read()); EngineLogger.debug("INK STORY LOADING TIME (ms): " + (System.currentTimeMillis() - initTime)); this.storyName = storyName; } catch (Exception e) { EngineLogger.error("Cannot load Ink Story: " + storyName + " " + e.getMessage()); } } public String getVariable(String name) { return story.getVariablesState().get(name).toString(); } public boolean compareVariable(String name, String value) { if(story.getVariablesState().get(name) instanceof InkList) { return ((InkList)story.getVariablesState().get(name)).ContainsItemNamed(value); } else { return story.getVariablesState().get(name).toString().equals(value); } } public void setVariable(String name, String value) throws Exception { if(story.getVariablesState().get(name) instanceof InkList) { ((InkList)story.getVariablesState().get(name)).addItem(value); } else story.getVariablesState().set(name, value); } private void continueMaximally() { String line = null; actions.clear(); HashMap<String, String> currentLineParams = new HashMap<String, String>(); while (story.canContinue()) { try { line = story.Continue(); currentLineParams.clear(); // Remove trailing '\n' if (!line.isEmpty()) line = line.substring(0, line.length() - 1); if (!line.isEmpty()) { EngineLogger.debug("INK LINE: " + line); processParams(story.getCurrentTags(), currentLineParams); // PROCESS COMMANDS if (line.charAt(0) == COMMAND_MARK) { processCommand(currentLineParams, line); } else { processTextLine(currentLineParams, line); } } else { EngineLogger.debug("INK EMPTY LINE!"); } } catch (Exception e) { EngineLogger.error(e.getMessage(), e); } if(story.getCurrentErrors() != null && !story.getCurrentErrors().isEmpty()) { EngineLogger.error(story.getCurrentErrors().get(0)); } } if (actions.size() > 0) { run(); } else { if (hasChoices()) { wasInCutmode = World.getInstance().inCutMode(); World.getInstance().setCutMode(false); } else if (cb != null) { ActionCallbackQueue.add(cb); } } } private void processParams(List<String> input, HashMap<String, String> output) { for (String t : input) { String key; String value; int i = t.indexOf(NAME_VALUE_TAG_SEPARATOR); // support ':' and '=' as param separator if(i == -1) i = t.indexOf(NAME_VALUE_PARAM_SEPARATOR); if (i != -1) { key = t.substring(0, i).trim(); value = t.substring(i + 1, t.length()).trim(); } else { key = t.trim(); value = null; } EngineLogger.debug("PARAM: " + key + " value: " + value); output.put(key, value); } } private void processCommand(HashMap<String, String> params, String line) { String commandName = null; String commandParams[] = null; int i = line.indexOf(NAME_VALUE_TAG_SEPARATOR); if (i == -1) { commandName = line.substring(1).trim(); } else { commandName = line.substring(1, i).trim(); commandParams = line.substring(i + 1).split(PARAM_SEPARATOR); processParams(Arrays.asList(commandParams), params); } if ("leave".equals(commandName)) { World.getInstance().setCurrentScene(params.get("scene")); } else if ("set".equals(commandName)) { World.getInstance().setModelProp(params.get("prop"), params.get("value")); } else { // for backward compatibility if ("action".equals(commandName)) { commandName = commandParams[0].trim(); params.remove(commandName); } // Some preliminar validation to see if it's an action if (commandName.length() > 0 && Character.isUpperCase(commandName.charAt(0))) { // Try to create action by default Action action; try { action = ActionFactory.createByClass("com.bladecoder.engine.actions." + commandName + "Action", params); actions.add(action); } catch (ClassNotFoundException | ReflectionException e) { EngineLogger.error(e.getMessage(), e); } } else { EngineLogger.error("Ink command not found: " + commandName); } } } private void processTextLine(HashMap<String, String> params, String line) { // Get actor name from Line. Actor is separated by ':'. // ej. "Johnny: Hello punks!" if (!params.containsKey("actor")) { int idx = line.indexOf(NAME_VALUE_TAG_SEPARATOR); if (idx != -1) { params.put("actor", line.substring(0, idx).trim()); line = line.substring(idx + 1).trim(); } } if (!params.containsKey("actor") && World.getInstance().getCurrentScene().getPlayer() != null) { // params.put("actor", Scene.VAR_PLAYER); if (!params.containsKey("type")) { params.put("type", Type.SUBTITLE.toString()); } } else if (params.containsKey("actor") && !params.containsKey("type")) { params.put("type", Type.TALK.toString()); } else if (!params.containsKey("type")) { params.put("type", Type.SUBTITLE.toString()); } params.put("text", line); try { if (!params.containsKey("actor")) { Action action = ActionFactory.createByClass("com.bladecoder.engine.actions.TextAction", params); actions.add(action); } else { Action action = ActionFactory.createByClass("com.bladecoder.engine.actions.SayAction", params); actions.add(action); } } catch (ClassNotFoundException | ReflectionException e) { EngineLogger.error(e.getMessage(), e); } } private void nextStep() { if (ip < 0) { continueMaximally(); } else { boolean stop = false; while (ip < actions.size() && !stop) { Action a = actions.get(ip); try { if (a.run(this)) stop = true; else ip++; } catch (Exception e) { EngineLogger.error("EXCEPTION EXECUTING ACTION: " + a.getClass().getSimpleName(), e); ip++; } } if (ip >= actions.size() && !stop) continueMaximally(); } } public Story getStory() { return story; } public void run(String path, ActionCallback cb) throws Exception { if (story == null) { EngineLogger.error("Ink Story not loaded!"); return; } this.cb = cb; story.choosePathString(path); continueMaximally(); } public boolean hasChoices() { return (story != null && actions.size() == 0 && story.getCurrentChoices().size() > 0); } public List<Choice> getChoices() { return story.getCurrentChoices(); } private String getJsonString(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); // Replace the BOM mark if (line != null) line = line.replace('\uFEFF', ' '); while (line != null) { sb.append(line); sb.append("\n"); line = br.readLine(); } return sb.toString(); } finally { br.close(); } } @Override public void resume() { ip++; nextStep(); } public void selectChoice(int i) { World.getInstance().setCutMode(wasInCutmode); try { story.chooseChoiceIndex(i); continueMaximally(); } catch (Exception e) { EngineLogger.error(e.getMessage(), e); } } @Override public ArrayList<Action> getActions() { return actions; } @Override public void run() { ip = 0; nextStep(); } @Override public int getIP() { return ip; } @Override public void setIP(int ip) { this.ip = ip; } @Override public void cancel() { ArrayList<Action> actions = getActions(); for (Action c : actions) { if (c instanceof VerbRunner) ((VerbRunner) c).cancel(); } ip = actions.size(); } @Override public String getTarget() { return null; } @Override public void write(Json json) { json.writeValue("wasInCutmode", wasInCutmode); json.writeValue("cb", ActionCallbackSerialization.find(cb)); // SAVE ACTIONS json.writeArrayStart("actions"); for (Action a : actions) { ActionUtils.writeJson(a, json); } json.writeArrayEnd(); json.writeValue("ip", ip); json.writeArrayStart("actionsSer"); for (Action a : actions) { if (a instanceof Serializable) { json.writeObjectStart(); ((Serializable) a).write(json); json.writeObjectEnd(); } } json.writeArrayEnd(); // SAVE STORY json.writeValue("storyName", storyName); if (story != null) { try { json.writeValue("story", story.getState().toJson()); } catch (Exception e) { EngineLogger.error(e.getMessage(), e); } } } @Override public void read(Json json, JsonValue jsonData) { wasInCutmode = json.readValue("wasInCutmode", Boolean.class, jsonData); cb = ActionCallbackSerialization.find(json.readValue("cb", String.class, jsonData)); // READ ACTIONS actions.clear(); JsonValue actionsValue = jsonData.get("actions"); for (int i = 0; i < actionsValue.size; i++) { JsonValue aValue = actionsValue.get(i); Action a = ActionUtils.readJson(json, aValue); actions.add(a); } ip = json.readValue("ip", Integer.class, jsonData); actionsValue = jsonData.get("actionsSer"); int i = 0; for (Action a : actions) { if (a instanceof Serializable && i < actionsValue.size) { if (actionsValue.get(i) == null) break; ((Serializable) a).read(json, actionsValue.get(i)); i++; } } // READ STORY String storyName = json.readValue("storyName", String.class, jsonData); String storyString = json.readValue("story", String.class, jsonData); if (storyString != null) { try { newStory(storyName); long initTime = System.currentTimeMillis(); story.getState().loadJson(storyString); EngineLogger.debug("INK SAVED STATE LOADING TIME (ms): " + (System.currentTimeMillis() - initTime)); } catch (Exception e) { EngineLogger.error(e.getMessage(), e); } } } }
package ai.susi.server.api.cms; import ai.susi.DAO; import ai.susi.json.JsonObjectWithDefault; import ai.susi.server.*; import org.json.JSONArray; import org.json.JSONObject; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.util.ArrayList; public class GetAllLanguages extends AbstractAPIHandler implements APIHandler { private static final long serialVersionUID = -7872551914189898030L; @Override public BaseUserRole getMinimalBaseUserRole() { return BaseUserRole.ANONYMOUS; } @Override public JSONObject getDefaultPermissions(BaseUserRole baseUserRole) { return null; } @Override public String getAPIPath() { return "/cms/getAllLanguages.json"; } @Override public ServiceResponse serviceImpl(Query call, HttpServletResponse response, Authorization rights, final JsonObjectWithDefault permissions) { String model_name = call.get("model", "general"); File model = new File(DAO.model_watch_dir, model_name); String group_name = call.get("group", "knowledge"); File group = new File(model, group_name); String[] languages = group.list((current, name) -> new File(current, name).isDirectory()); JSONArray languagesArray = new JSONArray(languages); return new ServiceResponse(languagesArray); } }
package org.jsimpledb.kv.raft; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Iterables; import com.google.common.primitives.Bytes; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.security.SecureRandom; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.dellroad.stuff.io.ByteBufferInputStream; import org.dellroad.stuff.io.ByteBufferOutputStream; import org.dellroad.stuff.java.TimedWait; import org.iq80.leveldb.Options; import org.iq80.leveldb.impl.Iq80DBFactory; import org.jsimpledb.kv.CloseableKVStore; import org.jsimpledb.kv.KVDatabase; import org.jsimpledb.kv.KVStore; import org.jsimpledb.kv.KVTransactionException; import org.jsimpledb.kv.KeyRange; import org.jsimpledb.kv.KeyRanges; import org.jsimpledb.kv.RetryTransactionException; import org.jsimpledb.kv.StaleTransactionException; import org.jsimpledb.kv.leveldb.LevelDBKVStore; import org.jsimpledb.kv.mvcc.AtomicKVStore; import org.jsimpledb.kv.mvcc.MutableView; import org.jsimpledb.kv.mvcc.Mutations; import org.jsimpledb.kv.mvcc.Reads; import org.jsimpledb.kv.mvcc.Writes; import org.jsimpledb.kv.raft.msg.AppendRequest; import org.jsimpledb.kv.raft.msg.AppendResponse; import org.jsimpledb.kv.raft.msg.CommitRequest; import org.jsimpledb.kv.raft.msg.CommitResponse; import org.jsimpledb.kv.raft.msg.GrantVote; import org.jsimpledb.kv.raft.msg.InstallSnapshot; import org.jsimpledb.kv.raft.msg.Message; import org.jsimpledb.kv.raft.msg.MessageSwitch; import org.jsimpledb.kv.raft.msg.RequestVote; import org.jsimpledb.kv.raft.net.Network; import org.jsimpledb.kv.raft.net.TCPNetwork; import org.jsimpledb.kv.util.PrefixKVStore; import org.jsimpledb.util.ByteUtil; import org.jsimpledb.util.LongEncoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RaftKVDatabase implements KVDatabase { /** * Default minimum election timeout ({@value #DEFAULT_MIN_ELECTION_TIMEOUT}ms). * * @see #setMinElectionTimeout */ public static final int DEFAULT_MIN_ELECTION_TIMEOUT = 750; /** * Default maximum election timeout ({@value #DEFAULT_MAX_ELECTION_TIMEOUT}ms). * * @see #setMaxElectionTimeout */ public static final int DEFAULT_MAX_ELECTION_TIMEOUT = 1000; /** * Default heartbeat timeout ({@value DEFAULT_HEARTBEAT_TIMEOUT}ms). * * @see #setHeartbeatTimeout */ public static final int DEFAULT_HEARTBEAT_TIMEOUT = 200; /** * Default maximum supported outstanding transaction duration ({@value DEFAULT_MAX_TRANSACTION_DURATION}ms). * * @see #setMaxTransactionDuration */ public static final int DEFAULT_MAX_TRANSACTION_DURATION = 5 * 1000; /** * Default maximum supported applied log entry memory usage ({@value DEFAULT_MAX_APPLIED_LOG_MEMORY} bytes). * * @see #setMaxAppliedLogMemory */ public static final long DEFAULT_MAX_APPLIED_LOG_MEMORY = 100 * 1024 * 1024; // 100MB /** * Default transaction commit timeout ({@value DEFAULT_COMMIT_TIMEOUT}). * * @see #setCommitTimeout * @see RaftKVTransaction#setTimeout */ public static final int DEFAULT_COMMIT_TIMEOUT = 5000; // 5 seconds // Internal constants private static final int MAX_SNAPSHOT_TRANSMIT_AGE = (int)TimeUnit.SECONDS.toMillis(90); // 90 seconds private static final int MAX_SLOW_FOLLOWER_APPLY_DELAY_HEARTBEATS = 10; private static final int MAX_UNAPPLIED_LOG_ENTRIES = 64; private static final int FOLLOWER_LINGER_HEARTBEATS = 3; // how long to keep updating removed followers private static final float MAX_CLOCK_DRIFT = 0.01f; // max clock drift (ratio) in one min election timeout // File prefixes and suffixes private static final String TX_FILE_PREFIX = "tx-"; private static final String TEMP_FILE_PREFIX = "temp-"; private static final String TEMP_FILE_SUFFIX = ".tmp"; private static final String KVSTORE_FILE_SUFFIX = ".kvstore"; private static final Pattern TEMP_FILE_PATTERN = Pattern.compile(".*" + Pattern.quote(TEMP_FILE_SUFFIX)); private static final Pattern KVSTORE_FILE_PATTERN = Pattern.compile(".*" + Pattern.quote(KVSTORE_FILE_SUFFIX)); // Keys for persistent Raft state private static final byte[] CLUSTER_ID_KEY = ByteUtil.parse("0001"); private static final byte[] CURRENT_TERM_KEY = ByteUtil.parse("0002"); private static final byte[] LAST_APPLIED_TERM_KEY = ByteUtil.parse("0003"); private static final byte[] LAST_APPLIED_INDEX_KEY = ByteUtil.parse("0004"); private static final byte[] LAST_APPLIED_CONFIG_KEY = ByteUtil.parse("0005"); private static final byte[] VOTED_FOR_KEY = ByteUtil.parse("0006"); // Prefix for all state machine key/value keys private static final byte[] STATE_MACHINE_PREFIX = ByteUtil.parse("80"); // Logging private final Logger log = LoggerFactory.getLogger(this.getClass()); // Configuration state private Network network = new TCPNetwork(); private String identity; private AtomicKVStore kvstore; private int minElectionTimeout = DEFAULT_MIN_ELECTION_TIMEOUT; private int maxElectionTimeout = DEFAULT_MAX_ELECTION_TIMEOUT; private int heartbeatTimeout = DEFAULT_HEARTBEAT_TIMEOUT; private int maxTransactionDuration = DEFAULT_MAX_TRANSACTION_DURATION; private int commitTimeout = DEFAULT_COMMIT_TIMEOUT; private long maxAppliedLogMemory = DEFAULT_MAX_APPLIED_LOG_MEMORY; private File logDir; // Raft runtime state private Role role; // Raft state: LEADER, FOLLOWER, or CANDIDATE private SecureRandom random; // used to randomize election timeout, etc. private int clusterId; // cluster ID (zero if unconfigured - usually) private long currentTerm; // current Raft term (zero if unconfigured) private long commitIndex; // current Raft commit index (zero if unconfigured) private long lastAppliedTerm; // key/value store last applied term (zero if unconfigured) private long lastAppliedIndex; // key/value store last applied index (zero if unconfigured) private final ArrayList<LogEntry> raftLog = new ArrayList<>(); // unapplied log entries (empty if unconfigured) private Map<String, String> lastAppliedConfig; // key/value store last applied config (empty if none) private Map<String, String> currentConfig; // most recent cluster config (empty if unconfigured) // Non-Raft runtime state private AtomicKVStore kv; private FileChannel logDirChannel; private ScheduledExecutorService executor; private String returnAddress; // return address for message currently being processed private final HashSet<String> transmitting = new HashSet<>(); // network addresses whose output queues are not empty private final HashMap<Long, RaftKVTransaction> openTransactions = new HashMap<>(); private final LinkedHashSet<Service> pendingService = new LinkedHashSet<>(); private boolean performingService; private boolean shuttingDown; // prevents new transactions from being created // Configuration public synchronized void setKVStore(AtomicKVStore kvstore) { Preconditions.checkState(this.role == null, "already started"); this.kvstore = kvstore; } public synchronized void setLogDirectory(File directory) { Preconditions.checkState(this.role == null, "already started"); this.logDir = directory; } public synchronized void setNetwork(Network network) { Preconditions.checkState(this.role == null, "already started"); this.network = network; } public synchronized void setIdentity(String identity) { Preconditions.checkState(this.role == null, "already started"); this.identity = identity; } /** * Get this node's Raft identity. * * @return the unique identity of this node in its cluster */ public synchronized String getIdentity() { return this.identity; } public synchronized void setMinElectionTimeout(int timeout) { Preconditions.checkArgument(timeout > 0, "timeout <= 0"); Preconditions.checkState(this.role == null, "already started"); this.minElectionTimeout = timeout; } public synchronized void setMaxElectionTimeout(int timeout) { Preconditions.checkArgument(timeout > 0, "timeout <= 0"); Preconditions.checkState(this.role == null, "already started"); this.maxElectionTimeout = timeout; } public synchronized void setHeartbeatTimeout(int timeout) { Preconditions.checkArgument(timeout > 0, "timeout <= 0"); Preconditions.checkState(this.role == null, "already started"); this.heartbeatTimeout = timeout; } public synchronized void setMaxTransactionDuration(int duration) { Preconditions.checkArgument(duration > 0, "duration <= 0"); this.maxTransactionDuration = duration; } public synchronized void setMaxAppliedLogMemory(long memory) { Preconditions.checkArgument(memory > 0, "memory <= 0"); this.maxAppliedLogMemory = memory; } public synchronized void setCommitTimeout(int timeout) { Preconditions.checkArgument(timeout >= 0, "timeout < 0"); this.commitTimeout = commitTimeout; } // Lifecycle @PostConstruct public synchronized void start() throws IOException { // Sanity check assert this.checkState(); if (this.role != null) return; Preconditions.checkState(!this.shuttingDown, "shutdown in progress"); Preconditions.checkState(this.logDir != null, "no log directory configured"); Preconditions.checkState(this.network != null, "no network configured"); Preconditions.checkState(this.kv == null, "key/value store exists"); Preconditions.checkState(this.minElectionTimeout <= this.maxElectionTimeout, "minElectionTimeout > maxElectionTimeout"); Preconditions.checkState(this.heartbeatTimeout < this.minElectionTimeout, "heartbeatTimeout >= minElectionTimeout"); Preconditions.checkState(this.identity != null, "no identity configured"); // Log this.info("starting " + this + " in directory " + this.logDir); // Start up local database boolean success = false; try { // Create/verify log directory if (!this.logDir.exists() && !this.logDir.isDirectory()) throw new IOException("failed to create directory `" + this.logDir + "'"); if (!this.logDir.isDirectory()) throw new IOException("file `" + this.logDir + "' is not a directory"); // By default use an atomic key/value store based on LevelDB if not explicitly specified if (this.kvstore != null) this.kv = this.kvstore; else { final File leveldbDir = new File(this.logDir, "levedb" + KVSTORE_FILE_SUFFIX); if (!leveldbDir.exists() && !leveldbDir.mkdirs()) throw new IOException("failed to create directory `" + leveldbDir + "'"); if (!leveldbDir.isDirectory()) throw new IOException("file `" + leveldbDir + "' is not a directory"); this.kv = new LevelDBKVStore(new Iq80DBFactory().open(leveldbDir, new Options().createIfMissing(true))); } // Open directory containing log entry files so we have a way to fsync() it assert this.logDirChannel == null; this.logDirChannel = FileChannel.open(this.logDir.toPath(), StandardOpenOption.READ); // Create randomizer assert this.random == null; this.random = new SecureRandom(); // Start up executor thread assert this.executor == null; this.executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable action) { return new ServiceThread(action); } }); // Start network this.network.start(new Network.Handler() { @Override public void handle(String sender, ByteBuffer buf) { RaftKVDatabase.this.handle(sender, buf); } @Override public void outputQueueEmpty(String address) { RaftKVDatabase.this.outputQueueEmpty(address); } }); // Reload persistent raft info this.clusterId = (int)this.decodeLong(CLUSTER_ID_KEY, 0); this.currentTerm = this.decodeLong(CURRENT_TERM_KEY, 0); final String votedFor = this.decodeString(VOTED_FOR_KEY, null); this.lastAppliedTerm = this.decodeLong(LAST_APPLIED_TERM_KEY, 0); this.lastAppliedIndex = this.decodeLong(LAST_APPLIED_INDEX_KEY, 0); this.lastAppliedConfig = this.decodeConfig(LAST_APPLIED_CONFIG_KEY); this.currentConfig = this.buildCurrentConfig(); // If we crashed part way through a snapshot install, recover by resetting state machine if (this.lastAppliedTerm < 0 || this.lastAppliedIndex < 0) { this.info("detected partially applied snapshot, resetting state machine"); if (!this.resetStateMachine(true)) throw new IOException("error resetting state machine"); } // Initialize commit index this.commitIndex = this.lastAppliedIndex; // Reload outstanding log entries from disk this.loadLog(); // Show recovered state this.info("recovered Raft state:" + "\n clusterId=" + (this.clusterId != 0 ? String.format("0x%08x", this.clusterId) : "none") + "\n currentTerm=" + this.currentTerm + "\n lastApplied=" + this.lastAppliedIndex + "t" + this.lastAppliedTerm + "\n lastAppliedConfig=" + this.lastAppliedConfig + "\n currentConfig=" + this.currentConfig + "\n votedFor=" + (votedFor != null ? "\"" + votedFor + "\"" : "nobody") + "\n log=" + this.raftLog); // Validate recovered state if (this.isConfigured()) { Preconditions.checkArgument(this.clusterId != 0); Preconditions.checkArgument(this.currentTerm > 0); Preconditions.checkArgument(this.getLastLogTerm() > 0); Preconditions.checkArgument(this.getLastLogIndex() > 0); Preconditions.checkArgument(!this.currentConfig.isEmpty()); } else { Preconditions.checkArgument(this.lastAppliedTerm == 0); Preconditions.checkArgument(this.lastAppliedIndex == 0); Preconditions.checkArgument(this.currentTerm == 0); Preconditions.checkArgument(this.getLastLogTerm() == 0); Preconditions.checkArgument(this.getLastLogIndex() == 0); Preconditions.checkArgument(this.currentConfig.isEmpty()); Preconditions.checkArgument(this.raftLog.isEmpty()); } // Start as follower (with unknown leader) this.changeRole(new FollowerRole(this, null, null, votedFor)); // Done success = true; } finally { if (!success) this.cleanup(); } // Sanity check assert this.checkState(); } /** * Stop this instance. * * <p> * Does nothing if not {@linkplain #start started} or in the process of shutting down. * </p> */ @PreDestroy public void stop() { // Set flag to prevent new transactions synchronized (this) { // Sanity check assert this.checkState(); if (this.role == null || this.shuttingDown) return; // Set shutting down flag this.info("starting shutdown of " + this); this.shuttingDown = true; // Fail all remaining open transactions for (RaftKVTransaction tx : new ArrayList<RaftKVTransaction>(this.openTransactions.values())) { switch (tx.getState()) { case EXECUTING: tx.rollback(); break; case COMMIT_READY: case COMMIT_WAITING: this.fail(tx, new KVTransactionException(tx, "database shutdown")); break; case COMPLETED: break; default: assert false; break; } } // Sleep while we wait for transactions to clean themselves up boolean done = false; try { done = TimedWait.wait(this, 5000, new org.dellroad.stuff.java.Predicate() { @Override public boolean test() { return RaftKVDatabase.this.openTransactions.isEmpty(); } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (!done) this.warn("open transactions not cleaned up during shutdown"); } // Shut down the executor and wait for pending tasks to finish this.executor.shutdownNow(); try { this.executor.awaitTermination(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // Final cleanup synchronized (this) { this.executor = null; this.cleanup(); } // Done this.info("completed shutdown of " + this); } private void cleanup() { assert Thread.holdsLock(this); assert this.openTransactions.isEmpty(); if (this.role != null) { this.role.shutdown(); this.role = null; } if (this.executor != null) { this.executor.shutdownNow(); try { this.executor.awaitTermination(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.executor = null; } if (this.kv != null) { if (this.kvstore == null) { final LevelDBKVStore ldb = (LevelDBKVStore)this.kv; Util.closeIfPossible(ldb); Util.closeIfPossible(ldb.getDB()); } this.kv = null; } Util.closeIfPossible(this.logDirChannel); this.logDirChannel = null; this.raftLog.clear(); this.random = null; this.network.stop(); this.currentTerm = 0; this.commitIndex = 0; this.clusterId = 0; this.lastAppliedTerm = 0; this.lastAppliedIndex = 0; this.lastAppliedConfig = null; this.currentConfig = null; this.transmitting.clear(); this.pendingService.clear(); this.shuttingDown = false; } /** * Initialize our in-memory state from the persistent state reloaded from disk. * This is invoked on initial startup. */ private void loadLog() throws IOException { // Sanity check assert Thread.holdsLock(this); // Scan for log entry files this.raftLog.clear(); for (File file : this.logDir.listFiles()) { // Is this a log entry file? if (LogEntry.LOG_FILE_PATTERN.matcher(file.getName()).matches()) { this.info("recovering log file " + file.getName()); this.raftLog.add(LogEntry.fromFile(file)); continue; } // Is this a leftover temporary file? if (TEMP_FILE_PATTERN.matcher(file.getName()).matches()) { this.info("deleting leftover temporary file " + file.getName()); if (!file.delete()) this.error("failed to delete leftover temporary file " + file); continue; } // Is this a KV store directory (expected)? if (KVSTORE_FILE_PATTERN.matcher(file.getName()).matches()) continue; // Unknown this.warn("ignoring unrecognized file " + file.getName() + " in my log directory"); } // Verify we have a contiguous range of log entries starting from the snapshot index; discard bogus log files Collections.sort(this.raftLog, LogEntry.SORT_BY_INDEX); long lastTermSeen = this.lastAppliedTerm; long expectedIndex = this.lastAppliedIndex + 1; for (Iterator<LogEntry> i = this.raftLog.iterator(); i.hasNext(); ) { final LogEntry logEntry = i.next(); String error = null; if (logEntry.getTerm() < lastTermSeen) error = "term " + logEntry.getTerm() + " < last applied term " + lastTermSeen; else if (logEntry.getIndex() < this.lastAppliedIndex) error = "index " + logEntry.getIndex() + " < last applied index " + this.lastAppliedIndex; else if (logEntry.getIndex() != expectedIndex) error = "index " + logEntry.getIndex() + " != expected index " + expectedIndex; if (error != null) { this.warn("deleting bogus log file " + logEntry.getFile().getName() + ": " + error); if (!logEntry.getFile().delete()) this.error("failed to delete bogus log file " + logEntry.getFile()); i.remove(); } else { expectedIndex++; lastTermSeen = logEntry.getTerm(); } } this.info("recovered " + this.raftLog.size() + " Raft log entries: " + this.raftLog); // Rebuild current configuration this.currentConfig = this.buildCurrentConfig(); } private Map<String, String> buildCurrentConfig() { // Start with last applied config final HashMap<String, String> config = new HashMap<>(this.lastAppliedConfig); // Apply any changes found in uncommitted log entries for (LogEntry logEntry : this.raftLog) logEntry.applyConfigChange(config); // Done return config; } // Configuration Stuff /** * Retrieve the unique 32-bit ID for this node's cluster. * * <p> * A value of zero indicates an unconfigured system. Usually the reverse true, though an unconfigured system * can have a non-zero cluster ID in the rare case where an error occurred persisting the initial log entry. * * @return unique cluster ID, or zero if this node is unconfigured */ public synchronized int getClusterId() { return this.clusterId; } /** * Retrieve the current cluster configuration as understood by this node. * * <p> * Configuration changes are performed and committed in the context of a normal transaction; see * {@link RaftKVTransaction#configChange RaftKVTransaction.configChange()}. * * <p> * If this system is unconfigured, an empty map is returned (and vice-versa). * * @return current configuration mapping from node identity to network address, or empty if this node is unconfigured */ public synchronized Map<String, String> getCurrentConfig() { return new HashMap<>(this.currentConfig); } /** * Determine whether this instance is configured. * * <p> * A node is configured iff it has added at least one Raft log entry (because the first log entry in any * new cluster always includes a configuration change that adds the first node in the cluster). * * @return true if this instance is configured, otherwise false */ public boolean isConfigured() { return this.lastAppliedIndex > 0 || !this.raftLog.isEmpty(); } /** * Determine whether this node thinks that it is part of the cluster, as currently configured on this node. * * @return true if this instance is part of the cluster, otherwise false */ public boolean isClusterMember() { return this.isClusterMember(this.identity); } /** * Determine whether this node thinks that the specified node is part of the cluster, as currently configured on this node. * * @param node node identity * @return true if the specified node is part of the cluster, otherwise false */ public boolean isClusterMember(String node) { return this.currentConfig.containsKey(node); } // Transactions @Override public synchronized RaftKVTransaction createTransaction() { // Sanity check assert this.checkState(); Preconditions.checkState(this.role != null, "not started"); Preconditions.checkState(!this.shuttingDown, "shutting down"); // Base transaction on the most recent log entry. This is itself a form of optimistic locking: we assume that the // most recent log entry has a high probability of being committed (in the Raft sense), which is of course required // in order to commit any transaction based on it. final MostRecentView view = new MostRecentView(); // Create transaction final RaftKVTransaction tx = new RaftKVTransaction(this, this.getLastLogTerm(), this.getLastLogIndex(), view.getSnapshot(), view.getView()); if (this.log.isDebugEnabled()) this.debug("created new transaction " + tx); this.openTransactions.put(tx.getTxId(), tx); // Set default commit timeout tx.setTimeout(this.commitTimeout); // Done return tx; } /** * Commit a transaction. */ void commit(final RaftKVTransaction tx) { try { // Mark transaction as "commit ready" - service thread will do the rest synchronized (this) { // Sanity check assert this.checkState(); assert this.role != null; // Check tx state switch (tx.getState()) { case EXECUTING: // Transition to COMMIT_READY state if (this.log.isDebugEnabled()) this.debug("committing transaction " + tx); tx.closeSnapshot(); tx.setState(TxState.COMMIT_READY); this.requestService(this.role.new CheckReadyTransactionService(tx)); // Setup commit timer final int timeout = tx.getTimeout(); if (timeout != 0) { final Timer commitTimer = new Timer("commit timer for " + tx, new Service(null, "commit timeout for tx#" + tx.getTxId()) { @Override public void run() { switch (tx.getState()) { case COMMIT_READY: case COMMIT_WAITING: RaftKVDatabase.this.fail(tx, new RetryTransactionException(tx, "transaction failed to complete within " + timeout + "ms (in state " + tx.getState() + ")")); break; default: break; } } }); commitTimer.timeoutAfter(tx.getTimeout()); tx.setCommitTimer(commitTimer); } break; case CLOSED: // this transaction has already been committed or rolled back throw new StaleTransactionException(tx); default: // another thread is already doing the commit this.warn("simultaneous commit()'s requested for " + tx + " by two different threads"); break; } } // Wait for completion try { tx.getCommitFuture().get(); } catch (InterruptedException e) { throw new RetryTransactionException(tx, "thread interrupted while waiting for commit", e); } catch (ExecutionException e) { final Throwable cause = e.getCause(); Util.prependCurrentStackTrace(cause, "Asynchronous Commit"); if (cause instanceof Error) throw (Error)cause; if (cause instanceof RuntimeException) throw (RuntimeException)cause; throw new KVTransactionException(tx, "commit failed", cause); // should never get here } } finally { this.cleanupTransaction(tx); } } /** * Rollback a transaction. */ synchronized void rollback(RaftKVTransaction tx) { // Sanity check assert this.checkState(); assert this.role != null; // Check tx state switch (tx.getState()) { case EXECUTING: if (this.log.isDebugEnabled()) this.debug("rolling back transaction " + tx); this.cleanupTransaction(tx); break; case CLOSED: break; default: // another thread is currently committing! this.warn("simultaneous commit() and rollback() requested for " + tx + " by two different threads"); break; } } private synchronized void cleanupTransaction(RaftKVTransaction tx) { // Debug if (this.log.isTraceEnabled()) this.trace("cleaning up transaction " + tx); // Do any per-role cleanups if (this.role != null) this.role.cleanupForTransaction(tx); // Close transaction's snapshot tx.closeSnapshot(); // Cancel commit timer final Timer commitTimer = tx.getCommitTimer(); if (commitTimer != null) commitTimer.cancel(); // Remove from open transactions set this.openTransactions.remove(tx.getTxId()); // Transition to CLOSED tx.setState(TxState.CLOSED); // Notify waiting thread if doing shutdown if (this.shuttingDown) this.notify(); } // Mark a transaction as having succeeded void succeed(RaftKVTransaction tx) { // Sanity check assert Thread.holdsLock(this); assert this.role != null; if (tx.getState().equals(TxState.COMPLETED) || tx.getState().equals(TxState.CLOSED)) return; // Succeed transaction if (this.log.isDebugEnabled()) this.debug("successfully committed " + tx); tx.getCommitFuture().succeed(); tx.setState(TxState.COMPLETED); this.role.cleanupForTransaction(tx); } // Mark a transaction as having failed void fail(RaftKVTransaction tx, Exception e) { // Sanity check assert Thread.holdsLock(this); assert this.role != null; if (tx.getState().equals(TxState.COMPLETED) || tx.getState().equals(TxState.CLOSED)) return; // Fail transaction if (this.log.isDebugEnabled()) this.debug("failed transaction " + tx + ": " + e); tx.getCommitFuture().fail(e); tx.setState(TxState.COMPLETED); this.role.cleanupForTransaction(tx); } // DataView /** * A view of the database based on the most recent log entry, if any, otherwise directly on the committed key/value store. * Caller is responsible for eventually closing the snapshot. */ private class MostRecentView { private final CloseableKVStore snapshot; private final MutableView view; public MostRecentView() { assert Thread.holdsLock(RaftKVDatabase.this); // Grab a snapshot of the key/value store this.snapshot = RaftKVDatabase.this.kv.snapshot(); // Create a view of just the state machine keys and values and successively layer unapplied log entries KVStore kview = PrefixKVStore.create(snapshot, STATE_MACHINE_PREFIX); for (LogEntry logEntry : RaftKVDatabase.this.raftLog) { final Writes writes = logEntry.getWrites(); if (!writes.isEmpty()) kview = new MutableView(kview, null, logEntry.getWrites()); } // Finalize this.view = new MutableView(kview); } public CloseableKVStore getSnapshot() { return this.snapshot; } public MutableView getView() { return this.view; } } // Service /** * Request service to be invoked after the current service (if any) completes. * * <p> * If {@code service} has an associated {@link Role}, and that {@link Role} is no longer active * when the service is handled, nothing will be done. * * @param service the service to perform */ private void requestService(Service service) { assert Thread.holdsLock(this); if (!this.pendingService.add(service)) return; if (this.performingService) return; try { this.executor.submit(new ErrorLoggingRunnable() { @Override protected void doRun() { RaftKVDatabase.this.handlePendingService(); } }); } catch (RejectedExecutionException e) { if (!this.shuttingDown) this.warn("executor task rejected, skipping", e); } } // Performs pending service requests (do not invoke directly) private synchronized void handlePendingService() { // Sanity check assert this.checkState(); assert Thread.currentThread() instanceof ServiceThread; if (this.role == null) return; // While there is work to do, do it this.performingService = true; try { while (!this.pendingService.isEmpty()) { final Iterator<Service> i = this.pendingService.iterator(); final Service service = i.next(); i.remove(); assert service.getRole() == null || service.getRole() == this.role; if (this.log.isTraceEnabled()) this.trace("SERVICE [" + service + "] in " + this.role); service.run(); } } finally { this.performingService = false; } } private class ServiceThread extends Thread { ServiceThread(Runnable action) { super(action); this.setName(RaftKVDatabase.this + " Service"); } } private abstract static class Service implements Runnable { private final Role role; private final String desc; protected Service(Role role, String desc) { this.role = role; this.desc = desc; } public Role getRole() { return this.role; } @Override public String toString() { return this.desc; } } // Timer /** * One shot timer that {@linkplain #requestService requests} a {@link Service} on expiration. * * <p> * This implementation avoids any race conditions between scheduling, firing, and cancelling. */ class Timer { private final Logger log = RaftKVDatabase.this.log; private final String name; private final Service service; private ScheduledFuture<?> future; private PendingTimeout pendingTimeout; // non-null IFF timeout has not been handled yet private Timestamp timeoutDeadline; public Timer(String name, Service service) { this.name = name; this.service = service; } public void cancel() { // Sanity check assert Thread.holdsLock(RaftKVDatabase.this); // Cancel existing timer, if any if (this.future != null) { this.future.cancel(false); this.future = null; } // Ensure the previously scheduled action does nothing if case we lose the cancel() race condition this.pendingTimeout = null; this.timeoutDeadline = null; } public void timeoutAfter(int delay) { // Sanity check assert Thread.holdsLock(RaftKVDatabase.this); Preconditions.checkArgument(delay >= 0, "delay < 0"); // Cancel existing timeout action, if any this.cancel(); assert this.future == null; assert this.pendingTimeout == null; assert this.timeoutDeadline == null; // Reschedule new timeout action this.timeoutDeadline = new Timestamp().offset(delay); if (this.log.isTraceEnabled()) { RaftKVDatabase.this.trace("rescheduling " + this.name + " for " + this.timeoutDeadline + " (" + delay + "ms from now)"); } this.pendingTimeout = new PendingTimeout(); try { this.future = RaftKVDatabase.this.executor.schedule(this.pendingTimeout, delay, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { if (!RaftKVDatabase.this.shuttingDown) RaftKVDatabase.this.warn("can't restart timer", e); } } /** * Force timer to expire immediately. */ public void timeoutNow() { this.timeoutAfter(0); } /** * Determine if this timer has expired and requires service handling, and reset it if so. * * <p> * If this timer is not running, has not yet expired, or has previously expired and this method was already * thereafter invoked, false is returned. Otherwise, true is returned, this timer is {@link #cancel}ed (if necessary), * and the caller is expected to handle the implied service need. * * @return true if timer needs handling, false otherwise */ public boolean pollForTimeout() { // Sanity check assert Thread.holdsLock(RaftKVDatabase.this); // Has timer expired? if (this.pendingTimeout == null || !this.timeoutDeadline.hasOccurred()) return false; // Yes, timer requires service if (Timer.this.log.isTraceEnabled()) RaftKVDatabase.this.trace(Timer.this.name + " expired " + -this.timeoutDeadline.offsetFromNow() + "ms ago"); this.cancel(); return true; } /** * Determine if this timer is running, i.e., will expire or has expired but * {@link #pollForTimeout} has not been invoked yet. */ public boolean isRunning() { return this.pendingTimeout != null; } private class PendingTimeout extends ErrorLoggingRunnable { @Override protected void doRun() { synchronized (RaftKVDatabase.this) { // Avoid cancel() race condition if (Timer.this.pendingTimeout != this) return; // Trigger service RaftKVDatabase.this.requestService(Timer.this.service); } } } } // Raft stuff /** * Reset the persisted state machine to its initial state. */ private boolean resetStateMachine(boolean initialize) { // Sanity check assert Thread.holdsLock(this); if (this.log.isDebugEnabled()) this.debug("resetting state machine"); // Set invalid values while we make non-atomic changes, in case we crash in the middle if (!this.recordLastApplied(-1, -1, null)) return false; // Delete all key/value pairs this.kv.removeRange(STATE_MACHINE_PREFIX, ByteUtil.getKeyAfterPrefix(STATE_MACHINE_PREFIX)); assert !this.kv.getRange(STATE_MACHINE_PREFIX, ByteUtil.getKeyAfterPrefix(STATE_MACHINE_PREFIX), false).hasNext(); // Delete all log files this.raftLog.clear(); for (File file : this.logDir.listFiles()) { if (LogEntry.LOG_FILE_PATTERN.matcher(file.getName()).matches()) { if (!file.delete()) this.error("failed to delete log file " + file); } } // Optionally finish intialization if (initialize && !this.recordLastApplied(0, 0, null)) return false; // Done if (this.log.isDebugEnabled()) this.debug("done resetting state machine"); return true; } /** * Record the last applied term, index, and configuration in the persistent store. */ private boolean recordLastApplied(long term, long index, Map<String, String> config) { // Sanity check assert Thread.holdsLock(this); if (this.log.isTraceEnabled()) this.trace("updating state machine last applied to " + index + "t" + term + " with config " + config); if (config == null) config = new HashMap<String, String>(0); // Prepare updates final Writes writes = new Writes(); writes.getPuts().put(LAST_APPLIED_TERM_KEY, LongEncoder.encode(term)); writes.getPuts().put(LAST_APPLIED_INDEX_KEY, LongEncoder.encode(index)); writes.getPuts().put(LAST_APPLIED_CONFIG_KEY, this.encodeConfig(config)); // Update persistent store try { this.kv.mutate(writes, true); } catch (Exception e) { this.error("error updating key/value store term/index to " + index + "t" + term, e); return false; } // Update in-memory copy this.lastAppliedTerm = Math.max(term, 0); this.lastAppliedIndex = Math.max(index, 0); this.lastAppliedConfig = config; this.commitIndex = this.lastAppliedIndex; this.currentConfig = this.buildCurrentConfig(); if (term >= 0 && index >= 0) this.info("new current configuration: " + this.currentConfig); return true; } /** * Update and persist a new current term. */ private boolean advanceTerm(long newTerm) { // Sanity check assert Thread.holdsLock(this); assert newTerm > this.currentTerm; this.info("advancing current term from " + this.currentTerm + " -> " + newTerm); // Update persistent store final Writes writes = new Writes(); writes.getPuts().put(CURRENT_TERM_KEY, LongEncoder.encode(newTerm)); writes.setRemoves(new KeyRanges(VOTED_FOR_KEY)); try { this.kv.mutate(writes, true); } catch (Exception e) { this.error("error persisting new term " + newTerm, e); return false; } // Update in-memory copy this.currentTerm = newTerm; return true; } /** * Join the specified cluster. * * @param newClusterId cluster ID, or zero to have one randomly assigned */ private boolean joinCluster(int newClusterId) { // Sanity check assert Thread.holdsLock(this); Preconditions.checkState(this.clusterId == 0); // Pick a new, random cluster ID if needed while (newClusterId == 0) newClusterId = this.random.nextInt(); // Persist it this.info("joining cluster with ID " + String.format("0x%08x", newClusterId)); final Writes writes = new Writes(); writes.getPuts().put(CLUSTER_ID_KEY, LongEncoder.encode(newClusterId)); try { this.kv.mutate(writes, true); } catch (Exception e) { this.error("error updating key/value store with new cluster ID", e); return false; } // Done this.clusterId = newClusterId; return true; } /** * Set the Raft role. * * @param role new role */ private void changeRole(Role role) { // Sanity check assert Thread.holdsLock(this); assert role != null; // Shutdown previous role (if any) if (this.role != null) { this.role.shutdown(); for (Iterator<Service> i = this.pendingService.iterator(); i.hasNext(); ) { final Service service = i.next(); if (service.getRole() != null) i.remove(); } } // Setup new role this.role = role; this.role.setup(); this.info("changing role to " + role); } /** * Append a log entry to the Raft log. * * @param term new log entry term * @param entry entry to add; the {@linkplain NewLogEntry#getTempFile temporary file} must be already durably persisted, * and will be renamed * @return new {@link LogEntry} * @throws Exception if an error occurs */ private LogEntry appendLogEntry(long term, NewLogEntry newLogEntry) throws Exception { // Sanity check assert Thread.holdsLock(this); assert this.role != null; assert newLogEntry != null; // Get file length final LogEntry.Data data = newLogEntry.getData(); final File tempFile = newLogEntry.getTempFile(); final long fileLength = Util.getLength(tempFile); // Create new log entry final LogEntry logEntry = new LogEntry(term, this.getLastLogIndex() + 1, this.logDir, data, fileLength); if (this.log.isDebugEnabled()) this.debug("adding new log entry " + logEntry + " using " + tempFile.getName()); // Atomically rename file and fsync() directory to durably persist Files.move(tempFile.toPath(), logEntry.getFile().toPath(), StandardCopyOption.ATOMIC_MOVE); this.logDirChannel.force(true); // Add new log entry to in-memory log this.raftLog.add(logEntry); // Update current config if (logEntry.applyConfigChange(this.currentConfig)) this.info("new current configuration: " + this.currentConfig); // Done return logEntry; } private long getLastLogIndex() { assert Thread.holdsLock(this); return this.lastAppliedIndex + this.raftLog.size(); } private long getLastLogTerm() { assert Thread.holdsLock(this); return this.getLogTermAtIndex(this.getLastLogIndex()); } private long getLogTermAtIndex(long index) { assert Thread.holdsLock(this); assert index >= this.lastAppliedIndex; assert index <= this.getLastLogIndex(); return index == this.lastAppliedIndex ? this.lastAppliedTerm : this.getLogEntryAtIndex(index).getTerm(); } private LogEntry getLogEntryAtIndex(long index) { assert Thread.holdsLock(this); assert index > this.lastAppliedIndex; assert index <= this.getLastLogIndex(); return this.raftLog.get((int)(index - this.lastAppliedIndex - 1)); } /** * Contains the information required to commit a new entry to the log. */ private class NewLogEntry { private final LogEntry.Data data; private final File tempFile; /** * Create an instance from a transaction and a temporary file * * @param data log entry mutations * @throws Exception if an error occurs */ public NewLogEntry(RaftKVTransaction tx, File tempFile) throws IOException { this.data = new LogEntry.Data(tx.getMutableView().getWrites(), tx.getConfigChange()); this.tempFile = tempFile; } /** * Create an instance from a transaction. * * @param data log entry mutations * @throws Exception if an error occurs */ public NewLogEntry(RaftKVTransaction tx) throws IOException { this.data = new LogEntry.Data(tx.getMutableView().getWrites(), tx.getConfigChange()); this.tempFile = File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_SUFFIX, RaftKVDatabase.this.logDir); try (FileWriter output = new FileWriter(this.tempFile)) { LogEntry.writeData(output, data); } } /** * Create an instance from a {@link LogEntry.Data} object. * * @param data mutation data * @throws Exception if an error occurs */ public NewLogEntry(LogEntry.Data data) throws IOException { this.data = data; this.tempFile = File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_SUFFIX, RaftKVDatabase.this.logDir); try (FileWriter output = new FileWriter(this.tempFile)) { LogEntry.writeData(output, data); } } /** * Create an instance from a serialized data in a {@link ByteBuffer}. * * @param buf buffer containing serialized mutations * @throws Exception if an error occurs */ public NewLogEntry(ByteBuffer dataBuf) throws IOException { // Copy data to temporary file this.tempFile = File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_SUFFIX, RaftKVDatabase.this.logDir); try (FileWriter output = new FileWriter(this.tempFile)) { while (dataBuf.hasRemaining()) output.getFileOutputStream().getChannel().write(dataBuf); } // Avoid having two copies of the data in memory at once dataBuf = null; // Deserialize data from file back into memory try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(tempFile), 4096)) { this.data = LogEntry.readData(input); } } public LogEntry.Data getData() { return this.data; } public File getTempFile() { return this.tempFile; } public void cancel() { this.tempFile.delete(); } } // Object @Override public String toString() { return this.getClass().getSimpleName() + "[identity=" + (this.identity != null ? "\"" + this.identity + "\"" : null) + ",logDir=" + this.logDir + ",term=" + this.currentTerm + ",commitIndex=" + this.commitIndex + ",lastApplied=" + this.lastAppliedIndex + "t" + this.lastAppliedTerm + ",raftLog=" + this.raftLog + ",role=" + this.role + (this.shuttingDown ? ",shuttingDown" : "") + "]"; } // Network.Handler and Messaging private void handle(String sender, ByteBuffer buf) { // Decode message final Message msg; try { msg = Message.decode(buf); } catch (IllegalArgumentException e) { this.error("rec'd bogus message from " + sender + ", ignoring", e); return; } // Receive message this.receiveMessage(sender, msg); } private synchronized void outputQueueEmpty(String address) { // Sanity check assert this.checkState(); // Update transmitting status if (!this.transmitting.remove(address)) return; if (this.log.isTraceEnabled()) this.trace("QUEUE_EMPTY address " + address + " in " + this.role); // Notify role if (this.role == null) return; this.role.outputQueueEmpty(address); } private boolean isTransmitting(String address) { return this.transmitting.contains(address); } // Messages private boolean sendMessage(Message msg) { // Sanity check assert Thread.holdsLock(this); // Get peer's address; if unknown, use the return address of the message being processed (if any) final String peer = msg.getRecipientId(); String address = this.currentConfig.get(peer); if (address == null) address = this.returnAddress; if (address == null) { this.warn("can't send " + msg + " to unknown peer \"" + peer + "\""); return false; } // Send message if (this.log.isTraceEnabled()) this.trace("XMIT " + msg + " to " + address); if (this.network.send(address, msg.encode())) { this.transmitting.add(address); return true; } // Transmit failed this.warn("transmit of " + msg + " to \"" + peer + "\" failed locally"); return false; } private synchronized void receiveMessage(String address, Message msg) { // Sanity check assert Thread.holdsLock(this); assert this.checkState(); if (this.role == null) { if (this.log.isDebugEnabled()) this.debug("rec'd " + msg + " rec'd in shutdown state; ignoring"); return; } // Sanity check cluster ID if (msg.getClusterId() == 0) { this.warn("rec'd " + msg + " with zero cluster ID from " + address + "; ignoring"); return; } if (this.clusterId != 0 && msg.getClusterId() != this.clusterId) { this.warn("rec'd " + msg + " with foreign cluster ID " + String.format("0x%08x", msg.getClusterId()) + " != " + String.format("0x%08x", this.clusterId) + "; ignoring"); return; } // Sanity check sender final String peer = msg.getSenderId(); if (peer.equals(this.identity)) { this.warn("rec'd " + msg + " from myself (\"" + peer + "\", address " + address + "); ignoring"); return; } // Sanity check recipient final String dest = msg.getRecipientId(); if (!dest.equals(this.identity)) { this.warn("rec'd misdirected " + msg + " intended for \"" + dest + "\" from " + address + "; ignoring"); return; } // Is sender's term too low? Ignore it if (msg.getTerm() < this.currentTerm) { this.info("rec'd " + msg + " with term " + msg.getTerm() + " < " + this.currentTerm + " from \"" + peer + "\" at " + address + ", ignoring"); return; } // Is my term too low? If so update and revert to follower if (msg.getTerm() > this.currentTerm) { // First check with current role; in some special cases we ignore this if (!this.role.mayAdvanceCurrentTerm(msg)) { if (this.log.isTraceEnabled()) { this.trace("rec'd " + msg + " with term " + msg.getTerm() + " > " + this.currentTerm + " from \"" + peer + "\" but current role says to ignore it"); } return; } // Revert to follower this.info("rec'd " + msg.getClass().getSimpleName() + " with term " + msg.getTerm() + " > " + this.currentTerm + " from \"" + peer + "\", updating term and " + (this.role instanceof FollowerRole ? "remaining a" : "reverting to") + " follower"); if (!this.advanceTerm(msg.getTerm())) return; this.changeRole(msg.isLeaderMessage() ? new FollowerRole(this, peer, address) : new FollowerRole(this)); } // Debug if (this.log.isTraceEnabled()) this.trace("RECV " + msg + " in " + this.role + " from " + address); // Handle message this.returnAddress = address; try { msg.visit(this.role); } finally { this.returnAddress = null; } } // Utility methods private long decodeLong(byte[] key, long defaultValue) throws IOException { final byte[] value = this.kv.get(key); if (value == null) return defaultValue; try { return LongEncoder.decode(value); } catch (IllegalArgumentException e) { throw new IOException("can't interpret encoded long value " + ByteUtil.toString(value) + " under key " + ByteUtil.toString(key), e); } } private String decodeString(byte[] key, String defaultValue) throws IOException { final byte[] value = this.kv.get(key); if (value == null) return defaultValue; final DataInputStream input = new DataInputStream(new ByteArrayInputStream(value)); try { return input.readUTF(); } catch (IOException e) { throw new IOException("can't interpret encoded string value " + ByteUtil.toString(value) + " under key " + ByteUtil.toString(key), e); } } private byte[] encodeString(String value) { final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final DataOutputStream output = new DataOutputStream(buf); try { output.writeUTF(value); output.flush(); } catch (IOException e) { throw new RuntimeException("unexpected error", e); } return buf.toByteArray(); } private Map<String, String> decodeConfig(byte[] key) throws IOException { final Map<String, String> config = new HashMap<>(); final byte[] value = this.kv.get(key); if (value == null) return config; try { final DataInputStream data = new DataInputStream(new ByteArrayInputStream(value)); while (true) { data.mark(1); if (data.read() == -1) break; data.reset(); config.put(data.readUTF(), data.readUTF()); } } catch (IOException e) { throw new IOException("can't interpret encoded config " + ByteUtil.toString(value) + " under key " + ByteUtil.toString(key), e); } return config; } private byte[] encodeConfig(Map<String, String> config) { final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final DataOutputStream data = new DataOutputStream(buf); try { for (Map.Entry<String, String> entry : config.entrySet()) { data.writeUTF(entry.getKey()); data.writeUTF(entry.getValue()); } data.flush(); } catch (IOException e) { throw new RuntimeException("unexpected error", e); } return buf.toByteArray(); } // Logging private void trace(String msg, Throwable t) { this.log.trace(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } private void trace(String msg) { this.log.trace(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } private void debug(String msg, Throwable t) { this.log.debug(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } private void debug(String msg) { this.log.debug(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } private void info(String msg, Throwable t) { this.log.info(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } private void info(String msg) { this.log.info(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } private void warn(String msg, Throwable t) { this.log.warn(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } private void warn(String msg) { this.log.warn(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } private void error(String msg, Throwable t) { this.log.error(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } private void error(String msg) { this.log.error(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } // Raft Roles private abstract static class Role implements MessageSwitch { protected final Logger log = LoggerFactory.getLogger(this.getClass()); protected final RaftKVDatabase raft; protected final Service checkReadyTransactionsService = new Service(this, "check ready transactions") { @Override public void run() { Role.this.checkReadyTransactions(); } }; protected final Service checkWaitingTransactionsService = new Service(this, "check waiting transactions") { @Override public void run() { Role.this.checkWaitingTransactions(); } }; protected final Service applyCommittedLogEntriesService = new Service(this, "apply committed logs") { @Override public void run() { Role.this.applyCommittedLogEntries(); } }; // Constructors protected Role(RaftKVDatabase raft) { this.raft = raft; assert Thread.holdsLock(this.raft); } // Lifecycle public void setup() { assert Thread.holdsLock(this.raft); this.raft.requestService(this.checkReadyTransactionsService); this.raft.requestService(this.checkWaitingTransactionsService); this.raft.requestService(this.applyCommittedLogEntriesService); } public void shutdown() { assert Thread.holdsLock(this.raft); for (RaftKVTransaction tx : this.raft.openTransactions.values()) this.cleanupForTransaction(tx); } // Service public abstract void outputQueueEmpty(String address); /** * Check transactions in the {@link TxState#COMMIT_READY} state to see if we can advance them. */ protected void checkReadyTransactions() { for (RaftKVTransaction tx : new ArrayList<RaftKVTransaction>(this.raft.openTransactions.values())) new CheckReadyTransactionService(tx).run(); } /** * Check transactions in the {@link TxState#COMMIT_WAITING} state to see if they are committed yet. * We invoke this service method whenever our {@code commitIndex} advances. */ protected void checkWaitingTransactions() { for (RaftKVTransaction tx : new ArrayList<RaftKVTransaction>(this.raft.openTransactions.values())) new CheckWaitingTransactionService(tx).run(); } /** * Apply committed but unapplied log entries to the state machine. * We invoke this service method whenever log entries are added or our {@code commitIndex} advances. */ protected void applyCommittedLogEntries() { // Apply committed log entries to the state machine while (this.raft.lastAppliedIndex < this.raft.commitIndex) { // Grab the first unwritten log entry final LogEntry logEntry = this.raft.raftLog.get(0); assert logEntry.getIndex() == this.raft.lastAppliedIndex + 1; // Check with subclass if (!this.mayApplyLogEntry(logEntry)) break; // Get the current config as of the log entry we're about to apply final HashMap<String, String> logEntryConfig = new HashMap<>(this.raft.lastAppliedConfig); logEntry.applyConfigChange(logEntryConfig); // Prepare combined Mutations containing prefixed log entry changes plus my own final Writes logWrites = logEntry.getWrites(); final Writes myWrites = new Writes(); myWrites.getPuts().put(LAST_APPLIED_TERM_KEY, LongEncoder.encode(logEntry.getTerm())); myWrites.getPuts().put(LAST_APPLIED_INDEX_KEY, LongEncoder.encode(logEntry.getIndex())); myWrites.getPuts().put(LAST_APPLIED_CONFIG_KEY, this.raft.encodeConfig(logEntryConfig)); final Mutations mutations = new Mutations() { @Override public Iterable<KeyRange> getRemoveRanges() { return Iterables.transform(logWrites.getRemoveRanges(), new PrefixKeyRangeFunction(STATE_MACHINE_PREFIX)); } @Override public Iterable<Map.Entry<byte[], byte[]>> getPutPairs() { return Iterables.concat( Iterables.transform(logWrites.getPutPairs(), new PrefixPutFunction(STATE_MACHINE_PREFIX)), myWrites.getPutPairs()); } @Override public Iterable<Map.Entry<byte[], Long>> getAdjustPairs() { return Iterables.transform(logWrites.getAdjustPairs(), new PrefixAdjustFunction(STATE_MACHINE_PREFIX)); } }; // Apply updates to the key/value store (durably); prefix all transaction keys with STATE_MACHINE_PREFIX if (this.log.isDebugEnabled()) this.debug("applying committed log entry " + logEntry + " to key/value store"); try { this.raft.kv.mutate(mutations, true); } catch (Exception e) { if (e instanceof RuntimeException && e.getCause() instanceof IOException) e = (IOException)e.getCause(); this.error("error applying log entry " + logEntry + " to key/value store", e); break; } // Update in-memory state this.raft.lastAppliedTerm = logEntry.getTerm(); assert logEntry.getIndex() == this.raft.lastAppliedIndex + 1; this.raft.lastAppliedIndex = logEntry.getIndex(); logEntry.applyConfigChange(this.raft.lastAppliedConfig); assert this.raft.currentConfig.equals(this.raft.buildCurrentConfig()); // Delete the log entry this.raft.raftLog.remove(0); if (!logEntry.getFile().delete()) this.error("failed to delete log file " + logEntry.getFile()); // Subclass hook this.logEntryApplied(logEntry); } } /** * Determine whether the given log entry may be applied to the state machine. */ protected boolean mayApplyLogEntry(LogEntry logEntry) { return true; } /** * Subclass hook invoked after a log entry has been applied to the state machine. * * @param logEntry the log entry just applied */ protected void logEntryApplied(LogEntry logEntry) { } // Transaction service classes protected abstract class AbstractTransactionService extends Service { protected final RaftKVTransaction tx; AbstractTransactionService(RaftKVTransaction tx, String desc) { super(Role.this, desc); assert tx != null; this.tx = tx; } @Override public final void run() { try { this.doRun(); } catch (KVTransactionException e) { Role.this.raft.fail(tx, e); } catch (Exception e) { Role.this.raft.fail(tx, new KVTransactionException(tx, e)); } } protected abstract void doRun(); @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != this.getClass()) return false; final AbstractTransactionService that = (AbstractTransactionService)obj; return this.tx.equals(that.tx); } @Override public int hashCode() { return this.tx.hashCode(); } } protected class CheckReadyTransactionService extends AbstractTransactionService { CheckReadyTransactionService(RaftKVTransaction tx) { super(tx, "check ready tx#" + tx.getTxId()); } @Override protected void doRun() { if (this.tx.getState().equals(TxState.COMMIT_READY)) Role.this.checkReadyTransaction(this.tx); } } protected class CheckWaitingTransactionService extends AbstractTransactionService { CheckWaitingTransactionService(RaftKVTransaction tx) { super(tx, "check waiting tx#" + tx.getTxId()); } @Override protected void doRun() { if (this.tx.getState().equals(TxState.COMMIT_WAITING)) Role.this.checkWaitingTransaction(this.tx); } } // Transactions /** * Check a transaction that is ready to be committed (in the {@link TxState#COMMIT_READY} state). * * <p> * This should be invoked: * <ul> * <li>After changing roles</li> * <li>After a transaction has entered the {@link TxState#COMMIT_READY} state</li> * <li>After the leader is newly known (in {@link FollowerRole})</li> * <li>After the leader's output queue goes from non-empty to empty (in {@link FollowerRole})</li> * <li>After the leader's {@code commitIndex} has advanced, in case a config change transaction * is waiting on a previous config change transaction (in {@link LeaderRole})</li> * </ul> * * @param tx the transaction * @throws KVTransactionException if an error occurs */ public abstract void checkReadyTransaction(RaftKVTransaction tx); /** * Check a transaction waiting for its log entry to be committed (in the {@link TxState#COMMIT_WAITING} state). * * <p> * This should be invoked: * <ul> * <li>After changing roles</li> * <li>After a transaction has entered the {@link TxState#COMMIT_WAITING} state</li> * <li>After advancing my {@code commitIndex} (as leader or follower)</li> * <li>After receiving an updated {@linkplain AppendResponse#getLeaderLeaseTimeout leader lease timeout} * (in {@link FollowerRole})</li> * </ul> * * @param tx the transaction * @throws KVTransactionException if an error occurs */ private void checkWaitingTransaction(RaftKVTransaction tx) { // Handle the case the transaction's committed log index has already been applied to the state machine final long commitIndex = tx.getCommitIndex(); if (commitIndex < this.raft.lastAppliedIndex) { // This can happen if we lose contact and by the time we're back the log entry has // already been applied to the state machine on some leader and that leader sent // use an InstallSnapshot message. We don't know whether it actually got committed // or not, so the transaction must be retried. throw new RetryTransactionException(tx, "committed log entry was missed"); } // Has the transaction's log entry been received and committed yet? if (commitIndex > this.raft.commitIndex) return; // Verify the term of the committed log entry; if not what we expect, the log entry was overwritten by a new leader final long commitTerm = tx.getCommitTerm(); if (this.raft.getLogTermAtIndex(commitIndex) != commitTerm) throw new RetryTransactionException(tx, "leader was deposed during commit and transaction's log entry overwritten"); // Check with subclass if (!this.mayCommit(tx)) return; // Transaction is officially committed now if (this.log.isTraceEnabled()) this.trace("commit successful for " + tx + " (commit index " + this.raft.commitIndex + " >= " + commitIndex + ")"); this.raft.succeed(tx); } protected boolean mayCommit(RaftKVTransaction tx) { return true; } /** * Perform any role-specific transaction cleanups. * * <p> * Invoked either when transaction is closed or this role is being shutdown. * * @param tx the transaction */ public abstract void cleanupForTransaction(RaftKVTransaction tx); /** * Check a transaction that is ready to be committed (in the {@link TxState#COMMIT_READY} state) for snapshot isolation. * * @param tx the transaction * @return true if snapshot isolation and moved to {@link TxState@COMMIT_WAITING} */ protected boolean checkReadyTransactionReadOnlySnapshot(RaftKVTransaction tx) { // Sanity check assert Thread.holdsLock(this.raft); assert tx.getState().equals(TxState.COMMIT_READY); // Check isolation if (!tx.isReadOnlySnapshot()) return false; // For snapshot isolation, we only need to wait for the commit of the transaction's base log entry tx.setCommitTerm(tx.getBaseTerm()); tx.setCommitIndex(tx.getBaseIndex()); tx.setState(TxState.COMMIT_WAITING); this.raft.requestService(new CheckWaitingTransactionService(tx)); // Done return true; } // Messages public boolean mayAdvanceCurrentTerm(Message msg) { return true; } protected void failUnexpectedMessage(Message msg) { this.warn("rec'd unexpected message " + msg + " while in role " + this + "; ignoring"); } // Debug boolean checkState() { return true; } // Logging protected void trace(String msg, Throwable t) { this.raft.trace(msg, t); } protected void trace(String msg) { this.raft.trace(msg); } protected void debug(String msg, Throwable t) { this.raft.debug(msg, t); } protected void debug(String msg) { this.raft.debug(msg); } protected void info(String msg, Throwable t) { this.raft.info(msg, t); } protected void info(String msg) { this.raft.info(msg); } protected void warn(String msg, Throwable t) { this.raft.warn(msg, t); } protected void warn(String msg) { this.raft.warn(msg); } protected void error(String msg, Throwable t) { this.raft.error(msg, t); } protected void error(String msg) { this.raft.error(msg); } // Object @Override public abstract String toString(); protected String toStringPrefix() { return this.getClass().getSimpleName() + "[term=" + this.raft.currentTerm + ",applied=" + this.raft.lastAppliedIndex + "t" + this.raft.lastAppliedTerm + ",commit=" + this.raft.commitIndex + ",log=" + this.raft.raftLog + "]"; } } // LEADER role private static class LeaderRole extends Role { // Our followers private final HashMap<String, Follower> followerMap = new HashMap<>(); // Our leadership "lease" timeout - i.e., the earliest time another leader could possibly be elected private Timestamp leaseTimeout = new Timestamp(); // Unapplied log entry memory usage private long totalLogEntryMemoryUsed; // Service tasks private final Service updateLeaderCommitIndexService = new Service(this, "update leader commitIndex") { @Override public void run() { LeaderRole.this.updateLeaderCommitIndex(); } }; private final Service updateLeaseTimeoutService = new Service(this, "update lease timeout") { @Override public void run() { LeaderRole.this.updateLeaseTimeout(); } }; private final Service updateKnownFollowersService = new Service(this, "update known followers") { @Override public void run() { LeaderRole.this.updateKnownFollowers(); } }; // Constructors public LeaderRole(RaftKVDatabase raft) { super(raft); } // Lifecycle @Override public void setup() { super.setup(); this.info("entering leader role in term " + this.raft.currentTerm); // Generate follower list this.updateKnownFollowers(); // Initialize log memory usage for (LogEntry logEntry : this.raft.raftLog) this.totalLogEntryMemoryUsed += logEntry.getFileSize(); // Append a "dummy" log entry with my current term. This allows us to advance the commit index when the last // entry in our log is from a prior term. This is needed to avoid the problem where a transaction could end up // waiting indefinitely for its log entry with a prior term number to be committed. final LogEntry logEntry; try { logEntry = this.applyNewLogEntry(this.raft.new NewLogEntry(new LogEntry.Data(new Writes(), null))); } catch (Exception e) { this.error("error attempting to apply initial log entry", e); return; } if (this.log.isDebugEnabled()) this.debug("added log entry " + logEntry + " to commit at the beginning of my new term"); } @Override public void shutdown() { super.shutdown(); for (Follower follower : this.followerMap.values()) follower.cleanup(); } // Service @Override public void outputQueueEmpty(String address) { // Find matching follower(s) and update them if needed for (Follower follower : this.followerMap.values()) { if (follower.getAddress().equals(address)) { if (this.log.isTraceEnabled()) this.trace("updating peer \"" + follower.getIdentity() + "\" after queue empty notification"); this.raft.requestService(new UpdateFollowerService(follower)); } } } @Override protected void logEntryApplied(LogEntry logEntry) { this.totalLogEntryMemoryUsed -= logEntry.getFileSize(); } @Override protected boolean mayApplyLogEntry(LogEntry logEntry) { // Are we running out of memory, or keeping around too many log entries? If so, go ahead. if (this.totalLogEntryMemoryUsed > this.raft.maxAppliedLogMemory || this.raft.raftLog.size() > MAX_UNAPPLIED_LOG_ENTRIES) { if (this.log.isTraceEnabled()) { this.trace("allowing log entry " + logEntry + " to be applied because memory usage " + this.totalLogEntryMemoryUsed + " > " + this.raft.maxAppliedLogMemory + " and/or log length " + this.raft.raftLog.size() + " > " + MAX_UNAPPLIED_LOG_ENTRIES); } return true; } // Try to keep log entries around for a minimum amount of time to facilitate long-running transactions if (logEntry.getAge() < this.raft.maxTransactionDuration) { if (this.log.isTraceEnabled()) { this.trace("delaying application of " + logEntry + " because it has age " + logEntry.getAge() + "ms < " + this.raft.maxTransactionDuration + "ms"); } return false; } // If any snapshots are in progress, we don't want to apply any log entries with index greater than the snapshot's // index, because then we'd "lose" the ability to update the follower with that log entry, and as a result just have // to send a snapshot again. However, we impose a limit on how long we'll wait for a slow follower. for (Follower follower : this.followerMap.values()) { final SnapshotTransmit snapshotTransmit = follower.getSnapshotTransmit(); if (snapshotTransmit == null) continue; if (snapshotTransmit.getSnapshotIndex() < logEntry.getIndex() && snapshotTransmit.getAge() < MAX_SNAPSHOT_TRANSMIT_AGE) { if (this.log.isTraceEnabled()) { this.trace("delaying application of " + logEntry + " because of in-progress snapshot install of " + snapshotTransmit.getSnapshotIndex() + "t" + snapshotTransmit.getSnapshotTerm() + " to " + follower); } return false; } } // If some follower does not yet have the log entry, wait for them to get it (up to some maximum time) if (logEntry.getAge() < MAX_SLOW_FOLLOWER_APPLY_DELAY_HEARTBEATS * this.raft.heartbeatTimeout) { for (Follower follower : this.followerMap.values()) { if (follower.getMatchIndex() < logEntry.getIndex()) { if (this.log.isTraceEnabled()) { this.trace("delaying application of " + logEntry + " (age " + logEntry.getAge() + " < " + (MAX_SLOW_FOLLOWER_APPLY_DELAY_HEARTBEATS * this.raft.heartbeatTimeout) + ") because of slow " + follower); } return false; } } } return true; } /** * Update my {@code commitIndex} based on followers' {@code matchIndex}'s. * * <p> * This should be invoked: * <ul> * <li>After any log entry has been added to the log, if we have zero followers</li> * <li>After a log entry that contains a configuration change has been added to the log</li> * <li>After a follower's {@linkplain Follower#getMatchIndex match index} has advanced</li> * </ul> */ private void updateLeaderCommitIndex() { // Update my commit index based on when a majority of cluster members have ack'd log entries final long lastLogIndex = this.raft.getLastLogIndex(); while (this.raft.commitIndex < lastLogIndex) { // Get the index in question final long index = this.raft.commitIndex + 1; // Count the number of nodes which have a copy of the log entry at index int numVotes = this.raft.isClusterMember() ? 1 : 0; // count myself, if member for (Follower follower : this.followerMap.values()) { // count followers who are members if (follower.getMatchIndex() >= index && this.raft.isClusterMember(follower.getIdentity())) numVotes++; } // Do a majority of cluster nodes have a copy of this log entry? final int majority = this.raft.currentConfig.size() / 2 + 1; if (numVotes < majority) break; // Log entry term must match my current term final LogEntry logEntry = this.raft.getLogEntryAtIndex(index); if (logEntry.getTerm() != this.raft.currentTerm) break; // Update commit index if (this.log.isDebugEnabled()) { this.debug("advancing commit index from " + this.raft.commitIndex + " -> " + index + " based on " + numVotes + "/" + this.raft.currentConfig.size() + " nodes having received " + logEntry); } this.raft.commitIndex = index; // Perform various service this.raft.requestService(this.checkReadyTransactionsService); this.raft.requestService(this.checkWaitingTransactionsService); this.raft.requestService(this.applyCommittedLogEntriesService); // Notify all (up-to-date) followers with the updated leaderCommit this.updateAllSynchronizedFollowersNow(); } // If we are no longer a member of our cluster, step down as leader after the latest config change is committed if (!this.raft.isClusterMember() && this.raft.commitIndex >= this.findMostRecentConfigChangeMatching(Predicates.<String[]>alwaysTrue())) { this.log.info("stepping down as leader of cluster (no longer a member)"); this.raft.changeRole(new FollowerRole(this.raft)); } } /** * Update my {@code leaseTimeout} based on followers' returned {@code leaderTimeout}'s. * * <p> * This should be invoked: * <ul> * <li>After a follower has replied with an {@link AppendResponse} containing a newer * {@linkplain AppendResponse#getLeaderTimestamp leader timestamp} than before</li> * </ul> */ private void updateLeaseTimeout() { // Only needed when we have followers final int numFollowers = this.followerMap.size(); if (numFollowers == 0) return; // Get all cluster member leader timestamps, sorted in increasing order final Timestamp[] leaderTimestamps = new Timestamp[this.raft.currentConfig.size()]; int index = 0; if (this.raft.isClusterMember()) leaderTimestamps[index++] = new Timestamp(); // only matters in single node cluster for (Follower follower : this.followerMap.values()) { if (this.raft.isClusterMember(follower.getIdentity())) leaderTimestamps[index++] = follower.getLeaderTimestamp(); } Preconditions.checkArgument(index == leaderTimestamps.length); // sanity check Arrays.sort(leaderTimestamps); // Calculate highest leaderTimeout shared by a majority of cluster members, based on sorted array: // # nodes timestamps // 5 [ ][ ][x][x][x] 3/5 x's make a majority at index (5 - 1)/2 = 2 // 6 [ ][ ][x][x][x][x] 4/6 x's make a majority at index (6 - 1)/2 = 2 // The minimum leaderTimeout shared by a majority of nodes is at index (leaderTimestamps.length - 1) / 2. // We then add the minimum election timeout, then subtract a little for clock drift. final Timestamp newLeaseTimeout = leaderTimestamps[(leaderTimestamps.length + 1) / 2] .offset((int)(this.raft.minElectionTimeout * (1.0f - MAX_CLOCK_DRIFT))); // Immediately notify any followers who are waiting on this updated timestamp (or any smaller timestamp) if (newLeaseTimeout.compareTo(this.leaseTimeout) > 0) { // Update my leader lease timeout if (this.log.isTraceEnabled()) this.trace("updating my lease timeout from " + this.leaseTimeout + " -> " + newLeaseTimeout); this.leaseTimeout = newLeaseTimeout; // Notify any followers who care for (Follower follower : this.followerMap.values()) { final NavigableSet<Timestamp> timeouts = follower.getCommitLeaseTimeouts().headSet(this.leaseTimeout, true); if (!timeouts.isEmpty()) { follower.updateNow(); // notify follower so it can commit waiting transaction(s) timeouts.clear(); } } } } /** * Update our list of followers to match our current configuration. * * <p> * This should be invoked: * <ul> * <li>After a log entry that contains a configuration change has been added to the log</li> * <li>When the {@linkplain Follower#getNextIndex next index} of a follower not in the current config advances</li> * </ul> */ private void updateKnownFollowers() { // Compare known followers with the current config and determine who needs to be be added or removed final HashSet<String> adds = new HashSet<>(this.raft.currentConfig.keySet()); adds.removeAll(this.followerMap.keySet()); adds.remove(this.raft.identity); final HashSet<String> dels = new HashSet<>(this.followerMap.keySet()); dels.removeAll(this.raft.currentConfig.keySet()); // Keep around a follower after its removal until it receives the config change that removed it for (Follower follower : this.followerMap.values()) { // Is this follower scheduled for deletion? final String peer = follower.getIdentity(); if (!dels.contains(peer)) continue; // Find the most recent log entry containing a config change in which the follower was removed final String node = follower.getIdentity(); final long index = this.findMostRecentConfigChangeMatching(new Predicate<String[]>() { @Override public boolean apply(String[] configChange) { return configChange[0].equals(node) && configChange[1] == null; } }); // If follower has not received that log entry yet, keep on updating them until they do if (follower.getMatchIndex() < index) dels.remove(peer); } // Add new followers for (String peer : adds) { final String address = this.raft.currentConfig.get(peer); final Follower follower = new Follower(peer, address, this.raft.getLastLogIndex()); this.debug("adding new follower \"" + peer + "\" at " + address); follower.setUpdateTimer( this.raft.new Timer("update timer for \"" + peer + "\"", new UpdateFollowerService(follower))); this.followerMap.put(peer, follower); follower.updateNow(); // schedule an immediate update } // Remove old followers for (String peer : dels) { final Follower follower = this.followerMap.remove(peer); this.debug("removing old follower \"" + peer + "\""); follower.cleanup(); } } /** * Check whether a follower needs an update and send one if so. * * <p> * This should be invoked: * <ul> * <li>After a new follower has been added</li> * <li>When the output queue for a follower goes from non-empty to empty</li> * <li>After the follower's {@linkplain Follower#getUpdateTimer update timer} has expired</li> * <li>After a new log entry has been added to the log (all followers)</li> * <li>After receiving an {@link AppendResponse} that caused the follower's * {@linkplain Follower#getNextIndex next index} to change</li> * <li>After receiving the first positive {@link AppendResponse} to a probe</li> * <li>After our {@code commitIndex} has advanced (all followers)</li> * <li>After our {@code leaseTimeout} has advanced past one or more of a follower's * {@linkplain Follower#getCommitLeaseTimeouts commit lease timeouts} (with update timer reset)</li> * <li>After sending a {@link CommitResponse} with a non-null {@linkplain CommitResponse#getCommitLeaderLeaseTimeout * commit leader lease timeout} (all followers) to probe for updated leader timestamps</li> * <li>After starting, aborting, or completing a snapshot install for a follower</li> * </ul> */ private void updateFollower(Follower follower) { // If follower has an in-progress snapshot that has become too stale, abort it final String peer = follower.getIdentity(); SnapshotTransmit snapshotTransmit = follower.getSnapshotTransmit(); if (snapshotTransmit != null && snapshotTransmit.getSnapshotIndex() < this.raft.lastAppliedIndex) { if (this.log.isDebugEnabled()) this.debug("aborting stale snapshot install for " + follower); follower.cancelSnapshotTransmit(); follower.updateNow(); } // Is follower's queue empty? If not, hold off until then if (this.raft.isTransmitting(follower.getAddress())) { if (this.log.isTraceEnabled()) this.trace("no update for \"" + peer + "\": output queue still not empty"); return; } // Handle any in-progress snapshot install if ((snapshotTransmit = follower.getSnapshotTransmit()) != null) { // Send the next chunk in transmission, if any final long pairIndex = snapshotTransmit.getPairIndex(); final ByteBuffer chunk = snapshotTransmit.getNextChunk(); boolean synced = true; if (chunk != null) { // Send next chunk final InstallSnapshot msg = new InstallSnapshot(this.raft.clusterId, this.raft.identity, peer, this.raft.currentTerm, snapshotTransmit.getSnapshotTerm(), snapshotTransmit.getSnapshotIndex(), pairIndex, pairIndex == 0 ? snapshotTransmit.getSnapshotConfig() : null, !snapshotTransmit.hasMoreChunks(), chunk); if (this.raft.sendMessage(msg)) return; if (this.log.isDebugEnabled()) this.debug("canceling snapshot install for " + follower + " due to failure to send " + msg); // Message failed -> snapshot is fatally wounded, so cancel it synced = false; } if (synced) this.info("completed snapshot install for out-of-date " + follower); // Snapshot transmit is complete (or failed) follower.cancelSnapshotTransmit(); // Trigger an immediate regular update follower.setNextIndex(snapshotTransmit.getSnapshotIndex() + 1); follower.setSynced(synced); follower.updateNow(); this.raft.requestService(new UpdateFollowerService(follower)); return; } // Are we still waiting for the update timer to expire? if (!follower.getUpdateTimer().pollForTimeout()) { boolean waitForTimerToExpire = true; // Don't wait for the update timer to expire if: // (a) The follower is sync'd; AND // (y) We have a new log entry that the follower doesn't have; OR // (y) We have a new leaderCommit that the follower doesn't have // The effect is that we will pipeline updates to synchronized followers. if (follower.isSynced() && (follower.getLeaderCommit() != this.raft.commitIndex || follower.getNextIndex() <= this.raft.getLastLogIndex())) waitForTimerToExpire = false; // Wait for timer to expire if (waitForTimerToExpire) { if (this.log.isTraceEnabled()) { this.trace("no update for \"" + follower.getIdentity() + "\": timer not expired yet, and follower is " + (follower.isSynced() ? "up to date" : "not synced")); } return; } } // Get index of the next log entry to send to follower final long nextIndex = follower.getNextIndex(); // If follower is too far behind, we must do a snapshot install if (nextIndex <= this.raft.lastAppliedIndex) { final MostRecentView view = this.raft.new MostRecentView(); follower.setSnapshotTransmit(new SnapshotTransmit(this.raft.getLastLogTerm(), this.raft.getLastLogIndex(), this.raft.lastAppliedConfig, view.getSnapshot(), view.getView())); this.info("started snapshot install for out-of-date " + follower); this.raft.requestService(new UpdateFollowerService(follower)); return; } // Restart update timer here (to avoid looping if an error occurs below) follower.getUpdateTimer().timeoutAfter(this.raft.heartbeatTimeout); // Send actual data if follower is synced and there is a log entry to send; otherwise, just send a probe final AppendRequest msg; if (!follower.isSynced() || nextIndex > this.raft.getLastLogIndex()) { msg = new AppendRequest(this.raft.clusterId, this.raft.identity, peer, this.raft.currentTerm, new Timestamp(), this.leaseTimeout, this.raft.commitIndex, this.raft.getLogTermAtIndex(nextIndex - 1), nextIndex - 1); // probe } else { // Get log entry to send final LogEntry logEntry = this.raft.getLogEntryAtIndex(nextIndex); // If the log entry correspond's to follower's transaction, don't send the data because follower already has it. // But only do this optimization the first time, in case something goes wrong on the follower's end. ByteBuffer mutationData = null; if (!follower.getSkipDataLogEntries().remove(logEntry)) { try { mutationData = logEntry.getContent(); } catch (IOException e) { this.error("error reading log file " + logEntry.getFile(), e); return; } } // Create message msg = new AppendRequest(this.raft.clusterId, this.raft.identity, peer, this.raft.currentTerm, new Timestamp(), this.leaseTimeout, this.raft.commitIndex, this.raft.getLogTermAtIndex(nextIndex - 1), nextIndex - 1, logEntry.getTerm(), mutationData); } // Send update final boolean sent = this.raft.sendMessage(msg); // Advance next index if a log entry was sent; we allow pipelining log entries when synchronized if (sent && !msg.isProbe()) { assert follower.isSynced(); follower.setNextIndex(Math.min(follower.getNextIndex(), this.raft.getLastLogIndex()) + 1); } // Update leaderCommit for follower if (sent) follower.setLeaderCommit(msg.getLeaderCommit()); } private void updateAllSynchronizedFollowersNow() { for (Follower follower : this.followerMap.values()) { if (follower.isSynced()) follower.updateNow(); } } private class UpdateFollowerService extends Service { private final Follower follower; UpdateFollowerService(Follower follower) { super(LeaderRole.this, "update follower \"" + follower.getIdentity() + "\""); assert follower != null; this.follower = follower; } @Override public void run() { LeaderRole.this.updateFollower(this.follower); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != this.getClass()) return false; final UpdateFollowerService that = (UpdateFollowerService)obj; return this.follower.equals(that.follower); } @Override public int hashCode() { return this.follower.hashCode(); } } // Transactions @Override public void checkReadyTransaction(final RaftKVTransaction tx) { // Sanity check assert Thread.holdsLock(this.raft); assert tx.getState().equals(TxState.COMMIT_READY); // Check snapshot isolation if (this.checkReadyTransactionReadOnlySnapshot(tx)) return; // Check for conflict final String error = this.checkConflicts(tx.getBaseTerm(), tx.getBaseIndex(), tx.getMutableView().getReads()); if (error != null) { if (this.log.isDebugEnabled()) this.debug("local transaction " + tx + " failed due to conflict: " + error); throw new RetryTransactionException(tx, error); } // Handle read-only vs. read-write transaction final Writes writes = tx.getMutableView().getWrites(); if (writes.isEmpty() && tx.getConfigChange() == null) { // Set commit term and index from last log entry tx.setCommitTerm(this.raft.getLastLogTerm()); tx.setCommitIndex(this.raft.getLastLogIndex()); if (this.log.isDebugEnabled()) { this.debug("commit is " + tx.getCommitIndex() + "t" + tx.getCommitTerm() + " for local read-only transaction " + tx); } // We will be able to commit this transaction immediately this.raft.requestService(new CheckWaitingTransactionService(tx)); } else { // Don't commit a new config change while there is any previous config change outstanding if (tx.getConfigChange() != null && this.isConfigChangeOutstanding()) return; // Commit transaction as a new log entry final LogEntry logEntry; try { logEntry = this.applyNewLogEntry(this.raft.new NewLogEntry(tx)); } catch (Exception e) { throw new KVTransactionException(tx, "error attempting to persist transaction", e); } if (this.log.isDebugEnabled()) this.debug("added log entry " + logEntry + " for local transaction " + tx); // Set commit term and index from new log entry tx.setCommitTerm(logEntry.getTerm()); tx.setCommitIndex(logEntry.getIndex()); // If there are no followers, we can commit this immediately if (this.followerMap.isEmpty()) this.raft.requestService(new CheckWaitingTransactionService(tx)); } // Update transaction state tx.setState(TxState.COMMIT_WAITING); tx.getMutableView().disableReadTracking(); // we no longer need this info } @Override public void cleanupForTransaction(RaftKVTransaction tx) { // nothing to do } private boolean isConfigChangeOutstanding() { for (int i = (int)(this.raft.commitIndex - this.raft.lastAppliedIndex) + 1; i < this.raft.raftLog.size(); i++) { if (this.raft.raftLog.get(i).getConfigChange() != null) return true; } return false; } // Message @Override public void caseAppendRequest(AppendRequest msg) { this.failDuplicateLeader(msg); } @Override public void caseAppendResponse(AppendResponse msg) { // Find follower final Follower follower = this.findFollower(msg); if (follower == null) return; // Update follower's last rec'd leader timestamp if (msg.getLeaderTimestamp().compareTo(follower.getLeaderTimestamp()) > 0) { follower.setLeaderTimestamp(msg.getLeaderTimestamp()); this.raft.requestService(this.updateLeaseTimeoutService); } // Ignore if a snapshot install is in progress if (follower.getSnapshotTransmit() != null) { if (this.log.isTraceEnabled()) this.trace("rec'd " + msg + " while sending snapshot install; ignoring"); return; } // Flag indicating we might want to update follower when done boolean updateFollowerAgain = false; // Update follower's match index if (msg.getMatchIndex() > follower.getMatchIndex()) { follower.setMatchIndex(msg.getMatchIndex()); this.raft.requestService(this.updateLeaderCommitIndexService); this.raft.requestService(this.applyCommittedLogEntriesService); if (!this.raft.isClusterMember(follower.getIdentity())) this.raft.requestService(this.updateKnownFollowersService); } // Check result and update follower's next index final boolean wasSynced = follower.isSynced(); final long previousNextIndex = follower.getNextIndex(); if (!msg.isSuccess()) follower.setNextIndex(Math.max(follower.getNextIndex() - 1, 1)); follower.setSynced(msg.isSuccess()); if (follower.isSynced() != wasSynced) { if (this.log.isDebugEnabled()) { this.debug("sync status of \"" + follower.getIdentity() + "\" changed -> " + (!follower.isSynced() ? "not " : "") + "synced"); } updateFollowerAgain = true; } // Use follower's match index as a lower bound on follower's next index. This is needed because in this implementation, // the application of leader log entries (to the state machine) may occur later than the application of follower log // entries, so it's possible a follower's state machine's index can advance past the leader's. In that case we want // to avoid the leader sending log entries that are prior to the follower's last committed index. follower.setNextIndex(Math.max(follower.getNextIndex(), follower.getMatchIndex() + 1)); // Use follower's last log index as an upper bound on follower's next index. follower.setNextIndex(Math.min(msg.getLastLogIndex() + 1, follower.getNextIndex())); // Update follower again if next index has changed updateFollowerAgain |= follower.getNextIndex() != previousNextIndex; // Debug if (this.log.isTraceEnabled()) this.trace("updated follower: " + follower + ", update again = " + updateFollowerAgain); // Immediately update follower again (if appropriate) if (updateFollowerAgain) this.raft.requestService(new UpdateFollowerService(follower)); } @Override public void caseCommitRequest(CommitRequest msg) { // Find follower final Follower follower = this.findFollower(msg); if (follower == null) return; // Decode reads final Reads reads; try { reads = Reads.deserialize(new ByteBufferInputStream(msg.getReadsData())); } catch (Exception e) { this.error("error decoding reads data in " + msg, e); this.raft.sendMessage(new CommitResponse(this.raft.clusterId, this.raft.identity, msg.getSenderId(), this.raft.currentTerm, msg.getTxId(), "error decoding reads data: " + e)); return; } // Check for conflict final String conflictMsg = this.checkConflicts(msg.getBaseTerm(), msg.getBaseIndex(), reads); if (conflictMsg != null) { if (this.log.isDebugEnabled()) this.debug("commit request " + msg + " failed due to conflict: " + conflictMsg); this.raft.sendMessage(new CommitResponse(this.raft.clusterId, this.raft.identity, msg.getSenderId(), this.raft.currentTerm, msg.getTxId(), conflictMsg)); return; } // Handle read-only vs. read-write transaction if (msg.isReadOnly()) { // Get current time final Timestamp minimumLeaseTimeout = new Timestamp(); // The follower may commit as soon as it sees the transaction's BASE log entry get committed. // Note, we don't need to wait for any subsequent log entries to be committed, because if they // are committed they are invisible to the transaction, and if they aren't ever committed then // whatever log entries replace them will necessarily have been created sometime after now. final CommitResponse response; if (this.leaseTimeout.compareTo(minimumLeaseTimeout) > 0) { // No other leader could have been elected yet as of right now, so the transaction can commit immediately response = new CommitResponse(this.raft.clusterId, this.raft.identity, msg.getSenderId(), this.raft.currentTerm, msg.getTxId(), msg.getBaseTerm(), msg.getBaseIndex()); } else { // Remember that this follower is now going to be waiting for this particular leaseTimeout follower.getCommitLeaseTimeouts().add(minimumLeaseTimeout); // Send immediate probes to all (up-to-date) followers in an attempt to increase our leaseTimeout quickly this.updateAllSynchronizedFollowersNow(); // Build response response = new CommitResponse(this.raft.clusterId, this.raft.identity, msg.getSenderId(), this.raft.currentTerm, msg.getTxId(), msg.getBaseTerm(), msg.getBaseIndex(), minimumLeaseTimeout); } // Send response this.raft.sendMessage(response); } else { // If the client is requesting a config change, we could check for an outstanding config change now and if so // delay our response until it completes, but that's not worth the trouble. Instead, applyNewLogEntry() will // throw an exception and the client will just just have to retry the transaction. // Commit mutations as a new log entry final LogEntry logEntry; try { logEntry = this.applyNewLogEntry(this.raft.new NewLogEntry(msg.getMutationData())); } catch (Exception e) { this.error("error appending new log entry for " + msg, e); this.raft.sendMessage(new CommitResponse(this.raft.clusterId, this.raft.identity, msg.getSenderId(), this.raft.currentTerm, msg.getTxId(), e.getMessage() != null ? e.getMessage() : "" + e)); return; } if (this.log.isDebugEnabled()) this.debug("added log entry " + logEntry + " for remote " + msg); // Follower transaction data optimization follower.getSkipDataLogEntries().add(logEntry); // Send response this.raft.sendMessage(new CommitResponse(this.raft.clusterId, this.raft.identity, msg.getSenderId(), this.raft.currentTerm, msg.getTxId(), logEntry.getTerm(), logEntry.getIndex())); } } @Override public void caseCommitResponse(CommitResponse msg) { this.failDuplicateLeader(msg); } @Override public void caseInstallSnapshot(InstallSnapshot msg) { this.failDuplicateLeader(msg); } @Override public void caseRequestVote(RequestVote msg) { // Too late dude, I already won the election if (this.log.isDebugEnabled()) this.debug("ignoring " + msg + " rec'd while in " + this); } @Override public void caseGrantVote(GrantVote msg) { // Thanks and all, but I already won the election if (this.log.isDebugEnabled()) this.debug("ignoring " + msg + " rec'd while in " + this); } private void failDuplicateLeader(Message msg) { // This should never happen - same term but two different leaders final boolean defer = this.raft.identity.compareTo(msg.getSenderId()) <= 0; this.error("detected a duplicate leader in " + msg + " - should never happen; possible inconsistent cluster" + " configuration on " + msg.getSenderId() + " (mine: " + this.raft.currentConfig + "); " + (defer ? "reverting to follower" : "ignoring")); if (defer) this.raft.changeRole(new FollowerRole(this.raft, msg.getSenderId(), this.raft.returnAddress)); } // Object @Override public String toString() { return this.toStringPrefix() + ",followerMap=" + this.followerMap + "]"; } // Debug @Override boolean checkState() { if (!super.checkState()) return false; for (Follower follower : this.followerMap.values()) { assert follower.getNextIndex() <= this.raft.getLastLogIndex() + 1; assert follower.getMatchIndex() <= this.raft.getLastLogIndex() + 1; assert follower.getLeaderCommit() <= this.raft.commitIndex; assert follower.getUpdateTimer().isRunning() || follower.getSnapshotTransmit() != null; } return true; } // Internal methods /** * Find the index of the most recent unapplied log entry having an associated config change matching the given predicate. * * @return most recent matching log entry, or zero if none found */ private long findMostRecentConfigChangeMatching(Predicate<String[]> predicate) { for (long index = this.raft.getLastLogIndex(); index > this.raft.lastAppliedIndex; index final String[] configChange = this.raft.getLogEntryAtIndex(index).getConfigChange(); if (configChange == null && predicate.apply(configChange)) return index; } return 0; } // Apply a new log entry to the Raft log private LogEntry applyNewLogEntry(NewLogEntry newLogEntry) throws Exception { // Do a couple of extra checks if a config change is included final String[] configChange = newLogEntry.getData().getConfigChange(); if (configChange != null) { // Disallow a config change while there is a previous uncommitted config change if (this.isConfigChangeOutstanding()) { newLogEntry.cancel(); throw new IllegalStateException("uncommitted config change outstanding"); } // Disallow a configuration change that removes the last node in a cluster if (this.raft.currentConfig.size() == 1 && configChange[1] == null) { final String lastNode = this.raft.currentConfig.keySet().iterator().next(); if (configChange[0].equals(lastNode)) { newLogEntry.cancel(); throw new IllegalArgumentException("can't remove the last node in a cluster (\"" + lastNode + "\")"); } } } // Append a new entry to the Raft log final LogEntry logEntry; boolean success = false; try { logEntry = this.raft.appendLogEntry(this.raft.currentTerm, newLogEntry); success = true; } finally { if (!success) newLogEntry.cancel(); } // Update follower list if configuration changed if (configChange != null) this.raft.requestService(this.updateKnownFollowersService); // Update memory usage this.totalLogEntryMemoryUsed += logEntry.getFileSize(); // Update commit index (this is only needed if config has changed, or in the single node case) if (configChange != null || this.followerMap.isEmpty()) this.raft.requestService(this.updateLeaderCommitIndexService); // Immediately update all up-to-date followers this.updateAllSynchronizedFollowersNow(); // Done return logEntry; } /** * Check whether a proposed transaction can commit without any MVCC conflict. * * @param file file containing serialized copy of {@link writes} (content must already be fsync()'d to disk!) * @param baseTerm the term of the log entry on which the transaction is based * @param baseIndex the index of the log entry on which the transaction is based * @param reads reads performed by the transaction * @param writes writes performed by the transaction * @return error message on failure, null for success */ public String checkConflicts(long baseTerm, long baseIndex, Reads reads) { // Validate the index of the log entry on which the transaction is based final long minIndex = this.raft.lastAppliedIndex; final long maxIndex = this.raft.getLastLogIndex(); if (baseIndex < minIndex) return "transaction is too old: snapshot index " + baseIndex + " < last applied log index " + minIndex; if (baseIndex > maxIndex) return "transaction is too new: snapshot index " + baseIndex + " > most recent log index " + maxIndex; // Validate the term of the log entry on which the transaction is based final long actualBaseTerm = this.raft.getLogTermAtIndex(baseIndex); if (baseTerm != actualBaseTerm) { return "transaction is based on an overwritten log entry with index " + baseIndex + " and term " + baseTerm + " != " + actualBaseTerm; } // Check for conflicts from intervening commits for (long index = baseIndex + 1; index <= maxIndex; index++) { final LogEntry logEntry = this.raft.getLogEntryAtIndex(index); if (reads.isConflict(logEntry.getWrites())) { return "writes of committed transaction at index " + index + " conflict with transaction reads from transaction base index " + baseIndex; } } // No conflict return null; } private Follower findFollower(Message msg) { final Follower follower = this.followerMap.get(msg.getSenderId()); if (follower == null) this.warn("rec'd " + msg + " from unknown follower \"" + msg.getSenderId() + "\", ignoring"); return follower; } } /** * Support superclass for {@link FollowerRole} and {@link CandidateRole}, which both have an election timer. */ private abstract static class NonLeaderRole extends Role { protected final Timer electionTimer = this.raft.new Timer("election timer", new Service(this, "election timeout") { @Override public void run() { NonLeaderRole.this.checkElectionTimeout(); } }); private final boolean startElectionTimer; // Constructors protected NonLeaderRole(RaftKVDatabase raft, boolean startElectionTimer) { super(raft); this.startElectionTimer = startElectionTimer; } // Lifecycle @Override public void setup() { super.setup(); if (this.startElectionTimer) this.restartElectionTimer(); } @Override public void shutdown() { super.shutdown(); this.electionTimer.cancel(); } // Service // Check for an election timeout private void checkElectionTimeout() { if (this.electionTimer.pollForTimeout()) { this.info("election timeout while in " + this); this.raft.changeRole(new CandidateRole(this.raft)); } } protected void restartElectionTimer() { // Sanity check assert Thread.holdsLock(this.raft); // Generate a randomized election timeout delay final int range = this.raft.maxElectionTimeout - this.raft.minElectionTimeout; final int randomizedPart = Math.round(this.raft.random.nextFloat() * range); // Restart timer this.electionTimer.timeoutAfter(this.raft.minElectionTimeout + randomizedPart); } // MessageSwitch @Override public void caseAppendResponse(AppendResponse msg) { this.failUnexpectedMessage(msg); } @Override public void caseCommitRequest(CommitRequest msg) { this.failUnexpectedMessage(msg); } } // FOLLOWER role private static class FollowerRole extends NonLeaderRole { private String leader; // our leader, if known private String leaderAddress; // our leader's network address private String votedFor; // the candidate we voted for this term private SnapshotReceive snapshotReceive; // in-progress snapshot install, if any private final HashMap<Long, PendingRequest> pendingRequests = new HashMap<>(); // wait for CommitResponse or log entry private final HashMap<Long, PendingWrite> pendingWrites = new HashMap<>(); // wait for AppendRequest with null data private final HashMap<Long, Timestamp> commitLeaderLeaseTimeoutMap // tx's waiting for leaderLeaseTimeout's = new HashMap<>(); private Timestamp lastLeaderMessageTime; // time of most recent rec'd AppendRequest private Timestamp leaderLeaseTimeout; // latest rec'd leader lease timeout // Constructors public FollowerRole(RaftKVDatabase raft) { this(raft, null, null, null); } public FollowerRole(RaftKVDatabase raft, String leader, String leaderAddress) { this(raft, leader, leaderAddress, leader); } public FollowerRole(RaftKVDatabase raft, String leader, String leaderAddress, String votedFor) { super(raft, raft.isClusterMember()); this.leader = leader; this.leaderAddress = leaderAddress; this.votedFor = votedFor; assert this.leaderAddress != null || this.leader == null; } // Lifecycle @Override public void setup() { super.setup(); this.info("entering follower role in term " + this.raft.currentTerm + (this.leader != null ? "; with leader \"" + this.leader + "\" at " + this.leaderAddress : "") + (this.votedFor != null ? "; having voted for \"" + this.votedFor + "\"" : "")); } @Override public void shutdown() { super.shutdown(); // Cancel any in-progress snapshot install if (this.snapshotReceive != null) { if (this.log.isDebugEnabled()) this.debug("aborting snapshot install due to leaving follower role"); this.raft.resetStateMachine(true); this.snapshotReceive = null; } // Fail any (read-only) transactions waiting on a minimum lease timeout from deposed leader for (RaftKVTransaction tx : new ArrayList<RaftKVTransaction>(this.raft.openTransactions.values())) { if (tx.getState().equals(TxState.COMMIT_WAITING) && this.commitLeaderLeaseTimeoutMap.containsKey(tx.getTxId())) this.raft.fail(tx, new RetryTransactionException(tx, "leader was deposed during commit")); } // Cleanup pending requests and commit writes this.pendingRequests.clear(); for (PendingWrite pendingWrite : this.pendingWrites.values()) pendingWrite.cleanup(); this.pendingWrites.clear(); } // Service @Override public void outputQueueEmpty(String address) { if (address.equals(this.leaderAddress)) this.raft.requestService(this.checkReadyTransactionsService); // TODO: track specific transactions } // Check whether the required minimum leader lease timeout has been seen, if any @Override protected boolean mayCommit(RaftKVTransaction tx) { // Is there a required minimum leader lease timeout associated with the transaction? final Timestamp commitLeaderLeaseTimeout = this.commitLeaderLeaseTimeoutMap.get(tx.getTxId()); if (commitLeaderLeaseTimeout == null) return true; // Do we know the leader's lease timeout yet? if (this.leaderLeaseTimeout == null) return false; // Verify leader's lease timeout has extended beyond that required by the transaction return this.leaderLeaseTimeout.compareTo(commitLeaderLeaseTimeout) >= 0; } /** * Check whether the election timer should be running, and make it so. * * <p> * This should be invoked: * <ul> * <li>After a log entry that contains a configuration change has been added to the log</li> * <li>When a snapshot install starts</li> * <li>When a snapshot install completes</li> * </ul> */ private void updateElectionTimer() { final boolean isClusterMember = this.raft.isClusterMember(); final boolean electionTimerRunning = this.electionTimer.isRunning(); if (isClusterMember && !electionTimerRunning) { if (this.log.isTraceEnabled()) this.trace("starting up election timer because I'm now part of the current config"); this.restartElectionTimer(); } else if (!isClusterMember && electionTimerRunning) { if (this.log.isTraceEnabled()) this.trace("stopping election timer because I'm no longer part of the current config"); this.electionTimer.cancel(); } } // Transactions @Override public void checkReadyTransaction(RaftKVTransaction tx) { // Sanity check assert Thread.holdsLock(this.raft); assert tx.getState().equals(TxState.COMMIT_READY); // Check snapshot isolation if (this.checkReadyTransactionReadOnlySnapshot(tx)) return; // Did we already send a CommitRequest for this transaction? PendingRequest pendingRequest = this.pendingRequests.get(tx.getTxId()); if (pendingRequest != null) { if (this.log.isTraceEnabled()) this.trace("leaving alone ready tx " + tx + " because request already sent"); return; } // If we are installing a snapshot, we must wait if (this.snapshotReceive != null) { if (this.log.isTraceEnabled()) this.trace("leaving alone ready tx " + tx + " because a snapshot install is in progress"); return; } // Handle situation where we are unconfigured and not part of any cluster yet if (!this.raft.isConfigured()) { // Get transaction mutations final Writes writes = tx.getMutableView().getWrites(); final String[] configChange = tx.getConfigChange(); // Allow an empty read-only transaction when unconfigured if (writes.isEmpty() && configChange == null) { this.raft.succeed(tx); return; } // Otherwise, we can only handle an initial config change that is adding the local node if (configChange == null || !configChange[0].equals(this.raft.identity) || configChange[1] == null) { throw new RetryTransactionException(tx, "unconfigured system: an initial configuration change adding" + " the local node (\"" + this.raft.identity + "\") as the first member of a new cluster is required"); } // Create a new cluster if needed if (this.raft.clusterId == 0) { this.info("creating new cluster"); if (!this.raft.joinCluster(0)) throw new KVTransactionException(tx, "error persisting new cluster ID"); } // Advance term assert this.raft.currentTerm == 0; if (!this.raft.advanceTerm(this.raft.currentTerm + 1)) throw new KVTransactionException(tx, "error advancing term"); // Append the first entry to the Raft log final LogEntry logEntry; try { logEntry = this.raft.appendLogEntry(this.raft.currentTerm, this.raft.new NewLogEntry(tx)); } catch (Exception e) { throw new KVTransactionException(tx, "error attempting to persist transaction", e); } if (this.log.isDebugEnabled()) this.debug("added log entry " + logEntry + " for local transaction " + tx); assert logEntry.getTerm() == 1; assert logEntry.getIndex() == 1; // Set commit term and index from new log entry tx.setCommitTerm(logEntry.getTerm()); tx.setCommitIndex(logEntry.getIndex()); this.raft.commitIndex = logEntry.getIndex(); // Update transaction state tx.setState(TxState.COMMIT_WAITING); tx.getMutableView().disableReadTracking(); // we no longer need this info // Immediately become the leader of our new single-node cluster assert this.raft.isConfigured(); this.info("appointing myself leader in newly created cluster"); this.raft.changeRole(new LeaderRole(this.raft)); return; } // If we don't have a leader yet, or leader's queue is full, we must wait if (this.leader == null || this.raft.isTransmitting(this.leaderAddress)) { if (this.log.isTraceEnabled()) { this.trace("leaving alone ready tx " + tx + " because leader " + (this.leader == null ? "is not known yet" : "\"" + this.leader + "\" is not writable yet")); } return; } // Serialize reads into buffer final Reads reads = tx.getMutableView().getReads(); final long readsDataSize = reads.serializedLength(); if (readsDataSize != (int)readsDataSize) throw new KVTransactionException(tx, "transaction read information exceeds maximum length"); final ByteBuffer readsData = Util.allocateByteBuffer((int)readsDataSize); try (ByteBufferOutputStream output = new ByteBufferOutputStream(readsData)) { reads.serialize(output); } catch (IOException e) { throw new RuntimeException("unexpected exception", e); } assert !readsData.hasRemaining(); readsData.flip(); // Handle read-only vs. read-write transaction final Writes writes = tx.getMutableView().getWrites(); FileWriter fileWriter = null; ByteBuffer mutationData = null; if (!writes.isEmpty() || tx.getConfigChange() != null) { // Serialize changes into a temporary file (but do not close or durably persist yet) final File file = new File(this.raft.logDir, String.format("%s%019d%s", TX_FILE_PREFIX, tx.getTxId(), TEMP_FILE_SUFFIX)); try { LogEntry.writeData((fileWriter = new FileWriter(file)), new LogEntry.Data(writes, tx.getConfigChange())); fileWriter.flush(); } catch (IOException e) { fileWriter.getFile().delete(); Util.closeIfPossible(fileWriter); throw new KVTransactionException(tx, "error saving transaction mutations to temporary file", e); } final long writeLength = fileWriter.getLength(); // Load serialized writes from file try { mutationData = Util.readFile(fileWriter.getFile(), writeLength); } catch (IOException e) { fileWriter.getFile().delete(); Util.closeIfPossible(fileWriter); throw new KVTransactionException(tx, "error reading transaction mutations from temporary file", e); } // Record pending commit write with temporary file final PendingWrite pendingWrite = new PendingWrite(tx, fileWriter); this.pendingWrites.put(tx.getTxId(), pendingWrite); } // Record pending request this.pendingRequests.put(tx.getTxId(), new PendingRequest(tx)); // Send commit request to leader final CommitRequest msg = new CommitRequest(this.raft.clusterId, this.raft.identity, this.leader, this.raft.currentTerm, tx.getTxId(), tx.getBaseTerm(), tx.getBaseIndex(), readsData, mutationData); if (this.log.isTraceEnabled()) this.trace("sending " + msg + " to \"" + this.leader + "\" for " + tx); if (!this.raft.sendMessage(msg)) throw new RetryTransactionException(tx, "error sending commit request to leader"); } @Override public void cleanupForTransaction(RaftKVTransaction tx) { this.pendingRequests.remove(tx.getTxId()); final PendingWrite pendingWrite = this.pendingWrites.remove(tx.getTxId()); if (pendingWrite != null) pendingWrite.cleanup(); this.commitLeaderLeaseTimeoutMap.remove(tx.getTxId()); } // Messages @Override public boolean mayAdvanceCurrentTerm(Message msg) { // Deny vote if we have heard from our leader within the minimum election timeout (dissertation, section 4.2.3) if (msg instanceof RequestVote && this.lastLeaderMessageTime != null && this.lastLeaderMessageTime.offsetFromNow() > -this.raft.minElectionTimeout) return false; return true; } @Override public void caseAppendRequest(AppendRequest msg) { // Record new cluster ID if we haven't done so already if (this.raft.clusterId == 0) this.raft.joinCluster(msg.getClusterId()); // Record leader if (!msg.getSenderId().equals(this.leader)) { if (this.leader != null && !this.leader.equals(msg.getSenderId())) { this.error("detected a conflicting leader in " + msg + " (previous leader was \"" + this.leader + "\") - should never happen; possible inconsistent cluster configuration (mine: " + this.raft.currentConfig + ")"); } this.leader = msg.getSenderId(); this.leaderAddress = this.raft.returnAddress; this.leaderLeaseTimeout = msg.getLeaderLeaseTimeout(); this.info("updated leader to \"" + this.leader + "\" at " + this.leaderAddress); this.raft.requestService(this.checkReadyTransactionsService); // allows COMMIT_READY transactions to be sent } // Get message info final long leaderCommitIndex = msg.getLeaderCommit(); final long leaderPrevTerm = msg.getPrevLogTerm(); final long leaderPrevIndex = msg.getPrevLogIndex(); final long logTerm = msg.getLogEntryTerm(); final long logIndex = leaderPrevIndex + 1; // Update timestamp last heard from leader this.lastLeaderMessageTime = new Timestamp(); // Update leader's lease timeout if (this.leaderLeaseTimeout == null || msg.getLeaderLeaseTimeout().compareTo(this.leaderLeaseTimeout) > 0) { if (this.log.isTraceEnabled()) this.trace("advancing leader lease timeout " + this.leaderLeaseTimeout + " -> " + msg.getLeaderLeaseTimeout()); this.leaderLeaseTimeout = msg.getLeaderLeaseTimeout(); this.raft.requestService(this.checkWaitingTransactionsService); } // If a snapshot install is in progress, cancel it if (this.snapshotReceive != null) { this.info("rec'd " + msg + " during in-progress " + this.snapshotReceive + "; aborting snapshot install and resetting state machine"); if (!this.raft.resetStateMachine(true)) return; this.snapshotReceive = null; this.updateElectionTimer(); } // Restart election timeout (if running) if (this.electionTimer.isRunning()) this.restartElectionTimer(); // Get my last log entry's index and term long lastLogTerm = this.raft.getLastLogTerm(); long lastLogIndex = this.raft.getLastLogIndex(); // Check whether our previous log entry term matches that of leader; if not, or it doesn't exist, request fails if (leaderPrevIndex < this.raft.lastAppliedIndex || leaderPrevIndex > lastLogIndex || leaderPrevTerm != this.raft.getLogTermAtIndex(leaderPrevIndex)) { if (this.log.isDebugEnabled()) this.debug("rejecting " + msg + " because previous log entry doesn't match"); this.raft.sendMessage(new AppendResponse(this.raft.clusterId, this.raft.identity, msg.getSenderId(), this.raft.currentTerm, msg.getLeaderTimestamp(), false, this.raft.lastAppliedIndex, this.raft.getLastLogIndex())); return; } // Check whether the message actually contains a log entry; if so, append it boolean success = true; if (!msg.isProbe()) { // Check for a conflicting (i.e., never committed, then overwritten) log entry that we need to clear away first if (logIndex <= lastLogIndex && this.raft.getLogTermAtIndex(logIndex) != msg.getLogEntryTerm()) { // Delete conflicting log entry, and all entries that follow it, from the log final int startListIndex = (int)(logIndex - this.raft.lastAppliedIndex - 1); final List<LogEntry> conflictList = this.raft.raftLog.subList(startListIndex, this.raft.raftLog.size()); for (LogEntry logEntry : conflictList) { this.info("deleting log entry " + logEntry + " overrwritten by " + msg); if (!logEntry.getFile().delete()) this.error("failed to delete log file " + logEntry.getFile()); } try { this.raft.logDirChannel.force(true); } catch (IOException e) { this.warn("errory fsync()'ing log directory " + this.raft.logDir, e); } conflictList.clear(); // Rebuild current config this.raft.currentConfig = this.raft.buildCurrentConfig(); // Update last log entry info lastLogTerm = this.raft.getLastLogTerm(); lastLogIndex = this.raft.getLastLogIndex(); } // Append the new log entry - if we don't already have it if (logIndex > lastLogIndex) { assert logIndex == lastLogIndex + 1; LogEntry logEntry = null; do { // If message contains no data, we expect to get the data from the corresponding transaction final ByteBuffer mutationData = msg.getMutationData(); if (mutationData == null) { // Find the matching pending commit write final PendingWrite pendingWrite; try { pendingWrite = Iterables.find(this.pendingWrites.values(), new Predicate<PendingWrite>() { @Override public boolean apply(PendingWrite pendingWrite) { final RaftKVTransaction tx = pendingWrite.getTx(); return tx.getState().equals(TxState.COMMIT_WAITING) && tx.getCommitTerm() == logTerm && tx.getCommitIndex() == logIndex; } }); } catch (NoSuchElementException e) { if (this.log.isDebugEnabled()) { this.debug("rec'd " + msg + " but no read-write transaction matching commit " + logIndex + "t" + logTerm + " found; rejecting"); } break; } // Commit's writes are no longer pending final RaftKVTransaction tx = pendingWrite.getTx(); this.pendingWrites.remove(tx.getTxId()); // Close and durably persist the associated temporary file try { pendingWrite.getFileWriter().close(); } catch (IOException e) { this.error("error closing temporary transaction file for " + tx, e); pendingWrite.cleanup(); break; } // Append a new log entry using temporary file try { logEntry = this.raft.appendLogEntry(logTerm, this.raft.new NewLogEntry(tx, pendingWrite.getFileWriter().getFile())); } catch (Exception e) { this.error("error appending new log entry for " + tx, e); pendingWrite.cleanup(); break; } // Debug if (this.log.isDebugEnabled()) { this.debug("now waiting for commit of " + tx.getCommitIndex() + "t" + tx.getCommitTerm() + " to commit " + tx); } } else { // Append new log entry normally using the data from the request try { logEntry = this.raft.appendLogEntry(logTerm, this.raft.new NewLogEntry(mutationData)); } catch (Exception e) { this.error("error appending new log entry", e); break; } } } while (false); // Start/stop election timer as needed if (logEntry != null && logEntry.getConfigChange() != null) this.updateElectionTimer(); // Success? success = logEntry != null; // Update last log entry info lastLogTerm = this.raft.getLastLogTerm(); lastLogIndex = this.raft.getLastLogIndex(); } } // Update my commit index final long newCommitIndex = Math.min(Math.max(leaderCommitIndex, this.raft.commitIndex), lastLogIndex); if (newCommitIndex > this.raft.commitIndex) { if (this.log.isDebugEnabled()) this.debug("updating leader commit index from " + this.raft.commitIndex + " -> " + newCommitIndex); this.raft.commitIndex = newCommitIndex; this.raft.requestService(this.checkWaitingTransactionsService); this.raft.requestService(this.applyCommittedLogEntriesService); } // Debug if (this.log.isTraceEnabled()) { this.trace("my updated follower state: " + "term=" + this.raft.currentTerm + " commitIndex=" + this.raft.commitIndex + " leaderLeaseTimeout=" + this.leaderLeaseTimeout + " lastApplied=" + this.raft.lastAppliedIndex + "t" + this.raft.lastAppliedTerm + " log=" + this.raft.raftLog); } // Send reply if (success) { this.raft.sendMessage(new AppendResponse(this.raft.clusterId, this.raft.identity, msg.getSenderId(), this.raft.currentTerm, msg.getLeaderTimestamp(), true, msg.isProbe() ? logIndex - 1 : logIndex, this.raft.getLastLogIndex())); } else { this.raft.sendMessage(new AppendResponse(this.raft.clusterId, this.raft.identity, msg.getSenderId(), this.raft.currentTerm, msg.getLeaderTimestamp(), false, this.raft.lastAppliedIndex, this.raft.getLastLogIndex())); } } @Override public void caseCommitResponse(CommitResponse msg) { // Find transaction final RaftKVTransaction tx = this.raft.openTransactions.get(msg.getTxId()); if (tx == null) // must have been rolled back locally return; // Sanity check transaction state if (!tx.getState().equals(TxState.COMMIT_READY)) { this.warn("rec'd " + msg + " for " + tx + " in state " + tx.getState() + "; ignoring"); return; } if (this.pendingRequests.remove(tx.getTxId()) == null) { if (this.log.isDebugEnabled()) this.debug("rec'd " + msg + " for " + tx + " not expecting a response; ignoring"); return; } // Check result if (this.log.isTraceEnabled()) this.trace("rec'd " + msg + " for " + tx); if (msg.isSuccess()) { tx.setCommitTerm(msg.getCommitTerm()); tx.setCommitIndex(msg.getCommitIndex()); if (msg.getCommitLeaderLeaseTimeout() != null) this.commitLeaderLeaseTimeoutMap.put(tx.getTxId(), msg.getCommitLeaderLeaseTimeout()); tx.setState(TxState.COMMIT_WAITING); tx.getMutableView().disableReadTracking(); // we no longer need this info this.raft.requestService(new CheckWaitingTransactionService(tx)); } else this.raft.fail(tx, new RetryTransactionException(tx, msg.getErrorMessage())); } @Override public void caseInstallSnapshot(InstallSnapshot msg) { // Restart election timer (if running) if (this.electionTimer.isRunning()) this.restartElectionTimer(); // Do we have an existing install? boolean startNewInstall = false; if (this.snapshotReceive != null) { // Does the message not match? if (!this.snapshotReceive.matches(msg)) { // If the message is NOT the first one in a new install, ignore it if (msg.getPairIndex() != 0) { if (this.log.isDebugEnabled()) this.debug("rec'd " + msg + " which doesn't match in-progress " + this.snapshotReceive + "; ignoring"); return; } // The message is the first one in a new install, so discard the existing install this.info("rec'd initial " + msg + " with in-progress " + this.snapshotReceive + "; aborting previous install"); startNewInstall = true; } } else { // If the message is NOT the first one in a new install, ignore it if (msg.getPairIndex() != 0) { this.info("rec'd non-initial " + msg + " with no in-progress snapshot install; ignoring"); return; } } // Get snapshot term and index final long term = msg.getSnapshotTerm(); final long index = msg.getSnapshotIndex(); // Set up new install if necessary if (this.snapshotReceive == null || startNewInstall) { assert msg.getPairIndex() == 0; if (!this.raft.resetStateMachine(false)) return; this.updateElectionTimer(); this.snapshotReceive = new SnapshotReceive( PrefixKVStore.create(this.raft.kv, STATE_MACHINE_PREFIX), term, index, msg.getSnapshotConfig()); this.info("starting new snapshot install from \"" + msg.getSenderId() + "\" of " + index + "t" + term + " with config " + msg.getSnapshotConfig()); } assert this.snapshotReceive.matches(msg); // Apply next chunk of key/value pairs if (this.log.isDebugEnabled()) this.debug("applying " + msg + " to " + this.snapshotReceive); try { this.snapshotReceive.applyNextChunk(msg.getData()); } catch (Exception e) { this.error("error applying snapshot to key/value store; resetting state machine", e); if (!this.raft.resetStateMachine(true)) return; this.updateElectionTimer(); this.snapshotReceive = null; return; } // If that was the last chunk, finalize persistent state if (msg.isLastChunk()) { final Map<String, String> snapshotConfig = this.snapshotReceive.getSnapshotConfig(); this.info("snapshot install from \"" + msg.getSenderId() + "\" of " + index + "t" + term + " with config " + snapshotConfig + " complete"); this.snapshotReceive = null; if (!this.raft.recordLastApplied(term, index, snapshotConfig)) this.raft.resetStateMachine(true); // if this fails we are really screwed this.updateElectionTimer(); } } @Override public void caseRequestVote(RequestVote msg) { // Did we already vote for somebody else? final String peer = msg.getSenderId(); if (this.votedFor != null && !this.votedFor.equals(peer)) { this.info("rec'd " + msg + "; rejected because we already voted for \"" + this.votedFor + "\""); return; } // Verify that we are allowed to vote for this peer if (msg.getLastLogTerm() < this.raft.getLastLogTerm() || (msg.getLastLogTerm() == this.raft.getLastLogTerm() && msg.getLastLogIndex() < this.raft.getLastLogIndex())) { this.info("rec'd " + msg + "; rejected because their log " + msg.getLastLogIndex() + "t" + msg.getLastLogTerm() + " loses to ours " + this.raft.getLastLogIndex() + "t" + this.raft.getLastLogTerm()); return; } // Persist our vote for this peer (if not already persisted) if (this.votedFor == null) { this.info("granting vote to \"" + peer + "\" in term " + this.raft.currentTerm); if (!this.updateVotedFor(peer)) return; } else this.info("confirming existing vote for \"" + peer + "\" in term " + this.raft.currentTerm); // Send reply this.raft.sendMessage(new GrantVote(this.raft.clusterId, this.raft.identity, peer, this.raft.currentTerm)); } @Override public void caseGrantVote(GrantVote msg) { // Ignore - we already lost the election to the real leader if (this.log.isDebugEnabled()) this.debug("ignoring " + msg + " rec'd while in " + this); } // Helper methods /** * Record the peer voted for in the current term. */ private boolean updateVotedFor(String recipient) { // Sanity check assert Thread.holdsLock(this.raft); assert recipient != null; // Update persistent store final Writes writes = new Writes(); writes.getPuts().put(VOTED_FOR_KEY, this.raft.encodeString(recipient)); try { this.raft.kv.mutate(writes, true); } catch (Exception e) { this.error("error persisting vote for \"" + recipient + "\"", e); return false; } // Done this.votedFor = recipient; return true; } // Object @Override public String toString() { return this.toStringPrefix() + (this.leader != null ? ",leader=\"" + this.leader + "\"" : "") + (this.votedFor != null ? ",votedFor=\"" + this.votedFor + "\"" : "") + (!this.pendingRequests.isEmpty() ? ",pendingRequests=" + this.pendingRequests.keySet() : "") + (!this.pendingWrites.isEmpty() ? ",pendingWrites=" + this.pendingWrites.keySet() : "") + (!this.commitLeaderLeaseTimeoutMap.isEmpty() ? ",leaseTimeouts=" + this.commitLeaderLeaseTimeoutMap.keySet() : "") + "]"; } // Debug @Override boolean checkState() { if (!super.checkState()) return false; assert this.leaderAddress != null || this.leader == null; assert this.electionTimer.isRunning() == this.raft.isClusterMember(); for (Map.Entry<Long, PendingRequest> entry : this.pendingRequests.entrySet()) { final long txId = entry.getKey(); final PendingRequest pendingRequest = entry.getValue(); final RaftKVTransaction tx = pendingRequest.getTx(); assert txId == tx.getTxId(); assert tx.getState().equals(TxState.COMMIT_READY); assert tx.getCommitTerm() == 0; assert tx.getCommitIndex() == 0; } for (Map.Entry<Long, PendingWrite> entry : this.pendingWrites.entrySet()) { final long txId = entry.getKey(); final PendingWrite pendingWrite = entry.getValue(); final RaftKVTransaction tx = pendingWrite.getTx(); assert txId == tx.getTxId(); assert tx.getState().equals(TxState.COMMIT_READY) || tx.getState().equals(TxState.COMMIT_WAITING); assert pendingWrite.getFileWriter().getFile().exists(); } return true; } // PendingRequest // Represents a transaction in COMMIT_READY for which a CommitRequest has been sent to the leader // but no CommitResponse has yet been received private class PendingRequest { private final RaftKVTransaction tx; PendingRequest(RaftKVTransaction tx) { this.tx = tx; assert !FollowerRole.this.pendingRequests.containsKey(tx.getTxId()); FollowerRole.this.pendingRequests.put(tx.getTxId(), this); } public RaftKVTransaction getTx() { return this.tx; } } // PendingWrite // Represents a read-write transaction in COMMIT_READY or COMMIT_WAITING for which the server's AppendRequest // will have null mutationData, because we will already have the data on hand waiting in a temporary file. This // is a simple optimization to avoid sending the same data from leader -> follower just sent from follower -> leader. private class PendingWrite { private final RaftKVTransaction tx; private final FileWriter fileWriter; PendingWrite(RaftKVTransaction tx, FileWriter fileWriter) { this.tx = tx; this.fileWriter = fileWriter; } public RaftKVTransaction getTx() { return this.tx; } public FileWriter getFileWriter() { return this.fileWriter; } public void cleanup() { this.fileWriter.getFile().delete(); Util.closeIfPossible(this.fileWriter); } } } // CANDIDATE role private static class CandidateRole extends NonLeaderRole { private final HashSet<String> votes = new HashSet<>(); // Constructors public CandidateRole(RaftKVDatabase raft) { super(raft, true); } // Lifecycle @Override public void setup() { super.setup(); // Increment term if (!this.raft.advanceTerm(this.raft.currentTerm + 1)) return; // Request votes from other peers final HashSet<String> voters = new HashSet<>(this.raft.currentConfig.keySet()); voters.remove(this.raft.identity); this.info("entering candidate role in term " + this.raft.currentTerm + "; requesting votes from " + voters); for (String voter : voters) { this.raft.sendMessage(new RequestVote(this.raft.clusterId, this.raft.identity, voter, this.raft.currentTerm, this.raft.getLastLogTerm(), this.raft.getLastLogIndex())); } } // Service @Override public void outputQueueEmpty(String address) { // nothing to do } // Transactions @Override public void checkReadyTransaction(RaftKVTransaction tx) { // Sanity check assert Thread.holdsLock(this.raft); assert tx.getState().equals(TxState.COMMIT_READY); // Check snapshot isolation if (this.checkReadyTransactionReadOnlySnapshot(tx)) return; // We can't do anything with it until we have a leader } @Override public void cleanupForTransaction(RaftKVTransaction tx) { // nothing to do } // MessageSwitch @Override public void caseAppendRequest(AppendRequest msg) { this.info("rec'd " + msg + " in " + this + "; reverting to follower"); this.raft.changeRole(new FollowerRole(this.raft, msg.getSenderId(), this.raft.returnAddress)); this.raft.receiveMessage(this.raft.returnAddress, msg); } // MessageSwitch @Override public void caseCommitResponse(CommitResponse msg) { // We could not have ever sent a CommitRequest in this term this.failUnexpectedMessage(msg); } @Override public void caseInstallSnapshot(InstallSnapshot msg) { // We could not have ever sent an AppendResponse in this term this.failUnexpectedMessage(msg); } @Override public void caseRequestVote(RequestVote msg) { // Ignore - we are also a candidate and have already voted for ourself if (this.log.isDebugEnabled()) this.debug("ignoring " + msg + " rec'd while in " + this); } @Override public void caseGrantVote(GrantVote msg) { // Record vote this.votes.add(msg.getSenderId()); this.info("rec'd election vote from \"" + msg.getSenderId() + "\" in term " + this.raft.currentTerm); // Tally votes final int allVotes = this.raft.currentConfig.size(); final int numVotes = this.votes.size() + (this.raft.isClusterMember() ? 1 : 0); final int minVotes = allVotes / 2 + 1; // require a majority // Did we win? if (numVotes >= minVotes) { this.info("won the election for term " + this.raft.currentTerm + " with " + numVotes + "/" + allVotes + " votes; BECOMING LEADER IN TERM " + this.raft.currentTerm); this.raft.changeRole(new LeaderRole(this.raft)); } } // Object @Override public String toString() { return this.toStringPrefix() + ",votes=" + this.votes + "]"; } // Debug @Override boolean checkState() { if (!super.checkState()) return false; assert this.electionTimer.isRunning(); assert this.raft.isClusterMember(); return true; } } // Prefix Functions private abstract static class AbstractPrefixFunction<F, T> implements Function<F, T> { protected final byte[] prefix; AbstractPrefixFunction(byte[] prefix) { this.prefix = prefix; } } private static class PrefixKeyRangeFunction extends AbstractPrefixFunction<KeyRange, KeyRange> { PrefixKeyRangeFunction(byte[] prefix) { super(prefix); } @Override public KeyRange apply(KeyRange range) { return range.prefixedBy(this.prefix); } } private static class PrefixPutFunction extends AbstractPrefixFunction<Map.Entry<byte[], byte[]>, Map.Entry<byte[], byte[]>> { PrefixPutFunction(byte[] prefix) { super(prefix); } @Override public Map.Entry<byte[], byte[]> apply(Map.Entry<byte[], byte[]> entry) { return new AbstractMap.SimpleEntry<byte[], byte[]>(Bytes.concat(this.prefix, entry.getKey()), entry.getValue()); } } private static class PrefixAdjustFunction extends AbstractPrefixFunction<Map.Entry<byte[], Long>, Map.Entry<byte[], Long>> { PrefixAdjustFunction(byte[] prefix) { super(prefix); } @Override public Map.Entry<byte[], Long> apply(Map.Entry<byte[], Long> entry) { return new AbstractMap.SimpleEntry<byte[], Long>(Bytes.concat(this.prefix, entry.getKey()), entry.getValue()); } } // Debug/Sanity Checking private abstract class ErrorLoggingRunnable implements Runnable { @Override public final void run() { try { this.doRun(); } catch (Throwable t) { RaftKVDatabase.this.error("exception in callback", t); } } protected abstract void doRun(); } private boolean checkState() { try { this.doCheckState(); } catch (AssertionError e) { throw new AssertionError("checkState() failure for \"" + this.identity + "\"", e); } return true; } private void doCheckState() { assert Thread.holdsLock(this); // Handle stopped state if (this.role == null) { assert this.kv == null; assert this.random == null; assert this.currentTerm == 0; assert this.commitIndex == 0; assert this.lastAppliedTerm == 0; assert this.lastAppliedIndex == 0; assert this.lastAppliedConfig == null; assert this.currentConfig == null; assert this.clusterId == 0; assert this.raftLog.isEmpty(); assert this.logDirChannel == null; assert this.executor == null; assert this.transmitting.isEmpty(); assert this.openTransactions.isEmpty(); assert this.pendingService.isEmpty(); assert !this.shuttingDown; return; } // Handle running state assert this.kv != null; assert this.random != null; assert this.executor != null; assert this.logDirChannel != null; assert !this.executor.isShutdown() || this.shuttingDown; assert this.currentTerm >= 0; assert this.commitIndex >= 0; assert this.lastAppliedTerm >= 0; assert this.lastAppliedIndex >= 0; assert this.lastAppliedConfig != null; assert this.currentConfig != null; assert this.currentTerm >= this.lastAppliedTerm; assert this.commitIndex >= this.lastAppliedIndex; assert this.commitIndex <= this.lastAppliedIndex + this.raftLog.size(); long index = this.lastAppliedIndex; long term = this.lastAppliedTerm; for (LogEntry logEntry : this.raftLog) { assert logEntry.getIndex() == index + 1; assert logEntry.getTerm() >= term; index = logEntry.getIndex(); term = logEntry.getTerm(); } // Check configured vs. unconfigured if (this.isConfigured()) { assert this.clusterId != 0; assert this.currentTerm > 0; assert this.lastAppliedTerm >= 0; assert this.lastAppliedIndex >= 0; assert !this.currentConfig.isEmpty(); assert this.currentConfig.equals(this.buildCurrentConfig()); assert this.getLastLogTerm() > 0; assert this.getLastLogIndex() > 0; } else { assert this.lastAppliedTerm == 0; assert this.lastAppliedIndex == 0; assert this.lastAppliedConfig.isEmpty(); assert this.currentConfig.isEmpty(); assert this.raftLog.isEmpty(); } // Check role assert this.role.checkState(); // Check transactions for (RaftKVTransaction tx : this.openTransactions.values()) tx.checkStateOpen(this.currentTerm, this.getLastLogIndex(), this.commitIndex); } }
package com.cloud.vm; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.Formatter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachVolumeAnswer; import com.cloud.agent.api.AttachVolumeCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; import com.cloud.agent.api.GetVmStatsAnswer; import com.cloud.agent.api.GetVmStatsCommand; import com.cloud.agent.api.ManageSnapshotAnswer; import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.CreatePrivateTemplateCommand; import com.cloud.alert.AlertManager; import com.cloud.api.BaseCmd; import com.cloud.async.AsyncJobExecutor; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobResult; import com.cloud.async.AsyncJobVO; import com.cloud.async.BaseAsyncJobExecutor; import com.cloud.async.executor.DestroyVMExecutor; import com.cloud.async.executor.OperationResponse; import com.cloud.async.executor.RebootVMExecutor; import com.cloud.async.executor.StartVMExecutor; import com.cloud.async.executor.StopVMExecutor; import com.cloud.async.executor.VMExecutorHelper; import com.cloud.async.executor.VMOperationListener; import com.cloud.async.executor.VMOperationParam; import com.cloud.capacity.dao.CapacityDao; import com.cloud.configuration.ResourceCount.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ResourceLimitDao; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.dc.Vlan.VlanType; import com.cloud.dc.VlanVO; import com.cloud.dc.dao.AccountVlanMapDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.VlanDao; import com.cloud.domain.dao.DomainDao; import com.cloud.event.EventState; import com.cloud.event.EventTypes; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InternalErrorException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.StorageUnavailableException; import com.cloud.ha.HighAvailabilityManager; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.DetailsDao; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor; import com.cloud.network.FirewallRuleVO; import com.cloud.network.IPAddressVO; import com.cloud.network.IpAddrAllocator; import com.cloud.network.LoadBalancerVMMapVO; import com.cloud.network.NetworkManager; import com.cloud.network.SecurityGroupVMMapVO; import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.LoadBalancerVMMapDao; import com.cloud.network.dao.SecurityGroupDao; import com.cloud.network.dao.SecurityGroupVMMapDao; import com.cloud.network.security.NetworkGroupManager; import com.cloud.network.security.NetworkGroupVO; import com.cloud.offering.NetworkOffering; import com.cloud.offering.ServiceOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.GuestOSVO; import com.cloud.storage.Snapshot; import com.cloud.storage.Snapshot.SnapshotType; import com.cloud.storage.SnapshotVO; import com.cloud.storage.Storage; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume; import com.cloud.storage.Volume.VolumeType; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.DiskTemplateDao; import com.cloud.storage.dao.GuestOSCategoryDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateHostDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.template.VirtualMachineTemplate.BootloaderType; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; import com.cloud.user.User; import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.user.dao.UserStatisticsDao; import com.cloud.uservm.UserVm; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.net.NetUtils; import com.cloud.vm.DomainRouter.Role; import com.cloud.vm.VirtualMachine.Event; import com.cloud.vm.VirtualMachine.Type; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.InstanceGroupVMMapDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.InstanceGroupDao; @Local(value={UserVmManager.class}) public class UserVmManagerImpl implements UserVmManager { private static final Logger s_logger = Logger.getLogger(UserVmManagerImpl.class); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds @Inject HostDao _hostDao = null; @Inject DetailsDao _detailsDao = null; @Inject DomainRouterDao _routerDao = null; @Inject ServiceOfferingDao _offeringDao = null; @Inject DiskOfferingDao _diskOfferingDao = null; @Inject UserStatisticsDao _userStatsDao = null; @Inject VMTemplateDao _templateDao = null; @Inject VMTemplateHostDao _templateHostDao = null; @Inject DiskTemplateDao _diskDao = null; @Inject DomainDao _domainDao = null; @Inject ResourceLimitDao _limitDao = null; @Inject UserVmDao _vmDao = null; @Inject VolumeDao _volsDao = null; @Inject DataCenterDao _dcDao = null; @Inject FirewallRulesDao _rulesDao = null; @Inject SecurityGroupDao _securityGroupDao = null; @Inject SecurityGroupVMMapDao _securityGroupVMMapDao = null; @Inject LoadBalancerVMMapDao _loadBalancerVMMapDao = null; @Inject LoadBalancerDao _loadBalancerDao = null; @Inject IPAddressDao _ipAddressDao = null; @Inject HostPodDao _podDao = null; @Inject CapacityDao _capacityDao = null; @Inject NetworkManager _networkMgr = null; @Inject StorageManager _storageMgr = null; @Inject SnapshotManager _snapshotMgr = null; @Inject AgentManager _agentMgr = null; @Inject AccountDao _accountDao = null; @Inject UserDao _userDao = null; @Inject SnapshotDao _snapshotDao = null; @Inject GuestOSDao _guestOSDao = null; @Inject GuestOSCategoryDao _guestOSCategoryDao = null; @Inject HighAvailabilityManager _haMgr = null; @Inject AlertManager _alertMgr = null; @Inject AccountManager _accountMgr; @Inject AsyncJobManager _asyncMgr; @Inject protected StoragePoolHostDao _storagePoolHostDao; @Inject VlanDao _vlanDao; @Inject AccountVlanMapDao _accountVlanMapDao; @Inject StoragePoolDao _storagePoolDao; @Inject VMTemplateHostDao _vmTemplateHostDao; @Inject NetworkGroupManager _networkGroupManager; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject EventDao _eventDao = null; @Inject InstanceGroupDao _vmGroupDao; @Inject InstanceGroupVMMapDao _groupVMMapDao; private IpAddrAllocator _IpAllocator; ScheduledExecutorService _executor = null; int _expungeInterval; int _expungeDelay; int _retry = 2; String _name; String _instance; String _zone; Random _rand = new Random(System.currentTimeMillis()); private ConfigurationDao _configDao; int _userVMCap = 0; final int _maxWeight = 256; @Override public UserVmVO getVirtualMachine(long vmId) { return _vmDao.findById(vmId); } @Override public List<? extends UserVm> getVirtualMachines(long hostId) { return _vmDao.listByHostId(hostId); } @Override public boolean resetVMPassword(long userId, long vmId, String password) { UserVmVO vm = _vmDao.findById(vmId); VMTemplateVO template = _templateDao.findById(vm.getTemplateId()); if (template.getEnablePassword()) { if (vm.getDomainRouterId() == null) /*TODO: add it for external dhcp mode*/ return true; if (_networkMgr.savePasswordToRouter(vm.getDomainRouterId(), vm.getPrivateIpAddress(), password)) { // Need to reboot the virtual machine so that the password gets redownloaded from the DomR, and reset on the VM if (!rebootVirtualMachine(userId, vmId)) { if (vm.getState() == State.Stopped) { return true; } return false; } else { return true; } } else { return false; } } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Reset password called for a vm that is not using a password enabled template"); } return false; } } @Override public void attachVolumeToVM(long vmId, long volumeId, Long deviceId, long startEventId) throws InternalErrorException { VolumeVO volume = _volsDao.findById(volumeId); UserVmVO vm = _vmDao.findById(vmId); EventVO event = new EventVO(); event.setType(EventTypes.EVENT_VOLUME_ATTACH); event.setUserId(1L); event.setAccountId(volume.getAccountId()); event.setState(EventState.Started); event.setStartId(startEventId); event.setDescription("Attaching volume: "+volumeId+" to Vm: "+vmId); _eventDao.persist(event); VolumeVO rootVolumeOfVm = null; List<VolumeVO> rootVolumesOfVm = _volsDao.findByInstanceAndType(vmId, VolumeType.ROOT); if (rootVolumesOfVm.size() != 1) { throw new InternalErrorException("The VM " + vm.getName() + " has more than one ROOT volume and is in an invalid state. Please contact Cloud Support."); } else { rootVolumeOfVm = rootVolumesOfVm.get(0); } List<VolumeVO> vols = _volsDao.findByInstance(vmId); if( deviceId != null ) { if( deviceId.longValue() > 15 || deviceId.longValue() == 0 || deviceId.longValue() == 3) { throw new RuntimeException("deviceId should be 1,2,4-15"); } for (VolumeVO vol : vols) { if (vol.getDeviceId().equals(deviceId)) { throw new RuntimeException("deviceId " + deviceId + " is used by VM " + vm.getName()); } } } else { // allocate deviceId here List<String> devIds = new ArrayList<String>(); for( int i = 1; i < 15; i++ ) { devIds.add(String.valueOf(i)); } devIds.remove("3"); for (VolumeVO vol : vols) { devIds.remove(vol.getDeviceId().toString().trim()); } deviceId = Long.parseLong(devIds.iterator().next()); } StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); DiskOfferingVO volumeDiskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); String[] volumeTags = volumeDiskOffering.getTagsArray(); StoragePoolVO sourcePool = _storagePoolDao.findById(volume.getPoolId()); List<StoragePoolVO> sharedVMPools = _storagePoolDao.findPoolsByTags(vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), vmRootVolumePool.getClusterId(), volumeTags, true); boolean moveVolumeNeeded = true; if (sharedVMPools.size() == 0) { String poolType; if (vmRootVolumePool.getClusterId() != null) { poolType = "cluster"; } else if (vmRootVolumePool.getPodId() != null) { poolType = "pod"; } else { poolType = "zone"; } throw new InternalErrorException("There are no storage pools in the VM's " + poolType + " with all of the volume's tags (" + volumeDiskOffering.getTags() + ")."); } else { Long sourcePoolDcId = sourcePool.getDataCenterId(); Long sourcePoolPodId = sourcePool.getPodId(); Long sourcePoolClusterId = sourcePool.getClusterId(); for (StoragePoolVO vmPool : sharedVMPools) { Long vmPoolDcId = vmPool.getDataCenterId(); Long vmPoolPodId = vmPool.getPodId(); Long vmPoolClusterId = vmPool.getClusterId(); if (sourcePoolDcId == vmPoolDcId && sourcePoolPodId == vmPoolPodId && sourcePoolClusterId == vmPoolClusterId) { moveVolumeNeeded = false; break; } } } if (moveVolumeNeeded) { // Move the volume to a storage pool in the VM's zone, pod, or cluster volume = _storageMgr.moveVolume(volume, vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), vmRootVolumePool.getClusterId()); } AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); if(asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); if(s_logger.isInfoEnabled()) s_logger.info("Trying to attaching volume " + volumeId +" to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status"); _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId); } String errorMsg = "Failed to attach volume: " + volume.getName() + " to VM: " + vm.getName(); boolean sendCommand = (vm.getState() == State.Running); AttachVolumeAnswer answer = null; Long hostId = vm.getHostId(); if (sendCommand) { AttachVolumeCommand cmd = new AttachVolumeCommand(true, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), deviceId); try { answer = (AttachVolumeAnswer)_agentMgr.send(hostId, cmd); } catch (Exception e) { throw new InternalErrorException(errorMsg + " due to: " + e.getMessage()); } } event = new EventVO(); event.setAccountId(volume.getAccountId()); event.setUserId(1L); event.setType(EventTypes.EVENT_VOLUME_ATTACH); event.setState(EventState.Completed); event.setStartId(startEventId); if (!sendCommand || (answer != null && answer.getResult())) { // Mark the volume as attached if( sendCommand ) { _volsDao.attachVolume(volume.getId(), vmId, answer.getDeviceId()); } else { _volsDao.attachVolume(volume.getId(), vmId, deviceId); } if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getName()); event.setLevel(EventVO.LEVEL_INFO); _eventDao.persist(event); } else { if (answer != null) { String details = answer.getDetails(); if (details != null && !details.isEmpty()) errorMsg += "; " + details; } throw new InternalErrorException(errorMsg); } } @Override public void detachVolumeFromVM(long volumeId, long startEventId, long deviceId, long instanceId) throws InternalErrorException { VolumeVO volume = null; if(volumeId!=0) { volume = _volsDao.findById(volumeId); } else { volume = _volsDao.findByInstanceAndDeviceId(instanceId, deviceId).get(0); } Long vmId = null; if(instanceId==0) { vmId = volume.getInstanceId(); } else { vmId = instanceId; } if (vmId == null) { return; } EventVO event = new EventVO(); event.setType(EventTypes.EVENT_VOLUME_DETACH); event.setUserId(1L); event.setAccountId(volume.getAccountId()); event.setState(EventState.Started); event.setStartId(startEventId); event.setDescription("Detaching volume: "+volumeId+" from Vm: "+vmId); _eventDao.persist(event); UserVmVO vm = _vmDao.findById(vmId); AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); if(asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); if(s_logger.isInfoEnabled()) s_logger.info("Trying to attaching volume " + volumeId +"to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status"); _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId); } String errorMsg = "Failed to detach volume: " + volume.getName() + " from VM: " + vm.getName(); boolean sendCommand = (vm.getState() == State.Running); Answer answer = null; if (sendCommand) { AttachVolumeCommand cmd = new AttachVolumeCommand(false, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), deviceId!=0 ? deviceId : volume.getDeviceId()); try { answer = _agentMgr.send(vm.getHostId(), cmd); } catch (Exception e) { throw new InternalErrorException(errorMsg + " due to: " + e.getMessage()); } } event = new EventVO(); event.setAccountId(volume.getAccountId()); event.setUserId(1L); event.setType(EventTypes.EVENT_VOLUME_DETACH); event.setState(EventState.Completed); event.setStartId(startEventId); if (!sendCommand || (answer != null && answer.getResult())) { // Mark the volume as detached _volsDao.detachVolume(volume.getId()); if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getName()); event.setLevel(EventVO.LEVEL_INFO); _eventDao.persist(event); } else { if (answer != null) { String details = answer.getDetails(); if (details != null && !details.isEmpty()) errorMsg += "; " + details; } throw new InternalErrorException(errorMsg); } } @Override public boolean attachISOToVM(long vmId, long isoId, boolean attach) { UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { return false; } else if (vm.getState() != State.Running) { return true; } // Get the path of the ISO String isoPath = _storageMgr.getAbsoluteIsoPath(isoId, vm.getDataCenterId()); String isoName = _templateDao.findById(isoId).getName(); if (isoPath == null) { // we can't send a null path to the ServerResource, so return false if we are unable to find the isoPath if (isoName.startsWith("xs-tools")) isoPath = isoName; else return false; } String vmName = vm.getInstanceName(); HostVO host = _hostDao.findById(vm.getHostId()); if (host == null) return false; AttachIsoCommand cmd = new AttachIsoCommand(vmName, isoPath, attach); Answer a = _agentMgr.easySend(vm.getHostId(), cmd); return (a != null); } @Override public UserVmVO startVirtualMachine(long userId, long vmId, String isoPath, long startEventId) throws ExecutionException, StorageUnavailableException, ConcurrentOperationException { return startVirtualMachine(userId, vmId, null, isoPath, startEventId); } @Override public boolean executeStartVM(StartVMExecutor executor, VMOperationParam param) { // TODO following implementation only do asynchronized operation at API level try { UserVmVO vm = start(param.getUserId(), param.getVmId(), null, param.getIsoPath(), param.getEventId()); if(vm != null) executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, VMExecutorHelper.composeResultObject( executor.getAsyncJobMgr().getExecutorContext().getManagementServer(), vm, null)); else executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, "Unable to start vm"); } catch (StorageUnavailableException e) { s_logger.debug("Unable to start vm because storage is unavailable: " + e.getMessage()); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.VM_ALLOCATION_ERROR, "Unable to start vm because storage is unavailable"); } catch (ConcurrentOperationException e) { s_logger.debug(e.getMessage()); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, e.getMessage()); } catch (ExecutionException e) { s_logger.debug(e.getMessage()); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, e.getMessage()); } return true; } @Override public UserVmVO startVirtualMachine(long userId, long vmId, String password, String isoPath, long startEventId) throws ExecutionException, StorageUnavailableException, ConcurrentOperationException { try { return start(userId, vmId, password, isoPath, startEventId); } catch (StorageUnavailableException e) { s_logger.debug("Unable to start vm because storage is unavailable: " + e.getMessage()); throw e; } catch (ConcurrentOperationException e) { s_logger.debug(e.getMessage()); throw e; } catch (ExecutionException e) { // TODO Auto-generated catch block s_logger.debug(e.getMessage()); throw e; } } @DB protected UserVmVO start(long userId, long vmId, String password, String isoPath, long startEventId) throws StorageUnavailableException, ConcurrentOperationException, ExecutionException { UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getRemoved() != null) { s_logger.debug("Unable to find " + vmId); return null; } EventVO event = new EventVO(); event.setType(EventTypes.EVENT_VM_START); event.setUserId(userId); event.setAccountId(vm.getAccountId()); event.setState(EventState.Started); event.setDescription("Starting Vm with Id: "+vmId); event.setStartId(startEventId); event = _eventDao.persist(event); //if there was no schedule event before, set start event as startEventId if(startEventId == 0 && event != null){ startEventId = event.getId(); } if (s_logger.isDebugEnabled()) { s_logger.debug("Starting VM: " + vmId); } State state = vm.getState(); if (state == State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("Starting an already started VM: " + vm.getId() + " - " + vm.getName() + "; state = " + vm.getState().toString()); } return vm; } String eventParams = "id=" + vm.getId() + "\nvmName=" + vm.getName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId(); event = new EventVO(); event.setType(EventTypes.EVENT_VM_START); event.setUserId(userId); event.setAccountId(vm.getAccountId()); event.setParameters(eventParams); event.setState(EventState.Completed); event.setStartId(startEventId); if (state.isTransitional()) { String description = "Concurrent operations on the vm " + vm.getId() + " - " + vm.getName() + "; state = " + state.toString(); event.setDescription(description); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); throw new ConcurrentOperationException(description); } DataCenterVO dc = _dcDao.findById(vm.getDataCenterId()); HostPodVO pod = _podDao.findById(vm.getPodId()); List<StoragePoolVO> sps = _storageMgr.getStoragePoolsForVm(vm.getId()); StoragePoolVO sp = sps.get(0); // FIXME VMTemplateVO template = _templateDao.findById(vm.getTemplateId()); ServiceOffering offering = _offeringDao.findById(vm.getServiceOfferingId()); long diskOfferingId = -1; // If an ISO path is passed in, boot from that ISO // Else, check if the VM already has an ISO attached to it. If so, start the VM with that ISO inserted, but don't boot from it. boolean bootFromISO = false; if (isoPath != null) { bootFromISO = true; } else { Long isoId = vm.getIsoId(); if (isoId != null) { isoPath = _storageMgr.getAbsoluteIsoPath(isoId, vm.getDataCenterId()); } } // Determine the VM's OS description String guestOSDescription; GuestOSVO guestOS = _guestOSDao.findById(vm.getGuestOSId()); if (guestOS == null) { String description = "Could not find guest OS description for vm: " + vm.getName(); s_logger.debug(description); event.setDescription(description); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); return null; } else { guestOSDescription = guestOS.getName(); } HashSet<Host> avoid = new HashSet<Host>(); HostVO host = (HostVO) _agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, vm, null, avoid); if (host == null) { String description = "Unable to find any host for " + vm.toString(); s_logger.error(description); event.setDescription(description); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); return null; } if (!_vmDao.updateIf(vm, Event.StartRequested, host.getId())) { String description = "Unable to start VM " + vm.toString() + " because the state is not correct."; s_logger.error(description); event.setDescription(description); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); return null; } boolean started = false; Transaction txn = Transaction.currentTxn(); try { String vnet = null; DomainRouterVO router = null; if (vm.getDomainRouterId() != null) { router = _networkMgr.addVirtualMachineToGuestNetwork(vm, password, startEventId); if (router == null) { s_logger.error("Unable to add vm " + vm.getId() + " - " + vm.getName()); _vmDao.updateIf(vm, Event.OperationFailed, null); if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("Unable to start VM: " + vm.getName()+"("+vm.getDisplayName()+")" + "; Unable to add VM to guest network"); else event.setDescription("Unable to start VM: " + vm.getName() + "; Unable to add VM to guest network"); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); return null; } vnet = router.getVnet(); s_logger.debug("VM: " + vm.getName() + " discovered vnet: " + vnet + " from router: " + router.getName()); if(NetworkManager.USE_POD_VLAN){ if(vm.getPodId() != router.getPodId()){ //VM is in a different Pod if(router.getZoneVlan() == null){ //Create Zone Vlan if not created already vnet = _networkMgr.createZoneVlan(router); if (vnet == null) { s_logger.error("Vlan creation failed. Unable to add vm " + vm.getId() + " - " + vm.getName()); return null; } } else { //Use existing zoneVlan vnet = router.getZoneVlan(); } } } } boolean mirroredVols = vm.isMirroredVols(); List<VolumeVO> rootVols = _volsDao.findByInstanceAndType(vm.getId(), VolumeType.ROOT); assert rootVols.size() == 1 : "How can we get " + rootVols.size() + " root volume for " + vm.getId(); String [] storageIps = new String[2]; VolumeVO vol = rootVols.get(0); List<VolumeVO> vols = _volsDao.findCreatedByInstance(vm.getId()); List<VolumeVO> vos = new ArrayList<VolumeVO>(); /*compete with take snapshot*/ for (VolumeVO userVmVol : vols) { vos.add(_volsDao.lock(userVmVol.getId(), true)); } Answer answer = null; int retry = _retry; do { if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to start vm " + vm.getName() + " on host " + host.toString()); } txn.start(); if (vm.getDomainRouterId() != null) { vm.setVnet(vnet); vm.setInstanceName(VirtualMachineName.attachVnet(vm.getName(), vm.getVnet())); } else { vm.setVnet("untagged"); } if( retry < _retry ) { if (!_vmDao.updateIf(vm, Event.OperationRetry, host.getId())) { String description = "Unable to start VM " + vm.toString() + " because the state is not correct."; s_logger.debug(description); event.setDescription(description); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); return null; } } txn.commit(); if( !_storageMgr.share(vm, vols, host, true) ) { s_logger.debug("Unable to share volumes to host " + host.toString()); continue; } int utilization = _userVMCap; //cpu_cap //Configuration cpu.uservm.cap is not available in default installation. Using this parameter is not encouraged int cpuWeight = _maxWeight; //cpu_weight // weight based allocation cpuWeight = (int)((offering.getSpeed()*0.99) / (float)host.getSpeed() * _maxWeight); if (cpuWeight > _maxWeight) { cpuWeight = _maxWeight; } int bits; if (template == null) { bits = 64; } else { bits = template.getBits(); } StartCommand cmdStart = new StartCommand(vm, vm.getInstanceName(), offering, offering.getRateMbps(), offering.getMulticastRateMbps(), router, storageIps, vol.getFolder(), vm.getVnet(), utilization, cpuWeight, vols, mirroredVols, bits, isoPath, bootFromISO, guestOSDescription); if (Storage.ImageFormat.ISO.equals(template.getFormat()) || template.isRequiresHvm()) { cmdStart.setBootloader(BootloaderType.HVM); } if (vm.getExternalVlanDbId() != null) { final VlanVO externalVlan = _vlanDao.findById(vm.getExternalVlanDbId()); cmdStart.setExternalVlan(externalVlan.getVlanId()); cmdStart.setExternalMacAddress(vm.getExternalMacAddress()); } try { answer = _agentMgr.send(host.getId(), cmdStart); if (answer.getResult()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Started vm " + vm.getName() + " on host " + host.toString()); } started = true; break; } s_logger.debug("Unable to start " + vm.toString() + " on host " + host.toString() + " due to " + answer.getDetails()); } catch (OperationTimedoutException e) { if (e.isActive()) { String description = "Unable to start vm " + vm.getName() + " due to operation timed out and it is active so scheduling a restart."; _haMgr.scheduleRestart(vm, true); host = null; s_logger.debug(description); event.setDescription(description); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); return null; } } catch (AgentUnavailableException e) { s_logger.debug("Agent " + host.toString() + " was unavailable to start VM " + vm.getName()); } avoid.add(host); _storageMgr.unshare(vm, vols, host); } while (--retry > 0 && (host = (HostVO)_agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, vm, null, avoid)) != null); if (host == null || retry <= 0) { if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("Unable to start VM: " + vm.getName()+"("+vm.getDisplayName()+")"+ " Reason: "+answer.getDetails()); else event.setDescription("Unable to start VM: " + vm.getName()+ " Reason: "+answer.getDetails()); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); throw new ExecutionException("Unable to start VM: " + vm.getName()+ " Reason: "+answer.getDetails()); } if (!_vmDao.updateIf(vm, Event.OperationSucceeded, host.getId())) { if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("unable to start VM: " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("unable to start VM: " + vm.getName()); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); throw new ConcurrentOperationException("Starting vm " + vm.getName() + " didn't work."); } if (s_logger.isDebugEnabled()) { s_logger.debug("Started vm " + vm.getName()); } if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("successfully started VM: " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("successfully started VM: " + vm.getName()); _eventDao.persist(event); _networkGroupManager.handleVmStateTransition(vm, State.Running); return _vmDao.findById(vm.getId()); } catch (Throwable th) { txn.rollback(); s_logger.error("While starting vm " + vm.getName() + ", caught throwable: ", th); if (!started) { vm.setVnet(null); txn.start(); if (_vmDao.updateIf(vm, Event.OperationFailed, null)) { txn.commit(); } } if (th instanceof StorageUnavailableException) { throw (StorageUnavailableException)th; } if (th instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)th; } if (th instanceof ExecutionException) { s_logger.warn(th.getMessage()); throw (ExecutionException)th; } String description = "Unable to start VM " + vm.getName() + " because of an unknown exception"; event.setDescription(description); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); return null; } } @Override public boolean stopVirtualMachine(long userId, long vmId) { if (s_logger.isDebugEnabled()) { s_logger.debug("Stopping vm=" + vmId); } UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is either removed or deleted."); } return true; } return stop(userId, vm, 0); } @Override public OperationResponse executeStopVM(final StopVMExecutor executor, final VMOperationParam param) { final UserVmVO vm = _vmDao.findById(param.getVmId()); OperationResponse response; String resultDescription = "Success"; if (vm == null || vm.getRemoved() != null) { resultDescription = "VM is either removed or deleted"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, resultDescription); if(s_logger.isDebugEnabled()) s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription); return response; } State state = vm.getState(); if (state == State.Stopped) { resultDescription = "VM is already stopped"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, resultDescription); if(s_logger.isDebugEnabled()) s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription); return response; } if (state == State.Creating || state == State.Destroyed || state == State.Expunging) { resultDescription = "VM is not in a stoppable state"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, resultDescription); if(s_logger.isDebugEnabled()) s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription); return response; } if (!_vmDao.updateIf(vm, Event.StopRequested, vm.getHostId())) { resultDescription = "VM is not in a state to stop"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); if(s_logger.isDebugEnabled()) s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); return response; } if (vm.getHostId() == null) { resultDescription = "VM host is null (invalid VM)"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); if(s_logger.isDebugEnabled()) s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); return response; } AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); if(asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); _asyncMgr.updateAsyncJobAttachment(job.getId(), "vm_instance", vm.getId()); } StopCommand cmd = new StopCommand(vm, vm.getInstanceName(), vm.getVnet()); try { long seq = _agentMgr.send(vm.getHostId(), new Command[] {cmd}, true, new VMOperationListener(executor, param, vm, 0)); resultDescription = "Execute asynchronize stop VM command: sending command to agent, seq - " + seq; if(s_logger.isDebugEnabled()) s_logger.debug(resultDescription); response = new OperationResponse(OperationResponse.STATUS_IN_PROGRESS, resultDescription); return response; } catch (AgentUnavailableException e) { resultDescription = "Agent is not available"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); _vmDao.updateIf(vm, Event.OperationFailed, vm.getHostId()); response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); return response; } } @Override public boolean rebootVirtualMachine(long userId, long vmId) { UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) { return false; } EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(vm.getAccountId()); event.setType(EventTypes.EVENT_VM_REBOOT); event.setParameters("id="+vm.getId() + "\nvmName=" + vm.getName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId()); if (vm.getState() == State.Running && vm.getHostId() != null) { RebootCommand cmd = new RebootCommand(vm.getInstanceName()); RebootAnswer answer = (RebootAnswer)_agentMgr.easySend(vm.getHostId(), cmd); if (answer != null) { if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("Successfully rebooted VM instance : " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("Successfully rebooted VM instance : " + vm.getName()); _eventDao.persist(event); return true; } else { if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("failed to reboot VM instance : " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("failed to reboot VM instance : " + vm.getName()); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); return false; } } else { return false; } } @Override public OperationResponse executeRebootVM(RebootVMExecutor executor, VMOperationParam param) { final UserVmVO vm = _vmDao.findById(param.getVmId()); String resultDescription; if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) { resultDescription = "VM does not exist or in destroying state"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); if(s_logger.isDebugEnabled()) s_logger.debug("Execute asynchronize Reboot VM command: " +resultDescription); return new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); } if (vm.getState() == State.Running && vm.getHostId() != null) { RebootCommand cmd = new RebootCommand(vm.getInstanceName()); try { long seq = _agentMgr.send(vm.getHostId(), new Command[] {cmd}, true, new VMOperationListener(executor, param, vm, 0)); resultDescription = "Execute asynchronize Reboot VM command: sending command to agent, seq - " + seq; if(s_logger.isDebugEnabled()) s_logger.debug(resultDescription); return new OperationResponse(OperationResponse.STATUS_IN_PROGRESS, resultDescription); } catch (AgentUnavailableException e) { resultDescription = "Agent is not available"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); return new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); } } resultDescription = "VM is not running or agent host is disconnected"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); return new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); } @Override public boolean upgradeVirtualMachine(long vmId, long serviceOfferingId) { UserVmVO vm = _vmDao.createForUpdate(vmId); vm.setServiceOfferingId(serviceOfferingId); vm.setHaEnabled(_serviceOfferingDao.findById(serviceOfferingId).getOfferHA()); return _vmDao.update(vmId, vm); } @Override public HashMap<Long, VmStatsEntry> getVirtualMachineStatistics(long hostId, String hostName, List<Long> vmIds) throws InternalErrorException { HashMap<Long, VmStatsEntry> vmStatsById = new HashMap<Long, VmStatsEntry>(); if (vmIds.isEmpty()) { return vmStatsById; } List<String> vmNames = new ArrayList<String>(); for (Long vmId : vmIds) { UserVmVO vm = _vmDao.findById(vmId); vmNames.add(vm.getInstanceName()); } Answer answer = _agentMgr.easySend(hostId, new GetVmStatsCommand(vmNames,_hostDao.findById(hostId).getGuid(), hostName)); if (answer == null || !answer.getResult()) { s_logger.warn("Unable to obtain VM statistics."); return null; } else { HashMap<String, VmStatsEntry> vmStatsByName = ((GetVmStatsAnswer) answer).getVmStatsMap(); if(vmStatsByName == null) { s_logger.warn("Unable to obtain VM statistics."); return null; } for (String vmName : vmStatsByName.keySet()) { vmStatsById.put(vmIds.get(vmNames.indexOf(vmName)), vmStatsByName.get(vmName)); } } return vmStatsById; } @DB protected String acquireGuestIpAddress(long dcId, long accountId, UserVmVO userVm) throws InternalErrorException { boolean routerLock = false; DomainRouterVO router = _routerDao.findBy(accountId, dcId); long routerId = router.getId(); Transaction txn = Transaction.currentTxn(); try { txn.start(); router = _routerDao.acquire(routerId); if (router == null) { throw new InternalErrorException("Unable to lock up the router:" + routerId); } routerLock = true; List<UserVmVO> userVms = _vmDao.listByAccountAndDataCenter(accountId, dcId); Set<Long> allPossibleIps = NetUtils.getAllIpsFromCidr(router.getGuestIpAddress(), NetUtils.getCidrSize(router.getGuestNetmask())); Set<Long> usedIps = new TreeSet<Long> (); for (UserVmVO vm: userVms) { if (vm.getGuestIpAddress() != null) { usedIps.add(NetUtils.ip2Long(vm.getGuestIpAddress())); } } if (usedIps.size() != 0) { allPossibleIps.removeAll(usedIps); } if (allPossibleIps.isEmpty()) { return null; } Iterator<Long> iterator = allPossibleIps.iterator(); long ipAddress = iterator.next().longValue(); String ipAddressStr = NetUtils.long2Ip(ipAddress); userVm.setGuestIpAddress(ipAddressStr); userVm.setGuestNetmask(router.getGuestNetmask()); String vmMacAddress = NetUtils.long2Mac( (NetUtils.mac2Long(router.getGuestMacAddress()) & 0xffffffff0000L) | (ipAddress & 0xffff) ); userVm.setGuestMacAddress(vmMacAddress); _vmDao.update(userVm.getId(), userVm); if (routerLock) { _routerDao.release(routerId); routerLock = false; } txn.commit(); return ipAddressStr; }finally { if (routerLock) { _routerDao.release(routerId); } } } public void releaseGuestIpAddress(UserVmVO userVm) { ServiceOffering offering = _offeringDao.findById(userVm.getServiceOfferingId()); if (offering.getGuestIpType() != NetworkOffering.GuestIpType.Virtualized) { IPAddressVO guestIP = (userVm.getGuestIpAddress() == null) ? null : _ipAddressDao.findById(userVm.getGuestIpAddress()); if (guestIP != null && guestIP.getAllocated() != null) { _ipAddressDao.unassignIpAddress(userVm.getGuestIpAddress()); s_logger.debug("Released guest IP address=" + userVm.getGuestIpAddress() + " vmName=" + userVm.getName() + " dcId=" + userVm.getDataCenterId()); EventVO event = new EventVO(); event.setUserId(User.UID_SYSTEM); event.setAccountId(userVm.getAccountId()); event.setType(EventTypes.EVENT_NET_IP_RELEASE); event.setParameters("guestIPaddress=" + userVm.getGuestIpAddress() + "\nvmName=" + userVm.getName() + "\ndcId=" + userVm.getDataCenterId()); event.setDescription("released a public ip: " + userVm.getGuestIpAddress()); _eventDao.persist(event); } else { if (_IpAllocator != null && _IpAllocator.exteralIpAddressAllocatorEnabled()) { String guestIp = userVm.getGuestIpAddress(); if (guestIp != null) { _IpAllocator.releasePrivateIpAddress(guestIp, userVm.getDataCenterId(), userVm.getPodId()); } } } } userVm.setGuestIpAddress(null); _vmDao.update(userVm.getId(), userVm); } @Override public UserVmVO allocate(String displayName, VMTemplateVO template, ServiceOfferingVO serviceOffering, NetworkOfferingVO[] networkOfferings, DiskOfferingVO[] diskOfferings, AccountVO owner, long userId) throws InsufficientCapacityException { /* long accountId = account.getId(); long dataCenterId = dc.getId(); long serviceOfferingId = offering.getId(); UserVmVO vm = new UserVmVO(); if (s_logger.isDebugEnabled()) { s_logger.debug("Creating vm for account id=" + account.getId() + ", name="+ account.getAccountName() + "; dc=" + dc.getName() + "; offering=" + offering.getId() + "; diskOffering=" + ((diskOffering != null) ? diskOffering.getName() : "none") + "; template=" + template.getId()); } DomainRouterVO router = _routerDao.findBy(accountId, dataCenterId, Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); if (router == null) { throw new InternalErrorException("Cannot find a router for account (" + accountId + "/" + account.getAccountName() + ") in " + dataCenterId); } // Determine the Guest OS Id long guestOSId; if (template != null) { guestOSId = template.getGuestOSId(); } else { throw new InternalErrorException("No template or ISO was specified for the VM."); } long numVolumes = -1; Transaction txn = Transaction.currentTxn(); long routerId = router.getId(); String name; txn.start(); account = _accountDao.lock(accountId, true); if (account == null) { throw new InternalErrorException("Unable to lock up the account: " + accountId); } // First check that the maximum number of UserVMs for the given accountId will not be exceeded if (_accountMgr.resourceLimitExceeded(account, ResourceType.user_vm)) { ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + account.getAccountName() + " has been exceeded."); rae.setResourceType("vm"); throw rae; } boolean isIso = Storage.ImageFormat.ISO.equals(template.getFormat()); numVolumes = (isIso || (diskOffering == null)) ? 1 : 2; _accountMgr.incrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.incrementResourceCount(account.getId(), ResourceType.volume, numVolumes); txn.commit(); name = VirtualMachineName.getVmName(vmId, accountId, _instance); String diskOfferingIdentifier = (diskOffering != null) ? String.valueOf(diskOffering.getId()) : "-1"; String eventParams = "id=" + vmId + "\nvmName=" + name + "\nsoId=" + serviceOfferingId + "\ndoId=" + diskOfferingIdentifier + "\ntId=" + template.getId() + "\ndcId=" + dataCenterId; EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(accountId); event.setStartId(startEventId); event.setState(EventState.Completed); event.setType(EventTypes.EVENT_VM_CREATE); event.setParameters(eventParams); try { Pair<HostPodVO, Long> pod = null; long poolid = 0; Set<Long> podsToAvoid = new HashSet<Long>(); while ((pod = _agentMgr.findPod(template, offering, dc, account.getId(), podsToAvoid)) != null) { if (vm == null) { vm = new UserVmVO(vmId, name, template.getId(), guestOSId, accountId, account.getDomainId().longValue(), serviceOfferingId, null, null, router.getGuestNetmask(), null,null,null, routerId, pod.first().getId(), dataCenterId, offering.getOfferHA(), displayName, group, userData); if (diskOffering != null) { vm.setMirroredVols(diskOffering.isMirrored()); } vm.setLastHostId(pod.second()); vm = _vmDao.persist(vm); } else { vm.setPodId(pod.first().getId()); _vmDao.updateIf(vm, Event.OperationRetry, null); } String ipAddressStr = acquireGuestIpAddress(dataCenterId, accountId, vm); if (ipAddressStr == null) { s_logger.warn("Failed user vm creation : no guest ip address available"); releaseGuestIpAddress(vm); ResourceAllocationException rae = new ResourceAllocationException("No guest ip addresses available for " + account.getAccountName() + " (try destroying some instances)"); rae.setResourceType("vm"); throw rae; } poolid = _storageMgr.createUserVM(account, vm, template, dc, pod.first(), offering, diskOffering, avoids); if ( poolid != 0) { break; } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find storage host in pod " + pod.first().getName() + " (id:" + pod.first().getId() + ") while creating " + vm.toString() + ", checking other pods"); } // if it fails at storage allocation round, reset lastHostId to "release" // the CPU/memory allocation on the candidate host vm.setLastHostId(null); _vmDao.update(vm.getId(), vm); podsToAvoid.add(pod.first().getId()); } if ((vm == null) || (poolid == 0)) { throw new ResourceAllocationException("Create VM " + ((vm == null) ? vmId : vm.toString()) + " failed due to no Storage Pool is available"); } txn.start(); if(vm != null && vm.getName() != null && vm.getDisplayName() != null) { if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("successfully created VM instance : " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("successfully created VM instance : " + vm.getName()); } else { event.setDescription("successfully created VM instance :"+name); } _eventDao.persist(event); _vmDao.updateIf(vm, Event.OperationSucceeded, null); if (s_logger.isDebugEnabled()) { s_logger.debug("vm created " + vmId); } txn.commit(); return _vmDao.findById(vmId); } catch (Throwable th) { s_logger.error("Unable to create vm", th); if (vm != null) { _vmDao.delete(vmId); } _accountMgr.decrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.decrementResourceCount(account.getId(), ResourceType.volume, numVolumes); String eventDescription = "Failed to create VM: "; if (vm == null) { eventDescription += "new instance"; } else { eventDescription += vm.getName(); if (!vm.getName().equals(vm.getDisplayName())) { eventDescription += " (" + vm.getDisplayName() + ")"; } } if (th instanceof ResourceAllocationException) { throw (ResourceAllocationException)th; } throw new CloudRuntimeException("Unable to create vm", th); } */ return null; } @Override @DB public UserVmVO createVirtualMachine(Long vmId, long userId, AccountVO account, DataCenterVO dc, ServiceOfferingVO offering, VMTemplateVO template, DiskOfferingVO diskOffering, String displayName, String userData, List<StoragePoolVO> avoids, long startEventId, long size) throws InternalErrorException, ResourceAllocationException { long accountId = account.getId(); long dataCenterId = dc.getId(); long serviceOfferingId = offering.getId(); UserVmVO vm = null; if (s_logger.isDebugEnabled()) { s_logger.debug("Creating vm for account id=" + account.getId() + ", name="+ account.getAccountName() + "; dc=" + dc.getName() + "; offering=" + offering.getId() + "; diskOffering=" + ((diskOffering != null) ? diskOffering.getName() : "none") + "; template=" + template.getId()); } DomainRouterVO router = _routerDao.findBy(accountId, dataCenterId, Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); if (router == null) { throw new InternalErrorException("Cannot find a router for account (" + accountId + "/" + account.getAccountName() + ") in " + dataCenterId); } // Determine the Guest OS Id long guestOSId; if (template != null) { guestOSId = template.getGuestOSId(); } else { throw new InternalErrorException("No template or ISO was specified for the VM."); } long numVolumes = -1; Transaction txn = Transaction.currentTxn(); long routerId = router.getId(); String name; txn.start(); account = _accountDao.lock(accountId, true); if (account == null) { throw new InternalErrorException("Unable to lock up the account: " + accountId); } // First check that the maximum number of UserVMs for the given accountId will not be exceeded if (_accountMgr.resourceLimitExceeded(account, ResourceType.user_vm)) { ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + account.getAccountName() + " has been exceeded."); rae.setResourceType("vm"); throw rae; } boolean isIso = Storage.ImageFormat.ISO.equals(template.getFormat()); numVolumes = (isIso || (diskOffering == null)) ? 1 : 2; _accountMgr.incrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.incrementResourceCount(account.getId(), ResourceType.volume, numVolumes); txn.commit(); name = VirtualMachineName.getVmName(vmId, accountId, _instance); String diskOfferingIdentifier = (diskOffering != null) ? String.valueOf(diskOffering.getId()) : "-1"; String eventParams = "id=" + vmId + "\nvmName=" + name + "\nsoId=" + serviceOfferingId + "\ndoId=" + diskOfferingIdentifier + "\ntId=" + template.getId() + "\ndcId=" + dataCenterId; EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(accountId); event.setStartId(startEventId); event.setState(EventState.Completed); event.setType(EventTypes.EVENT_VM_CREATE); event.setParameters(eventParams); try { Pair<HostPodVO, Long> pod = null; long poolid = 0; Set<Long> podsToAvoid = new HashSet<Long>(); while ((pod = _agentMgr.findPod(template, offering, dc, account.getId(), podsToAvoid)) != null) { if (vm == null) { vm = new UserVmVO(vmId, name, template.getId(), guestOSId, accountId, account.getDomainId(), serviceOfferingId, null, null, router.getGuestNetmask(), null,null,null, routerId, pod.first().getId(), dataCenterId, offering.getOfferHA(), displayName, userData); if (diskOffering != null) { vm.setMirroredVols(diskOffering.isMirrored()); } vm.setLastHostId(pod.second()); vm = _vmDao.persist(vm); } else { vm.setPodId(pod.first().getId()); _vmDao.updateIf(vm, Event.OperationRetry, null); } String ipAddressStr = acquireGuestIpAddress(dataCenterId, accountId, vm); if (ipAddressStr == null) { s_logger.warn("Failed user vm creation : no guest ip address available"); releaseGuestIpAddress(vm); ResourceAllocationException rae = new ResourceAllocationException("No guest ip addresses available for " + account.getAccountName() + " (try destroying some instances)"); rae.setResourceType("vm"); throw rae; } poolid = _storageMgr.createUserVM(account, vm, template, dc, pod.first(), offering, diskOffering, avoids,size); if ( poolid != 0) { break; } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find storage host in pod " + pod.first().getName() + " (id:" + pod.first().getId() + ") while creating " + vm.toString() + ", checking other pods"); } // if it fails at storage allocation round, reset lastHostId to "release" // the CPU/memory allocation on the candidate host vm.setLastHostId(null); _vmDao.update(vm.getId(), vm); podsToAvoid.add(pod.first().getId()); } if(pod == null){ throw new ResourceAllocationException("Create VM " + ((vm == null) ? vmId : vm.toString()) + " failed. There are no pods with enough CPU/memory"); } if ((vm == null) || (poolid == 0)) { throw new ResourceAllocationException("Create VM " + ((vm == null) ? vmId : vm.toString()) + " failed due to no Storage Pool is available"); } txn.start(); if(vm != null && vm.getName() != null && vm.getDisplayName() != null) { if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("successfully created VM instance : " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("successfully created VM instance : " + vm.getName()); } else { event.setDescription("successfully created VM instance :"+name); } _eventDao.persist(event); _vmDao.updateIf(vm, Event.OperationSucceeded, null); if (s_logger.isDebugEnabled()) { s_logger.debug("vm created " + vmId); } txn.commit(); return _vmDao.findById(vmId); } catch (Throwable th) { s_logger.error("Unable to create vm", th); if (vm != null) { _vmDao.expunge(vmId); } _accountMgr.decrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.decrementResourceCount(account.getId(), ResourceType.volume, numVolumes); String eventDescription = "Failed to create VM: "; if (vm == null) { eventDescription += "new instance"; } else { eventDescription += vm.getName(); if (!vm.getName().equals(vm.getDisplayName())) { eventDescription += " (" + vm.getDisplayName() + ")"; } } if (th instanceof ResourceAllocationException) { throw (ResourceAllocationException)th; } throw new CloudRuntimeException("Unable to create vm", th); } } @Override @DB public boolean destroyVirtualMachine(long userId, long vmId) { UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + vmId); } return true; } if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vmId); } if (!stop(userId, vm, 0)) { s_logger.error("Unable to stop vm so we can't destroy it: " + vmId); return false; } Transaction txn = Transaction.currentTxn(); txn.start(); EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(vm.getAccountId()); event.setType(EventTypes.EVENT_VM_DESTROY); event.setParameters("id="+vm.getId() + "\nvmName=" + vm.getName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId()); if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("Successfully destroyed VM instance : " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("Successfully destroyed VM instance : " + vm.getName()); _eventDao.persist(event); _accountMgr.decrementResourceCount(vm.getAccountId(), ResourceType.user_vm); if (!destroy(vm)) { return false; } cleanNetworkRules(userId, vmId); // Mark the VM's disks as destroyed List<VolumeVO> volumes = _volsDao.findByInstance(vmId); for (VolumeVO volume : volumes) { _storageMgr.destroyVolume(volume); } txn.commit(); return true; } @Override @DB public OperationResponse executeDestroyVM(DestroyVMExecutor executor, VMOperationParam param) { UserVmVO vm = _vmDao.findById(param.getVmId()); State state = vm.getState(); OperationResponse response; String resultDescription = "Success"; if (vm == null || state == State.Destroyed || state == State.Expunging || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + param.getVmId()); } resultDescription = "VM does not exist or already in destroyed state"; response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); return response; } if(state == State.Stopping) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is being stopped: " + param.getVmId()); } resultDescription = "VM is being stopped, please re-try later"; response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); return response; } if (state == State.Running) { if (vm.getHostId() == null) { resultDescription = "VM host is null (invalid VM)"; response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); if(s_logger.isDebugEnabled()) s_logger.debug("Execute asynchronize destroy VM command: " + resultDescription); return response; } if (!_vmDao.updateIf(vm, Event.StopRequested, vm.getHostId())) { resultDescription = "Failed to issue stop command, please re-try later"; response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); if(s_logger.isDebugEnabled()) s_logger.debug("Execute asynchronize destroy VM command:" + resultDescription); return response; } long childEventId = executor.getAsyncJobMgr().getExecutorContext().getManagementServer().saveStartedEvent(param.getUserId(), param.getAccountId(), EventTypes.EVENT_VM_STOP, "stopping vm " + vm.getName(), 0); param.setChildEventId(childEventId); StopCommand cmd = new StopCommand(vm, vm.getInstanceName(), vm.getVnet()); try { long seq = _agentMgr.send(vm.getHostId(), new Command[] {cmd}, true, new VMOperationListener(executor, param, vm, 0)); resultDescription = "Execute asynchronize destroy VM command: sending stop command to agent, seq - " + seq; if(s_logger.isDebugEnabled()) s_logger.debug(resultDescription); response = new OperationResponse(OperationResponse.STATUS_IN_PROGRESS, resultDescription); return response; } catch (AgentUnavailableException e) { resultDescription = "Agent is not available"; response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); return response; } } Transaction txn = Transaction.currentTxn(); txn.start(); _accountMgr.decrementResourceCount(vm.getAccountId(), ResourceType.user_vm); if (!_vmDao.updateIf(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId()) ) { resultDescription = "Unable to destroy the vm because it is not in the correct state"; s_logger.debug(resultDescription + vm.toString()); txn.rollback(); response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); return response; } // Now that the VM is destroyed, clean the network rules associated with it. cleanNetworkRules(param.getUserId(), vm.getId()); // Mark the VM's root disk as destroyed List<VolumeVO> volumes = _volsDao.findByInstanceAndType(vm.getId(), VolumeType.ROOT); for (VolumeVO volume : volumes) { _storageMgr.destroyVolume(volume); } // Mark the VM's data disks as detached volumes = _volsDao.findByInstanceAndType(vm.getId(), VolumeType.DATADISK); for (VolumeVO volume : volumes) { _volsDao.detachVolume(volume.getId()); } txn.commit(); response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription); executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, "success"); return response; } @Override @DB public boolean recoverVirtualMachine(long vmId) throws ResourceAllocationException, InternalErrorException { UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is removed: " + vmId); } return false; } if (vm.getState() != State.Destroyed) { if (s_logger.isDebugEnabled()) { s_logger.debug("vm is not in the right state: " + vmId); } return true; } if (s_logger.isDebugEnabled()) { s_logger.debug("Recovering vm " + vmId); } EventVO event = new EventVO(); event.setUserId(1L); event.setAccountId(vm.getAccountId()); event.setType(EventTypes.EVENT_VM_CREATE); event.setParameters("id="+vm.getId() + "\nvmName=" + vm.getName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId()); Transaction txn = Transaction.currentTxn(); AccountVO account = null; txn.start(); account = _accountDao.lock(vm.getAccountId(), true); //if the account is deleted, throw error if(account.getRemoved()!=null) throw new InternalErrorException("Unable to recover VM as the account is deleted"); // First check that the maximum number of UserVMs for the given accountId will not be exceeded if (_accountMgr.resourceLimitExceeded(account, ResourceType.user_vm)) { ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + account.getAccountName() + " has been exceeded."); rae.setResourceType("vm"); event.setLevel(EventVO.LEVEL_ERROR); if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("Failed to recover VM instance : " + vm.getName()+"("+vm.getDisplayName()+")" + "; the resource limit for account: " + account.getAccountName() + " has been exceeded."); else event.setDescription("Failed to recover VM instance : " + vm.getName() + "; the resource limit for account: " + account.getAccountName() + " has been exceeded."); _eventDao.persist(event); txn.commit(); throw rae; } _haMgr.cancelDestroy(vm, vm.getHostId()); _accountMgr.incrementResourceCount(account.getId(), ResourceType.user_vm); if (!_vmDao.updateIf(vm, Event.RecoveryRequested, null)) { s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId); return false; } // Recover the VM's disks List<VolumeVO> volumes = _volsDao.findByInstanceIdDestroyed(vmId); for (VolumeVO volume : volumes) { _volsDao.recoverVolume(volume.getId()); // Create an event long templateId = -1; long diskOfferingId = -1; if(volume.getTemplateId() !=null){ templateId = volume.getTemplateId(); } diskOfferingId = volume.getDiskOfferingId(); long sizeMB = volume.getSize()/(1024*1024); String eventParams = "id=" + volume.getId() +"\ndoId="+diskOfferingId+"\ntId="+templateId+"\ndcId="+volume.getDataCenterId()+"\nsize="+sizeMB; EventVO volEvent = new EventVO(); volEvent.setAccountId(volume.getAccountId()); volEvent.setUserId(1L); volEvent.setType(EventTypes.EVENT_VOLUME_CREATE); volEvent.setParameters(eventParams); StoragePoolVO pool = _storagePoolDao.findById(volume.getPoolId()); volEvent.setDescription("Created volume: "+ volume.getName() +" with size: " + sizeMB + " MB in pool: " + pool.getName()); _eventDao.persist(volEvent); } _accountMgr.incrementResourceCount(account.getId(), ResourceType.volume, new Long(volumes.size())); event.setLevel(EventVO.LEVEL_INFO); if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("successfully recovered VM instance : " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("successfully recovered VM instance : " + vm.getName()); _eventDao.persist(event); txn.commit(); return true; } @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; ComponentLocator locator = ComponentLocator.getCurrentLocator(); _configDao = locator.getDao(ConfigurationDao.class); if (_configDao == null) { throw new ConfigurationException("Unable to get the configuration dao."); } Map<String, String> configs = _configDao.getConfiguration("AgentManager", params); String value = configs.get("start.retry"); _retry = NumbersUtil.parseInt(value, 2); _instance = configs.get("instance.name"); if (_instance == null) { _instance = "DEFAULT"; } String workers = configs.get("expunge.workers"); int wrks = NumbersUtil.parseInt(workers, 10); String time = configs.get("expunge.interval"); _expungeInterval = NumbersUtil.parseInt(time, 86400); time = configs.get("expunge.delay"); _expungeDelay = NumbersUtil.parseInt(time, _expungeInterval); String maxCap = configs.get("cpu.uservm.cap"); _userVMCap = NumbersUtil.parseInt(maxCap, 0); _executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("UserVm-Scavenger")); _haMgr.registerHandler(Type.User, this); s_logger.info("User VM Manager is configured."); Adapters<IpAddrAllocator> ipAllocators = locator.getAdapters(IpAddrAllocator.class); if (ipAllocators != null && ipAllocators.isSet()) { Enumeration<IpAddrAllocator> it = ipAllocators.enumeration(); _IpAllocator = it.nextElement(); } return true; } @Override public String getName() { return _name; } @Override public boolean start() { _executor.scheduleWithFixedDelay(new ExpungeTask(this), _expungeInterval, _expungeInterval, TimeUnit.SECONDS); return true; } @Override public boolean stop() { _executor.shutdown(); return true; } protected UserVmManagerImpl() { } @Override public Command cleanup(UserVmVO vm, String vmName) { if (vmName != null) { return new StopCommand(vm, vmName, VirtualMachineName.getVnet(vmName)); } else if (vm != null) { return new StopCommand(vm, vm.getVnet()); } else { throw new CloudRuntimeException("Shouldn't even be here!"); } } @Override public void completeStartCommand(UserVmVO vm) { _vmDao.updateIf(vm, Event.AgentReportRunning, vm.getHostId()); _networkGroupManager.handleVmStateTransition(vm, State.Running); } @Override public void completeStopCommand(UserVmVO instance) { completeStopCommand(1L, instance, Event.AgentReportStopped, 0); } @Override @DB public void completeStopCommand(long userId, UserVmVO vm, Event e, long startEventId) { Transaction txn = Transaction.currentTxn(); try { String vnet = vm.getVnet(); vm.setVnet(null); vm.setProxyAssignTime(null); vm.setProxyId(null); txn.start(); if (!_vmDao.updateIf(vm, e, null)) { s_logger.debug("Unable to update "); return; } if ((vm.getDomainRouterId() != null) && _vmDao.listBy(vm.getDomainRouterId(), State.Starting, State.Running).size() == 0) { DomainRouterVO router = _routerDao.findById(vm.getDomainRouterId()); if (router.getState().equals(State.Stopped)) { _dcDao.releaseVnet(vnet, router.getDataCenterId(), router.getAccountId()); } } txn.commit(); _networkGroupManager.handleVmStateTransition(vm, State.Stopped); } catch (Throwable th) { s_logger.error("Error during stop: ", th); throw new CloudRuntimeException("Error during stop: ", th); } EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(vm.getAccountId()); event.setType(EventTypes.EVENT_VM_STOP); event.setState(EventState.Completed); event.setStartId(startEventId); event.setParameters("id="+vm.getId() + "\n" + "vmName=" + vm.getName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId()); if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("Successfully stopped VM instance : " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("Successfully stopped VM instance : " + vm.getName()); _eventDao.persist(event); if (_storageMgr.unshare(vm, null) == null) { s_logger.warn("Unable to set share to false for " + vm.toString()); } } @Override public UserVmVO get(long id) { return getVirtualMachine(id); } public String getRandomPrivateTemplateName() { return UUID.randomUUID().toString(); } @Override public Long convertToId(String vmName) { if (!VirtualMachineName.isValidVmName(vmName, _instance)) { return null; } return VirtualMachineName.getVmId(vmName); } @Override public UserVmVO start(long vmId, long startEventId) throws StorageUnavailableException, ConcurrentOperationException, ExecutionException { return start(1L, vmId, null, null, startEventId); } @Override public boolean stop(UserVmVO vm, long startEventId) { return stop(1L, vm, startEventId); } private boolean stop(long userId, UserVmVO vm, long startEventId) { State state = vm.getState(); if (state == State.Stopped) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already stopped: " + vm.toString()); } return true; } if (state == State.Creating || state == State.Destroyed || state == State.Expunging) { s_logger.warn("Stopped called on " + vm.toString() + " but the state is " + state.toString()); return true; } if (!_vmDao.updateIf(vm, Event.StopRequested, vm.getHostId())) { s_logger.debug("VM is not in a state to stop: " + vm.getState().toString()); return false; } if (vm.getHostId() == null) { s_logger.debug("Host id is null so we can't stop it. How did we get into here?"); return false; } EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(vm.getAccountId()); event.setType(EventTypes.EVENT_VM_STOP); event.setStartId(startEventId); event.setParameters("id="+vm.getId() + "\n" + "vmName=" + vm.getName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId()); StopCommand stop = new StopCommand(vm, vm.getInstanceName(), vm.getVnet()); boolean stopped = false; try { Answer answer = _agentMgr.send(vm.getHostId(), stop); if (!answer.getResult()) { s_logger.warn("Unable to stop vm " + vm.getName() + " due to " + answer.getDetails()); } else { stopped = true; } } catch(AgentUnavailableException e) { s_logger.warn("Agent is not available to stop vm " + vm.toString()); } catch(OperationTimedoutException e) { s_logger.warn("operation timed out " + vm.toString()); } if (stopped) { completeStopCommand(userId, vm, Event.OperationSucceeded, 0); } else { if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("failed to stop VM instance : " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("failed to stop VM instance : " + vm.getName()); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); _vmDao.updateIf(vm, Event.OperationFailed, vm.getHostId()); s_logger.error("Unable to stop vm " + vm.getName()); } return stopped; } @Override @DB public boolean destroy(UserVmVO vm) { if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm.toString()); } if (!_vmDao.updateIf(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm.toString()); return false; } return true; } @Override public HostVO prepareForMigration(UserVmVO vm) throws StorageUnavailableException { long vmId = vm.getId(); boolean mirroredVols = vm.isMirroredVols(); DataCenterVO dc = _dcDao.findById(vm.getDataCenterId()); HostPodVO pod = _podDao.findById(vm.getPodId()); ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId()); VMTemplateVO template = _templateDao.findById(vm.getTemplateId()); List<StoragePoolVO> sps = _storageMgr.getStoragePoolsForVm(vm.getId()); StoragePoolVO sp = sps.get(0); // FIXME List<VolumeVO> vols = _volsDao.findCreatedByInstance(vmId); String [] storageIps = new String[2]; VolumeVO vol = vols.get(0); storageIps[0] = vol.getHostIp(); if (mirroredVols && (vols.size() == 2)) { storageIps[1] = vols.get(1).getHostIp(); } PrepareForMigrationCommand cmd = new PrepareForMigrationCommand(vm.getInstanceName(), vm.getVnet(), storageIps, vols, mirroredVols); HostVO vmHost = null; HashSet<Host> avoid = new HashSet<Host>(); HostVO fromHost = _hostDao.findById(vm.getHostId()); if (fromHost.getHypervisorType() != Hypervisor.Type.KVM && fromHost.getClusterId() == null) { s_logger.debug("The host is not in a cluster"); return null; } avoid.add(fromHost); while ((vmHost = (HostVO)_agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, vm, null, avoid)) != null) { avoid.add(vmHost); if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to migrate router to host " + vmHost.getName()); } if( !_storageMgr.share(vm, vols, vmHost, false) ) { s_logger.warn("Can not share " + vm.toString() + " on host " + vmHost.getId()); throw new StorageUnavailableException(vmHost.getId()); } Answer answer = _agentMgr.easySend(vmHost.getId(), cmd); if (answer != null && answer.getResult()) { return vmHost; } _storageMgr.unshare(vm, vols, vmHost); } return null; } @Override public boolean migrate(UserVmVO vm, HostVO host) throws AgentUnavailableException, OperationTimedoutException { HostVO fromHost = _hostDao.findById(vm.getHostId()); if (!_vmDao.updateIf(vm, Event.MigrationRequested, vm.getHostId())) { s_logger.debug("State for " + vm.toString() + " has changed so migration can not take place."); return false; } boolean isWindows = _guestOSCategoryDao.findById(_guestOSDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); MigrateCommand cmd = new MigrateCommand(vm.getInstanceName(), host.getPrivateIpAddress(), isWindows); Answer answer = _agentMgr.send(fromHost.getId(), cmd); if (answer == null) { return false; } List<VolumeVO> vols = _volsDao.findCreatedByInstance(vm.getId()); if (vols.size() == 0) { return true; } _storageMgr.unshare(vm, vols, fromHost); return true; } @DB public void expunge() { List<UserVmVO> vms = _vmDao.findDestroyedVms(new Date(System.currentTimeMillis() - ((long)_expungeDelay << 10))); s_logger.info("Found " + vms.size() + " vms to expunge."); for (UserVmVO vm : vms) { long vmId = vm.getId(); releaseGuestIpAddress(vm); vm.setGuestNetmask(null); vm.setGuestMacAddress(null); if (!_vmDao.updateIf(vm, Event.ExpungeOperation, null)) { s_logger.info("vm " + vmId + " is skipped because it is no longer in Destroyed state"); continue; } List<VolumeVO> vols = null; try { vols = _volsDao.findByInstanceIdDestroyed(vmId); _storageMgr.destroy(vm, vols); _vmDao.remove(vm.getId()); _networkGroupManager.removeInstanceFromGroups(vm.getId()); removeInstanceFromGroup(vm.getId()); s_logger.debug("vm is destroyed"); } catch (Exception e) { s_logger.info("VM " + vmId +" expunge failed due to " + e.getMessage()); } } List<VolumeVO> destroyedVolumes = _volsDao.findByDetachedDestroyed(); s_logger.info("Found " + destroyedVolumes.size() + " detached volumes to expunge."); _storageMgr.destroy(null, destroyedVolumes); } @Override @DB public boolean completeMigration(UserVmVO vm, HostVO host) throws AgentUnavailableException, OperationTimedoutException { CheckVirtualMachineCommand cvm = new CheckVirtualMachineCommand(vm.getInstanceName()); CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer)_agentMgr.send(host.getId(), cvm); if (!answer.getResult()) { s_logger.debug("Unable to complete migration for " + vm.toString()); _vmDao.updateIf(vm, Event.AgentReportStopped, null); return false; } State state = answer.getState(); if (state == State.Stopped) { s_logger.warn("Unable to complete migration as we can not detect it on " + host.toString()); _vmDao.updateIf(vm, Event.AgentReportStopped, null); return false; } if (s_logger.isDebugEnabled()) { s_logger.debug("Marking port " + answer.getVncPort() + " on " + host.getId()); } Transaction txn = Transaction.currentTxn(); try { txn.start(); _vmDao.updateIf(vm, Event.OperationSucceeded, host.getId()); txn.commit(); return true; } catch(Exception e) { s_logger.warn("Exception during completion of migration process " + vm.toString()); return false; } } @Override public boolean destroyTemplateSnapshot(Long userId, long snapshotId) { boolean success = false; SnapshotVO snapshot = _snapshotDao.findById(Long.valueOf(snapshotId)); if (snapshot != null) { VolumeVO volume = _volsDao.findById(snapshot.getVolumeId()); ManageSnapshotCommand cmd = new ManageSnapshotCommand(ManageSnapshotCommand.DESTROY_SNAPSHOT, snapshotId, snapshot.getPath(), snapshot.getName(), null); Answer answer = null; String basicErrMsg = "Failed to destroy template snapshot: " + snapshot.getName(); Long storagePoolId = volume.getPoolId(); answer = _storageMgr.sendToHostsOnStoragePool(storagePoolId, cmd, basicErrMsg); if ((answer != null) && answer.getResult()) { // delete the snapshot from the database _snapshotDao.expunge(snapshotId); success = true; } if (answer != null) { s_logger.error(answer.getDetails()); } } return success; } @Override @DB public SnapshotVO createTemplateSnapshot(long userId, long volumeId) { SnapshotVO createdSnapshot = null; VolumeVO volume = _volsDao.lock(volumeId, true); Long id = null; // Determine the name for this snapshot String timeString = DateUtil.getDateDisplayString(DateUtil.GMT_TIMEZONE, new Date(), DateUtil.YYYYMMDD_FORMAT); String snapshotName = volume.getName() + "_" + timeString; // Create the Snapshot object and save it so we can return it to the user SnapshotType snapshotType = SnapshotType.TEMPLATE; SnapshotVO snapshot = new SnapshotVO(volume.getAccountId(), volume.getId(), null, snapshotName, (short)snapshotType.ordinal(), snapshotType.name()); snapshot = _snapshotDao.persist(snapshot); id = snapshot.getId(); // Send a ManageSnapshotCommand to the agent ManageSnapshotCommand cmd = new ManageSnapshotCommand(ManageSnapshotCommand.CREATE_SNAPSHOT, id, volume.getPath(), snapshotName, null); String basicErrMsg = "Failed to create snapshot for volume: " + volume.getId(); // This can be sent to a KVM host too. We are only taking snapshots on primary storage, which doesn't require XenServer. // So shouldBeSnapshotCapable is set to false. ManageSnapshotAnswer answer = (ManageSnapshotAnswer) _storageMgr.sendToHostsOnStoragePool(volume.getPoolId(), cmd, basicErrMsg); // Update the snapshot in the database if ((answer != null) && answer.getResult()) { // The snapshot was successfully created Transaction txn = Transaction.currentTxn(); txn.start(); createdSnapshot = _snapshotDao.findById(id); createdSnapshot.setPath(answer.getSnapshotPath()); createdSnapshot.setStatus(Snapshot.Status.CreatedOnPrimary); _snapshotDao.update(id, createdSnapshot); txn.commit(); // Don't Create an event for Template Snapshots for now. } else { if (answer != null) { s_logger.error(answer.getDetails()); } // The snapshot was not successfully created Transaction txn = Transaction.currentTxn(); txn.start(); createdSnapshot = _snapshotDao.findById(id); _snapshotDao.expunge(id); txn.commit(); createdSnapshot = null; } return createdSnapshot; } @Override public void cleanNetworkRules(long userId, long instanceId) { UserVmVO vm = _vmDao.findById(instanceId); String guestIpAddr = vm.getGuestIpAddress(); long accountId = vm.getAccountId(); // clean up any load balancer rules and security group mappings for this VM List<SecurityGroupVMMapVO> securityGroupMappings = _securityGroupVMMapDao.listByInstanceId(vm.getId()); for (SecurityGroupVMMapVO securityGroupMapping : securityGroupMappings) { String ipAddress = securityGroupMapping.getIpAddress(); // find the router from the ipAddress DomainRouterVO router = null; if (vm.getDomainRouterId() != null) router = _routerDao.findById(vm.getDomainRouterId()); else continue; // grab all the firewall rules List<FirewallRuleVO> fwRules = _rulesDao.listForwardingByPubAndPrivIp(true, ipAddress, vm.getGuestIpAddress()); for (FirewallRuleVO fwRule : fwRules) { fwRule.setEnabled(false); } List<FirewallRuleVO> updatedRules = _networkMgr.updateFirewallRules(ipAddress, fwRules, router); // Save and create the event String description; String type = EventTypes.EVENT_NET_RULE_DELETE; String ruleName = "ip forwarding"; String level = EventVO.LEVEL_INFO; if (updatedRules != null) { _securityGroupVMMapDao.remove(securityGroupMapping.getId()); for (FirewallRuleVO updatedRule : updatedRules) { _rulesDao.remove(updatedRule.getId()); description = "deleted " + ruleName + " rule [" + updatedRule.getPublicIpAddress() + ":" + updatedRule.getPublicPort() + "]->[" + updatedRule.getPrivateIpAddress() + ":" + updatedRule.getPrivatePort() + "]" + " " + updatedRule.getProtocol(); EventVO fwRuleEvent = new EventVO(); fwRuleEvent.setUserId(userId); fwRuleEvent.setAccountId(accountId); fwRuleEvent.setType(type); fwRuleEvent.setDescription(description); fwRuleEvent.setLevel(level); _eventDao.persist(fwRuleEvent); } // save off an event for removing the security group EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(vm.getAccountId()); event.setType(EventTypes.EVENT_PORT_FORWARDING_SERVICE_REMOVE); event.setDescription("Successfully removed port forwarding service " + securityGroupMapping.getSecurityGroupId() + " from virtual machine " + vm.getName()); event.setLevel(EventVO.LEVEL_INFO); String params = "sgId="+securityGroupMapping.getSecurityGroupId()+"\nvmId="+vm.getId(); event.setParameters(params); _eventDao.persist(event); } } List<LoadBalancerVMMapVO> loadBalancerMappings = _loadBalancerVMMapDao.listByInstanceId(vm.getId()); for (LoadBalancerVMMapVO loadBalancerMapping : loadBalancerMappings) { List<FirewallRuleVO> lbRules = _rulesDao.listByLoadBalancerId(loadBalancerMapping.getLoadBalancerId()); FirewallRuleVO targetLbRule = null; for (FirewallRuleVO lbRule : lbRules) { if (lbRule.getPrivateIpAddress().equals(guestIpAddr)) { targetLbRule = lbRule; targetLbRule.setEnabled(false); break; } } if (targetLbRule != null) { String ipAddress = targetLbRule.getPublicIpAddress(); DomainRouterVO router = _routerDao.findById(vm.getDomainRouterId()); _networkMgr.updateFirewallRules(ipAddress, lbRules, router); // now that the rule has been disabled, delete it, also remove the mapping from the load balancer mapping table _rulesDao.remove(targetLbRule.getId()); _loadBalancerVMMapDao.remove(loadBalancerMapping.getId()); // save off the event for deleting the LB rule EventVO lbRuleEvent = new EventVO(); lbRuleEvent.setUserId(userId); lbRuleEvent.setAccountId(accountId); lbRuleEvent.setType(EventTypes.EVENT_NET_RULE_DELETE); lbRuleEvent.setDescription("deleted load balancer rule [" + targetLbRule.getPublicIpAddress() + ":" + targetLbRule.getPublicPort() + "]->[" + targetLbRule.getPrivateIpAddress() + ":" + targetLbRule.getPrivatePort() + "]" + " " + targetLbRule.getAlgorithm()); lbRuleEvent.setLevel(EventVO.LEVEL_INFO); _eventDao.persist(lbRuleEvent); } } } public VMTemplateVO createPrivateTemplateRecord(Long userId, long volumeId, String name, String description, long guestOSId, Boolean requiresHvm, Integer bits, Boolean passwordEnabled, boolean isPublic, boolean featured) throws InvalidParameterValueException { VMTemplateVO privateTemplate = null; UserVO user = _userDao.findById(userId); if (user == null) { throw new InvalidParameterValueException("User " + userId + " does not exist"); } VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { throw new InvalidParameterValueException("Volume with ID: " + volumeId + " does not exist"); } int bitsValue = ((bits == null) ? 64 : bits.intValue()); boolean requiresHvmValue = ((requiresHvm == null) ? true : requiresHvm.booleanValue()); boolean passwordEnabledValue = ((passwordEnabled == null) ? false : passwordEnabled.booleanValue()); // if the volume is a root disk, try to find out requiresHvm and bits if possible if (Volume.VolumeType.ROOT.equals(volume.getVolumeType())) { Long instanceId = volume.getInstanceId(); if (instanceId != null) { UserVm vm = _vmDao.findById(instanceId); if (vm != null) { VMTemplateVO origTemplate = _templateDao.findById(vm.getTemplateId()); if (!ImageFormat.ISO.equals(origTemplate.getFormat()) && !ImageFormat.RAW.equals(origTemplate.getFormat())) { bitsValue = origTemplate.getBits(); requiresHvmValue = origTemplate.requiresHvm(); } } } } GuestOSVO guestOS = _guestOSDao.findById(guestOSId); if (guestOS == null) { throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist."); } String uniqueName = Long.valueOf((userId == null)?1:userId).toString() + Long.valueOf(volumeId).toString() + UUID.nameUUIDFromBytes(name.getBytes()).toString(); Long nextTemplateId = _templateDao.getNextInSequence(Long.class, "id"); privateTemplate = new VMTemplateVO(nextTemplateId, uniqueName, name, ImageFormat.RAW, isPublic, featured, null, null, null, requiresHvmValue, bitsValue, volume.getAccountId(), null, description, passwordEnabledValue, guestOS.getId(), true); return _templateDao.persist(privateTemplate); } @Override @DB public VMTemplateVO createPrivateTemplate(VMTemplateVO template, Long userId, long snapshotId, String name, String description) { VMTemplateVO privateTemplate = null; long templateId = template.getId(); SnapshotVO snapshot = _snapshotDao.findById(snapshotId); if (snapshot != null) { Long volumeId = snapshot.getVolumeId(); VolumeVO volume = _volsDao.findById(volumeId); StringBuilder userFolder = new StringBuilder(); Formatter userFolderFormat = new Formatter(userFolder); userFolderFormat.format("u%06d", snapshot.getAccountId()); String uniqueName = getRandomPrivateTemplateName(); long zoneId = volume.getDataCenterId(); HostVO secondaryStorageHost = _storageMgr.getSecondaryStorageHost(zoneId); String secondaryStorageURL = _storageMgr.getSecondaryStorageURL(zoneId); if (secondaryStorageHost == null || secondaryStorageURL == null) { s_logger.warn("Did not find the secondary storage URL in the database."); return null; } Command cmd = null; String backupSnapshotUUID = snapshot.getBackupSnapshotId(); if (backupSnapshotUUID != null) { // We are creating a private template from a snapshot which has been backed up to secondary storage. Long dcId = volume.getDataCenterId(); Long accountId = volume.getAccountId(); String origTemplateInstallPath = null; if (ImageFormat.ISO != _snapshotMgr.getImageFormat(volumeId)) { Long origTemplateId = volume.getTemplateId(); VMTemplateHostVO vmTemplateHostVO = _templateHostDao.findByHostTemplate(secondaryStorageHost.getId(), origTemplateId); origTemplateInstallPath = vmTemplateHostVO.getInstallPath(); } cmd = new CreatePrivateTemplateFromSnapshotCommand(_storageMgr.getPrimaryStorageNameLabel(volume), secondaryStorageURL, dcId, accountId, volumeId, backupSnapshotUUID, snapshot.getName(), origTemplateInstallPath, templateId, name); } else { cmd = new CreatePrivateTemplateCommand(secondaryStorageURL, templateId, volume.getAccountId(), name, uniqueName, _storageMgr.getPrimaryStorageNameLabel(volume), snapshot.getPath(), snapshot.getName(), userFolder.toString()); } // FIXME: before sending the command, check if there's enough capacity on the storage server to create the template String basicErrMsg = "Failed to create template from snapshot: " + snapshot.getName(); // This can be sent to a KVM host too. CreatePrivateTemplateAnswer answer = (CreatePrivateTemplateAnswer) _storageMgr.sendToHostsOnStoragePool(volume.getPoolId(), cmd, basicErrMsg); if ((answer != null) && answer.getResult()) { privateTemplate = _templateDao.findById(templateId); Long origTemplateId = volume.getTemplateId(); VMTemplateVO origTemplate = null; if (origTemplateId != null) { origTemplate = _templateDao.findById(origTemplateId); } if ((origTemplate != null) && !Storage.ImageFormat.ISO.equals(origTemplate.getFormat())) { // We made a template from a root volume that was cloned from a template privateTemplate.setFileSystem(origTemplate.getFileSystem()); privateTemplate.setRequiresHvm(origTemplate.requiresHvm()); privateTemplate.setBits(origTemplate.getBits()); } else { // We made a template from a root volume that was not cloned from a template, or a data volume privateTemplate.setFileSystem(Storage.FileSystem.Unknown); privateTemplate.setRequiresHvm(true); privateTemplate.setBits(64); } String answerUniqueName = answer.getUniqueName(); if (answerUniqueName != null) { privateTemplate.setUniqueName(answerUniqueName); } else { privateTemplate.setUniqueName(uniqueName); } ImageFormat format = answer.getImageFormat(); if (format != null) { privateTemplate.setFormat(format); } else { // This never occurs. // Specify RAW format makes it unusable for snapshots. privateTemplate.setFormat(ImageFormat.RAW); } _templateDao.update(templateId, privateTemplate); // add template zone ref for this template _templateDao.addTemplateToZone(privateTemplate, zoneId); VMTemplateHostVO templateHostVO = new VMTemplateHostVO(secondaryStorageHost.getId(), templateId); templateHostVO.setDownloadPercent(100); templateHostVO.setDownloadState(Status.DOWNLOADED); templateHostVO.setInstallPath(answer.getPath()); templateHostVO.setLastUpdated(new Date()); templateHostVO.setSize(answer.getVirtualSize()); _templateHostDao.persist(templateHostVO); // Increment the number of templates _accountMgr.incrementResourceCount(volume.getAccountId(), ResourceType.template); } else { // Remove the template record _templateDao.remove(templateId); } } return privateTemplate; } @DB @Override public UserVmVO createDirectlyAttachedVM(Long vmId, long userId, AccountVO account, DataCenterVO dc, ServiceOfferingVO offering, VMTemplateVO template, DiskOfferingVO diskOffering, String displayName, String userData, List<StoragePoolVO> a, List<NetworkGroupVO> networkGroups, long startEventId, long size) throws InternalErrorException, ResourceAllocationException { long accountId = account.getId(); long dataCenterId = dc.getId(); long serviceOfferingId = offering.getId(); long templateId = -1; if (template != null) templateId = template.getId(); if (s_logger.isDebugEnabled()) { s_logger.debug("Creating directly attached vm for account id=" + account.getId() + ", name="+ account.getAccountName() + "; dc=" + dc.getName() + "; offering=" + offering.getId() + "; diskOffering=" + ((diskOffering != null) ? diskOffering.getName() : "none") + "; template=" + templateId); } // Determine the Guest OS Id long guestOSId; if (template != null) { guestOSId = template.getGuestOSId(); } else { throw new InternalErrorException("No template or ISO was specified for the VM."); } Transaction txn = Transaction.currentTxn(); txn.start(); account = _accountDao.lock(accountId, true); if (account == null) { throw new InternalErrorException("Unable to lock up the account: " + accountId); } // First check that the maximum number of UserVMs for the given accountId will not be exceeded if (_accountMgr.resourceLimitExceeded(account, ResourceType.user_vm)) { ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + account.getAccountName() + " has been exceeded."); rae.setResourceType("vm"); throw rae; } _accountMgr.incrementResourceCount(account.getId(), ResourceType.user_vm); boolean isIso = Storage.ImageFormat.ISO.equals(template.getFormat()); long numVolumes = (isIso || (diskOffering == null)) ? 1 : 2; _accountMgr.incrementResourceCount(account.getId(), ResourceType.volume, numVolumes); txn.commit(); try { UserVmVO vm = null; final String name = VirtualMachineName.getVmName(vmId, accountId, _instance); final String[] macAddresses = _dcDao.getNextAvailableMacAddressPair(dc.getId()); long routerId = -1; long poolId = 0; Pair<HostPodVO, Long> pod = null; DomainRouterVO router = null; Set<Long> avoids = new HashSet<Long>(); VlanVO guestVlan = null; List<VlanVO> vlansForAccount = _vlanDao.listVlansForAccountByType(dc.getId(), account.getId(), VlanType.DirectAttached); List<VlanVO> vlansForPod = null; List<VlanVO> zoneWideVlans = null; boolean forAccount = false; boolean forZone = false; if (vlansForAccount.size() > 0) { forAccount = true; guestVlan = vlansForAccount.get(0);//FIXME: iterate over all vlans } else { //list zone wide vlans that are direct attached and tagged //if exists pick random one //set forZone = true //note the dao method below does a NEQ on vlan id, hence passing untagged zoneWideVlans = _vlanDao.searchForZoneWideVlans(dc.getId(),VlanType.DirectAttached.toString(),"untagged"); if(zoneWideVlans!=null && zoneWideVlans.size()>0){ forZone = true; guestVlan = zoneWideVlans.get(0);//FIXME: iterate over all vlans } } while ((pod = _agentMgr.findPod(template, offering, dc, account.getId(), avoids)) != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Attempting to create direct attached vm in pod " + pod.first().getName()); } if (!forAccount && !forZone) { vlansForPod = _vlanDao.listVlansForPodByType(pod.first().getId(), VlanType.DirectAttached); if (vlansForPod.size() < 1) { avoids.add(pod.first().getId()); if (s_logger.isDebugEnabled()) { s_logger.debug("No direct attached vlans available in pod " + pod.first().getName() + " (id:" + pod.first().getId() + "), checking other pods"); } continue; } guestVlan = vlansForPod.get(0);//FIXME: iterate over all vlans } List<DomainRouterVO> rtrs = _routerDao.listByVlanDbId(guestVlan.getId()); assert rtrs.size() < 2 : "How did we get more than one router per vlan?"; if (rtrs.size() > 0) { router = rtrs.get(0); routerId = router.getId(); } else if (rtrs.size() == 0) { router = _networkMgr.createDhcpServerForDirectlyAttachedGuests(userId, accountId, dc, pod.first(), pod.second(), guestVlan); if (router == null) { avoids.add(pod.first().getId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to create DHCP server in vlan " + guestVlan.getVlanId() + ", pod=" + pod.first().getName() + " (podid:" + pod.first().getId() + "), checking other pods"); } continue; } routerId = router.getId(); } String guestIp = null; if(forAccount) { for(VlanVO vlanForAcc : vlansForAccount) { guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForAcc.getId(), false); if(guestIp!=null) break; //got an ip } } else if(!forAccount && !forZone) { //i.e. for pod for(VlanVO vlanForPod : vlansForPod) { guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForPod.getId(), false); if(guestIp!=null) break;//got an ip } } else { //for zone for(VlanVO vlanForZone : zoneWideVlans) { guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForZone.getId(), false); if(guestIp!=null) break;//found an ip } } if (guestIp == null) { s_logger.debug("No guest IP available in pod id=" + pod.first().getId()); avoids.add(pod.first().getId()); continue; } s_logger.debug("Acquired a guest IP, ip=" + guestIp); String guestMacAddress = macAddresses[0]; String externalMacAddress = macAddresses[1]; Long externalVlanDbId = null; vm = new UserVmVO(vmId, name, templateId, guestOSId, accountId, account.getDomainId(), serviceOfferingId, guestMacAddress, guestIp, guestVlan.getVlanNetmask(), null, externalMacAddress, externalVlanDbId, routerId, pod.first().getId(), dataCenterId, offering.getOfferHA(), displayName, userData); if (diskOffering != null) { vm.setMirroredVols(diskOffering.isMirrored()); } vm.setLastHostId(pod.second()); vm = _vmDao.persist(vm); boolean addedToGroups = _networkGroupManager.addInstanceToGroups(vmId, networkGroups); if (!addedToGroups) { s_logger.warn("Not all specified network groups can be found"); _vmDao.expunge(vm.getId()); throw new InvalidParameterValueException("Not all specified network groups can be found"); } vm = _vmDao.findById(vmId); try { poolId = _storageMgr.createUserVM(account, vm, template, dc, pod.first(), offering, diskOffering, a,size); } catch (CloudRuntimeException e) { _vmDao.expunge(vmId); _ipAddressDao.unassignIpAddress(guestIp); s_logger.debug("Released a guest ip address because we could not find storage: ip=" + guestIp); guestIp = null; if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find storage host in pod " + pod.first().getName() + " (id:" + pod.first().getId() + "), checking other pods"); } avoids.add(pod.first().getId()); continue; // didn't find a storage host in pod, go to the next pod } EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(accountId); event.setType(EventTypes.EVENT_NET_IP_ASSIGN); event.setParameters("guestIPaddress=" + guestIp + "\nvmName=" + vm.getName() + "\ndcId=" + vm.getDataCenterId()); event.setDescription("acquired a public ip: " + guestIp); _eventDao.persist(event); break; // if we got here, we found a host and can stop searching the pods } if (poolId == 0) { if(vm != null && vm.getName()!=null && vm.getDisplayName() != null) { if(!vm.getName().equals(vm.getDisplayName())) s_logger.debug("failed to create VM instance : " + name+"("+vm.getInstanceName()+")"); else s_logger.debug("failed to create VM instance : " + name); } else { s_logger.debug("failed to create VM instance : " + name); throw new InternalErrorException("We could not find a suitable pool for creating this directly attached vm"); } _accountMgr.decrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.decrementResourceCount(account.getId(), ResourceType.volume, numVolumes); return null; } txn.start(); EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(accountId); event.setType(EventTypes.EVENT_VM_CREATE); event.setStartId(startEventId); event.setState(EventState.Completed); String diskOfferingIdentifier = (diskOffering != null) ? String.valueOf(diskOffering.getId()) : "-1"; String eventParams = "id=" + vm.getId() + "\nvmName=" + vm.getName() + "\nsoId=" + vm.getServiceOfferingId() + "\ndoId=" + diskOfferingIdentifier + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId(); event.setParameters(eventParams); if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("successfully created VM instance : " + vm.getName()+"("+vm.getInstanceName()+")"); else event.setDescription("successfully created VM instance : " + vm.getName()); _eventDao.persist(event); _vmDao.updateIf(vm, Event.OperationSucceeded, null); if (s_logger.isDebugEnabled()) { s_logger.debug("vm created " + vmId); } txn.commit(); return _vmDao.findById(vmId); } catch (Throwable th) { _accountMgr.decrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.decrementResourceCount(account.getId(), ResourceType.volume, numVolumes); s_logger.error("Unable to create vm", th); throw new CloudRuntimeException("Unable to create vm: "+th.getMessage(), th); } } @DB @Override public UserVmVO createDirectlyAttachedVMExternal(Long vmId, long userId, AccountVO account, DataCenterVO dc, ServiceOfferingVO offering, VMTemplateVO template, DiskOfferingVO diskOffering, String displayName, String userData, List<StoragePoolVO> a, List<NetworkGroupVO> networkGroups, long startEventId, long size) throws InternalErrorException, ResourceAllocationException { long accountId = account.getId(); long dataCenterId = dc.getId(); long serviceOfferingId = offering.getId(); long templateId = -1; if (template != null) templateId = template.getId(); if (s_logger.isDebugEnabled()) { s_logger.debug("Creating directly attached vm for account id=" + account.getId() + ", name="+ account.getAccountName() + "; dc=" + dc.getName() + "; offering=" + offering.getId() + "; diskOffering=" + ((diskOffering != null) ? diskOffering.getName() : "none") + "; template=" + templateId); } // Determine the Guest OS Id long guestOSId; if (template != null) { guestOSId = template.getGuestOSId(); } else { throw new InternalErrorException("No template or ISO was specified for the VM."); } boolean isIso = Storage.ImageFormat.ISO.equals(template.getFormat()); long numVolumes = (isIso || (diskOffering == null)) ? 1 : 2; Transaction txn = Transaction.currentTxn(); try { UserVmVO vm = null; txn.start(); account = _accountDao.lock(accountId, true); if (account == null) { throw new InternalErrorException("Unable to lock up the account: " + accountId); } // First check that the maximum number of UserVMs for the given accountId will not be exceeded if (_accountMgr.resourceLimitExceeded(account, ResourceType.user_vm)) { ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + account.getAccountName() + " has been exceeded."); rae.setResourceType("vm"); throw rae; } final String name = VirtualMachineName.getVmName(vmId, accountId, _instance); final String[] macAddresses = _dcDao.getNextAvailableMacAddressPair(dc.getId()); Long routerId = null; long poolId = 0; Pair<HostPodVO, Long> pod = null; Set<Long> avoids = new HashSet<Long>(); while ((pod = _agentMgr.findPod(template, offering, dc, account.getId(), avoids)) != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Attempting to create direct attached vm in pod " + pod.first().getName()); } String guestMacAddress = macAddresses[0]; String externalMacAddress = macAddresses[1]; IpAddrAllocator.IpAddr publicIp = _IpAllocator.getPrivateIpAddress(guestMacAddress, dc.getId(), pod.first().getId()); String publicIpAddr = null; String publicIpNetMask = null; if (publicIp == null) { s_logger.debug("Failed to get public ip address from external dhcp server"); } else { publicIpAddr = publicIp.ipaddr; publicIpNetMask = publicIp.netMask; } vm = new UserVmVO(vmId, name, templateId, guestOSId, accountId, account.getDomainId(), serviceOfferingId, guestMacAddress, publicIpAddr, publicIpNetMask, null, externalMacAddress, null, routerId, pod.first().getId(), dataCenterId, offering.getOfferHA(), displayName, userData); if (diskOffering != null) { vm.setMirroredVols(diskOffering.isMirrored()); } vm.setLastHostId(pod.second()); _vmDao.persist(vm); _networkGroupManager.addInstanceToGroups(vmId, networkGroups); _accountMgr.incrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.incrementResourceCount(account.getId(), ResourceType.volume, numVolumes); txn.commit(); vm = _vmDao.findById(vmId); try { poolId = _storageMgr.createUserVM(account, vm, template, dc, pod.first(), offering, diskOffering,a,size); } catch (CloudRuntimeException e) { _vmDao.expunge(vmId); _accountMgr.decrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.decrementResourceCount(account.getId(), ResourceType.volume, numVolumes); if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find storage host in pod " + pod.first().getName() + " (id:" + pod.first().getId() + "), checking other pods"); } avoids.add(pod.first().getId()); continue; // didn't find a storage host in pod, go to the next pod } break; // if we got here, we found a host and can stop searching the pods } if (poolId == 0) { if(vm != null && vm.getName()!=null && vm.getDisplayName() != null) { if(!vm.getName().equals(vm.getDisplayName())) s_logger.debug("failed to create VM instance : " + name+"("+vm.getDisplayName()+")"); else s_logger.debug("failed to create VM instance : " + name); } else { s_logger.debug("failed to create VM instance : " + name); } _accountMgr.decrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.decrementResourceCount(account.getId(), ResourceType.volume, numVolumes); txn.commit(); return null; } txn.start(); EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(accountId); event.setType(EventTypes.EVENT_VM_CREATE); event.setStartId(startEventId); event.setState(EventState.Completed); String diskOfferingIdentifier = (diskOffering != null) ? String.valueOf(diskOffering.getId()) : "-1"; String eventParams = "id=" + vm.getId() + "\nvmName=" + vm.getName() + "\nsoId=" + vm.getServiceOfferingId() + "\ndoId=" + diskOfferingIdentifier + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId(); event.setParameters(eventParams); if(!vm.getName().equals(vm.getDisplayName())) event.setDescription("successfully created VM instance : " + vm.getName()+"("+vm.getDisplayName()+")"); else event.setDescription("successfully created VM instance : " + vm.getName()); _eventDao.persist(event); _vmDao.updateIf(vm, Event.OperationSucceeded, null); if (s_logger.isDebugEnabled()) { s_logger.debug("vm created " + vmId); } txn.commit(); return _vmDao.findById(vmId); } catch (ResourceAllocationException rae) { _accountMgr.decrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.decrementResourceCount(account.getId(), ResourceType.volume, numVolumes); if (s_logger.isInfoEnabled()) { s_logger.info("Failed to create VM for account " + accountId + " due to maximum number of virtual machines exceeded."); } throw rae; } catch (Throwable th) { _accountMgr.decrementResourceCount(account.getId(), ResourceType.user_vm); _accountMgr.decrementResourceCount(account.getId(), ResourceType.volume, numVolumes); s_logger.error("Unable to create vm", th); throw new CloudRuntimeException("Unable to create vm", th); } } protected class ExpungeTask implements Runnable { UserVmManagerImpl _vmMgr; public ExpungeTask(UserVmManagerImpl vmMgr) { _vmMgr = vmMgr; } public void run() { GlobalLock scanLock = GlobalLock.getInternLock("UserVMExpunge"); try { if(scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { try { reallyRun(); } finally { scanLock.unlock(); } } } finally { scanLock.releaseRef(); } } public void reallyRun() { try { s_logger.info("UserVm Expunge Thread is running."); _vmMgr.expunge(); } catch (Exception e) { s_logger.error("Caught the following Exception", e); } } } @DB @Override public InstanceGroupVO createVmGroup(String name, Long accountId) { final Transaction txn = Transaction.currentTxn(); AccountVO account = null; txn.start(); try { account = _accountDao.acquire(accountId); //to ensure duplicate vm group names are not created. if (account == null) { s_logger.warn("Failed to acquire lock on account"); return null; } InstanceGroupVO group = _vmGroupDao.findByAccountAndName(accountId, name); if (group == null){ group = new InstanceGroupVO(name, accountId); group = _vmGroupDao.persist(group); } return group; } finally { if (account != null) { _accountDao.release(accountId); } txn.commit(); } } @Override public boolean deleteVmGroup(long groupId){ //delete all the mappings from group_vm_map table List<InstanceGroupVMMapVO> groupVmMaps = _groupVMMapDao.listByGroupId(groupId); for (InstanceGroupVMMapVO groupMap : groupVmMaps) { SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao.createSearchCriteria(); sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId()); _groupVMMapDao.expunge(sc); } if (_vmGroupDao.remove(groupId)) { return true; } else { return false; } } @Override @DB public boolean addInstanceToGroup(long userVmId, String groupName) { UserVmVO vm = _vmDao.findById(userVmId); InstanceGroupVO group = _vmGroupDao.findByAccountAndName(vm.getAccountId(), groupName); //Create vm group if the group doesn't exist for this account if (group == null) { group = createVmGroup(groupName, vm.getAccountId()); } if (group != null) { final Transaction txn = Transaction.currentTxn(); txn.start(); UserVm userVm = _vmDao.acquire(userVmId); if (userVm == null) { s_logger.warn("Failed to acquire lock on user vm id=" + userVmId); } try { //don't let the group be deleted when we are assigning vm to it. InstanceGroupVO ngrpLock = _vmGroupDao.lock(group.getId(), false); if (ngrpLock == null) { s_logger.warn("Failed to acquire lock on vm group id=" + group.getId() + " name=" + group.getName()); txn.rollback(); return false; } //Currently don't allow to assign a vm to more than one group if (_groupVMMapDao.listByInstanceId(userVmId) != null) { //Delete all mappings from group_vm_map table List<InstanceGroupVMMapVO> groupVmMaps = _groupVMMapDao.listByInstanceId(userVmId); for (InstanceGroupVMMapVO groupMap : groupVmMaps) { SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao.createSearchCriteria(); sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId()); _groupVMMapDao.expunge(sc); } } InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(group.getId(), userVmId); _groupVMMapDao.persist(groupVmMapVO); txn.commit(); return true; } finally { if (userVm != null) { _vmDao.release(userVmId); } } } return false; } @Override public InstanceGroupVO getGroupForVm(long vmId) { //TODO - in future releases vm can be assigned to multiple groups; but currently return just one group per vm try { List<InstanceGroupVMMapVO> groupsToVmMap = _groupVMMapDao.listByInstanceId(vmId); if(groupsToVmMap != null && groupsToVmMap.size() != 0){ InstanceGroupVO group = _vmGroupDao.findById(groupsToVmMap.get(0).getGroupId()); return group; } else { return null; } } catch (Exception e){ s_logger.warn("Error trying to get group for a vm: "+e); return null; } } public void removeInstanceFromGroup(long vmId) { try { List<InstanceGroupVMMapVO> groupVmMaps = _groupVMMapDao.listByInstanceId(vmId); for (InstanceGroupVMMapVO groupMap : groupVmMaps) { SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao.createSearchCriteria(); sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId()); _groupVMMapDao.expunge(sc); } } catch (Exception e){ s_logger.warn("Error trying to remove vm from group: "+e); } } }
package org.wyona.yanel.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.api.attributes.ModifiableV1; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.MapFactory; import org.wyona.yanel.util.ResourceAttributeHelper; import org.apache.log4j.Category; public class YanelServlet extends HttpServlet { private static Category log = Category.getInstance(YanelServlet.class); private ServletConfig config; ResourceTypeRegistry rtr; public void init(ServletConfig config) { this.config = config; rtr = new ResourceTypeRegistry(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(!authorize(request, response)) { // HTTP Authorization/Authentication // TODO: Phoenix has not HTTP BASIC or DIGEST implemented yet! /* response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\""); response.sendError(response.SC_UNAUTHORIZED); */ // Custom Authorization/Authentication // TODO: Check if this is a neutron request or just a common GET request StringBuffer sb = new StringBuffer(""); String neutronVersions = request.getHeader("Neutron"); if (neutronVersions != null) { sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authorization denied: " + request.getRequestURL() + "?" + request.getQueryString() + "</message>"); sb.append("<authentication>"); sb.append("<login url=\"http://...?action=logout\">"); sb.append("<form>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); sb.append("<logout url=\"http://...?action=login\"/>"); sb.append("</authentication>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); } else { sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Authorization denied: " + request.getRequestURL() + "?" + request.getQueryString() + "</p>"); sb.append("</body>"); sb.append("</html>"); } PrintWriter w = response.getWriter(); w.print(sb); return; } View view = null; StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); String servletContextRealPath = config.getServletContext().getRealPath("/"); sb.append("<yanel servlet-context-real-path=\""+servletContextRealPath+"\" xmlns=\"http: sb.append("<request uri=\""+request.getRequestURI()+"\" servlet-path=\""+request.getServletPath()+"\"/>"); HttpSession session = request.getSession(true); sb.append("<session id=\""+session.getId()+"\">"); Enumeration enum = session.getAttributeNames(); if (!enum.hasMoreElements()) { sb.append("<no-attributes/>"); } while (enum.hasMoreElements()) { String name = (String)enum.nextElement(); String value = session.getAttribute(name).toString(); sb.append("<attribute name=\"" + name + "\">" + value + "</attribute>"); } sb.append("</session>"); MapFactory mf = MapFactory.newInstance(); Map map = mf.newMap(); String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath())); if (rti != null) { ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti); sb.append("<resource-type-identifier namespace=\"" + rtd.getResourceTypeNamespace() + "\" local-name=\"" + rtd.getResourceTypeLocalName() + "\"/>"); try { Resource res = rtr.newResource(rti); res.setRTD(rtd); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { sb.append("<resource>View Descriptors: " + ((ViewableV1) res).getViewDescriptors() + "</resource>"); String viewId = null; view = ((ViewableV1) res).getView(request, viewId); } else { sb.append("<resource>" + res.getClass().getName() + " is not viewable!</resource>"); } } catch(Exception e) { sb.append("<exception>" + e + "</exception>"); log.error(e.getMessage(), e); } } else { sb.append("<no-resource-type-identifier-found servlet-path=\""+request.getServletPath()+"\"/>"); } sb.append("</yanel>"); String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("checkout")) { log.error("DEBUG: Checkout data ..."); // TODO: Implement checkout ... // acquireLock(); } if (view != null) { response.setContentType(view.getMimeType()); java.io.InputStream is = view.getInputStream(); byte buffer[] = new byte[8192]; int bytesRead; bytesRead = is.read(buffer); if (bytesRead == -1) { response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); writer.print("No content!"); return; } java.io.OutputStream os = response.getOutputStream(); os.write(buffer, 0, bytesRead); while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } return; } else { response.setContentType("application/xml"); PrintWriter writer = response.getWriter(); writer.print(sb); return; } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(!authorize(request, response)) { // HTTP Authorization/Authentication response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\""); response.sendError(response.SC_UNAUTHORIZED); // Custom Authorization/Authentication return; } String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.error("DEBUG: Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.error("DEBUG: Checkin data ..."); save(request, response); // TODO: Implement checkin ... // releaseLock(); return; } else { log.warn("No parameter yanel.resource.usecase!"); PrintWriter writer = response.getWriter(); response.setContentType("application/xhtml+xml"); writer.println("<html>"); writer.println("<body>"); writer.println("No parameter yanel.resource.usecase!"); writer.println("</body>"); writer.println("</html>"); } } /** * TODO: Reuse code doPost resp. share code with doPut */ public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(!authorize(request, response)) { // HTTP Authorization/Authentication response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\""); response.sendError(response.SC_UNAUTHORIZED); // Custom Authorization/Authentication return; } String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.error("DEBUG: Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.error("DEBUG: Checkin data ..."); save(request, response); // TODO: Implement checkin ... // releaseLock(); return; } else { log.warn("No parameter yanel.resource.usecase!"); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>No parameter yanel.resource.usecase!</p>"); sb.append("</body>"); sb.append("</html>"); response.setContentType("application/xhtml+xml"); PrintWriter writer = response.getWriter(); writer.print(sb); } } private Resource getResource(HttpServletRequest request) { MapFactory mf = MapFactory.newInstance(); Map map = mf.newMap(); String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath())); if (rti != null) { ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti); try { Resource res = rtr.newResource(rti); res.setRTD(rtd); return res; } catch(Exception e) { log.error(e.getMessage(), e); return null; } } else { log.error("<no-resource-type-identifier-found servlet-path=\""+request.getServletPath()+"\"/>"); return null; } } private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuffer sb = new StringBuffer(); log.error("DEBUG: Save data ..."); java.io.InputStream in = request.getInputStream(); java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) byte[] memBuffer = baos.toByteArray(); // TODO: Check on well-formedness ... javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); parser.parse(new java.io.ByteArrayInputStream(memBuffer)); //org.w3c.dom.Document document = parser.parse(new ByteArrayInputStream(memBuffer)); } catch (org.xml.sax.SAXException e) { log.warn("Data is not well-formed: "+e.getMessage()); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Data is not well-formed: "+e.getMessage()+"</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } catch (Exception e) { log.error(e.getMessage()); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>"+e.getMessage()+"</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } log.error("INFO: Data seems to be well-formed :-)"); /* if (bytesRead == -1) { response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); writer.print("No content!"); return; } */ /* java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); out.write(buffer, 0, bytesRead); while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } log.error("DEBUG: Received Data: " + out.toString()); */ Resource res = getResource(request); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { String contentType = request.getContentType(); log.error("DEBUG: Content-Type: " + contentType); // TODO: Compare mime-type from response with mime-type of resource //if (contentType.equals("text/xml")) { ... } byte[] buffer = new byte[8192]; int bytesRead; java.io.ByteArrayInputStream memIn = new java.io.ByteArrayInputStream(memBuffer); java.io.OutputStream out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath())); while ((bytesRead = memIn.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Data has been saved ...</p>"); sb.append("</body>"); sb.append("</html>"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("application/xhtml+xml"); log.error("INFO: Data has been saved ..."); } else { log.warn(res.getClass().getName() + " is not modifiable!"); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<resource>" + res.getClass().getName() + " is not modifiable!</resource>"); sb.append("</body>"); sb.append("</html>"); response.setContentType("application/xhtml+xml"); } } /** * Authorize request * TODO: Replace hardcoded policies ... */ private boolean authorize(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.error("DEBUG: Save data ..."); return true; } else if (value != null && value.equals("checkin")) { log.error("DEBUG: Checkin data ..."); } else if (value != null && value.equals("checkout")) { log.error("DEBUG: Checkout data ..."); } else { log.debug("No parameter yanel.resource.usecase!"); return true; } // HTTP Authorization String authorization = request.getHeader("Authorization"); log.error("DEBUG: Authorization Header: " + authorization); if (authorization != null && authorization.toUpperCase().startsWith("BASIC")) { // Get encoded user and password, comes after "BASIC " String userpassEncoded = authorization.substring(6); // Decode it, using any base 64 decoder sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); log.error("DEBUG: userpassDecoded: " + userpassDecoded); if (userpassDecoded.equals("lenya:levi")) { return true; } log.warn("Authorization denied: " + request.getRequestURL() + "?" + request.getQueryString()); return false; } // Custom Authorization log.warn("Authorization denied: " + request.getRequestURL() + "?" + request.getQueryString()); return false; } }
package mm.da; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import java.sql.Statement; import java.time.LocalDate; import mm.model.AcademicInstitute; import mm.model.Meeting; import mm.model.Meeting.meetingStatus; import mm.model.Meeting.meetingType; import mm.model.Mentee; import mm.model.Mentor; import mm.model.Pair; import mm.model.Session; import mm.model.TsofenT; import mm.model.User; import mm.model.User.userType; import mm.model.WorkPlace; public class DataAccess implements DataInterface { private Connection c; final String selectLogin = "Select * From users where email=?"; final String selectLogin1 = "Select * From mentors where id=?"; final String selectLogin2 = "Select * From mentees where id=?"; final String selectByType = "Select * from users where type=?"; final String selectByID = "Select * From users where id=?"; final String selectMentor = "Select * from users RIGHT JOIN mentors ON users.id = mentors.id"; final String selectMentee = "Select * from users RIGHT JOIN mentees ON users.id = mentees.id"; final String sessionId = "Select * From sessions where userId=?"; //to check final String getMenteeofPair = "Select * From pairs where menteeId=?, activeStatus=?"; final String getMentorofPair = "Select * From pairs where mentorId=?, activeStatus=?"; final String updateUserBase = "UPDATE users SET firstName=?, lastName=?, phoneNumber=?, gender=?, address=?, notes=?, profilePicture=?, active=? WHERE id=?"; final String updateUserMentor = "UPDATE mentors SET experience=?, role=?, company=?, volunteering=?, workHistory=? WHERE id=?"; final String updateUserMentee = "UPDATE mentees SET remainingSemesters=?, graduationStatus=?, academicInstitute=?, average=?, academicDicipline1=?, academicDicipline2=?, signedEULA=?, resume=?, gradeSheet=? WHERE id=?"; final String deactivateUser = "UPDATE users SET active=0 WHERE id=?"; final String addBaseUser = "INSERT INTO users (type, firstName, lastName, email, phoneNumber, password, gender, address, notes, profilePicture, active) VALUES (?,?,?,?,?,?,?,?,?,?,?)"; final String addMenteeUser = "INSERT INTO mentees (id, remainingSemesters, graduationStatus, academicInstitute, average, academicDicipline1, academicDicipline2, signedEULA, resume, gradeSheet) VALUES (?,?,?,?,?,?,?,?,?,?)"; final String addMentorUser = "INSERT INTO mentors (id, experience, role, company, volunteering, workHistory) VALUES (?,?,?,?,?,?)"; final String insertPair = "INSERT INTO pairs (mentorId, menteeId, activeStatus, startDate) VALUES (?,?,?,?)"; final String selectAllPairs = "Select * from pairs"; final String selectPairId = "Select * From pairs Where pairId=?"; final String updateActiveStatus = "UPDATE pairs SET activeStatus=0 WHERE pairId=?"; final String selectMeeting = "Select * From activities where mentorId=? "; final String selectMeeting2 = "Select * From activites where menteeId=? "; final String addUserSession = "INSERT INTO session (userId, token, creationDate, expirationDate, deviceId) VALUES (?,?,?,?,?)"; final String selectMeetingById = "Select * From activities where activityId=?"; final String selectMeetingByPair = "Select * From activities where pairId=?"; final String addMeeting = "INSERT INTO activities (pairId,mentorId,menteeId,note,status,menteeReport,mentorReport,menteePrivateReport,mentorPrivateReport,meetingType,subject,location,date,startingTime,endingTime,mentorComplete,menteeComplete)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; final String getAllMenteesWithoutMentor = "select u.*,m.* from users as u LEFT JOIN mentees as m ON u.id = m.id where m.id in (select menteeID from pairs where menteeId = m.id and activeStatus = 0 ) or NOT EXISTS(select menteeID from pairs where menteeId = m.id and activeStatus != 0)"; final String getAllMentorsWithoutMentees = "select u.*,m.* from users as u LEFT JOIN mentors as m ON u.id = m.id where m.id in (select mentorId from pairs where mentorId = m.id and activeStatus = 0 ) or NOT EXISTS(select mentorId from pairs where mentorId = m.id and activeStatus != 0)"; final String insertAcademicinstitute = "INSERT INTO academicinstitute (name, area, city) VALUES (?,?,?)"; final String getMeetings1 = "Select * From activites where mentorId=? AND status=? ORDER BY date DESC LIMIT ?, ?"; final String getMeetings2 = "Select * From activites where menteeId=? AND status=? ORDER BY date DESC LIMIT ?, ? "; final String selectAcademicInstitute ="Select * From academicinstitute"; public DataAccess() { Logger logger = Logger.getLogger(DataAccess.class.getName()); logger.log(Level.INFO, "DataAccess c'tor: attempting connection..."); c = util.DBUtil.getConnection(); if (c == null) { logger.log(Level.SEVERE, "Connection Failed"); } else { logger.log(Level.INFO, "Connection Established"); } } public User login(String email) throws SQLException { Logger logger = Logger.getLogger(DataAccess.class.getName()); if (c == null) { logger.log(Level.SEVERE, "Connection Failed"); return null; } PreparedStatement stm = c.prepareStatement(selectLogin); stm.setString(1, email); ResultSet rs = stm.executeQuery(); User u = null; if (rs.next()) { int type = rs.getInt(2); switch (type) { case 0: // Admin logger.log(Level.WARNING, "User type Admin, no admins exist in the system at this time"); break; case 1: // Tsofen member logger.log(Level.INFO, "User type Tsofen"); u = new TsofenT(rs.getInt(1), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8), rs.getString(9), rs.getString(10), rs.getString(11), rs.getBoolean(12), userType.TSOFEN); break; case 2:// Mentor logger.log(Level.INFO, "User type Mentor"); PreparedStatement stm2 = c.prepareStatement(selectLogin1); stm2.setInt(1, rs.getInt(1)); ResultSet rs2 = stm2.executeQuery(); if(rs2.next()) u = new Mentor(rs.getInt(1), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8), rs.getString(9), rs.getString(10), rs.getString(11), rs.getBoolean(12), userType.MENTOR, rs2.getString(2), rs2.getString(3), rs2.getInt(4), rs2.getString(5), rs2.getString(6)); rs2.close(); stm2.close(); break; case 3:// Mentee logger.log(Level.INFO, "User type Mentee"); PreparedStatement stm3 = c.prepareStatement(selectLogin2); stm3.setInt(1, rs.getInt(1)); ResultSet rs3 = stm3.executeQuery(); if(rs3.next()) u = new Mentee(rs.getInt(DataContract.UsersTable.COL_ID), rs.getString(DataContract.UsersTable.COL_FIRSTNAME), rs.getString(DataContract.UsersTable.COL_LASTNAME), rs.getString(DataContract.UsersTable.COL_EMAIL), rs.getString(DataContract.UsersTable.COL_PHONENUMBER), rs.getString(DataContract.UsersTable.COL_PASSWORD), rs.getInt(DataContract.UsersTable.COL_GENDER), rs.getString(DataContract.UsersTable.COL_ADDRESS), rs.getString(DataContract.UsersTable.COL_PROFILEPICTURE), rs.getString(DataContract.UsersTable.COL_NOTES), rs.getBoolean(DataContract.UsersTable.COL_ACTIVE), userType.MENTEE, rs3.getFloat(DataContract.MenteeTable.COL_REMAININGSEMESTERS), rs3.getString(DataContract.MenteeTable.COL_GRADUATIONSTATUS), rs3.getInt(DataContract.MenteeTable.COL_ACADEMICINSTITUTE), rs3.getFloat(DataContract.MenteeTable.COL_AVERAGE), rs3.getString(DataContract.MenteeTable.COL_ACADEMICDICIPLINE1), rs3.getString(DataContract.MenteeTable.COL_ACADEMICDICIPLINE2), rs3.getBoolean(DataContract.MenteeTable.COL_SIGNEDEULA), rs3.getString(DataContract.MenteeTable.COL_RESUME), rs3.getString(DataContract.MenteeTable.COL_GRADESHEET)); break; default: logger.log(Level.WARNING, "User type unknown"); break; } } rs.close(); stm.close(); return u; } public boolean editUser(User user) throws SQLException { PreparedStatement stm = c.prepareStatement(selectByID); stm.setInt(1, user.getId()); ResultSet rs = stm.executeQuery(); if (!rs.next()) // user does not exist return false; PreparedStatement stm2 = c.prepareStatement(updateUserBase); stm2.setString(1, user.getFirstName()); stm2.setString(2, user.getLastName()); stm2.setString(3, user.getPhoneNumber()); stm2.setInt(4, user.getGender()); stm2.setString(5, user.getAddress()); stm2.setString(6, user.getNote()); stm2.setString(7, user.getProfilePicture()); stm2.setInt(8, user.isActive() ? 1 : 0); stm2.setInt(9, user.getId()); stm2.executeUpdate(); if (user.getType() == userType.TSOFEN || user.getType() == userType.ADMIN) return true; if (user.getType() == userType.MENTOR) { PreparedStatement stm3 = c.prepareStatement(updateUserMentor); stm3.setString(1, ((Mentor) user).getExperience()); stm3.setString(2, ((Mentor) user).getRole()); stm3.setInt(3, ((Mentor) user).getCompany()); stm3.setString(4, ((Mentor) user).getVolunteering()); stm3.setString(5, ((Mentor) user).getWorkHistory()); stm3.setInt(6, user.getId()); stm3.executeUpdate(); return true; } if (user.getType() == userType.MENTEE) { PreparedStatement stm4 = c.prepareStatement(updateUserMentee); stm4.setFloat(1, ((Mentee) user).getRemainingSemesters()); stm4.setString(2, ((Mentee) user).getGraduationStatus()); stm4.setInt(3, ((Mentee) user).getAcademiclnstitution()); stm4.setFloat(4, ((Mentee) user).getAverage()); stm4.setString(5, ((Mentee) user).getAcademicDicipline()); stm4.setString(6, ((Mentee) user).getAcademicDicipline2()); stm4.setInt(7, ((Mentee) user).getSignedEULA() ? 1 : 0); stm4.setString(8, ((Mentee) user).getResume()); stm4.setString(9, ((Mentee) user).getGradeSheet()); stm4.setInt(10, user.getId()); stm4.executeUpdate(); return true; } return false; } public boolean deactivateUser(int id) throws SQLException { PreparedStatement stm = c.prepareStatement(selectByID); stm.setInt(1, id); ResultSet rs = stm.executeQuery(); if (rs.next()) { PreparedStatement stm2 = c.prepareStatement(deactivateUser); stm2.setInt(1, id); return true; } return false; } /* * public ArrayList<User> getAllMentors(int id) throws SQLException { * ArrayList<User> list= new ArrayList<User>(); PreparedStatement stm = * c.prepareStatement(findMentorsOfMentee); stm.setInt(1, id); ResultSet rs * = stm.executeQuery(); while (rs.next()) { list.add(new * Mentor(rs.getInt(1), rs.getString(3), rs.getString(4), rs.getString(5), * rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), * rs.getString(10), rs.getBoolean(11), userType.MENTOR, rs2.getString(2), * rs2.getString(3), rs2.getInt(4), rs2.getString(5), rs2.getString(6))); } * return null; } */ @Override public boolean addUser(User u) throws SQLException { PreparedStatement stm = c.prepareStatement(selectLogin); stm.setString(1, u.getEmail()); ResultSet rs = stm.executeQuery(); if (rs.next()) // user exists { System.out.println("rs.next(): " + rs.getString(3)); // return false; } PreparedStatement stm2 = c.prepareStatement(addBaseUser); stm2.setInt(1, u.getType().getValue()); stm2.setString(2, u.getFirstName()); stm2.setString(3, u.getLastName()); stm2.setString(4, u.getEmail()); stm2.setString(5, u.getPhoneNumber()); stm2.setString(6, u.getPassword()); stm2.setInt(7, u.getGender()); stm2.setString(8, u.getAddress()); stm2.setString(9, u.getNote()); stm2.setString(10, u.getProfilePicture()); stm2.setInt(11, u.isActive() ? 1 : 0); stm2.executeUpdate(); stm = c.prepareStatement(selectLogin); stm.setString(1, u.getEmail()); rs = stm.executeQuery(); int id = 0; if (rs.next()) // user exists { id = rs.getInt(1); } else { return false; } if (u.getType() == userType.TSOFEN || u.getType() == userType.ADMIN) return true; if (u.getType() == userType.MENTOR) { PreparedStatement stm3 = c.prepareStatement(addMentorUser); stm3.setInt(1, id); stm3.setString(2, ((Mentor) u).getExperience()); stm3.setString(3, ((Mentor) u).getRole()); stm3.setInt(4, ((Mentor) u).getCompany()); stm3.setString(5, ((Mentor) u).getVolunteering()); stm3.setString(6, ((Mentor) u).getWorkHistory()); stm3.executeUpdate(); return true; } if (u.getType() == userType.MENTEE) { PreparedStatement stm4 = c.prepareStatement(addMenteeUser); stm4.setInt(1, id); stm4.setFloat(2, ((Mentee) u).getRemainingSemesters()); stm4.setString(3, ((Mentee) u).getGraduationStatus()); stm4.setInt(4, ((Mentee) u).getAcademiclnstitution()); stm4.setFloat(5, ((Mentee) u).getAverage()); stm4.setString(6, ((Mentee) u).getAcademicDicipline()); stm4.setString(7, ((Mentee) u).getAcademicDicipline2()); stm4.setInt(8, ((Mentee) u).getSignedEULA() ? 1 : 0); stm4.setString(9, ((Mentee) u).getResume()); stm4.setString(10, ((Mentee) u).getGradeSheet()); stm4.executeUpdate(); return true; } return false; } @Override public ArrayList<User> getUsers(userType type) throws SQLException { User u = null; ArrayList<User> users = new ArrayList<User>(); switch (type) { case ADMIN: break; case TSOFEN: PreparedStatement stm = c.prepareStatement(selectByType); stm.setInt(1, type.getValue()); ResultSet r = stm.executeQuery(); while (r.next()) { u = new TsofenT(r.getInt(1), r.getString(3), r.getString(4), r.getString(5), r.getString(6), r.getString(7), r.getInt(8), r.getString(9), r.getString(10), r.getString(11), r.getBoolean(12), userType.TSOFEN); users.add(u); } break; case MENTOR: Statement stm2 = c.createStatement(); stm2.executeQuery("selectMentor"); ResultSet r2 = stm2.getResultSet(); while (r2.next()) { u = new Mentor(r2.getInt(1), r2.getString(3), r2.getString(4), r2.getString(5), r2.getString(6), r2.getString(7), r2.getInt(8), r2.getString(9), r2.getString(10), r2.getString(11), r2.getBoolean(12), userType.MENTOR, r2.getString(14), r2.getString(15), r2.getInt(16), r2.getString(5), r2.getString(6)); users.add(u); } break; case MENTEE: Statement stm3 = c.createStatement(); stm3.executeQuery("selectMentee"); ResultSet r3 = stm3.getResultSet(); while (r3.next()) { u = new Mentee(r3.getInt(DataContract.UsersTable.COL_ID), r3.getString(DataContract.UsersTable.COL_FIRSTNAME), r3.getString(DataContract.UsersTable.COL_LASTNAME), r3.getString(DataContract.UsersTable.COL_EMAIL), r3.getString(DataContract.UsersTable.COL_PHONENUMBER), r3.getString(DataContract.UsersTable.COL_PASSWORD), r3.getInt(DataContract.UsersTable.COL_GENDER), r3.getString(DataContract.UsersTable.COL_ADDRESS), r3.getString(DataContract.UsersTable.COL_PROFILEPICTURE), r3.getString(DataContract.UsersTable.COL_NOTES), r3.getBoolean(DataContract.UsersTable.COL_ACTIVE), userType.MENTEE, r3.getFloat(DataContract.MenteeTable.COL_REMAININGSEMESTERS), r3.getString(DataContract.MenteeTable.COL_GRADUATIONSTATUS), r3.getInt(DataContract.MenteeTable.COL_ACADEMICINSTITUTE), r3.getFloat(DataContract.MenteeTable.COL_AVERAGE), r3.getString(DataContract.MenteeTable.COL_ACADEMICDICIPLINE1), r3.getString(DataContract.MenteeTable.COL_ACADEMICDICIPLINE2), r3.getBoolean(DataContract.MenteeTable.COL_SIGNEDEULA), r3.getString(DataContract.MenteeTable.COL_RESUME), r3.getString(DataContract.MenteeTable.COL_GRADESHEET)); users.add(u); } break; default: break; } return users; } @Override public User getUser(int id) throws SQLException { User user = null; PreparedStatement stm = c.prepareStatement(selectByID); stm.setInt(1, id); ResultSet rs = stm.executeQuery(); if (rs.next()) { int type = rs.getInt(2); switch (type) { case 0: break; case 1: user = new TsofenT(rs.getInt(1), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8), rs.getString(9), rs.getString(10), rs.getString(11), rs.getBoolean(12), userType.TSOFEN); break; case 2: PreparedStatement stm2 = c.prepareStatement(selectLogin1); stm2.setInt(1, rs.getInt(DataContract.UsersTable.COL_ID)); ResultSet rs2 = stm2.executeQuery(); if (rs2.next()) user = new Mentor(rs.getInt(DataContract.UsersTable.COL_ID), rs.getString(DataContract.UsersTable.COL_FIRSTNAME), rs.getString(DataContract.UsersTable.COL_LASTNAME), rs.getString(DataContract.UsersTable.COL_EMAIL), rs.getString(DataContract.UsersTable.COL_PHONENUMBER), rs.getString(DataContract.UsersTable.COL_PASSWORD), rs.getInt(DataContract.UsersTable.COL_GENDER), rs.getString(DataContract.UsersTable.COL_ADDRESS), rs.getString(DataContract.UsersTable.COL_NOTES), rs.getString(DataContract.UsersTable.COL_PROFILEPICTURE), rs.getBoolean(DataContract.UsersTable.COL_ACTIVE), userType.MENTOR, rs2.getString(DataContract.MentorsTable.COL_EXPERIENCE), rs2.getString(DataContract.MentorsTable.COL_ROLE), rs2.getInt(DataContract.MentorsTable.COL_COMPANY), rs2.getString(DataContract.MentorsTable.COL_VOLUNTEERING), rs2.getString(DataContract.MentorsTable.COL_WORKHISTORY)); break; case 3: PreparedStatement stm3 = c.prepareStatement(selectLogin2); stm3.setInt(1, rs.getInt(1)); ResultSet rs3 = stm3.executeQuery(); if (rs3.next()) user = new Mentee(rs.getInt(DataContract.UsersTable.COL_ID), rs.getString(DataContract.UsersTable.COL_FIRSTNAME), rs.getString(DataContract.UsersTable.COL_LASTNAME), rs.getString(DataContract.UsersTable.COL_EMAIL), rs.getString(DataContract.UsersTable.COL_PHONENUMBER), rs.getString(DataContract.UsersTable.COL_PASSWORD), rs.getInt(DataContract.UsersTable.COL_GENDER), rs.getString(DataContract.UsersTable.COL_ADDRESS), rs.getString(DataContract.UsersTable.COL_PROFILEPICTURE), rs.getString(DataContract.UsersTable.COL_NOTES), rs.getBoolean(DataContract.UsersTable.COL_ACTIVE), userType.MENTEE, rs3.getFloat(DataContract.MenteeTable.COL_REMAININGSEMESTERS), rs3.getString(DataContract.MenteeTable.COL_GRADUATIONSTATUS), rs3.getInt(DataContract.MenteeTable.COL_ACADEMICINSTITUTE), rs3.getFloat(DataContract.MenteeTable.COL_AVERAGE), rs3.getString(DataContract.MenteeTable.COL_ACADEMICDICIPLINE1), rs3.getString(DataContract.MenteeTable.COL_ACADEMICDICIPLINE2), rs3.getBoolean(DataContract.MenteeTable.COL_SIGNEDEULA), rs3.getString(DataContract.MenteeTable.COL_RESUME), rs3.getString(DataContract.MenteeTable.COL_GRADESHEET)); break; default: break; } } return user; } @Override public ArrayList<Pair> getAllPairs() throws SQLException { Pair p = new Pair(); ArrayList<Pair> pair = new ArrayList<Pair>(); Statement stm = c.createStatement(); stm.executeQuery("selectAllPairs"); ResultSet r = stm.getResultSet(); while (r.next()) { p = new Pair(r.getInt(1), r.getInt(2), r.getInt(3), r.getInt(4), r.getLong(5), r.getLong(6), r.getString(7), r.getString(8)); pair.add(p); } return pair; } @Override public boolean addPair(int mentorId, int menteeId) throws SQLException { PreparedStatement stm = c.prepareStatement(selectLogin1); stm.setInt(1, mentorId); ResultSet rs = stm.executeQuery(); if (!rs.next()) // user does not exist return false; stm = c.prepareStatement(selectLogin2); stm.setInt(1, menteeId); ResultSet rs1 = stm.executeQuery(); if (!rs1.next()) // user does not exist return false; stm = c.prepareStatement(insertPair); // checking witch user is the mentor and witch is the mentee stm.setInt(1, mentorId); stm.setInt(2, menteeId); stm.setInt(3, 1); stm.setDate(4, Date.valueOf(LocalDate.now())); stm.executeUpdate(); return true; } @Override public boolean disconnectPair(int pairId) { try { PreparedStatement stm = c.prepareStatement(updateActiveStatus); stm.setInt(1, pairId); stm.executeUpdate(); } catch (SQLException e) { return false; } return true; } @Override public Pair getPair(int pairId) throws SQLException { PreparedStatement stm = c.prepareStatement(selectPairId); stm.setInt(1, pairId); ResultSet rs = stm.executeQuery(); if (!rs.next()) // user does not exist return null; Date d = rs.getDate(DataContract.PairsTable.COL_ENDDATE); long l = -1 ; if(d!=null) l=d.getTime(); return new Pair(rs.getInt(DataContract.PairsTable.COL_PAIRID), rs.getInt(DataContract.PairsTable.COL_MENTORID), rs.getInt(DataContract.PairsTable.COL_MENTEEID), getUser(rs.getInt(DataContract.PairsTable.COL_MENTORID)), getUser(rs.getInt(DataContract.PairsTable.COL_MENTEEID)), rs.getInt(DataContract.PairsTable.COL_ACTIVESTATUS), rs.getDate(DataContract.PairsTable.COL_STARTDATE).getTime(), l, rs.getString(DataContract.PairsTable.COL_JOINTMESSAGE), rs.getString(DataContract.PairsTable.COL_TSOFENMESSAGE)); } @Override public ArrayList<Session> getUserSessions(int id) throws SQLException { ArrayList<Session> session = new ArrayList<Session>(); Session s = null; PreparedStatement stm = c.prepareStatement(sessionId); stm.setInt(1, id); ResultSet rs = stm.executeQuery(); if (rs.next()) { s = new Session(id, rs.getString(2), rs.getLong(3), rs.getLong(4), rs.getString(5)); session.add(s); } return session; } @Override public ArrayList<Meeting> getUserMeetings(int id) throws SQLException { ArrayList<Meeting> meeting = new ArrayList<Meeting>(); Meeting meet = null; PreparedStatement stm = c.prepareStatement(selectMeeting); stm.setInt(1, id); ResultSet rs = stm.executeQuery(); if (rs.next()) { meet = new Meeting(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getString(5), meetingStatus.valueOf(rs.getInt(6)), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), mm.model.Meeting.meetingType.SMS, rs.getString(12), rs.getString(13), rs.getLong(14), rs.getTime(15), rs.getTime(16), rs.getBoolean(17), rs.getBoolean(18)); } else { PreparedStatement stm1 = c.prepareStatement(selectMeeting2); stm1.setInt(1, id); ResultSet rs1 = stm.executeQuery(); if (rs1.next()) { meet = new Meeting(rs1.getInt(1), rs1.getInt(2), rs1.getInt(3), rs1.getInt(4), rs1.getString(5), meetingStatus.valueOf(rs.getInt(6)), rs1.getString(7), rs1.getString(8), rs1.getString(9), rs1.getString(10), mm.model.Meeting.meetingType.SMS, rs1.getString(12), rs1.getString(13), rs1.getLong(14), rs1.getTime(15), rs1.getTime(16), rs1.getBoolean(17), rs1.getBoolean(18)); meeting.add(meet); }} return meeting; } @Override public Mentor getMentorOfMentee(int menteeId) throws SQLException { PreparedStatement stm = c.prepareStatement(getMenteeofPair); stm.setInt(1, menteeId); stm.setInt(2, 1); ResultSet rs = stm.executeQuery(); return (Mentor) getUser(rs.getInt(2)); } @Override public ArrayList<Mentee> getMenteesOfMentor(int mentorId) throws SQLException { ArrayList<Mentee> mentees = new ArrayList<Mentee>(); PreparedStatement stm = c.prepareStatement(getMentorofPair); stm.setInt(1, mentorId); stm.setInt(2, 1); ResultSet rs = stm.executeQuery(); while (!rs.next()) { mentees.add((Mentee) getUser(rs.getInt(3))); } return mentees; } @Override public Meeting getMeetingById(int meetingId) throws SQLException { Meeting m = null; PreparedStatement stm = c.prepareStatement(selectMeetingById); stm.setInt(1, meetingId); ResultSet rs = stm.executeQuery(); if (rs.next()) { m = new Meeting(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getString(5), meetingStatus.valueOf(rs.getInt(6)), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), meetingType.getByValue(rs.getInt(11)), rs.getString(12), rs.getString(13), rs.getLong(14), rs.getTime(15), rs.getTime(16), rs.getBoolean(17), rs.getBoolean(18)); } return m; } @Override public boolean startUserSession(Session session) throws SQLException { PreparedStatement stm = c.prepareStatement(addUserSession); stm.setInt(1, session.getUserId()); stm.setString(2, session.getToken()); stm.setLong(3, session.getCreationDate()); stm.setLong(4, session.getExpirationDate()); stm.setString(5, session.getDeviceId()); stm.executeUpdate(); return true; } @Override public boolean addMeeting(Meeting meeting) { try { PreparedStatement stm = c.prepareStatement(addMeeting); stm.setInt(1, meeting.getPairId()); stm.setInt(2,meeting.getMentorId()); stm.setInt(3, meeting.getMenteeId()); stm.setString(4, meeting.getNote()); stm.setInt(5, Integer.valueOf(meeting.getStatus().ordinal())); stm.setString(6, meeting.getMenteeReport()); stm.setString(7, meeting.getMentorReport()); stm.setString(8, meeting.getMenteePrivateReport()); stm.setString(9, meeting.getMentorPrivateReport()); stm.setInt(10, Integer.valueOf(meeting.getMeetingType().ordinal())); stm.setString(11,meeting.getSubject()); stm.setString(12,meeting.getLocation()); stm.setLong(13,meeting.getDate()); stm.setString(14,meeting.getStartingDate().toString()); stm.setString(15,meeting.getEndingDate().toString()); stm.setBoolean(16,meeting.getMentorComplete()); stm.setBoolean(17,meeting.getMenteeComplete()); stm.executeUpdate(); } catch (SQLException e) { return false; } return true; } @Override public boolean approveMeeting(int meetingId, boolean status) throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean confirmMeeting(int meetingId, boolean status) throws SQLException { // TODO Auto-generated method stub return false; } @Override public ArrayList<Meeting> getMeetingsByPairId(int pairId) throws SQLException { ArrayList<Meeting> m = new ArrayList<Meeting>(); Meeting meeting = null; PreparedStatement stm = c.prepareStatement(selectMeetingByPair); stm.setInt(1, pairId); ResultSet rs = stm.executeQuery(); if (rs.next()) { meeting = new Meeting(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getString(5), meetingStatus.valueOf(rs.getInt(6)), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), meetingType.getByValue(rs.getInt(11)), rs.getString(12), rs.getString(13), rs.getLong(14), rs.getTime(15), rs.getTime(16), rs.getBoolean(17), rs.getBoolean(18)); m.add(meeting); } return m; } @Override public ArrayList<Mentee> getAllMenteesWithoutMentor() throws SQLException { Mentee u = null; ArrayList<Mentee> menteesList = new ArrayList<Mentee>(); Statement stm = c.createStatement(); stm.executeQuery(getAllMenteesWithoutMentor); ResultSet r = stm.getResultSet(); while (r.next()) { u = new Mentee(r.getInt(DataContract.UsersTable.COL_ID), r.getString(DataContract.UsersTable.COL_FIRSTNAME), r.getString(DataContract.UsersTable.COL_LASTNAME), r.getString(DataContract.UsersTable.COL_EMAIL), r.getString(DataContract.UsersTable.COL_PHONENUMBER), r.getString(DataContract.UsersTable.COL_PASSWORD), r.getInt(DataContract.UsersTable.COL_GENDER), r.getString(DataContract.UsersTable.COL_ADDRESS), r.getString(DataContract.UsersTable.COL_PROFILEPICTURE), r.getString(DataContract.UsersTable.COL_NOTES), r.getBoolean(DataContract.UsersTable.COL_ACTIVE), userType.MENTEE, r.getFloat(DataContract.MenteeTable.COL_REMAININGSEMESTERS), r.getString(DataContract.MenteeTable.COL_GRADUATIONSTATUS), r.getInt(DataContract.MenteeTable.COL_ACADEMICINSTITUTE), r.getFloat(DataContract.MenteeTable.COL_AVERAGE), r.getString(DataContract.MenteeTable.COL_ACADEMICDICIPLINE1), r.getString(DataContract.MenteeTable.COL_ACADEMICDICIPLINE2), r.getBoolean(DataContract.MenteeTable.COL_SIGNEDEULA), r.getString(DataContract.MenteeTable.COL_RESUME), r.getString(DataContract.MenteeTable.COL_GRADESHEET)); menteesList.add(u); } return menteesList; } @Override public ArrayList<Mentor> getAllMentorsWithoutMentees() throws SQLException { Mentor u = null; ArrayList<Mentor> mentorList = new ArrayList<Mentor>(); Statement stm = c.createStatement(); stm.executeQuery(getAllMentorsWithoutMentees); ResultSet r = stm.getResultSet(); while (r.next()) { u = new Mentor(r.getInt(1), r.getString(3), r.getString(4), r.getString(5), r.getString(6), r.getString(7), r.getInt(8), r.getString(9), r.getString(10), r.getString(11), r.getBoolean(12), userType.MENTOR, r.getString(13), r.getString(14), r.getInt(15), r.getString(16), r.getString(17)); mentorList.add(u); } return mentorList; } @Override public boolean addWorkPlace(WorkPlace workplace) { // TODO Auto-generated method stub return false; } @Override public ArrayList<Meeting> getMeetingByStatus(int userId,meetingStatus status,int count,int page) throws SQLException{ ArrayList<Meeting> m = new ArrayList<Meeting>(); PreparedStatement stm = null; userType type = getUser(userId).getType(); if (type == userType.MENTEE) { stm=c.prepareStatement(getMeetings2); } if(type == userType.MENTOR) { stm=c.prepareStatement(getMeetings1); } if(stm!=null) { stm.setInt(1,userId); stm.setInt(2, status.ordinal()); stm.setInt(3, (page-1)*(count)); stm.setInt(4, count); ResultSet rs=stm.executeQuery(); m=new ArrayList<Meeting>(); while (rs.next()) { Meeting meet = new Meeting(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getString(5),status, rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), meetingType.getByValue(rs.getInt(11)), rs.getString(12), rs.getString(13), rs.getLong(14), rs.getTime(15), rs.getTime(16), rs.getBoolean(17), rs.getBoolean(18)); m.add(meet); } } return m; } @Override public boolean addAcademicInstitute(AcademicInstitute a) throws SQLException { PreparedStatement stm = c.prepareStatement(insertAcademicinstitute); stm.setString(1, a.getName()); stm.setString(2, a.getArea()); stm.setString(3, a.getCity()); stm.executeUpdate(); return true; } @Override public ArrayList<AcademicInstitute> getAllAcademiclnstitution() throws SQLException { ArrayList<AcademicInstitute> a = new ArrayList<AcademicInstitute>(); AcademicInstitute academic = null; PreparedStatement stm = c.prepareStatement(selectAcademicInstitute); ResultSet rs = stm.executeQuery(); while (rs.next()) { academic = new AcademicInstitute(rs.getInt(DataContract.AcademicInstituteTable.COL_ID), rs.getString(DataContract.AcademicInstituteTable.COL_NAME), rs.getString(DataContract.AcademicInstituteTable.COL_AREA), rs.getString(DataContract.AcademicInstituteTable.COL_CITY)); a.add(academic); } return a; } @Override public ArrayList<WorkPlace> getAllWorkingPlace() throws SQLException { // TODO Auto-generated method stub return null; } }
package tests.net.sf.jabref.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.util.Calendar; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.TimeZone; import javax.xml.transform.TransformerException; import junit.framework.TestCase; import net.sf.jabref.AuthorList; import net.sf.jabref.BibtexEntry; import net.sf.jabref.BibtexEntryType; import net.sf.jabref.Globals; import net.sf.jabref.JabRefPreferences; import net.sf.jabref.Util; import net.sf.jabref.imports.BibtexParser; import net.sf.jabref.imports.ParserResult; import net.sf.jabref.util.EncryptionNotSupportedException; import net.sf.jabref.util.XMPSchemaBibtex; import net.sf.jabref.util.XMPUtil; import org.jempbox.xmp.XMPMetadata; import org.jempbox.xmp.XMPSchema; import org.jempbox.xmp.XMPSchemaBasic; import org.jempbox.xmp.XMPSchemaDublinCore; import org.jempbox.xmp.XMPSchemaMediaManagement; import org.pdfbox.exceptions.COSVisitorException; import org.pdfbox.pdmodel.PDDocument; import org.pdfbox.pdmodel.PDDocumentCatalog; import org.pdfbox.pdmodel.PDPage; import org.pdfbox.pdmodel.common.PDMetadata; import org.pdfbox.util.XMLUtil; /** * * Limitations: The test suite only handles UTF8. Not UTF16. * * @author Christopher Oezbek <oezi@oezi.de> */ public class XMPUtilTest extends TestCase { /** * Wrap bibtex-data (<bibtex:author>...) into an rdf:Description. * * @param bibtex * @return */ public static String bibtexDescription(String bibtex) { return " <rdf:Description rdf:about='' xmlns:bibtex='http://jabref.sourceforge.net/bibteXMP/'>\n" + bibtex + "\n" + " </rdf:Description>\n"; } /** * Wrap bibtex-descriptions (rdf:Description) into the xpacket header. * * @param bibtexDescriptions * @return */ public static String bibtexXPacket(String bibtexDescriptions) { StringBuffer xmp = new StringBuffer(); xmp.append("<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?>\n"); xmp.append(" <x:xmpmeta xmlns:x='adobe:ns:meta/'>\n"); xmp .append(" <rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns xmp.append(bibtexDescriptions); xmp.append(" </rdf:RDF>\n"); xmp.append(" </x:xmpmeta>\n"); xmp.append("<?xpacket end='r'?>"); return xmp.toString(); } /** * Write a manually constructed xmp-string to file * * @param xmpString * @throws Exception */ public void writeManually(File tempFile, String xmpString) throws Exception { PDDocument document = null; try { document = PDDocument.load(tempFile.getAbsoluteFile()); if (document.isEncrypted()) { System.err .println("Error: Cannot add metadata to encrypted document."); System.exit(1); } PDDocumentCatalog catalog = document.getDocumentCatalog(); // Convert to UTF8 and make available for metadata. ByteArrayOutputStream bs = new ByteArrayOutputStream(); OutputStreamWriter os = new OutputStreamWriter(bs, "UTF8"); os.write(xmpString); os.close(); ByteArrayInputStream in = new ByteArrayInputStream(bs.toByteArray()); PDMetadata metadataStream = new PDMetadata(document, in, false); catalog.setMetadata(metadataStream); document.save(tempFile.getAbsolutePath()); } finally { if (document != null) document.close(); } } public static BibtexEntry bibtexString2BibtexEntry(String s) throws IOException { ParserResult result = BibtexParser.parse(new StringReader(s)); Collection<BibtexEntry> c = result.getDatabase().getEntries(); assertEquals(1, c.size()); return c.iterator().next(); } public static String bibtexEntry2BibtexString(BibtexEntry e) throws IOException { StringWriter sw = new StringWriter(); e.write(sw, new net.sf.jabref.export.LatexFieldFormatter(), false); return sw.getBuffer().toString(); } /* TEST DATA */ public String t1BibtexString() { return "@article{canh05,\n" + " author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.},\n" + " title = {Effective work practices for floss development: A model and propositions},\n" + " booktitle = {Hawaii International Conference On System Sciences (HICSS)},\n" + " year = {2005},\n" + " owner = {oezbek},\n" + " timestamp = {2006.05.29},\n" + " url = {http://james.howison.name/publications.html}}\n"; } public BibtexEntry t1BibtexEntry() throws IOException { return bibtexString2BibtexEntry(t1BibtexString()); } public String t2XMP() { return "<rdf:Description rdf:about='' xmlns:bibtex='http://jabref.sourceforge.net/bibteXMP/' " + "bibtex:title='ptmztn' " + "bibtex:bibtexkey='OezbekC06' " + "bibtex:entrytype='INCOLLECTION' " + "bibtex:year='2003' " + "bibtex:booktitle='Proceedings of the of the 25th International Conference on \n Software-Engineering (Portland, Oregon)' " + ">\n" + "<bibtex:pdf>YeKis03 - Towards.pdf</bibtex:pdf>\n" + "</rdf:Description>\n"; } public String t2BibtexString() throws IOException { return bibtexEntry2BibtexString(t2BibtexEntry()); } public BibtexEntry t2BibtexEntry() { BibtexEntry e = new BibtexEntry(Util.createNeutralId(), BibtexEntryType.INCOLLECTION); e.setField("title", "ptmztn"); e.setField("bibtexkey", "OezbekC06"); e.setField("year", "2003"); e .setField( "booktitle", "Proceedings of the of the 25th International Conference on Software-Engineering (Portland, Oregon)"); e.setField("pdf", "YeKis03 - Towards.pdf"); return e; } public BibtexEntry t3BibtexEntry() { BibtexEntry e = new BibtexEntry(); e.setType(BibtexEntryType.INPROCEEDINGS); e.setField("title", "Hypersonic ultra-sound"); e.setField("bibtexkey", "Clarkson06"); e.setField("author", "Kelly Clarkson and Ozzy Osbourne"); e.setField("journal", "International Journal of High Fidelity"); e.setField("booktitle", "Catch-22"); e.setField("editor", "Huey Duck and Dewey Duck and Louie Duck"); e.setField("pdf", "YeKis03 - Towards.pdf"); e.setField("keywords", "peanut,butter,jelly"); e.setField("year", "1982"); e.setField("month", "#jul#"); e .setField( "abstract", "The success of the Linux operating system has demonstrated the viability of an alternative form of software development open source software that challenges traditional assumptions about software markets. Understanding what drives open source developers to participate in open source projects is crucial for assessing the impact of open source software. This article identifies two broad types of motivations that account for their participation in open source projects. The first category includes internal factors such as intrinsic motivation and altruism, and the second category focuses on external rewards such as expected future returns and personal needs. This article also reports the results of a survey administered to open source programmers."); return e; } public String t3BibtexString() throws IOException { return bibtexEntry2BibtexString(t3BibtexEntry()); } public String t3XMP() { return bibtexDescription("<bibtex:title>Hypersonic ultra-sound</bibtex:title>\n" + "<bibtex:author><rdf:Seq>\n" + " <rdf:li>Kelly Clarkson</rdf:li>" + " <rdf:li>Ozzy Osbourne</rdf:li>" + "</rdf:Seq></bibtex:author>" + "<bibtex:editor><rdf:Seq>" + " <rdf:li>Huey Duck</rdf:li>" + " <rdf:li>Dewey Duck</rdf:li>" + " <rdf:li>Louie Duck</rdf:li>" + "</rdf:Seq></bibtex:editor>" + "<bibtex:bibtexkey>Clarkson06</bibtex:bibtexkey>" + "<bibtex:journal>International Journal of High Fidelity</bibtex:journal>" + "<bibtex:booktitle>Catch-22</bibtex:booktitle>" + "<bibtex:pdf>YeKis03 - Towards.pdf</bibtex:pdf>" + "<bibtex:keywords>peanut,butter,jelly</bibtex:keywords>" + "<bibtex:entrytype>Inproceedings</bibtex:entrytype>" + "<bibtex:year>1982</bibtex:year>" + "<bibtex:month>#jul#</bibtex:month>" + "<bibtex:abstract>The success of the Linux operating system has demonstrated the viability of an alternative form of software development open source software that challenges traditional assumptions about software markets. Understanding what drives open source developers to participate in open source projects is crucial for assessing the impact of open source software. This article identifies two broad types of motivations that account for their participation in open source projects. The first category includes internal factors such as intrinsic motivation and altruism, and the second category focuses on external rewards such as expected future returns and personal needs. This article also reports the results of a survey administered to open source programmers.</bibtex:abstract>"); } /** * The PDF file that basically all operations are done upon. */ File pdfFile; /** * Create a temporary PDF-file with a single empty page. */ public void setUp() throws IOException, COSVisitorException { pdfFile = File.createTempFile("JabRef", ".pdf"); PDDocument pdf = null; try { pdf = new PDDocument(); pdf.addPage(new PDPage()); // Need page to open in Acrobat pdf.save(pdfFile.getAbsolutePath()); } finally { if (pdf != null) pdf.close(); } // Don't forget to initialize the preferences if (Globals.prefs == null) { Globals.prefs = JabRefPreferences.getInstance(); } // Store Privacy Settings prefs = JabRefPreferences.getInstance(); use = prefs.getBoolean("useXmpPrivacyFilter"); privacyFilters = prefs.getStringArray("xmpPrivacyFilters"); // The code assumes privacy filters to be off prefs.putBoolean("useXmpPrivacyFilter", false); } JabRefPreferences prefs; boolean use; String[] privacyFilters; /** * Delete the temporary file. */ public void tearDown() { pdfFile.delete(); prefs.putBoolean("useXmpPrivacyFilter", use); prefs.putStringArray("xmpPrivacyFilter", privacyFilters); } /** * Most basic test for reading. * * @throws Exception */ public void testReadXMPSimple() throws Exception { String bibtex = "<bibtex:year>2003</bibtex:year>\n" + "<bibtex:title>Beach sand convolution by surf-wave optimzation</bibtex:title>\n" + "<bibtex:bibtexkey>OezbekC06</bibtex:bibtexkey>\n"; writeManually(pdfFile, bibtexXPacket(bibtexDescription(bibtex))); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry e = (BibtexEntry) l.get(0); assertNotNull(e); assertEquals("OezbekC06", e.getCiteKey()); assertEquals("2003", e.getField("year")); assertEquals("Beach sand convolution by surf-wave optimzation", e .getField("title")); assertEquals(BibtexEntryType.OTHER, e.getType()); } /** * Is UTF8 handling working? This is because Java by default uses the * platform encoding or a special UTF-kind. * * @throws Exception */ public void testReadXMPUTF8() throws Exception { String bibtex = "<bibtex:year>2003</bibtex:year>\n" + "<bibtex:title>ptmztn</bibtex:title>\n" + "<bibtex:bibtexkey>OezbekC06</bibtex:bibtexkey>\n"; writeManually(pdfFile, bibtexXPacket(bibtexDescription(bibtex))); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry e = (BibtexEntry) l.get(0); assertNotNull(e); assertEquals("OezbekC06", e.getCiteKey()); assertEquals("2003", e.getField("year")); assertEquals("ptmztn", e.getField("title")); assertEquals(BibtexEntryType.OTHER, e.getType()); } /** * Make sure that the privacy filter works. * * @throws IOException * Should not happen. * @throws TransformerException * Should not happen. */ public void testPrivacyFilter() throws IOException, TransformerException { { // First set: prefs.putBoolean("useXmpPrivacyFilter", true); prefs.putStringArray("xmpPrivacyFilter", new String[] { "author;title;note" }); BibtexEntry e = t1BibtexEntry(); XMPUtil.writeXMP(pdfFile, e, null); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry x = (BibtexEntry) l.get(0); Set<String> ts = x.getAllFields(); assertEquals(8, ts.size()); ts.contains("bibtextype"); ts.contains("bibtexkey"); ts.contains("booktitle"); ts.contains("year"); ts.contains("owner"); ts.contains("timestamp"); ts.contains("year"); ts.contains("url"); } { // First set: prefs.putBoolean("useXmpPrivacyFilter", true); prefs .putStringArray( "xmpPrivacyFilter", new String[] { "author;title;note;booktitle;year;owner;timestamp" }); BibtexEntry e = t1BibtexEntry(); XMPUtil.writeXMP(pdfFile, e, null); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry x = (BibtexEntry) l.get(0); Set<String> ts = x.getAllFields(); assertEquals(8, ts.size()); ts.contains("bibtextype"); ts.contains("bibtexkey"); ts.contains("year"); ts.contains("url"); } } /** * Are authors and editors correctly read? * * @throws Exception */ public void testReadXMPSeq() throws Exception { String bibtex = "<bibtex:author><rdf:Seq>\n" + " <rdf:li>Kelly Clarkson</rdf:li>" + " <rdf:li>Ozzy Osbourne</rdf:li>" + "</rdf:Seq></bibtex:author>" + "<bibtex:editor><rdf:Seq>" + " <rdf:li>Huey Duck</rdf:li>" + " <rdf:li>Dewey Duck</rdf:li>" + " <rdf:li>Louie Duck</rdf:li>" + "</rdf:Seq></bibtex:editor>" + "<bibtex:bibtexkey>Clarkson06</bibtex:bibtexkey>"; writeManually(pdfFile, bibtexXPacket(bibtexDescription(bibtex))); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry e = (BibtexEntry) l.get(0); assertNotNull(e); assertEquals("Clarkson06", e.getCiteKey()); assertEquals("Kelly Clarkson and Ozzy Osbourne", e.getField("author")); assertEquals("Huey Duck and Dewey Duck and Louie Duck", e .getField("editor")); assertEquals(BibtexEntryType.OTHER, e.getType()); } /** * Is the XMPEntryType correctly set? * * @throws Exception */ public void testReadXMPEntryType() throws Exception { String bibtex = "<bibtex:entrytype>ARticle</bibtex:entrytype>"; writeManually(pdfFile, bibtexXPacket(bibtexDescription(bibtex))); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry e = (BibtexEntry) l.get(0); assertNotNull(e); assertEquals(BibtexEntryType.ARTICLE, e.getType()); } public static String readManually(File tempFile) throws IOException { PDDocument document = null; try { document = PDDocument.load(tempFile.getAbsoluteFile()); if (document.isEncrypted()) { System.err .println("Error: Cannot add metadata to encrypted document."); System.exit(1); } PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata meta = catalog.getMetadata(); if (meta == null) { return null; } else { // PDMetadata.getInputStreamAsString() does not work // Convert to UTF8 and make available for metadata. InputStreamReader is = new InputStreamReader(meta .createInputStream(), "UTF8"); return slurp(is).trim(); // Trim to kill padding end-newline. } } finally { if (document != null) document.close(); } } /** * Test whether the helper function work correctly. * * @throws Exception */ public void testWriteReadManually() throws Exception { String bibtex = "<bibtex:year>2003</bibtex:year>\n" + "<bibtex:title>ptmztn</bibtex:title>\n" + "<bibtex:bibtexkey>OezbekC06</bibtex:bibtexkey>\n"; writeManually(pdfFile, bibtexXPacket(bibtexDescription(bibtex))); assertEquals(bibtexXPacket(bibtexDescription(bibtex)), readManually(pdfFile)); bibtex = "<bibtex:author><rdf:Seq>\n" + " <rdf:li>Kelly Clarkson</rdf:li>" + " <rdf:li>Ozzy Osbourne</rdf:li>" + "</rdf:Seq></bibtex:author>" + "<bibtex:editor><rdf:Seq>" + " <rdf:li>Huey Duck</rdf:li>" + " <rdf:li>Dewey Duck</rdf:li>" + " <rdf:li>Louie Duck</rdf:li>" + "</rdf:Seq></bibtex:editor>" + "<bibtex:bibtexkey>Clarkson06</bibtex:bibtexkey>"; writeManually(pdfFile, bibtexXPacket(bibtexDescription(bibtex))); assertEquals(bibtexXPacket(bibtexDescription(bibtex)), readManually(pdfFile)); } /** * Test that readXMP and writeXMP work together. * * @throws Exception */ public void testReadWriteXMP() throws Exception { ParserResult result = BibtexParser .parse(new StringReader( "@article{canh05," + " author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.}," + "\n" + " title = {Effective work practices for floss development: A model and propositions}," + "\n" + " booktitle = {Hawaii International Conference On System Sciences (HICSS)}," + "\n" + " year = {2005}," + "\n" + " owner = {oezbek}," + "\n" + " timestamp = {2006.05.29}," + "\n" + " url = {http://james.howison.name/publications.html}" + "\n" + "}")); Collection<BibtexEntry> c = result.getDatabase().getEntries(); assertEquals(1, c.size()); BibtexEntry e = (BibtexEntry) c.iterator().next(); XMPUtil.writeXMP(pdfFile, e, null); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry x = (BibtexEntry) l.get(0); assertEquals(e, x); } /** * Are newlines in the XML processed correctly? * * @throws Exception */ public void testNewlineHandling() throws Exception { { String bibtex = "<bibtex:title>\nHallo\nWorld \nthis \n is\n\nnot \n\nan \n\n exercise \n \n.\n \n\n</bibtex:title>\n" + "<bibtex:tabs>\nHallo\tWorld \tthis \t is\t\tnot \t\tan \t\n exercise \t \n.\t \n\t</bibtex:tabs>\n" + "<bibtex:abstract>\n\nAbstract preserve\n\t Whitespace\n\n</bibtex:abstract>"; writeManually(pdfFile, bibtexXPacket(bibtexDescription(bibtex))); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry e = (BibtexEntry) l.get(0); assertNotNull(e); assertEquals("Hallo World this is not an exercise .", e .getField("title")); assertEquals("Hallo World this is not an exercise .", e .getField("tabs")); assertEquals("\n\nAbstract preserve\n\t Whitespace\n\n", e .getField("abstract")); } } /** * Test whether XMP.readFile can deal with text-properties that are not * element-nodes, but attribute-nodes * * @throws Exception */ public void testAttributeRead() throws Exception { // test 1 has attributes String bibtex = t2XMP(); writeManually(pdfFile, bibtexXPacket(bibtex)); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry e = (BibtexEntry) l.get(0); assertEquals(t2BibtexEntry(), e); } public void testEmpty() throws Exception { assertEquals(null, XMPUtil.readXMP(pdfFile)); } /** * Tests whether writing BibTex.xmp will preserve existing XMP-descriptions. * * @throws Exception * (indicating an failure) */ @SuppressWarnings("unchecked") public void testSimpleUpdate() throws Exception { String s = " <rdf:Description rdf:about=''" + " xmlns:xmp='http://ns.adobe.com/xap/1.0/'>" + " <xmp:CreatorTool>Acrobat PDFMaker 7.0.7</xmp:CreatorTool>" + " <xmp:ModifyDate>2006-08-07T18:50:24+02:00</xmp:ModifyDate>" + " <xmp:CreateDate>2006-08-07T14:44:24+02:00</xmp:CreateDate>" + " <xmp:MetadataDate>2006-08-07T18:50:24+02:00</xmp:MetadataDate>" + " </rdf:Description>" + "" + " <rdf:Description rdf:about=''" + " xmlns:xapMM='http://ns.adobe.com/xap/1.0/mm/'>" + " <xapMM:DocumentID>uuid:843cd67d-495e-4c1e-a4cd-64178f6b3299</xapMM:DocumentID>" + " <xapMM:InstanceID>uuid:1e56b4c0-6782-440d-ba76-d2b3d87547d1</xapMM:InstanceID>" + " <xapMM:VersionID>" + " <rdf:Seq>" + " <rdf:li>17</rdf:li>" + " </rdf:Seq>" + " </xapMM:VersionID>" + " </rdf:Description>" + "" + " <rdf:Description rdf:about=''" + " xmlns:dc='http://purl.org/dc/elements/1.1/'>" + " <dc:format>application/pdf</dc:format>" + "</rdf:Description>"; writeManually(pdfFile, bibtexXPacket(s)); // Nothing there yet, but should not crash assertEquals(0, XMPUtil.readXMP(pdfFile).size()); s = " <rdf:Description rdf:about=''" + " xmlns:xmp='http://ns.adobe.com/xap/1.0/'>" + " <xmp:CreatorTool>Acrobat PDFMaker 7.0.7</xmp:CreatorTool>" + " <xmp:ModifyDate>2006-08-07T18:50:24+02:00</xmp:ModifyDate>" + " <xmp:CreateDate>2006-08-07T14:44:24+02:00</xmp:CreateDate>" + " <xmp:MetadataDate>2006-08-07T18:50:24+02:00</xmp:MetadataDate>" + " </rdf:Description>" + "" + " <rdf:Description rdf:about=''" + " xmlns:xapMM='http://ns.adobe.com/xap/1.0/mm/'>" + " <xapMM:DocumentID>uuid:843cd67d-495e-4c1e-a4cd-64178f6b3299</xapMM:DocumentID>" + " <xapMM:InstanceID>uuid:1e56b4c0-6782-440d-ba76-d2b3d87547d1</xapMM:InstanceID>" + " <xapMM:VersionID>" + " <rdf:Seq>" + " <rdf:li>17</rdf:li>" + " </rdf:Seq>" + " </xapMM:VersionID>" + " </rdf:Description>" + "" + " <rdf:Description rdf:about=''" + " xmlns:dc='http://purl.org/dc/elements/1.1/'>" + " <dc:format>application/pdf</dc:format>" + " <dc:title>" + " <rdf:Alt>" + " <rdf:li xml:lang='x-default'>Questionnaire.pdf</rdf:li>" + " </rdf:Alt>" + " </dc:title>" + "" + "</rdf:Description>"; writeManually(pdfFile, bibtexXPacket(s)); // Title is Questionnaire.pdf so the DublinCore fallback should hit assertEquals(1, XMPUtil.readXMP(pdfFile).size()); { // Now write new packet and check if it was correctly written XMPUtil.writeXMP(pdfFile, t1BibtexEntry(), null); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry e = (BibtexEntry) l.get(0); assertEquals(t1BibtexEntry(), e); // This is what we really want to test: Is the rest of the // descriptions still there? PDDocument document = null; try { document = PDDocument.load(pdfFile.getAbsoluteFile()); if (document.isEncrypted()) { throw new IOException( "Error: Cannot read metadata from encrypted document."); } PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata metaRaw = catalog.getMetadata(); XMPMetadata meta; if (metaRaw != null) { meta = new XMPMetadata(XMLUtil.parse(metaRaw .createInputStream())); } else { meta = new XMPMetadata(); } meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class); List<XMPSchema> schemas = meta.getSchemas(); assertEquals(4, schemas.size()); schemas = meta .getSchemasByNamespaceURI(XMPSchemaBibtex.NAMESPACE); assertEquals(1, schemas.size()); schemas = meta .getSchemasByNamespaceURI(XMPSchemaDublinCore.NAMESPACE); assertEquals(1, schemas.size()); XMPSchemaDublinCore dc = (XMPSchemaDublinCore) schemas.get(0); assertEquals("application/pdf", dc.getFormat()); schemas = meta .getSchemasByNamespaceURI(XMPSchemaBasic.NAMESPACE); assertEquals(1, schemas.size()); XMPSchemaBasic bs = (XMPSchemaBasic) schemas.get(0); assertEquals("Acrobat PDFMaker 7.0.7", bs.getCreatorTool()); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 2006); c.set(Calendar.MONTH, Calendar.AUGUST); c.set(Calendar.DATE, 7); c.set(Calendar.HOUR, 14); c.set(Calendar.MINUTE, 44); c.set(Calendar.SECOND, 24); c.setTimeZone(TimeZone.getTimeZone("GMT+2")); Calendar other = bs.getCreateDate(); assertEquals(c.get(Calendar.YEAR), other.get(Calendar.YEAR)); assertEquals(c.get(Calendar.MONTH), other.get(Calendar.MONTH)); assertEquals(c.get(Calendar.DATE), other.get(Calendar.DATE)); assertEquals(c.get(Calendar.HOUR), other.get(Calendar.HOUR)); assertEquals(c.get(Calendar.MINUTE), other.get(Calendar.MINUTE)); assertEquals(c.get(Calendar.SECOND), other.get(Calendar.SECOND)); assertTrue(c.getTimeZone().hasSameRules(other.getTimeZone())); schemas = meta .getSchemasByNamespaceURI(XMPSchemaMediaManagement.NAMESPACE); assertEquals(1, schemas.size()); XMPSchemaMediaManagement mm = (XMPSchemaMediaManagement) schemas .get(0); assertEquals("17", mm.getSequenceList("xapMM:VersionID").get(0)); } finally { if (document != null) { document.close(); } } } { // Now alter the Bibtex entry, write it and do all the checks again BibtexEntry toSet = t1BibtexEntry(); toSet.setField("author", "Pokemon!"); XMPUtil.writeXMP(pdfFile, toSet, null); List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry e = (BibtexEntry) l.get(0); assertEquals(toSet, e); // This is what we really want to test: Is the rest of the // descriptions still there? PDDocument document = null; try { document = PDDocument.load(pdfFile.getAbsoluteFile()); if (document.isEncrypted()) { throw new IOException( "Error: Cannot read metadata from encrypted document."); } PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata metaRaw = catalog.getMetadata(); XMPMetadata meta; if (metaRaw != null) { meta = new XMPMetadata(XMLUtil.parse(metaRaw .createInputStream())); } else { meta = new XMPMetadata(); } meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class); List schemas = meta.getSchemas(); assertEquals(4, schemas.size()); schemas = meta .getSchemasByNamespaceURI(XMPSchemaBibtex.NAMESPACE); assertEquals(1, schemas.size()); schemas = meta .getSchemasByNamespaceURI(XMPSchemaDublinCore.NAMESPACE); assertEquals(1, schemas.size()); XMPSchemaDublinCore dc = (XMPSchemaDublinCore) schemas.get(0); assertEquals("application/pdf", dc.getFormat()); schemas = meta .getSchemasByNamespaceURI(XMPSchemaBasic.NAMESPACE); assertEquals(1, schemas.size()); XMPSchemaBasic bs = (XMPSchemaBasic) schemas.get(0); assertEquals("Acrobat PDFMaker 7.0.7", bs.getCreatorTool()); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 2006); c.set(Calendar.MONTH, 7); c.set(Calendar.DATE, 7); c.set(Calendar.HOUR, 14); c.set(Calendar.MINUTE, 44); c.set(Calendar.SECOND, 24); c.setTimeZone(TimeZone.getTimeZone("GMT+2")); Calendar other = bs.getCreateDate(); assertEquals(c.get(Calendar.YEAR), other.get(Calendar.YEAR)); assertEquals(c.get(Calendar.MONTH), other.get(Calendar.MONTH)); assertEquals(c.get(Calendar.DATE), other.get(Calendar.DATE)); assertEquals(c.get(Calendar.HOUR), other.get(Calendar.HOUR)); assertEquals(c.get(Calendar.MINUTE), other.get(Calendar.MINUTE)); assertEquals(c.get(Calendar.SECOND), other.get(Calendar.SECOND)); assertTrue(c.getTimeZone().hasSameRules(other.getTimeZone())); schemas = meta .getSchemasByNamespaceURI(XMPSchemaMediaManagement.NAMESPACE); assertEquals(1, schemas.size()); XMPSchemaMediaManagement mm = (XMPSchemaMediaManagement) schemas .get(0); assertEquals("17", mm.getSequenceList("xapMM:VersionID").get(0)); } finally { if (document != null) { document.close(); } } } } /** * Is XML in text properties properly escaped? * * @throws Exception * */ public void testXMLEscape() throws Exception { ParserResult result = BibtexParser .parse(new StringReader( "@article{canh05," + " author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.}," + "\n" + " title = {</bibtex:title> \" bla \" '' '' && & for floss development: A model and propositions}," + "\n" + " booktitle = {<randomXML>}," + "\n" + " year = {2005}," + "\n" + " owner = {oezbek}," + "\n" + " timestamp = {2006.05.29}," + "\n" + " url = {http://james.howison.name/publications.html}" + "\n" + "}")); Collection<BibtexEntry> c = result.getDatabase().getEntries(); assertEquals(1, c.size()); BibtexEntry e = (BibtexEntry) c.iterator().next(); XMPUtil.writeXMP(pdfFile, e, null); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry x = (BibtexEntry) l.get(0); assertEquals(e, x); } public void assertEquals(BibtexEntry expected, BibtexEntry actual) { assertEquals(expected.getCiteKey(), actual.getCiteKey()); assertEquals(expected.getType(), actual.getType()); for (String field : expected.getAllFields()){ if (field.toString().toLowerCase().equals("author") || field.toString().toLowerCase().equals("editor")) { AuthorList expectedAuthors = AuthorList.getAuthorList(expected .getField(field.toString()).toString()); AuthorList actualAuthors = AuthorList.getAuthorList(actual .getField(field.toString()).toString()); assertEquals(expectedAuthors, actualAuthors); } else { assertEquals( "" + field.toString(), expected.getField(field.toString()).toString(), actual .getField(field.toString()).toString()); } } assertEquals(expected.getAllFields().size(), actual.getAllFields().size()); } /** * * @depends XMPUtilTest.testReadMultiple() */ public void testXMPreadString() throws Exception { ParserResult result = BibtexParser.parse(new StringReader( "@article{canh05," + " author = {Crowston, K. and Annabi, H.},\n" + " title = {Title A}}\n" + "@inProceedings{foo," + " author={Norton Bar}}")); Collection<BibtexEntry> c = result.getDatabase().getEntries(); assertEquals(2, c.size()); String xmp = XMPUtil.toXMP(c, null); /* Test minimal syntaxical completeness */ assertTrue(0 < xmp.indexOf("xpacket")); assertTrue(0 < xmp.indexOf("adobe:ns:meta")); assertTrue(0 < xmp .indexOf("<bibtex:bibtexkey>canh05</bibtex:bibtexkey>") || 0 < xmp.indexOf("bibtex:bibtexkey=")); assertTrue(0 < xmp.indexOf("<rdf:li>Norton Bar</rdf:li>")); assertTrue(0 < xmp.indexOf("id='W5M0MpCehiHzreSzNTczkc9d'?>") || 0 < xmp.indexOf("id=\"W5M0MpCehiHzreSzNTczkc9d\"?>")); assertTrue(0 < xmp .indexOf("xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns || 0 < xmp .indexOf("xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns assertTrue(0 < xmp.indexOf("<rdf:Description")); assertTrue(0 < xmp.indexOf("<?xpacket end='w'?>") || 0 < xmp.indexOf("<?xpacket end=\"w\"?>")); /* Test contents of string */ writeManually(pdfFile, xmp); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile); assertEquals(2, l.size()); BibtexEntry a = (BibtexEntry) l.get(0); BibtexEntry b = (BibtexEntry) l.get(1); if (a.getCiteKey().equals("foo")) { BibtexEntry tmp = a; a = b; b = tmp; } assertEquals("canh05", a.getCiteKey()); assertEquals("K. Crowston and H. Annabi", a.getField("author")); assertEquals("Title A", a.getField("title")); assertEquals(BibtexEntryType.ARTICLE, a.getType()); assertEquals("foo", b.getCiteKey()); assertEquals("Norton Bar", b.getField("author")); assertEquals(BibtexEntryType.INPROCEEDINGS, b.getType()); } /** * Tests whether it is possible to read several BibtexEntries * * @throws Exception * */ public void testReadMultiple() throws Exception { String bibtex = t2XMP() + t3XMP(); writeManually(pdfFile, bibtexXPacket(bibtex)); // Read from file List<BibtexEntry> l = XMPUtil.readXMP(pdfFile); assertEquals(2, l.size()); BibtexEntry a = (BibtexEntry) l.get(0); BibtexEntry b = (BibtexEntry) l.get(1); if (a.getCiteKey().equals("Clarkson06")) { BibtexEntry tmp = a; a = b; b = tmp; } assertEquals(t2BibtexEntry(), a); assertEquals(t3BibtexEntry(), b); } /** * Tests whether it is possible to write several Bibtexentries * * @throws TransformerException * @throws IOException * */ public void testWriteMultiple() throws IOException, TransformerException { List<BibtexEntry> l = new LinkedList<BibtexEntry>(); l.add(t2BibtexEntry()); l.add(t3BibtexEntry()); XMPUtil.writeXMP(pdfFile, l, null, false); l = XMPUtil.readXMP(pdfFile); assertEquals(2, l.size()); BibtexEntry a = l.get(0); BibtexEntry b = l.get(1); if (a.getCiteKey().equals("Clarkson06")) { BibtexEntry tmp = a; a = b; b = tmp; } assertEquals(t2BibtexEntry(), a); assertEquals(t3BibtexEntry(), b); } @SuppressWarnings("unchecked") public void testReadWriteDC() throws IOException, TransformerException { List<BibtexEntry> l = new LinkedList<BibtexEntry>(); l.add(t3BibtexEntry()); XMPUtil.writeXMP(pdfFile, l, null, true); PDDocument document = PDDocument.load(pdfFile.getAbsoluteFile()); try { if (document.isEncrypted()) { System.err .println("Error: Cannot add metadata to encrypted document."); System.exit(1); } assertEquals("Kelly Clarkson and Ozzy Osbourne", document .getDocumentInformation().getAuthor()); assertEquals("Hypersonic ultra-sound", document .getDocumentInformation().getTitle()); assertEquals("Huey Duck and Dewey Duck and Louie Duck", document .getDocumentInformation().getCustomMetadataValue( "bibtex/editor")); assertEquals("Clarkson06", document.getDocumentInformation() .getCustomMetadataValue("bibtex/bibtexkey")); assertEquals("peanut,butter,jelly", document .getDocumentInformation().getKeywords()); assertEquals(t3BibtexEntry(), XMPUtil .getBibtexEntryFromDocumentInformation(document .getDocumentInformation())); PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata metaRaw = catalog.getMetadata(); if (metaRaw == null) { fail(); } XMPMetadata meta = new XMPMetadata(XMLUtil.parse(metaRaw .createInputStream())); meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class); // Check Dublin Core List<XMPSchema> schemas = meta .getSchemasByNamespaceURI("http://purl.org/dc/elements/1.1/"); assertEquals(1, schemas.size()); XMPSchemaDublinCore dcSchema = (XMPSchemaDublinCore) schemas .iterator().next(); assertNotNull(dcSchema); assertEquals("Hypersonic ultra-sound", dcSchema.getTitle()); assertEquals("1982-07", dcSchema.getSequenceList("dc:date").get(0)); assertEquals("Kelly Clarkson", dcSchema.getCreators().get(0)); assertEquals("Ozzy Osbourne", dcSchema.getCreators().get(1)); assertEquals("Huey Duck", dcSchema.getContributors().get(0)); assertEquals("Dewey Duck", dcSchema.getContributors().get(1)); assertEquals("Louie Duck", dcSchema.getContributors().get(2)); assertEquals("Inproceedings", dcSchema.getTypes().get(0)); assertEquals("bibtex/bibtexkey/Clarkson06", dcSchema .getRelationships().get(0)); assertEquals("peanut", dcSchema.getSubjects().get(0)); assertEquals("butter", dcSchema.getSubjects().get(1)); assertEquals("jelly", dcSchema.getSubjects().get(2)); /** * Bibtexkey, Journal, pdf, booktitle */ assertEquals(4, dcSchema.getRelationships().size()); assertEquals(t3BibtexEntry(), XMPUtil .getBibtexEntryFromDublinCore(dcSchema)); } finally { document.close(); } } @SuppressWarnings("unchecked") public void testWriteSingleUpdatesDCAndInfo() throws IOException, TransformerException { List<BibtexEntry> l = new LinkedList<BibtexEntry>(); l.add(t3BibtexEntry()); XMPUtil.writeXMP(pdfFile, l, null, true); PDDocument document = PDDocument.load(pdfFile.getAbsoluteFile()); try { if (document.isEncrypted()) { System.err .println("Error: Cannot add metadata to encrypted document."); System.exit(1); } assertEquals("Kelly Clarkson and Ozzy Osbourne", document .getDocumentInformation().getAuthor()); assertEquals("Hypersonic ultra-sound", document .getDocumentInformation().getTitle()); assertEquals("Huey Duck and Dewey Duck and Louie Duck", document .getDocumentInformation().getCustomMetadataValue( "bibtex/editor")); assertEquals("Clarkson06", document.getDocumentInformation() .getCustomMetadataValue("bibtex/bibtexkey")); assertEquals("peanut,butter,jelly", document .getDocumentInformation().getKeywords()); assertEquals(t3BibtexEntry(), XMPUtil .getBibtexEntryFromDocumentInformation(document .getDocumentInformation())); PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata metaRaw = catalog.getMetadata(); if (metaRaw == null) { fail(); } XMPMetadata meta = new XMPMetadata(XMLUtil.parse(metaRaw .createInputStream())); meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class); // Check Dublin Core List<XMPSchema> schemas = meta .getSchemasByNamespaceURI("http://purl.org/dc/elements/1.1/"); assertEquals(1, schemas.size()); XMPSchemaDublinCore dcSchema = (XMPSchemaDublinCore) schemas .iterator().next(); assertNotNull(dcSchema); assertEquals("Hypersonic ultra-sound", dcSchema.getTitle()); assertEquals("1982-07", dcSchema.getSequenceList("dc:date").get(0)); assertEquals("Kelly Clarkson", dcSchema.getCreators().get(0)); assertEquals("Ozzy Osbourne", dcSchema.getCreators().get(1)); assertEquals("Huey Duck", dcSchema.getContributors().get(0)); assertEquals("Dewey Duck", dcSchema.getContributors().get(1)); assertEquals("Louie Duck", dcSchema.getContributors().get(2)); assertEquals("Inproceedings", dcSchema.getTypes().get(0)); assertEquals("bibtex/bibtexkey/Clarkson06", dcSchema .getRelationships().get(0)); assertEquals("peanut", dcSchema.getSubjects().get(0)); assertEquals("butter", dcSchema.getSubjects().get(1)); assertEquals("jelly", dcSchema.getSubjects().get(2)); /** * Bibtexkey, Journal, pdf, booktitle */ assertEquals(4, dcSchema.getRelationships().size()); assertEquals(t3BibtexEntry(), XMPUtil .getBibtexEntryFromDublinCore(dcSchema)); } finally { document.close(); } } @SuppressWarnings("unchecked") public void testReadRawXMP() throws Exception { ParserResult result = BibtexParser .parse(new StringReader( "@article{canh05," + " author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.},\n" + " title = {Effective work practices for floss development: A model and propositions},\n" + " booktitle = {Hawaii International Conference On System Sciences (HICSS)},\n" + " year = {2005},\n" + " owner = {oezbek},\n" + " timestamp = {2006.05.29},\n" + " url = {http://james.howison.name/publications.html}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); BibtexEntry e = (BibtexEntry) c.iterator().next(); XMPUtil.writeXMP(pdfFile, e, null); XMPMetadata metadata = XMPUtil.readRawXMP(pdfFile); List<XMPSchema> schemas = metadata.getSchemas(); assertEquals(2, schemas.size()); schemas = metadata.getSchemasByNamespaceURI(XMPSchemaBibtex.NAMESPACE); assertEquals(1, schemas.size()); XMPSchemaBibtex bib = (XMPSchemaBibtex) schemas.get(0); List<String> authors = bib.getSequenceList("author"); assertEquals(4, authors.size()); assertEquals("K. Crowston", authors.get(0)); assertEquals("H. Annabi", authors.get(1)); assertEquals("J. Howison", authors.get(2)); assertEquals("C. Masango", authors.get(3)); assertEquals("Article", bib.getTextProperty("entrytype")); assertEquals( "Effective work practices for floss development: A model and propositions", bib.getTextProperty("title")); assertEquals( "Hawaii International Conference On System Sciences (HICSS)", bib.getTextProperty("booktitle")); assertEquals("2005", bib.getTextProperty("year")); assertEquals("oezbek", bib.getTextProperty("owner")); assertEquals("http://james.howison.name/publications.html", bib .getTextProperty("url")); } /** * Test whether the command-line client works correctly with writing a * single entry * * @throws Exception * */ public void testCommandLineSingleBib() throws Exception { // First check conversion from .bib to .xmp File tempBib = File.createTempFile("JabRef", ".bib"); FileWriter fileWriter = null; try { fileWriter = new FileWriter(tempBib); fileWriter.write(t1BibtexString()); fileWriter.close(); ByteArrayOutputStream s = new ByteArrayOutputStream(); PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); XMPUtil.main(new String[] { tempBib.getAbsolutePath() }); System.setOut(oldOut); s.close(); String xmp = s.toString(); writeManually(pdfFile, xmp); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile); assertEquals(1, l.size()); assertEquals(t1BibtexEntry(), (BibtexEntry) l.get(0)); } finally { if (fileWriter != null) fileWriter.close(); if (tempBib != null) tempBib.delete(); } } /** * * * @depends XMPUtil.writeXMP * */ public void testCommandLineSinglePdf() throws Exception { { // Write XMP to file BibtexEntry e = t1BibtexEntry(); XMPUtil.writeXMP(pdfFile, e, null); ByteArrayOutputStream s = new ByteArrayOutputStream(); PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); XMPUtil.main(new String[] { pdfFile.getAbsolutePath() }); System.setOut(oldOut); s.close(); String bibtex = s.toString(); ParserResult result = BibtexParser.parse(new StringReader(bibtex)); Collection<BibtexEntry> c = result.getDatabase().getEntries(); assertEquals(1, c.size()); BibtexEntry x = (BibtexEntry) c.iterator().next(); assertEquals(e, x); } { // Write XMP to file BibtexEntry e = t1BibtexEntry(); XMPUtil.writeXMP(pdfFile, e, null); ByteArrayOutputStream s = new ByteArrayOutputStream(); PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); XMPUtil.main(new String[] { "-x", pdfFile.getAbsolutePath() }); System.setOut(oldOut); s.close(); String xmp = s.toString(); /* Test minimal syntaxical completeness */ assertTrue(0 < xmp.indexOf("xpacket")); assertTrue(0 < xmp.indexOf("adobe:ns:meta")); assertTrue(0 < xmp .indexOf("<bibtex:bibtexkey>canh05</bibtex:bibtexkey>") || 0 < xmp.indexOf("bibtex:bibtexkey=")); assertTrue(0 < xmp.indexOf("<rdf:li>K. Crowston</rdf:li>")); assertTrue(0 < xmp.indexOf("id='W5M0MpCehiHzreSzNTczkc9d'?>") || 0 < xmp.indexOf("id=\"W5M0MpCehiHzreSzNTczkc9d\"?>")); assertTrue(0 < xmp .indexOf("xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns || 0 < xmp .indexOf("xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns assertTrue(0 < xmp.indexOf("<rdf:Description")); assertTrue(0 < xmp.indexOf("<?xpacket end='w'?>") || 0 < xmp.indexOf("<?xpacket end=\"w\"?>")); /* Test contents of string */ writeManually(pdfFile, xmp); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile); assertEquals(1, l.size()); assertEquals(t1BibtexEntry(), (BibtexEntry) l.get(0)); } } /** * Test whether the command-line client can pick one of several entries from * a bibtex file * * @throws Exception * */ public void testCommandLineByKey() throws Exception { File tempBib = File.createTempFile("JabRef", ".bib"); FileWriter fileWriter = null; try { fileWriter = new FileWriter(tempBib); fileWriter.write(t1BibtexString()); fileWriter.write(t2BibtexString()); fileWriter.close(); { // First try canh05 ByteArrayOutputStream s = new ByteArrayOutputStream(); PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); XMPUtil.main(new String[] { "canh05", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath() }); System.setOut(oldOut); s.close(); // PDF should be annotated: List<BibtexEntry> l = XMPUtil.readXMP(pdfFile); assertEquals(1, l.size()); assertEquals(t1BibtexEntry(), (BibtexEntry) l.get(0)); } { // Now try OezbekC06 ByteArrayOutputStream s = new ByteArrayOutputStream(); PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); XMPUtil.main(new String[] { "OezbekC06", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath() }); System.setOut(oldOut); s.close(); // PDF should be annotated: List<BibtexEntry> l = XMPUtil.readXMP(pdfFile); assertEquals(1, l.size()); assertEquals(t2BibtexEntry(), (BibtexEntry) l.get(0)); } } finally { if (fileWriter != null) fileWriter.close(); if (tempBib != null) tempBib.delete(); } } /** * Test whether the command-line client can deal with several bibtex * entries. * */ public void testCommandLineSeveral() throws Exception { File tempBib = File.createTempFile("JabRef", ".bib"); FileWriter fileWriter = null; try { fileWriter = new FileWriter(tempBib); fileWriter.write(t1BibtexString()); fileWriter.write(t3BibtexString()); fileWriter.close(); ByteArrayOutputStream s = new ByteArrayOutputStream(); PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); XMPUtil.main(new String[] { tempBib.getAbsolutePath(), pdfFile.getAbsolutePath() }); System.setOut(oldOut); s.close(); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile); assertEquals(2, l.size()); BibtexEntry a = (BibtexEntry) l.get(0); BibtexEntry b = (BibtexEntry) l.get(1); if (a.getCiteKey().equals("Clarkson06")) { BibtexEntry tmp = a; a = b; b = tmp; } BibtexEntry t1 = t1BibtexEntry(); BibtexEntry t3 = t3BibtexEntry(); // Writing and reading will resolve strings! t3.setField("month", "July"); assertEquals(t1, a); assertEquals(t3, b); } finally { if (fileWriter != null) fileWriter.close(); if (tempBib != null) tempBib.delete(); } } /** * Test that readXMP and writeXMP work together. * * @throws Exception */ public void testResolveStrings() throws Exception { ParserResult original = BibtexParser .parse(new StringReader( "@string{ crow = \"Crowston, K.\"}\n" + "@string{ anna = \"Annabi, H.\"}\n" + "@string{ howi = \"Howison, J.\"}\n" + "@string{ masa = \"Masango, C.\"}\n" + "@article{canh05," + " author = {#crow# and #anna# and #howi# and #masa#}," + "\n" + " title = {Effective work practices for floss development: A model and propositions}," + "\n" + " booktitle = {Hawaii International Conference On System Sciences (HICSS)}," + "\n" + " year = {2005}," + "\n" + " owner = {oezbek}," + "\n" + " timestamp = {2006.05.29}," + "\n" + " url = {http://james.howison.name/publications.html}" + "\n" + "}")); Collection<BibtexEntry> c = original.getDatabase().getEntries(); assertEquals(1, c.size()); BibtexEntry e = (BibtexEntry) c.iterator().next(); XMPUtil.writeXMP(pdfFile, e, original.getDatabase()); List<BibtexEntry> l = XMPUtil.readXMP(pdfFile.getAbsoluteFile()); assertEquals(1, l.size()); BibtexEntry x = (BibtexEntry) l.get(0); assertEquals( AuthorList .getAuthorList("Crowston, K. and Annabi, H. and Howison, J. and Masango, C."), AuthorList.getAuthorList(x.getField("author").toString())); } /** * Test that we cannot use encrypted PDFs. */ public void testEncryption() throws Exception { // // PDF was created using: // PDDocument pdf = null; // try { // pdf = new PDDocument(); // pdf.addPage(new PDPage()); // Need page to open in Acrobat // pdf.encrypt("hello", "world"); // pdf.save("d:/download/encrypted.pdf"); // } finally { // if (pdf != null) // pdf.close(); try { XMPUtil.readXMP("src/tests/encrypted.pdf"); fail(); } catch (EncryptionNotSupportedException e) { } try { XMPUtil.writeXMP("src/tests/encrypted.pdf", t1BibtexEntry(), null); fail(); } catch (EncryptionNotSupportedException e) { } } /** * A better testcase for resolveStrings. Makes sure that also the document * information and dublin core are written correctly. * * Data was contributed by Philip K.F. Hlzenspies (p.k.f.holzenspies [at] utwente.nl). * * @throws IOException * @throws FileNotFoundException * @throws TransformerException * */ @SuppressWarnings("unchecked") public void testResolveStrings2() throws FileNotFoundException, IOException, TransformerException { ParserResult result = BibtexParser.parse(new FileReader( "src/tests/net/sf/jabref/util/twente.bib")); assertEquals("Arvind", result.getDatabase().resolveForStrings( "#Arvind#")); AuthorList originalAuthors = AuthorList .getAuthorList("Patterson, David and Arvind and Asanov\\'\\i{}c, Krste and Chiou, Derek and Hoe, James and Kozyrakis, Christos and Lu, S{hih-Lien} and Oskin, Mark and Rabaey, Jan and Wawrzynek, John"); try { XMPUtil.writeXMP(pdfFile, result.getDatabase().getEntryByKey( "Patterson06"), result.getDatabase()); // Test whether we the main function can load the bibtex correctly BibtexEntry b = XMPUtil.readXMP(pdfFile).get(0); assertEquals(originalAuthors, AuthorList.getAuthorList(b.getField( "author").toString())); // Next check from Document Information PDDocument document = PDDocument.load(pdfFile.getAbsoluteFile()); try { assertEquals(originalAuthors, AuthorList.getAuthorList(document .getDocumentInformation().getAuthor())); b = XMPUtil.getBibtexEntryFromDocumentInformation(document .getDocumentInformation()); assertEquals(originalAuthors, AuthorList.getAuthorList(b .getField("author").toString())); // Now check from Dublin Core PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata metaRaw = catalog.getMetadata(); if (metaRaw == null) { fail(); } XMPMetadata meta = new XMPMetadata(XMLUtil.parse(metaRaw .createInputStream())); meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class); List<XMPSchema> schemas = meta .getSchemasByNamespaceURI("http://purl.org/dc/elements/1.1/"); assertEquals(1, schemas.size()); XMPSchemaDublinCore dcSchema = (XMPSchemaDublinCore) schemas .iterator().next(); assertNotNull(dcSchema); assertEquals("David Patterson", dcSchema.getCreators().get(0)); assertEquals("Arvind", dcSchema.getCreators().get(1)); assertEquals("Krste Asanov\\'\\i{}c", dcSchema.getCreators() .get(2)); b = XMPUtil.getBibtexEntryFromDublinCore(dcSchema); assertEquals(originalAuthors, AuthorList.getAuthorList(b .getField("author").toString())); } finally { document.close(); } } finally { pdfFile.delete(); } } /** * Read the contents of a reader as one string * * @param reader * @return * @throws IOException */ public static String slurp(Reader reader) throws IOException { char[] chars = new char[4092]; StringBuffer totalBuffer = new StringBuffer(); int bytesRead; while ((bytesRead = reader.read(chars)) != -1) { if (bytesRead == 4092) { totalBuffer.append(chars); } else { totalBuffer.append(new String(chars, 0, bytesRead)); } } return totalBuffer.toString(); } }
package mm.da; import java.sql.Statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import mm.model.Mentee; import mm.model.Mentor; import mm.model.TsofenT; import mm.model.User; import mm.model.User.userType; public class DataAccess { private static boolean isLoadedDriver; static { try { Class.forName("com.mysql.jdbc.Driver"); isLoadedDriver = true; } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); isLoadedDriver = false; } } final String url = "jdbc:mysql://node4644-env-8285750.elastyco.com:3600/db"; private Connection c; final String selectLogin = "Select * From users where email=?"; final String selectLogin1 = "Select * From mentor where id=?"; final String selectLogin2 = "Select * From mentee where id=?"; public DataAccess() { try { if(isLoadedDriver){ c = DriverManager.getConnection(url, "root", "ESEahn57327"); // TODO: when in // production // make sure to // have valid // credentials } } catch (SQLException e) { e.printStackTrace(); } } public User login(String email) throws SQLException { PreparedStatement stm = c.prepareStatement(selectLogin); stm.setString(1, email); ResultSet rs = stm.executeQuery(); User u = null; if (rs.next()) { int type = rs.getInt(2); switch (type) { case 0: break; case 1: u = new TsofenT(rs.getInt(1), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getBoolean(11), userType.TSOFEN); break; case 2: PreparedStatement stm2 = c.prepareStatement(selectLogin1); stm2.setInt(1, rs.getInt(1)); ResultSet rs2 = stm.executeQuery(); u = new Mentor(rs.getInt(1), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getBoolean(11), userType.MENTOR, rs2.getString(2), rs2.getString(3), rs2.getInt(4), rs2.getString(5), rs2.getString(6)); break; case 3: PreparedStatement stm3 = c.prepareStatement(selectLogin2); stm3.setInt(1, rs.getInt(1)); ResultSet rs3 = stm.executeQuery(); u = new Mentee(rs.getInt(1), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getBoolean(11), userType.MENTEE, rs3.getFloat(2), rs3.getString(3), rs3.getString(4), rs3.getFloat(5), rs3.getString(6), rs3.getString(7), rs3.getBoolean(8)); break; default: break; } } return u; } }
package justaway.signinwithtwitter; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Locale; import twitter4j.DirectMessage; import twitter4j.MediaEntity; import twitter4j.Status; import twitter4j.User; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v4.util.LruCache; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; public class TwitterAdapter extends ArrayAdapter<Row> { private Context context; private ArrayList<Row> statuses = new ArrayList<Row>(); private LayoutInflater inflater; private int layout; private LruCache<String, Bitmap> mMemoryCache; private static int limit = 500; public TwitterAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); this.inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.context = context; this.layout = textViewResourceId; // Get max available VM memory, exceeding this amount will throw an // OutOfMemory exception. Stored in kilobytes as LruCache takes an // int in its constructor. final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. final int cacheSize = maxMemory / 2; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @SuppressLint("NewApi") @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size will be measured in kilobytes rather than // number of items. return bitmap.getByteCount() / 1024; } }; } @Override public void add(Row row) { super.add(row); this.statuses.add(row); this.limitation(); } @Override public void insert(Row row, int index) { super.insert(row, index); this.statuses.add(index, row); this.limitation(); } public void limitation() { int size = this.statuses.size(); if (size > limit) { int count = size - limit; for (int i = 0; i < count; i++) { super.remove(this.statuses.remove(size - i - 1)); } } } @Override public void clear() { super.clear(); this.statuses.clear(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { // null view = inflater.inflate(this.layout, null); } Row row = (Row) statuses.get(position); if (row.isDirectMessage()) { DirectMessage message = row.getMessage(); if (message == null) { return view; } renderMessage(view, message); } else { Status status = row.getStatus(); if (status == null) { return view; } Status retweet = status.getRetweetedStatus(); if (row.isFavorite()) { renderStatus(view, status, null, row.getSource()); } else if (retweet == null) { renderStatus(view, status, null, null); } else { renderStatus(view, retweet, status, null); } } if (position == 0) { ((MainActivity) context).showTopView(); } return view; } private void renderMessage(View view, DirectMessage message) { ((TextView) view.findViewById(R.id.display_name)).setText(message .getSender().getName()); ((TextView) view.findViewById(R.id.screen_name)).setText("@" + message.getSender().getScreenName()); ((TextView) view.findViewById(R.id.status)).setText("D " + message.getRecipientScreenName() + " " + message.getText()); SimpleDateFormat date_format = new SimpleDateFormat( "MM'/'dd' 'hh':'mm':'ss", Locale.ENGLISH); ((TextView) view.findViewById(R.id.datetime)).setText(date_format .format(message.getCreatedAt())); view.findViewById(R.id.via).setVisibility(View.GONE); view.findViewById(R.id.retweet).setVisibility(View.GONE); view.findViewById(R.id.images).setVisibility(View.GONE); ImageView icon = (ImageView) view.findViewById(R.id.icon); ProgressBar wait = (ProgressBar) view.findViewById(R.id.WaitBar); renderIcon(wait, icon, message.getSender().getBiggerProfileImageURL()); } private void renderStatus(View view, Status status, Status retweet, User favorite) { ((TextView) view.findViewById(R.id.display_name)).setText(status .getUser().getName()); ((TextView) view.findViewById(R.id.screen_name)).setText("@" + status.getUser().getScreenName()); ((TextView) view.findViewById(R.id.status)).setText(status.getText()); SimpleDateFormat date_format = new SimpleDateFormat( "MM'/'dd' 'hh':'mm':'ss", Locale.ENGLISH); ((TextView) view.findViewById(R.id.datetime)).setText(date_format .format(status.getCreatedAt())); ((TextView) view.findViewById(R.id.via)).setText("via " + getClientName(status.getSource())); view.findViewById(R.id.via).setVisibility(View.VISIBLE); // fav if (favorite != null) { ((TextView) view.findViewById(R.id.retweet_by)) .setText("favorited by " + favorite.getScreenName() + "(" + favorite.getName() + ")"); ImageView icon = (ImageView) view.findViewById(R.id.retweet_icon); ProgressBar wait = (ProgressBar) view .findViewById(R.id.retweet_wait); renderIcon(wait, icon, favorite.getMiniProfileImageURL()); view.findViewById(R.id.retweet).setVisibility(View.VISIBLE); } else if (retweet != null) { ((TextView) view.findViewById(R.id.retweet_by)) .setText("retweeted by " + retweet.getUser().getScreenName() + "(" + retweet.getUser().getName() + ") and " + String.valueOf(status.getRetweetCount()) + " others"); ImageView icon = (ImageView) view.findViewById(R.id.retweet_icon); ProgressBar wait = (ProgressBar) view .findViewById(R.id.retweet_wait); renderIcon(wait, icon, retweet.getUser().getMiniProfileImageURL()); view.findViewById(R.id.retweet).setVisibility(View.VISIBLE); } else { view.findViewById(R.id.retweet).setVisibility(View.GONE); } ImageView icon = (ImageView) view.findViewById(R.id.icon); ProgressBar wait = (ProgressBar) view.findViewById(R.id.WaitBar); renderIcon(wait, icon, status.getUser().getBiggerProfileImageURL()); icon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO: UserProfileActivity System.out.println("icon touch!"); } }); MediaEntity[] medias = retweet != null ? retweet.getMediaEntities() : status.getMediaEntities(); LinearLayout images = (LinearLayout) view.findViewById(R.id.images); images.removeAllViews(); if (medias.length > 0) { for (final MediaEntity url : medias) { ImageView image = new ImageView(context); image.setScaleType(ImageView.ScaleType.CENTER_CROP); images.addView(image, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, 120)); renderIcon(null, image, url.getMediaURL()); image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ImageView imageView = new ImageView(context); Dialog dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(imageView); renderIcon(null, imageView, url.getMediaURL()); dialog.show(); } }); } images.setVisibility(View.VISIBLE); } else { images.setVisibility(View.GONE); } } private void renderIcon(ProgressBar wait, ImageView icon, String url) { if (wait != null) { wait.setVisibility(View.VISIBLE); } icon.setVisibility(View.GONE); String tag = (String) icon.getTag(); if (tag != null && tag == url) { } else { icon.setTag(url); Bitmap image = mMemoryCache.get(url); if (image == null) { ImageGetTask task = new ImageGetTask(icon, wait); task.execute(url); } else { icon.setImageBitmap(image); icon.setVisibility(View.VISIBLE); if (wait != null) { wait.setVisibility(View.GONE); } } } } private String getClientName(String source) { String[] tokens = source.split("[<>]"); if (tokens.length > 1) { return tokens[2]; } else { return tokens[0]; } } class ImageGetTask extends AsyncTask<String, Void, Bitmap> { private ImageView image; private String tag; private ProgressBar bar; public ImageGetTask(ImageView image, ProgressBar bar) { this.image = image; this.bar = bar; this.tag = image.getTag().toString(); } @Override protected Bitmap doInBackground(String... params) { // HttpBitmap synchronized (context) { try { URL imageUrl = new URL(params[0]); InputStream imageIs; imageIs = imageUrl.openStream(); Bitmap bitmap = BitmapFactory.decodeStream(imageIs); return bitmap; } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } } } @Override protected void onPostExecute(Bitmap bitmap) { // Tag // Tag if (tag.equals(image.getTag())) { if (bitmap != null) { mMemoryCache.put(tag, bitmap); image.setImageBitmap(bitmap); } else { // image.setImageDrawable(context.getResources().getDrawable( // R.drawable.x)); } image.setVisibility(View.VISIBLE); if (bar != null) { bar.setVisibility(View.GONE); } } } } }
package com.phr.main; import com.badlogic.gdx.Game; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Rectangle; import com.phr.main.screens.GameScreen; public class PixHellGame extends Game { public static final int ENEMY_SPAWN = 1; public static final int VIRTUAL_WIDTH = 500; public static final int VIRTUAL_HEIGHT = 800; public static final float ASPECT_RATIO = ((float) VIRTUAL_WIDTH) / ((float) VIRTUAL_HEIGHT); public Rectangle viewport; public static final int MAX_Y = 350; public static final int MIN_Y = 20; // SB used for drawing sprites public SpriteBatch batch; @Override public void create() { batch = new SpriteBatch(); this.setScreen(new GameScreen(this)); } @Override public void render() { super.render(); } @Override public void dispose() { batch.dispose(); } }
package com.kk.bus; /** * Bus interface class. * * @author Jiri Krivanek */ public class Bus { private final RegisteredEvents mRegisteredEvents = new RegisteredEvents(); /** * Registers an object with the event bus. * <p/> * <dl><dt><b>Note:</b></dt><dd>Registering the same object more than once has no effect (no reference * counting).</dd></dl> * <p/> * The register method is called for the specified object from within certain {@link DeliveryContext}. The events * for that object will be delivered from within the same context. * * @param objectToRegister * The object to register to the event bus. */ public void register(Object objectToRegister) { mRegisteredEvents.register(this, objectToRegister); } /** * Unregisters the object from the event bus. * <p/> * <dl><dt><b>Note:</b></dt><dd>Unregistering the object which was not registered (or was already unregistered) has * no effect.</dd></dl> * <p/> * <dl><dt><b>Attention:</b></dt><dd>Unregister method MUST be called from the same thread from which the register * was called, otherwise race conditions may happen.</dd></dl> * * @param objectToUnregister * The object to unregister from the event bus. */ public void unregister(Object objectToUnregister) { mRegisteredEvents.unregister(objectToUnregister); } /** * Posts an event to the event bus. * <p/> * The event will be delivered to all registered objects. The delivery will occurs on the {@link DeliveryContext} on * which the {@link #register(Object)} method was called for that delivery context. * * @param event * The event to post to the event bus. */ public void post(Object event) { mRegisteredEvents.post(event); } }
package net.databinder.models; import java.util.Iterator; import net.databinder.DataStaticService; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Projections; import org.apache.wicket.markup.repeater.data.IDataProvider; import org.apache.wicket.model.BoundCompoundPropertyModel; import org.apache.wicket.model.IModel; /** * Provides query results to DataView and related components. Like the Hibernate model classes, * the results of this provider can be altered by query binders and criteria builders. By default * this provider wraps items in a compound property model in addition to a Hibernate model. * This is convenient for mapping DataView subcomponents as bean properties (as with * PropertyListView). However, <b>DataTable will not work with a compound property model.</b> * Call setWrapWithPropertyModel(false) when using with DataTable, DataGridView, or any * other time you do not want a compound property model. * @author Nathan Hamblen */ public class DatabinderProvider implements IDataProvider { private Class objectClass; private ICriteriaBuilder criteriaBuilder, sortCriteriaBuilder; private String queryString, countQueryString; private IQueryBinder queryBinder, countQueryBinder; /** Controls wrapping with a compound property model. */ private boolean wrapWithPropertyModel = true; private Object factoryKey; /** * Provides all entities of the given class. */ public DatabinderProvider(Class objectClass) { this.objectClass = objectClass; } /** * Provides entities of the given class meeting the supplied criteria. */ public DatabinderProvider(Class objectClass, ICriteriaBuilder criteriaBuilder) { this(objectClass); this.criteriaBuilder = criteriaBuilder; } /** * Provides entities of the given class meeting the supplied critiera and sort criteria. The * sort criteria is not applied to the count query (as it should not affect the count). When returning * results it is applied in addition to the standard criteria, so it is not necessary to duplicate * filter or other criteria in the sort criteria. * @param criteriaBuilder standard criteria applied to both the count and actual results * @param sortCriteriaBuilder sort criteria applied only to the actual results */ public DatabinderProvider(Class objectClass, ICriteriaBuilder criteriaBuilder, ICriteriaBuilder sortCriteriaBuilder) { this(objectClass, criteriaBuilder); this.sortCriteriaBuilder = sortCriteriaBuilder; } /** * Provides entities matching the given query. The count query * is derived by prefixing "select count(*)" to the given query; this will fail if * the supplied query has a select clause. */ public DatabinderProvider(String query) { this.queryString = query; } /** * Provides entities matching the given queries. */ public DatabinderProvider(String query, String countQuery) { this.queryString = query; this.countQueryString = countQuery; } /** * Provides entities matching the given query with bound parameters. The count query * is derived by prefixing "select count(*)" to the given query; this will fail if * the supplied query has a select clause. */ public DatabinderProvider(String query, IQueryBinder queryBinder) { this(query); this.queryBinder = queryBinder; } /** * Provides entities matching the given queries with bound parameters. * @param query query to return entities * @param queryBinder binder for the standard query * @param countQuery query to return count of entities * @param countQueryBinder binder for the count query (may be same as queryBinder) */ public DatabinderProvider(String query, IQueryBinder queryBinder, String countQuery, IQueryBinder countQueryBinder) { this(query, queryBinder); this.countQueryString = countQuery; this.countQueryBinder = countQueryBinder; } /** @return session factory key, or null for the default factory */ public Object getFactoryKey() { return factoryKey; } /** * Set a factory key other than the default (null). * @param session factory key * @return this, for chaining */ public DatabinderProvider setFactoryKey(Object key) { this.factoryKey = key; return this; } /** Used only by deprecated subclasses. Please ignore. */ protected void setCriteriaBuilder(ICriteriaBuilder criteriaBuilder) { this.criteriaBuilder = criteriaBuilder; } /** Used only by deprecated subclasses. Please ignore. */ protected void setSortCriteriaBuilder(ICriteriaBuilder sortCriteriaBuilder) { this.sortCriteriaBuilder = sortCriteriaBuilder; } /** Used only by deprecated subclasses. Please ignore. */ protected void setQueryBinder(IQueryBinder queryBinder) { this.queryBinder = queryBinder; } /** * It should not be necessary to override (or call) this default implementation. */ public final Iterator iterator(int first, int count) { Session sess = DataStaticService.getHibernateSession(factoryKey); if (queryString != null) { org.hibernate.Query q = sess.createQuery(queryString); if (queryBinder != null) queryBinder.bind(q); q.setFirstResult(first); q.setMaxResults(count); return q.iterate(); } Criteria crit = sess.createCriteria(objectClass); if (criteriaBuilder != null) criteriaBuilder.build(crit); if (sortCriteriaBuilder != null) sortCriteriaBuilder.build(crit); crit.setFirstResult(first); crit.setMaxResults(count); return crit.list().iterator(); } /** * It should not be necessary to override (or call) this default implementation. */ public final int size() { Session sess = DataStaticService.getHibernateSession(factoryKey); if (countQueryString != null) { Query query = sess.createQuery(countQueryString); if (countQueryBinder != null) countQueryBinder.bind(query); return ((Long) query.uniqueResult()).intValue(); } if (queryString != null) { String synthCountQuery = "select count(*) " + queryString; Query query = sess.createQuery(synthCountQuery); if (queryBinder != null) queryBinder.bind(query); return ((Long) query.uniqueResult()).intValue(); } Criteria crit = sess.createCriteria(objectClass); if (criteriaBuilder != null) criteriaBuilder.build(crit); crit.setProjection(Projections.rowCount()); Integer size = (Integer) crit.uniqueResult(); return size == null ? 0 : size; } /** * @return true if wrapping items with a compound property model (the default) */ public boolean getWrapWithPropertyModel() { return wrapWithPropertyModel; } /** * @param wrapInCompoundModel false to not wrap items in a compound property model (true is default) */ public void setWrapWithPropertyModel(boolean wrapInCompoundModel) { this.wrapWithPropertyModel = wrapInCompoundModel; } /** * Wraps object in HiberanteObjectModel, and also BoundCompoundPropertyModel if * wrapInCompoundModel is true. * @param object object DataView would like to wrap * @return object wrapped in a HibernateObjectModel and possibly BoundCompoundPropertyModel */ public IModel model(Object object) { HibernateObjectModel model = new HibernateObjectModel(object); return wrapWithPropertyModel ? new BoundCompoundPropertyModel(model) : model; } /** * Please use the base DatabinderProvider with independent criteria builders. This subclass * will be removed in a future release. * @deprecated */ public static abstract class CriteriaBuilder extends DatabinderProvider implements ICriteriaBuilder { public CriteriaBuilder(Class objectClass) { super(objectClass); setCriteriaBuilder(this); setSortCriteriaBuilder(new ICriteriaBuilder() { public void build(Criteria criteria) { sort(criteria); } }); setWrapWithPropertyModel(false); } protected void sort(Criteria crit) { } } /** * Please use the base DatabinderProvider with independent query binders. This subclass * will be removed from a future release. * @deprecated */ public static abstract class QueryBinder extends DatabinderProvider implements IQueryBinder { String queryString; public QueryBinder(String queryString) { super(queryString); setQueryBinder(this); setWrapWithPropertyModel(false); } /** * This method will not be called. Please use the base DatabinderProvider. */ protected final String count (String queryString) { return null; } /** * This method will not be called. Please use the base DatabinderProvider. */ protected final String sort(String queryString) { return null; } } /** This provider has nothing to detach. */ public void detach() { } }
package cc.adjusting.piece; import java.awt.BasicStroke; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import cc.adjusting.ChineseCharacterTypeAdjuster; import cc.moveable_type.ChineseCharacterMovableTypeTzu; import cc.moveable_type.ChineseCharacterMovableTypeWen; import cc.moveable_type.piece.PieceMovableType; import cc.moveable_type.piece.PieceMovableTypeTzu; import cc.moveable_type.piece.PieceMovableTypeWen; import cc.moveable_type.rectangular_area.RectangularArea; /** * @author Ihc * */ public class SimplePieceAdjuster implements ChineseCharacterTypeAdjuster { /** * (non-Javadoc) * * @see cc.adjusting.ChineseCharacterTypeAdjuster#adjustWen(cc.moveable_type. * ChineseCharacterMovableTypeWen) */ @Override public void adjustWen( ChineseCharacterMovableTypeWen chineseCharacterMovableTypeWen) { PieceMovableTypeWen pieceMovableTypeWen = (PieceMovableTypeWen) chineseCharacterMovableTypeWen; RectangularArea rectangularArea = pieceMovableTypeWen.getPiece(); AffineTransform affineTransform = getAffineTransform(rectangularArea);// TODO shrinkPieceByFixingStroke(rectangularArea, affineTransform); return; } /** * (non-Javadoc) * * @see cc.adjusting.ChineseCharacterTypeAdjuster#adjustTzu(cc.moveable_type. * ChineseCharacterMovableTypeTzu) */ @Override public void adjustTzu(ChineseCharacterMovableTypeTzu tzu) { PieceMovableTypeTzu pieceMovableTypeTzu = (PieceMovableTypeTzu) tzu; RectangularArea rectangularArea = pieceMovableTypeTzu.getPiece(); AffineTransform affineTransform = getAffineTransform(rectangularArea); rectangularArea.transform(affineTransform); for (int i = 0; i < pieceMovableTypeTzu.getChildren().length; ++i) { PieceMovableType child = (PieceMovableType) pieceMovableTypeTzu .getChildren()[i]; Rectangle2D childTerritory = child.getPiece().getTerritory(); childTerritory.setRect( childTerritory.getX() * affineTransform.getScaleX(), childTerritory.getY() * affineTransform.getScaleY(), childTerritory.getWidth() * affineTransform.getScaleX(), childTerritory.getHeight() * affineTransform.getScaleY()); pieceMovableTypeTzu.getChildren()[i].adjust(this); } } /** * rectangularArea * * @param rectangularArea * * @return */ protected AffineTransform getAffineTransform(RectangularArea rectangularArea) { Rectangle2D territory = rectangularArea.getTerritory(); Rectangle2D bounds = rectangularArea.getBounds2D(); AffineTransform affineTransform = new AffineTransform(); affineTransform.setToScale(territory.getWidth() / bounds.getWidth(), territory.getHeight() / bounds.getHeight()); return affineTransform; } protected double computeBoldCoefficient(RectangularArea rectangularArea) { ShapeInformation shapeInformation = new ShapeInformation( rectangularArea); return shapeInformation.getApproximativeRegion() / shapeInformation.getApproximativeCircumference(); } protected float getStorkeWidthByCoefficient( RectangularArea rectangularArea, double originBoldCoefficient) { float miniWidth = 0.0f, maxiWidth = (float) originBoldCoefficient; while (miniWidth + getPrecision() < maxiWidth) { float middleWidth = 0.5f * (miniWidth + maxiWidth); RectangularArea boldSurface = getBoldSurface(rectangularArea, middleWidth); boldSurface.add(rectangularArea); double nowBoldCoefficient = computeBoldCoefficient(boldSurface); // System.out.println("now=" + nowBoldCoefficient + " mini=" // + miniWidth + " maxi=" + maxiWidth); if (nowBoldCoefficient < originBoldCoefficient) miniWidth = middleWidth; else maxiWidth = middleWidth; } return miniWidth; } protected RectangularArea getBoldSurface(RectangularArea rectangularArea, float strokeWidth) { Stroke basicStroke = new BasicStroke(strokeWidth); return new RectangularArea( basicStroke.createStrokedShape(rectangularArea)); } protected void shrinkPieceByFixingStroke(RectangularArea rectangularArea, AffineTransform affineTransform) { // javadoc double originBoldCoefficient = computeBoldCoefficient(rectangularArea); rectangularArea.transform(affineTransform); float strokeWidth = getStorkeWidthByCoefficient(rectangularArea, originBoldCoefficient); RectangularArea boldSurface = getBoldSurface(rectangularArea, strokeWidth); rectangularArea.add(boldSurface); return; } public double getPrecision() { return 1e-1; } }
package chord.analyses.logsite; import java.util.List; import joeq.Class.jq_Method; import joeq.Compiler.Quad.BasicBlock; import joeq.Compiler.Quad.ControlFlowGraph; import joeq.Compiler.Quad.Operand.RegisterOperand; import joeq.Compiler.Quad.RegisterFactory.Register; import joeq.Compiler.Quad.Quad; import lombok.Data; import chord.project.Chord; import chord.project.ClassicProject; import chord.project.analyses.JavaAnalysis; import chord.project.analyses.ProgramRel; import com.google.common.collect.Lists; /** * This implements a simple analysis that prints the call-site -> call target * information. The name of the analysis is "logsite-java". TODO: add a filter * to keep only LOG.info calls. */ @Chord(name = "logsite-java", consumes = { "I", "V", "IinvkArg", "VT", "IM" } // This // analysis // uses // relation // which // is a // tuple // in the format of (call-site quad, target method), that contains // all the call-site <-> target information. This is computed in // alias/cipa_0cfa.dlog. This means that the underlying system will // run "cipa-0cfa-dlog" analysis first! ) public class LogsiteAnalysis extends JavaAnalysis { final List<String> logMethods = Lists.newArrayList("info", "debug", "warn", "error", "println"); public void run() { // // TODO: limit to our file, not libraries // // TODO: values of things, especially the static part // ArrayList<Integer> valid = new ArrayList<Integer>(); // ArrayList<Register> validRegs = new ArrayList<Register>(); // DomI domI = (DomI) ClassicProject.g().getTrgt("I"); // DomV domV = (DomV) ClassicProject.g().getTrgt("V"); // int numI = domI.size(); // for (int iIdx = 0; iIdx < numI; iIdx++) { // Quad q = (Quad) domI.get(iIdx); // jq_Method method = q.getMethod(); // if (method.getName().toString().equals("println") && // method.getDeclaringClass().getSourceFileName().startsWith("java")) { // valid.add(iIdx); // ProgramRel relIinvkArg = (ProgramRel) // ClassicProject.g().getTrgt("IinvkArg"); // relIinvkArg.load(); // Load the IM relation. // for (IntTrio tuple : relIinvkArg.getAry3IntTuples()) { // if (valid.contains(tuple.idx0)) { // Register register = domV.get(tuple.idx2); // validRegs.add(register); // ProgramRel relVT = (ProgramRel) ClassicProject.g().getTrgt("VT"); // relVT.load(); // Load the IM relation. // for (Object[] tuple : relVT.getAryNValTuples()) { // Register r = (Register) tuple[0]; // if (validRegs.contains(r)) { // jq_Type type = (jq_Type) tuple[1]; ProgramRel relIM = (ProgramRel) ClassicProject.g().getTrgt("IM"); relIM.load(); // Load the IM relation. for (Object[] tuple : relIM.getAryNValTuples()) { // iterate through every tuple in IM Quad q = (Quad) tuple[0]; // the call-site, in quad format jq_Method m_caller = q.getMethod(); // method enclosing the call // site String file = m_caller.getDeclaringClass().getSourceFileName(); // file jq_Method m_callee = (jq_Method) tuple[1]; // the callee method if (file.startsWith("java") || !logMethods.contains(m_callee.getName().toString())) { continue; } List<RegId> regIds = Lists.newArrayList(); joeq.Util.Templates.List.RegisterOperand usedRegisters = q.getUsedRegisters(); // this // should // the // register // whose // value // printed for (int i = 0; i < usedRegisters.size(); i++) { RegisterOperand reg = usedRegisters.getRegisterOperand(i); regIds.add(new RegId(reg.getRegister())); } while (true) { ControlFlowGraph cfg = m_caller.getCFG(); joeq.Util.Templates.ListIterator.BasicBlock reversePostOrderIterator = cfg.reversePostOrderIterator(); while (reversePostOrderIterator.hasNext()) { BasicBlock bb = reversePostOrderIterator.nextBasicBlock(); for (int i = 0; i < bb.size(); i++) { Quad quad = bb.getQuad(i); joeq.Util.Templates.List.RegisterOperand regs = quad.getDefinedRegisters(); for (int j = 0; j < regs.size(); j++) { RegisterOperand reg = regs.getRegisterOperand(j); RegId regId = new RegId(reg.getRegister()); if (regIds.contains(regId)) { System.out.println("found the definition of " + regId); System.out.println(quad); regIds.remove(regId); joeq.Util.Templates.List.RegisterOperand usedRegs = quad.getUsedRegisters(); for (int k = 0; k < usedRegs.size(); k++) { RegId newRegId = new RegId(usedRegs.getRegisterOperand(k).getRegister()); System.out.println("now looking for definition of " + newRegId); regIds.add(newRegId); } } } } } } // int line = q.getLineNumber(); // line number // System.out.println("LogSiteAnalysis: call instruction at line: " + line + "@" + file + " is to target: " + m_callee); } } @Data public static class RegId { final int number; final boolean isTemp; public RegId(Register r) { this.number = r.getNumber(); this.isTemp = r.isTemp(); } } }
package com.backtype.hadoop.pail; import com.backtype.hadoop.formats.RecordInputStream; import com.backtype.hadoop.formats.RecordOutputStream; import com.backtype.hadoop.formats.SequenceFileInputStream; import com.backtype.hadoop.formats.SequenceFileOutputStream; import com.backtype.support.KeywordArgParser; import com.backtype.support.Utils; import com.hadoop.compression.lzo.LzoCodec; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.SequenceFile.CompressionType; import org.apache.hadoop.io.compress.BZip2Codec; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.DefaultCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapred.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SequenceFileFormat implements PailFormat { public static final String TYPE_ARG = "compressionType"; public static final String CODEC_ARG = "compressionCodec"; public static final String TYPE_ARG_NONE = "none"; public static final String TYPE_ARG_RECORD = "record"; public static final String TYPE_ARG_BLOCK = "block"; public static final String CODEC_ARG_DEFAULT = "default"; public static final String CODEC_ARG_GZIP = "gzip"; public static final String CODEC_ARG_BZIP2 = "bzip2"; public static final String CODEC_ARG_LZO = "lzo"; private static final Map<String, CompressionType> TYPES = new HashMap<String, CompressionType>() {{ put(TYPE_ARG_RECORD, CompressionType.RECORD); put(TYPE_ARG_BLOCK, CompressionType.BLOCK); }}; private static final Map<String, CompressionCodec> CODECS = new HashMap<String, CompressionCodec>() {{ put(CODEC_ARG_DEFAULT, new DefaultCodec()); put(CODEC_ARG_GZIP, new GzipCodec()); put(CODEC_ARG_BZIP2, new BZip2Codec()); put(CODEC_ARG_LZO, new LzoCodec()); }}; private String _typeArg; private String _codecArg; public SequenceFileFormat(Map<String, Object> args) { args = new KeywordArgParser() .add(TYPE_ARG, null, true, TYPE_ARG_RECORD, TYPE_ARG_BLOCK) .add(CODEC_ARG, CODEC_ARG_DEFAULT, false, CODEC_ARG_DEFAULT, CODEC_ARG_GZIP, CODEC_ARG_BZIP2, CODEC_ARG_LZO) .parse(args); _typeArg = (String) args.get(TYPE_ARG); _codecArg = (String) args.get(CODEC_ARG); } public RecordInputStream getInputStream(FileSystem fs, Path path) throws IOException { return new SequenceFileInputStream(fs, path); } public RecordOutputStream getOutputStream(FileSystem fs, Path path) throws IOException { CompressionType type = TYPES.get(_typeArg); CompressionCodec codec = CODECS.get(_codecArg); if(type==null) return new SequenceFileOutputStream(fs, path); else return new SequenceFileOutputStream(fs, path, type, codec); } public Class<? extends InputFormat> getInputFormatClass() { return SequenceFilePailInputFormat.class; } public static class SequenceFilePailRecordReader implements RecordReader<PailRecordInfo, BytesWritable> { private static Logger LOG = LoggerFactory.getLogger(SequenceFilePailRecordReader.class); public static final int NUM_TRIES = 10; JobConf conf; PailInputSplit split; int recordsRead; long currentStartOffset = 0; Reporter reporter; SequenceFileRecordReader<BytesWritable, NullWritable> delegate; boolean isBlockCompressed = false; public SequenceFilePailRecordReader(JobConf conf, PailInputSplit split, Reporter reporter) throws IOException { this.split = split; this.conf = conf; this.recordsRead = 0; this.reporter = reporter; LOG.info("Processing pail file " + split.getPath().toString()); ifBlockCompressed(); resetDelegate(); } private void resetDelegate() throws IOException { this.delegate = new SequenceFileRecordReader<BytesWritable, NullWritable>(conf, split); BytesWritable dummyValue = new BytesWritable(); for(int i=0; i<recordsRead; i++) { long posBeforeNext = delegate.getPos(); delegate.next(dummyValue, NullWritable.get()); long posAfterNext = delegate.getPos(); checkForOffsetDuringBlockCompression(posBeforeNext, posAfterNext); } } private void ifBlockCompressed() throws IOException { SequenceFile.Reader reader = new SequenceFile.Reader(FileSystem.get(conf), split.getPath(), conf); this.isBlockCompressed = reader.isBlockCompressed(); reader.close(); } private void progress() { if(reporter!=null) { reporter.progress(); } } private void checkForOffsetDuringBlockCompression(long posBeforeReading, long posAfterReading) { if(isBlockCompressed) { if (posAfterReading != posBeforeReading) { recordsRead = 0; currentStartOffset = posBeforeReading; } else { recordsRead++; } } else { recordsRead++; } } public boolean next(PailRecordInfo k, BytesWritable v) throws IOException { /** * There's 2 bugs that happen here, both resulting in indistinguishable EOFExceptions. * * 1. Random EOFExceptions when reading data off of S3. Usually succeeds on the 2nd try. * 2. Corrupted files most likely due to network corruption (which isn't handled by Hadoop/S3 integration). * These always result in error. * * The strategy is to retry a few times. If it fails every time then we're in case #2, and the best thing we can do * is continue on and accept the data loss. If we're in case #1, it'll just succeed. */ for(int i=0; i<NUM_TRIES; i++) { try { long posBeforeNext = delegate.getPos(); boolean ret = delegate.next(v, NullWritable.get()); long posAfterNext = delegate.getPos(); checkForOffsetDuringBlockCompression(posBeforeNext, posAfterNext); k.setFullPath(split.getPath().toString()); k.setPailRelativePath(split.getPailRelPath()); k.setSplitStartOffset(currentStartOffset); k.setRecordsToSkip(recordsRead); return ret; } catch(EOFException e) { progress(); Utils.sleep(10000); //in case it takes time for S3 to recover progress(); //this happens due to some sort of S3 corruption bug. LOG.error("Hit an EOF exception while processing file " + split.getPath().toString() + " with records read = " + recordsRead); resetDelegate(); } } //stop trying to read the file at this point and discard the rest of the file return false; } public PailRecordInfo createKey() { return new PailRecordInfo(); } public BytesWritable createValue() { return new BytesWritable(); } public long getPos() throws IOException { return delegate.getPos(); } public void close() throws IOException { delegate.close(); } public float getProgress() throws IOException { return delegate.getProgress(); } } public static class SequenceFilePailInputFormat extends SequenceFileInputFormat<PailRecordInfo, BytesWritable> { private Pail _currPail; @Override public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { List<InputSplit> ret = new ArrayList<InputSplit>(); Path[] roots = FileInputFormat.getInputPaths(job); for(int i=0; i < roots.length; i++) { _currPail = new Pail(roots[i].toString()); InputSplit[] splits = super.getSplits(job, numSplits); for(InputSplit split: splits) { ret.add(new PailInputSplit(_currPail.getFileSystem(), _currPail.getInstanceRoot(), _currPail.getSpec(), job, (FileSplit) split)); } } return ret.toArray(new InputSplit[ret.size()]); } @Override protected FileStatus[] listStatus(JobConf job) throws IOException { List<Path> paths = PailFormatFactory.getPailPaths(_currPail, job); FileSystem fs = _currPail.getFileSystem(); FileStatus[] ret = new FileStatus[paths.size()]; for(int i=0; i<paths.size(); i++) { ret[i] = fs.getFileStatus(paths.get(i).makeQualified(fs)); } return ret; } @Override public RecordReader<PailRecordInfo, BytesWritable> getRecordReader(InputSplit split, JobConf job, Reporter reporter) throws IOException { return new SequenceFilePailRecordReader(job, (PailInputSplit) split, reporter); } } }
package com.SphereEngine.Api; import java.util.Map; import java.util.HashMap; import com.google.gson.JsonObject; public class CompilersClientV3 { /** * Instance of the ApiClient */ private ApiClient apiClient; /** * Module name of the API */ private String module = "compilers"; /** * Version of the API */ private String version = "v3"; /** * Constructor * * @param {String} accessToken - Sphere Engine Compilers access token * @param {String} endpoint - Sphere Engine Compilers endpoint */ public CompilersClientV3(String accessToken, String endpoint) { apiClient = new ApiClient(accessToken, createEndpointLink(endpoint)); } /** * Create a complete API endpoint url * * @param {String} endpoint - partial endpoint * @return Complete API endpoint url */ private String createEndpointLink(String endpoint) { if (!endpoint.contains(".")) { return endpoint + "." + module + "." + "sphere-engine.com/api/" + version; } else { return endpoint + "/api/" + version; } } /** * Test method * * @throws NotAuthorizedException for invalid access token * @return API response */ public JsonObject test() { return apiClient.callApi("/test", "GET", null, null, null, null, null); } /** * List of all compilers * * @throws NotAuthorizedException for invalid access token * @return API response */ public JsonObject getCompilers() { return apiClient.callApi("/compilers", "GET", null, null, null, null, null); } /** * Create a new submission * * @param {string} source - source code * @param {integer} compiler - Compiler ID * @param {string} input - data that will be given to the program on stdin * @throws NotAuthorizedException for invalid access token * @return API response */ public JsonObject createSubmission(String source, Integer compiler, String input) { Map<String, String> postParams = new HashMap<String,String>(); postParams.put("sourceCode", source); postParams.put("language", compiler.toString()); postParams.put("input", input); return apiClient.callApi("/submissions", "POST", null, null, postParams, null, null); } /** * Create a new submission with empty input * * @param {string} source - source code * @param {integer} compiler - Compiler ID * @throws NotAuthorizedException for invalid access token * @return API response */ public JsonObject createSubmission(String source, Integer compiler) { return createSubmission(source, compiler, ""); } /** * Create a new C++ submission with empty input * * @param {string} source - source code * @throws NotAuthorizedException for invalid access token * @return API response */ public JsonObject createSubmission(String source) { return createSubmission(source, 1, ""); } /** * Create an empty C++ submission with empty input * * @param {string} source - source code * @throws NotAuthorizedException for invalid access token * @return API response */ public JsonObject createSubmission() { return createSubmission("", 1, ""); } /** * Fetch submission details * * @param {integer} id - Submission id * @param {boolean} withSource - determines whether source code of the submission should be returned * @param {boolean} withInput - determines whether input data of the submission should be returned * @param {boolean} withOutput - determines whether output produced by the program should be returned * @param {boolean} withStderr - determines whether stderr should be returned * @param {boolean} withCmpinfo - determines whether compilation information should be returned * @throws NotAuthorizedException for invalid access token * @throws NotFoundException for non existing submission * @return API response */ public JsonObject getSubmission(Integer id, Boolean withSource, Boolean withInput, Boolean withOutput, Boolean withStderr, Boolean withCmpinfo) { Map<String, String> urlParams = new HashMap<String,String>(); Map<String, String> queryParams = new HashMap<String,String>(); urlParams.put("id", id.toString()); queryParams.put("withSource", (withSource) ? "1" : "0"); queryParams.put("withInput", (withInput) ? "1" : "0"); queryParams.put("withOutput", (withOutput) ? "1" : "0"); queryParams.put("withStderr", (withStderr) ? "1" : "0"); queryParams.put("withCmpinfo", (withCmpinfo) ? "1" : "0"); return apiClient.callApi("/submissions/{id}", "GET", urlParams, queryParams, null, null, null); } /** * Fetch submission details * * @param {integer} id - Submission id * @param {boolean} withSource - determines whether source code of the submission should be returned * @param {boolean} withInput - determines whether input data of the submission should be returned * @param {boolean} withOutput - determines whether output produced by the program should be returned * @param {boolean} withStderr - determines whether stderr should be returned * @throws NotAuthorizedException for invalid access token * @throws NotFoundException for non existing submission * @return API response */ public JsonObject getSubmission(Integer id, Boolean withSource, Boolean withInput, Boolean withOutput, Boolean withStderr) { return getSubmission(id, withSource, withInput, withOutput, withStderr, false); } /** * Fetch submission details * * @param {integer} id - Submission id * @param {boolean} withSource - determines whether source code of the submission should be returned * @param {boolean} withInput - determines whether input data of the submission should be returned * @param {boolean} withOutput - determines whether output produced by the program should be returned * @throws NotAuthorizedException for invalid access token * @throws NotFoundException for non existing submission * @return API response */ public JsonObject getSubmission(Integer id, Boolean withSource, Boolean withInput, Boolean withOutput) { return getSubmission(id, withSource, withInput, withOutput, false, false); } /** * Fetch submission details * * @param {integer} id - Submission id * @param {boolean} withSource - determines whether source code of the submission should be returned * @param {boolean} withInput - determines whether input data of the submission should be returned * @throws NotAuthorizedException for invalid access token * @throws NotFoundException for non existing submission * @return API response */ public JsonObject getSubmission(Integer id, Boolean withSource, Boolean withInput) { return getSubmission(id, withSource, withInput, false, false, false); } /** * Fetch submission details * * @param {integer} id - Submission id * @param {boolean} withSource - determines whether source code of the submission should be returned * @throws NotAuthorizedException for invalid access token * @throws NotFoundException for non existing submission * @return API response */ public JsonObject getSubmission(Integer id, Boolean withSource) { return getSubmission(id, withSource, false, false, false, false); } /** * Fetch submission details * * @param {integer} id - Submission id * @throws NotAuthorizedException for invalid access token * @throws NotFoundException for non existing submission * @return API response */ public JsonObject getSubmission(Integer id) { return getSubmission(id, false, false, false, false, false); } }
package com.ecyrd.jspwiki.search; import java.io.IOException; import java.util.Collection; import java.util.Properties; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.util.ClassUtil; import com.ecyrd.jspwiki.filters.BasicPageFilter; import com.ecyrd.jspwiki.filters.FilterException; import com.ecyrd.jspwiki.providers.ProviderException; /** * Manages searching the Wiki. * * @author Arent-Jan Banck for Informatica * @since 2.2.21. */ public class SearchManager extends BasicPageFilter { private static final Logger log = Logger.getLogger(SearchManager.class); private static String DEFAULT_SEARCHPROVIDER = "com.ecyrd.jspwiki.search.LuceneSearchProvider"; public static final String PROP_USE_LUCENE = "jspwiki.useLucene"; public static final String PROP_SEARCHPROVIDER = "jspwiki.searchProvider"; private SearchProvider m_searchProvider = null; public SearchManager( WikiEngine engine, Properties properties ) throws WikiException { initialize( engine, properties ); } /** * This particular method starts off indexing and all sorts of various activities, * so you need to run this last, after things are done. * * @param engine * @param properties * @throws WikiException */ public void initialize(WikiEngine engine, Properties properties) throws WikiException { loadSearchProvider(properties); try { m_searchProvider.initialize(engine, properties); } catch (NoRequiredPropertyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void loadSearchProvider(Properties properties) { // See if we're using Lucene, and if so, ensure that its // index directory is up to date. String useLucene = properties.getProperty(PROP_USE_LUCENE); // FIXME: Obsolete, remove, or change logic to first load searchProvder? // If the old jspwiki.useLucene property is set we use that instead of the searchProvider class. if( useLucene != null ) { log.info( PROP_USE_LUCENE+" is deprecated; please use "+PROP_SEARCHPROVIDER+"=<your search provider> instead." ); if( TextUtil.isPositive( useLucene ) ) { m_searchProvider = new LuceneSearchProvider(); } else { m_searchProvider = new BasicSearchProvider(); } log.debug("useLucene was set, loading search provider " + m_searchProvider); return; } String providerClassName = properties.getProperty( PROP_SEARCHPROVIDER, DEFAULT_SEARCHPROVIDER ); try { Class providerClass = ClassUtil.findClass( "com.ecyrd.jspwiki.search", providerClassName ); m_searchProvider = (SearchProvider)providerClass.newInstance(); } catch( ClassNotFoundException e ) { log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e); } catch( InstantiationException e ) { log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e); } catch( IllegalAccessException e ) { log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e); } if( null == m_searchProvider ) { // FIXME: Make a static with the default search provider m_searchProvider = new BasicSearchProvider(); } log.debug("Loaded search provider " + m_searchProvider); } public SearchProvider getSearchEngine() { return m_searchProvider; } /** * Sends a search to the current search provider. The query is is whatever native format * the query engine wants to use. * * @param query The query. Null is safe, and is interpreted as an empty query. * @return A collection of WikiPages that matched. */ public Collection findPages( String query ) throws ProviderException, IOException { if( query == null ) query = ""; return m_searchProvider.findPages( query ); } /** * Removes the page from the search cache (if any). * @param page The page to remove */ public void pageRemoved(WikiPage page) { m_searchProvider.pageRemoved(page); } public void postSave( WikiContext wikiContext, String content ) { reindexPage( wikiContext.getPage() ); } /** * Forces the reindex of the given page. * * @param page */ public void reindexPage(WikiPage page) { m_searchProvider.reindexPage(page); } }
package com.electronwill.toml; import java.io.Writer; /** * A Writer writing in a StringBuilder. This is NOT Thread safe. * * @author TheElectronWill */ public class FastStringWriter extends Writer { /** * The underlying StringBuilder. Everything is appended to it. */ private final StringBuilder sb; /** * Creates a new FastStringWriter with a default StringBuilder */ public FastStringWriter() { sb = new StringBuilder(); } /** * Creates a new FastStringWriter with a given StringBuilder. It will append everything to this StringBuilder. * * @param sb the StringBuilder */ public FastStringWriter(StringBuilder sb) { this.sb = sb; } /** * Returns the underlying StringBuilder. * * @return the underlying StringBuilder */ public StringBuilder getBuilder() { return sb; } /** * Returns the content of the underlying StringBuilder, as a String. Equivalent to {@link #getBuilder()#toString()}. * * @return the content of the underlying StringBuilder */ @Override public String toString() { return sb.toString(); } @Override public FastStringWriter append(char c) { sb.append(c); return this; } @Override public FastStringWriter append(CharSequence csq, int start, int end) { sb.append(csq, start, end); return this; } @Override public FastStringWriter append(CharSequence csq) { sb.append(csq); return this; } @Override public void write(String str, int off, int len) { sb.append(str, off, off + len); } @Override public void write(String str) { sb.append(str); } @Override public void write(char[] cbuf, int off, int len) { sb.append(cbuf, off, len); } @Override public void write(int c) { sb.append(c); } /** * This method does nothing. */ @Override public void flush() {} /** * This method does nothing. */ @Override public void close() {} }
package com.irccloud.android; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.zip.GZIPInputStream; import javax.net.ssl.HttpsURLConnection; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import com.codebutler.android_websockets.WebSocketClient; public class NetworkConnection { private static final String TAG = "IRCCloud"; private static NetworkConnection instance = null; public static final int STATE_DISCONNECTED = 0; public static final int STATE_CONNECTING = 1; public static final int STATE_CONNECTED = 2; public static final int STATE_DISCONNECTING = 3; private int state = STATE_DISCONNECTED; private WebSocketClient client = null; private UserInfo userInfo = null; private ArrayList<Handler> handlers = null; private String session = null; private int last_reqid = 0; private Timer shutdownTimer = null; private Timer idleTimer = null; private long idle_interval = 0; public static final int EVENT_CONNECTIVITY = 0; public static final int EVENT_USERINFO = 1; public static final int EVENT_MAKESERVER = 2; public static final int EVENT_MAKEBUFFER = 3; public static final int EVENT_DELETEBUFFER = 4; public static final int EVENT_BUFFERMSG = 5; public static final int EVENT_HEARTBEATECHO = 6; public static final int EVENT_CHANNELINIT = 7; public static final int EVENT_CHANNELTOPIC = 8; public static final int EVENT_JOIN = 9; public static final int EVENT_PART = 10; public static final int EVENT_NICKCHANGE = 11; public static final int EVENT_QUIT = 12; public static final int EVENT_MEMBERUPDATES = 13; public static final int EVENT_USERCHANNELMODE = 14; public static final int EVENT_BUFFERARCHIVED = 15; public static final int EVENT_BUFFERUNARCHIVED = 16; public static final int EVENT_RENAMECONVERSATION = 17; public static final int EVENT_STATUSCHANGED = 18; public static final int EVENT_CONNECTIONDELETED = 19; public static final int EVENT_AWAY = 20; public static final int EVENT_SELFBACK = 21; public static final int EVENT_KICK = 22; public static final int EVENT_CHANNELMODE = 23; public static final int EVENT_CHANNELTIMESTAMP = 24; public static final int EVENT_SELFDETAILS = 25; public static final int EVENT_USERMODE = 26; public static final int EVENT_SETIGNORES = 27; public static final int EVENT_BADCHANNELKEY = 28; public static final int EVENT_OPENBUFFER = 29; public static final int EVENT_NOSUCHCHANNEL = 30; public static final int EVENT_NOSUCHNICK = 31; public static final int EVENT_BACKLOG_START = 100; public static final int EVENT_BACKLOG_END = 101; Object parserLock = new Object(); public static NetworkConnection getInstance() { if(instance == null) { instance = new NetworkConnection(); } return instance; } public int getState() { return state; } public void disconnect() { if(client!=null) { state = STATE_DISCONNECTING; client.disconnect(); } else { state = STATE_DISCONNECTED; } if(idleTimer != null) { idleTimer.cancel(); idleTimer = null; } } public String login(String email, String password) throws IOException { String postdata = "email="+email+"&password="+password; String response = doPost(new URL("https://alpha.irccloud.com/chat/login"), postdata); try { Log.d(TAG, "Result: " + response); JSONObject o = new JSONObject(response); return o.getString("session"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public void connect(String sk) { session = sk; List<BasicNameValuePair> extraHeaders = Arrays.asList( new BasicNameValuePair("Cookie", "session="+session) ); client = new WebSocketClient(URI.create("wss://alpha.irccloud.com"), new WebSocketClient.Listener() { @Override public void onConnect() { Log.d(TAG, "Connected!"); state = STATE_CONNECTED; notifyHandlers(EVENT_CONNECTIVITY, null); } @Override public void onMessage(String message) { if(message.length() > 0) { try { synchronized(parserLock) { parse_object(new IRCCloudJSONObject(message), false); } } catch (JSONException e) { Log.e(TAG, "Unable to parse: " + message); // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public void onMessage(byte[] data) { //Log.d(TAG, String.format("Got binary message! %s", toHexString(data)); } @Override public void onDisconnect(int code, String reason) { Log.d(TAG, String.format("Disconnected! Code: %d Reason: %s", code, reason)); if(state != STATE_DISCONNECTING) schedule_idle_timer(); state = STATE_DISCONNECTED; notifyHandlers(EVENT_CONNECTIVITY, null); } @Override public void onError(Exception error) { Log.e(TAG, "Error!", error); } }, extraHeaders); state = STATE_CONNECTING; notifyHandlers(EVENT_CONNECTIVITY, null); client.connect(); } public int heartbeat(long selected_buffer, int cid, long bid, long last_seen_eid) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "heartbeat"); o.put("selectedBuffer", selected_buffer); JSONObject eids = new JSONObject(); eids.put(String.valueOf(bid), last_seen_eid); JSONObject cids = new JSONObject(); cids.put(String.valueOf(cid), eids); o.put("seenEids", cids.toString()); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int disconnect(int cid, String message) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "disconnect"); o.put("cid", cid); o.put("msg", message); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int reconnect(int cid) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "reconnect"); o.put("cid", cid); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int say(int cid, String to, String message) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "say"); o.put("cid", cid); o.put("to", to); o.put("msg", message); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int join(int cid, String channel, String key) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "join"); o.put("cid", cid); o.put("channel", channel); o.put("key", key); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int part(int cid, String channel, String message) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "part"); o.put("cid", cid); o.put("channel", channel); o.put("msg", message); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int kick(int cid, String channel, String nick, String message) { return say(cid, channel, "/kick " + nick + " " + message); } public int mode(int cid, String channel, String mode) { return say(cid, channel, "/mode " + channel + " " + mode); } public int invite(int cid, String channel, String nick) { return say(cid, channel, "/invite " + nick + " " + channel); } public int archiveBuffer(int cid, long bid) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "archive-buffer"); o.put("cid", cid); o.put("id", bid); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int unarchiveBuffer(int cid, long bid) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "unarchive-buffer"); o.put("cid", cid); o.put("id", bid); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int deleteBuffer(int cid, long bid) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "delete-buffer"); o.put("cid", cid); o.put("id", bid); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int deleteServer(int cid) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "delete-connection"); o.put("cid", cid); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int addServer(String hostname, int port, int ssl, String netname, String nickname, String realname, String server_pass, String nickserv_pass, String joincommands, String channels) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "add-server"); o.put("hostname", hostname); o.put("port", port); o.put("ssl", ssl); o.put("netname", netname); o.put("nickname", nickname); o.put("realname", realname); o.put("server_pass", server_pass); o.put("nspass", nickserv_pass); o.put("joincommands", joincommands); o.put("channels", channels); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int editServer(int cid, String hostname, int port, int ssl, String netname, String nickname, String realname, String server_pass, String nickserv_pass, String joincommands) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "edit-server"); o.put("hostname", hostname); o.put("port", port); o.put("ssl", ssl); o.put("netname", netname); o.put("nickname", nickname); o.put("realname", realname); o.put("server_pass", server_pass); o.put("nspass", nickserv_pass); o.put("joincommands", joincommands); o.put("cid", cid); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int ignore(int cid, String mask) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "ignore"); o.put("cid", cid); o.put("mask", mask); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public int unignore(int cid, String mask) { try { JSONObject o = new JSONObject(); o.put("_reqid", last_reqid++); o.put("_method", "unignore"); o.put("cid", cid); o.put("mask", mask); client.send(o.toString()); return last_reqid; } catch (JSONException e) { e.printStackTrace(); return -1; } } public void request_backlog(int cid, long bid, long beforeId) { try { if(Looper.myLooper() == null) Looper.prepare(); if(beforeId > 0) new OOBIncludeTask().execute(new URL("https://alpha.irccloud.com/chat/backlog?cid="+cid+"&bid="+bid+"&beforeid="+beforeId)); else new OOBIncludeTask().execute(new URL("https://alpha.irccloud.com/chat/backlog?cid="+cid+"&bid="+bid)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void schedule_idle_timer() { if(idleTimer != null) { idleTimer.cancel(); idleTimer = null; } idleTimer = new Timer(); idleTimer.schedule( new TimerTask(){ public void run() { Log.i("IRCCloud", "Websocket idle time exceeded, reconnecting..."); client.disconnect(); client.connect(); idleTimer = null; } }, idle_interval + 10000); } @SuppressWarnings("unchecked") private void parse_object(IRCCloudJSONObject object, boolean backlog) throws JSONException { //Log.d(TAG, "New event: " + object); if(!object.has("type")) { //TODO: This is probably a command response, parse it and send the result back up to the UI! Log.d(TAG, "Response: " + object); return; } String type = object.type(); if(type != null && type.length() > 0) { if(type.equalsIgnoreCase("header")) { idle_interval = object.getLong("idle_interval"); } else if(type.equalsIgnoreCase("idle") || type.equalsIgnoreCase("end_of_backlog") || type.equalsIgnoreCase("backlog_complete")) { } else if(type.equalsIgnoreCase("num_invites")) { if(userInfo != null) userInfo.num_invites = object.getInt("num_invites"); } else if(type.equalsIgnoreCase("stat_user")) { userInfo = new UserInfo(object); notifyHandlers(EVENT_USERINFO, userInfo); } else if(type.equalsIgnoreCase("bad_channel_key")) { notifyHandlers(EVENT_BADCHANNELKEY, object); } else if(type.equalsIgnoreCase("open_buffer")) { notifyHandlers(EVENT_OPENBUFFER, object); } else if(type.equalsIgnoreCase("no_such_channel")) { notifyHandlers(EVENT_NOSUCHCHANNEL, object); } else if(type.equalsIgnoreCase("no_such_nick")) { notifyHandlers(EVENT_NOSUCHNICK, object); } else if(type.equalsIgnoreCase("makeserver") || type.equalsIgnoreCase("server_details_changed")) { ServersDataSource s = ServersDataSource.getInstance(); s.deleteServer(object.getInt("cid")); ServersDataSource.Server server = s.createServer(object.getInt("cid"), object.getString("name"), object.getString("hostname"), object.getInt("port"), object.getString("nick"), object.getString("status"), object.getString("lag").equalsIgnoreCase("undefined")?0:object.getLong("lag"), object.getBoolean("ssl")?1:0, object.getString("realname"), object.getString("server_pass"), object.getString("nickserv_pass"), object.getString("join_commands"), object.getJSONObject("fail_info").toString(), object.getString("away"), object.getJSONArray("ignores")); if(!backlog) notifyHandlers(EVENT_MAKESERVER, server); } else if(type.equalsIgnoreCase("connection_deleted")) { ServersDataSource s = ServersDataSource.getInstance(); s.deleteAllDataForServer(object.getInt("cid")); if(!backlog) notifyHandlers(EVENT_CONNECTIONDELETED, object.getInt("cid")); } else if(type.equalsIgnoreCase("makebuffer")) { BuffersDataSource b = BuffersDataSource.getInstance(); ChannelsDataSource c = ChannelsDataSource.getInstance(); b.deleteBuffer(object.getInt("bid")); c.deleteChannel(object.getInt("bid")); BuffersDataSource.Buffer buffer = b.createBuffer(object.getInt("bid"), object.getInt("cid"), (object.has("min_eid") && !object.getString("min_eid").equalsIgnoreCase("undefined"))?object.getLong("min_eid"):0, (object.has("last_seen_eid") && !object.getString("last_seen_eid").equalsIgnoreCase("undefined"))?object.getLong("last_seen_eid"):-1, object.getString("name"), object.getString("buffer_type"), (object.has("archived") && object.getBoolean("archived"))?1:0, (object.has("deferred") && object.getBoolean("deferred"))?1:0); if(!backlog) notifyHandlers(EVENT_MAKEBUFFER, buffer); } else if(type.equalsIgnoreCase("delete_buffer")) { BuffersDataSource b = BuffersDataSource.getInstance(); b.deleteAllDataForBuffer(object.getInt("bid")); if(!backlog) notifyHandlers(EVENT_DELETEBUFFER, object.getInt("bid")); } else if(type.equalsIgnoreCase("buffer_archived")) { BuffersDataSource b = BuffersDataSource.getInstance(); b.updateArchived(object.getInt("bid"), 1); if(!backlog) notifyHandlers(EVENT_BUFFERARCHIVED, object.getInt("bid")); } else if(type.equalsIgnoreCase("buffer_unarchived")) { BuffersDataSource b = BuffersDataSource.getInstance(); b.updateArchived(object.getInt("bid"), 0); if(!backlog) notifyHandlers(EVENT_BUFFERUNARCHIVED, object.getInt("bid")); } else if(type.equalsIgnoreCase("rename_conversation")) { BuffersDataSource b = BuffersDataSource.getInstance(); b.updateName(object.getInt("bid"), object.getString("new_name")); if(!backlog) notifyHandlers(EVENT_RENAMECONVERSATION, object.getInt("bid")); } else if(type.equalsIgnoreCase("status_changed")) { ServersDataSource s = ServersDataSource.getInstance(); s.updateStatus(object.getInt("cid"), object.getString("new_status"), object.getJSONObject("fail_info").toString()); if(!backlog) notifyHandlers(EVENT_STATUSCHANGED, object); } else if(type.equalsIgnoreCase("buffer_msg") || type.equalsIgnoreCase("buffer_me_msg") || type.equalsIgnoreCase("server_motdstart") || type.equalsIgnoreCase("notice") || type.equalsIgnoreCase("server_welcome") || type.equalsIgnoreCase("server_motd") || type.equalsIgnoreCase("server_endofmotd") || type.equalsIgnoreCase("services_down") || type.equalsIgnoreCase("server_luserclient") || type.equalsIgnoreCase("server_luserop") || type.equalsIgnoreCase("server_luserconns") || type.equalsIgnoreCase("myinfo") || type.equalsIgnoreCase("hidden_host_set") || type.equalsIgnoreCase("server_luserme") || type.equalsIgnoreCase("server_n_local") || type.equalsIgnoreCase("server_luserchannels") || type.equalsIgnoreCase("connecting_failed") || type.equalsIgnoreCase("nickname_in_use") || type.equalsIgnoreCase("server_n_global") || type.equalsIgnoreCase("motd_response") || type.equalsIgnoreCase("server_luserunknown") || type.equalsIgnoreCase("socket_closed") || type.equalsIgnoreCase("channel_mode_list_change") || type.equalsIgnoreCase("server_yourhost") || type.equalsIgnoreCase("server_created") || type.equalsIgnoreCase("inviting_to_channel") || type.equalsIgnoreCase("error")) { EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_BUFFERMSG, object); } else if(type.equalsIgnoreCase("channel_init")) { ChannelsDataSource c = ChannelsDataSource.getInstance(); c.deleteChannel(object.getLong("bid")); ChannelsDataSource.Channel channel = c.createChannel(object.getInt("cid"), object.getLong("bid"), object.getString("chan"), object.getJSONObject("topic").isNull("text")?"":object.getJSONObject("topic").getString("text"), object.getJSONObject("topic").getLong("time"), object.getJSONObject("topic").getString("nick"), object.getString("channel_type"), object.getString("mode"), object.getLong("timestamp")); UsersDataSource u = UsersDataSource.getInstance(); u.deleteUsersForChannel(object.getInt("cid"), object.getString("chan")); JSONArray users = object.getJSONArray("members"); for(int i = 0; i < users.length(); i++) { JSONObject user = users.getJSONObject(i); u.createUser(object.getInt("cid"), object.getString("chan"), user.getString("nick"), user.getString("usermask"), user.getString("mode"), user.getBoolean("away")?1:0); } if(!backlog) notifyHandlers(EVENT_CHANNELINIT, channel); } else if(type.equalsIgnoreCase("channel_topic")) { ChannelsDataSource c = ChannelsDataSource.getInstance(); c.updateTopic(object.getLong("bid"), object.getString("topic"), object.getLong("eid"), object.getString("author")); EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_CHANNELTOPIC, object); } else if(type.equalsIgnoreCase("channel_url")) { ChannelsDataSource c = ChannelsDataSource.getInstance(); c.updateURL(object.getLong("bid"), object.getString("url")); } else if(type.equalsIgnoreCase("channel_mode") || type.equalsIgnoreCase("channel_mode_is")) { ChannelsDataSource c = ChannelsDataSource.getInstance(); c.updateMode(object.getLong("bid"), object.getString("newmode")); EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_CHANNELMODE, object); } else if(type.equalsIgnoreCase("channel_timestamp")) { ChannelsDataSource c = ChannelsDataSource.getInstance(); c.updateTimestamp(object.getLong("bid"), object.getLong("timestamp")); if(!backlog) notifyHandlers(EVENT_CHANNELTIMESTAMP, object); } else if(type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("you_joined_channel")) { UsersDataSource u = UsersDataSource.getInstance(); u.deleteUser(object.getInt("cid"), object.getString("chan"), object.getString("nick")); u.createUser(object.getInt("cid"), object.getString("chan"), object.getString("nick"), object.getString("hostmask"), "", 0); EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_JOIN, object); } else if(type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("you_parted_channel")) { UsersDataSource u = UsersDataSource.getInstance(); u.deleteUser(object.getInt("cid"), object.getString("chan"), object.getString("nick")); EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog && type.equalsIgnoreCase("you_parted_channel")) { ChannelsDataSource c = ChannelsDataSource.getInstance(); c.deleteChannel(object.getInt("bid")); } if(!backlog) notifyHandlers(EVENT_PART, object); } else if(type.equalsIgnoreCase("quit")) { UsersDataSource u = UsersDataSource.getInstance(); u.deleteUser(object.getInt("cid"), object.getString("chan"), object.getString("nick")); EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_QUIT, object); } else if(type.equalsIgnoreCase("quit_server")) { EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_QUIT, object); } else if(type.equalsIgnoreCase("kicked_channel") || type.equalsIgnoreCase("you_kicked_channel")) { UsersDataSource u = UsersDataSource.getInstance(); u.deleteUser(object.getInt("cid"), object.getString("chan"), object.getString("nick")); EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog && type.equalsIgnoreCase("you_kicked_channel")) { ChannelsDataSource c = ChannelsDataSource.getInstance(); c.deleteChannel(object.getInt("bid")); } if(!backlog) notifyHandlers(EVENT_KICK, object); } else if(type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("you_nickchange")) { ChannelsDataSource c = ChannelsDataSource.getInstance(); ChannelsDataSource.Channel chan = c.getChannelForBuffer(object.getLong("bid")); if(chan != null) { UsersDataSource u = UsersDataSource.getInstance(); u.updateNick(object.getInt("cid"), chan.name, object.getString("oldnick"), object.getString("newnick")); } EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_NICKCHANGE, object); } else if(type.equalsIgnoreCase("user_channel_mode")) { ChannelsDataSource c = ChannelsDataSource.getInstance(); ChannelsDataSource.Channel chan = c.getChannelForBuffer(object.getLong("bid")); if(chan != null) { UsersDataSource u = UsersDataSource.getInstance(); u.updateMode(object.getInt("cid"), chan.name, object.getString("nick"), object.getString("newmode")); } EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_USERCHANNELMODE, object); } else if(type.equalsIgnoreCase("member_updates")) { JSONObject updates = object.getJSONObject("updates"); Iterator<String> i = updates.keys(); while(i.hasNext()) { String nick = i.next(); JSONObject user = updates.getJSONObject(nick); ChannelsDataSource c = ChannelsDataSource.getInstance(); ChannelsDataSource.Channel chan = c.getChannelForBuffer(object.getLong("bid")); if(chan != null) { UsersDataSource u = UsersDataSource.getInstance(); u.updateAway(object.getInt("cid"), chan.name, user.getString("nick"), user.getBoolean("away")?1:0); u.updateHostmask(object.getInt("cid"), chan.name, user.getString("nick"), user.getString("usermask")); } } if(!backlog) notifyHandlers(EVENT_MEMBERUPDATES, null); } else if(type.equalsIgnoreCase("user_away") || type.equalsIgnoreCase("away")) { BuffersDataSource b = BuffersDataSource.getInstance(); UsersDataSource u = UsersDataSource.getInstance(); ChannelsDataSource c = ChannelsDataSource.getInstance(); ChannelsDataSource.Channel chan = c.getChannelForBuffer(object.getLong("bid")); if(chan != null) { u.updateAwayMsg(object.getInt("cid"), chan.name, object.getString("nick"), 1, object.getString("msg")); } else { b.updateAway(object.getInt("bid"), object.getString("msg")); } if(!backlog) notifyHandlers(EVENT_AWAY, object); } else if(type.equalsIgnoreCase("self_away")) { ServersDataSource s = ServersDataSource.getInstance(); UsersDataSource u = UsersDataSource.getInstance(); u.updateSelfAwayMsg(object.getInt("cid"), object.getString("nick"), 1, object.getString("away_msg")); s.updateAway(object.getInt("cid"), object.getString("away_msg")); if(!backlog) notifyHandlers(EVENT_AWAY, object); } else if(type.equalsIgnoreCase("self_back")) { ServersDataSource s = ServersDataSource.getInstance(); UsersDataSource u = UsersDataSource.getInstance(); u.updateSelfAwayMsg(object.getInt("cid"), object.getString("nick"), 0, ""); s.updateAway(object.getInt("cid"), ""); if(!backlog) notifyHandlers(EVENT_AWAY, object); } else if(type.equalsIgnoreCase("self_details")) { ServersDataSource s = ServersDataSource.getInstance(); s.updateUsermask(object.getInt("cid"), object.getString("usermask")); EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_SELFDETAILS, object); } else if(type.equalsIgnoreCase("user_mode")) { ServersDataSource s = ServersDataSource.getInstance(); s.updateMode(object.getInt("cid"), object.getString("newmode")); EventsDataSource e = EventsDataSource.getInstance(); e.addEvent(object); if(!backlog) notifyHandlers(EVENT_USERMODE, object); } else if(type.equalsIgnoreCase("connection_lag")) { ServersDataSource s = ServersDataSource.getInstance(); s.updateLag(object.getInt("cid"), object.getLong("lag")); } else if(type.equalsIgnoreCase("isupport_params")) { ServersDataSource s = ServersDataSource.getInstance(); s.updateIsupport(object.getInt("cid"), object.getJSONObject("params")); } else if(type.equalsIgnoreCase("set_ignores") || type.equalsIgnoreCase("ignore_list")) { ServersDataSource s = ServersDataSource.getInstance(); s.updateIgnores(object.getInt("cid"), object.getJSONArray("masks")); if(!backlog) notifyHandlers(EVENT_SETIGNORES, object); } else if(type.equalsIgnoreCase("heartbeat_echo")) { JSONObject seenEids = object.getJSONObject("seenEids"); Iterator<String> i = seenEids.keys(); while(i.hasNext()) { String cid = i.next(); JSONObject eids = seenEids.getJSONObject(cid); Iterator<String> j = eids.keys(); while(j.hasNext()) { String bid = j.next(); long eid = eids.getLong(bid); BuffersDataSource.getInstance().updateLastSeenEid(Integer.valueOf(bid), eid); } } if(!backlog) notifyHandlers(EVENT_HEARTBEATECHO, null); } else if(type.equalsIgnoreCase("oob_include")) { try { if(Looper.myLooper() == null) Looper.prepare(); new OOBIncludeTask().execute(new URL("https://alpha.irccloud.com" + object.getString("url"))); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Log.e(TAG, "Unhandled type: " + object); } } if(idle_interval > 0) schedule_idle_timer(); } private String doGet(URL url) throws IOException { Log.d(TAG, "Requesting: " + url); HttpURLConnection conn = null; if (url.getProtocol().toLowerCase().equals("https")) { HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); conn = https; } else { conn = (HttpURLConnection) url.openConnection(); } conn.setRequestMethod("GET"); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Cookie", "session="+session); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Content-type", "application/json"); conn.setRequestProperty("Accept-Encoding", "gzip"); BufferedReader reader = null; String response = ""; conn.connect(); try { if(conn.getInputStream() != null) { if(conn.getContentEncoding().equalsIgnoreCase("gzip")) reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(conn.getInputStream())), 512); else reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512); } } catch (IOException e) { if(conn.getErrorStream() != null) { if(conn.getContentEncoding().equalsIgnoreCase("gzip")) reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(conn.getErrorStream())), 512); else reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512); } } if(reader != null) { response = toString(reader); reader.close(); } return response; } private String doPost(URL url, String postdata) throws IOException { Log.d(TAG, "POSTing to: " + url); HttpURLConnection conn = null; if (url.getProtocol().toLowerCase().equals("https")) { HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); conn = https; } else { conn = (HttpURLConnection) url.openConnection(); } conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); OutputStream ostr = null; try { ostr = conn.getOutputStream(); ostr.write(postdata.getBytes()); } finally { if (ostr != null) ostr.close(); } BufferedReader reader = null; String response = ""; conn.connect(); try { if(conn.getInputStream() != null) { reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512); } } catch (IOException e) { if(conn.getErrorStream() != null) { reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512); } } if(reader != null) { response = toString(reader); reader.close(); } return response; } private static String toString(BufferedReader reader) throws IOException { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } return sb.toString(); } public void addHandler(Handler handler) { if(handlers == null) handlers = new ArrayList<Handler>(); handlers.add(handler); if(shutdownTimer != null) { shutdownTimer.cancel(); shutdownTimer = null; } } public void removeHandler(Handler handler) { handlers.remove(handler); if(handlers.isEmpty() && shutdownTimer == null) { shutdownTimer = new Timer(); shutdownTimer.schedule( new TimerTask(){ public void run() { if(handlers.isEmpty()) { disconnect(); } shutdownTimer = null; } }, 5*60000); //TODO: Make this value configurable } } private void notifyHandlers(int message, Object object) { for(int i = 0; i < handlers.size(); i++) { Handler handler = handlers.get(i); Message msg = handler.obtainMessage(message, object); handler.sendMessage(msg); } } public UserInfo getUserInfo() { return userInfo; } public class UserInfo { String name; String email; boolean verified; long last_selected_bid; long connections; long active_connections; long join_date; boolean auto_away; String limits_name; long limit_networks; boolean limit_passworded_servers; long limit_zombiehours; boolean limit_download_logs; long limit_maxhistorydays; int num_invites; JSONObject prefs; public UserInfo(IRCCloudJSONObject object) throws JSONException { name = object.getString("name"); email = object.getString("email"); verified = object.getBoolean("verified"); last_selected_bid = object.getLong("last_selected_bid"); connections = object.getLong("num_connections"); active_connections = object.getLong("num_active_connections"); join_date = object.getLong("join_date"); auto_away = object.getBoolean("autoaway"); if(object.has("prefs") && !object.getString("prefs").equals("null")) prefs = new JSONObject(object.getString("prefs")); else prefs = null; limits_name = object.getString("limits_name"); JSONObject limits = object.getJSONObject("limits"); limit_networks = limits.getLong("networks"); limit_passworded_servers = limits.getBoolean("passworded_servers"); limit_zombiehours = limits.getLong("zombiehours"); limit_download_logs = limits.getBoolean("download_logs"); limit_maxhistorydays = limits.getLong("maxhistorydays"); } } private class OOBIncludeTask extends AsyncTask<URL, Void, Boolean> { String json = null; @Override protected Boolean doInBackground(URL... url) { try { json = doGet(url[0]); synchronized(parserLock) { long time = System.currentTimeMillis(); Log.i("IRCCloud", "Beginning backlog..."); notifyHandlers(EVENT_BACKLOG_START, null); JSONArray a = new JSONArray(json); for(int i = 0; i < a.length(); i++) parse_object(new IRCCloudJSONObject(a.getJSONObject(i)), true); Log.i("IRCCloud", "Backlog complete!"); Log.i("IRCCloud", "Backlog processing took: " + (System.currentTimeMillis() - time) + "ms"); } notifyHandlers(EVENT_BACKLOG_END, null); return true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } } }
package com.kii.example.sync; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import org.json.JSONException; import com.kii.cloud.storage.EasyClient; import com.kii.cloud.storage.dataType.KiiUser; import com.kii.cloud.storage.manager.AuthManager; import com.kii.cloud.storage.response.CloudExecutionException; import com.kii.mobilesdk.bridge.KiiUMInfo; import com.kii.sync.KiiClient; import com.kii.sync.KiiFile; import com.kii.sync.KiiFileUtil; import com.kii.sync.SyncMsg; import com.kii.sync.utils.Base64; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.text.Html; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class HelloSyncActivity extends Activity { KiiClient kiiClient; AuthManager authMan; Handler myHandler; String userName = "testUser"; public static final String appId = "c42a57d0"; public static final String appKey = "224b6595df9387530feb6f696a51c658"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); kiiClient = KiiClient.getInstance(this.getApplicationContext()); kiiClient.setServerBaseUrl("http://dev-usergrid.kii.com"); myHandler = new Handler(); myHandler.post(new Runnable() { @Override public void run() { new Thread(new Runnable() { public void run() { createUser(); uploadFile(); updateMain(); } }).start(); } }); } private void createUser() { // Set Application ID and Application Key. EasyClient.start(this, appId, appKey); EasyClient.getInstance().setBaseURL("http://dev-usergrid.kii.com:12110"); authMan = EasyClient.getUserManager(); KiiUser kUser = new KiiUser(); // Create User by communicating KiiCloud with User Manager SDK. try { userName = userName + Long.toString(System.currentTimeMillis()); kUser.setUsername(userName); authMan.createUser(kUser, "1234"); authMan.login(userName, "1234"); } catch (CloudExecutionException e) { e.printStackTrace(); throw new RuntimeException("Create user Failed!"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Create user Failed!"); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException("Create user Failed!"); } KiiUMInfo umInfo = new KiiUMInfo(this, userName, "1234", "KII_ID", userName); // Pass the User Information to Sync SDK. kiiClient.setKiiUMInfo(umInfo); } private void uploadFile() { try { kiiClient.initSync(); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException("Sync Failed!"); } catch (InstantiationException e) { e.printStackTrace(); throw new RuntimeException("Sync Failed!"); } File txtFile = createFile(); KiiFile kFile = KiiFileUtil.createKiiFileFromFile(txtFile.getAbsolutePath()); int ret = kiiClient.upload(kFile); if (ret != SyncMsg.OK) { throw new RuntimeException("Sync Failed! code: " + ret); } } private File createFile() { File f = new File(Environment.getExternalStorageDirectory(), "hello.txt"); try { f.createNewFile(); PrintWriter p = new PrintWriter(f); p.write("Hello, Sync"); p.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return f; } private void updateMain() { myHandler.post(new Runnable() { @Override public void run() { TextView linkURL = (TextView) HelloSyncActivity.this.findViewById(R.id.url_link); MovementMethod method = LinkMovementMethod.getInstance(); linkURL.setMovementMethod(method); linkURL.setText(getLink()); linkURL.setVisibility(View.VISIBLE); EditText userNameET = (EditText)HelloSyncActivity.this.findViewById(R.id.username_disp); userNameET.setText(userName); userNameET.setVisibility(View.VISIBLE); } }); } private CharSequence getLink() { Uri.Builder b = new Uri.Builder(); Log.v("HelloSync", Base64.encodeToString((appId+":"+appKey).getBytes(), Base64.DEFAULT)); String lUrl = b.scheme("http") .authority("dev-usergrid.kii.com") .appendQueryParameter( "app", Base64.encodeToString( (appId + ":" + appKey).getBytes(), Base64.DEFAULT)).build().toString(); String htmlLink = "<a href=\"" + lUrl + "\">Sync Success! on Web UI you can see the data uploaded!\nPlease copy user name bellow before click.</a>"; CharSequence seq = Html.fromHtml(htmlLink); return seq; } }
package com.mac.tarchan.desktop; import java.awt.EventQueue; import java.awt.Window; import javax.swing.UIManager; /** * DesktopSupport * * @author tarchan */ public class DesktopSupport { /** * Look&Feel * * @see UIManager#setLookAndFeel(String) */ public static void useSystemLookAndFeel() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception x) { throw new RuntimeException(x); } } public static void useSystemProxies() { System.setProperty("java.net.useSystemProxies", "true"); } public static void printEventDispatchThread() { boolean isEventDispatchThread = EventQueue.isDispatchThread(); if (isEventDispatchThread) { System.out.println("isEventDispatchThread: " + isEventDispatchThread + ", " + Thread.currentThread()); } else { System.err.println("isEventDispatchThread: " + isEventDispatchThread + ", " + Thread.currentThread()); } } /** * * * @param command * @see EventQueue#invokeLater(Runnable) */ public static void execute(Runnable command) { EventQueue.invokeLater(command); } /** * * * @param window * @see EventQueue#invokeLater(Runnable) */ public static void show(final Window window) { execute(new Runnable() { public void run() { window.setVisible(true); } }); } /** * * * @param window * @see EventQueue#invokeLater(Runnable) * @deprecated {@link #show(Window)} */ public static void windowVisible(final Window window) { show(window); } }
package com.maddyhome.idea.vim.group; import com.intellij.ide.bookmarks.Bookmark; import com.intellij.ide.bookmarks.BookmarkManager; import com.intellij.ide.bookmarks.BookmarksListener; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.command.Command; import com.maddyhome.idea.vim.command.CommandState; import com.maddyhome.idea.vim.common.*; import com.maddyhome.idea.vim.helper.EditorHelper; import com.maddyhome.idea.vim.helper.SearchHelper; import com.maddyhome.idea.vim.option.OptionsManager; import org.jdom.Element; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.ref.WeakReference; import java.util.*; import java.util.stream.Collectors; /** * This class contains all the mark related functionality */ public class MarkGroup { public static final char MARK_VISUAL_START = '<'; public static final char MARK_VISUAL_END = '>'; public static final char MARK_CHANGE_START = '['; public static final char MARK_CHANGE_END = ']'; public static final char MARK_CHANGE_POS = '.'; public void editorReleased(@NotNull EditorFactoryEvent event) { // Save off the last caret position of the file before it is closed Editor editor = event.getEditor(); setMark(editor, '"', editor.getCaretModel().getOffset()); } /** * Saves the caret location prior to doing a jump * * @param editor The editor the jump will occur in */ public void saveJumpLocation(@NotNull Editor editor) { addJump(editor, true); setMark(editor, '\''); IdeDocumentHistory.getInstance(editor.getProject()).includeCurrentCommandAsNavigation(); } /** * Gets the requested mark for the editor * * @param editor The editor to get the mark for * @param ch The desired mark * @return The requested mark if set, null if not set */ public @Nullable Mark getMark(@NotNull Editor editor, char ch) { Mark mark = null; if (ch == '`') ch = '\''; // Make sure this is a valid mark if (VALID_GET_MARKS.indexOf(ch) < 0) return null; VirtualFile vf = EditorHelper.getVirtualFile(editor); if ("{}".indexOf(ch) >= 0 && vf != null) { int offset = SearchHelper.findNextParagraph(editor, editor.getCaretModel().getPrimaryCaret(), ch == '{' ? -1 : 1, false); offset = EditorHelper.normalizeOffset(editor, offset, false); LogicalPosition lp = editor.offsetToLogicalPosition(offset); mark = new VimMark(ch, lp.line, lp.column, vf.getPath(), extractProtocol(vf)); } else if ("()".indexOf(ch) >= 0 && vf != null) { int offset = SearchHelper.findNextSentenceStart(editor, editor.getCaretModel().getPrimaryCaret(), ch == '(' ? -1 : 1, false, true); offset = EditorHelper.normalizeOffset(editor, offset, false); LogicalPosition lp = editor.offsetToLogicalPosition(offset); mark = new VimMark(ch, lp.line, lp.column, vf.getPath(), extractProtocol(vf)); } // If this is a file mark, get the mark from this file else if (FILE_MARKS.indexOf(ch) >= 0) { final HashMap fmarks = getFileMarks(editor.getDocument()); if (fmarks != null) { mark = (Mark)fmarks.get(ch); if (mark != null && mark.isClear()) { fmarks.remove(ch); mark = null; } } } // This is a mark from another file else if (GLOBAL_MARKS.indexOf(ch) >= 0) { mark = globalMarks.get(ch); if (mark != null && mark.isClear()) { globalMarks.remove(ch); mark = null; } } return mark; } /** * Get the requested jump. * * @param count Postive for next jump (Ctrl-I), negative for previous jump (Ctrl-O). * @return The jump or null if out of range. */ public @Nullable Jump getJump(int count) { int index = jumps.size() - 1 - (jumpSpot - count); if (index < 0 || index >= jumps.size()) { return null; } else { jumpSpot -= count; return jumps.get(index); } } /** * Get's a mark from the file * * @param editor The editor to get the mark from * @param ch The mark to get * @return The mark in the current file, if set, null if no such mark */ public @Nullable Mark getFileMark(@NotNull Editor editor, char ch) { if (ch == '`') ch = '\''; final HashMap fmarks = getFileMarks(editor.getDocument()); if (fmarks == null) { return null; } Mark mark = (Mark)fmarks.get(ch); if (mark != null && mark.isClear()) { fmarks.remove(ch); mark = null; } return mark; } /** * Sets the specified mark to the caret position of the editor * * @param editor The editor to get the current position from * @param ch The mark set set * @return True if a valid, writable mark, false if not */ public boolean setMark(@NotNull Editor editor, char ch) { return VALID_SET_MARKS.indexOf(ch) >= 0 && setMark(editor, ch, editor.getCaretModel().getOffset()); } /** * Sets the specified mark to the specified location. * * @param editor The editor the mark is associated with * @param ch The mark to set * @param offset The offset to set the mark to * @return true if able to set the mark, false if not */ public boolean setMark(@NotNull Editor editor, char ch, int offset) { if (ch == '`') ch = '\''; LogicalPosition lp = editor.offsetToLogicalPosition(offset); final VirtualFile vf = EditorHelper.getVirtualFile(editor); if (vf == null) { return false; } // File specific marks get added to the file if (FILE_MARKS.indexOf(ch) >= 0) { HashMap<Character, Mark> fmarks = getFileMarks(editor.getDocument()); if (fmarks == null) return false; Mark mark = new VimMark(ch, lp.line, lp.column, vf.getPath(), extractProtocol(vf)); fmarks.put(ch, mark); } // Global marks get set to both the file and the global list of marks else if (GLOBAL_MARKS.indexOf(ch) >= 0) { HashMap<Character, Mark> fmarks = getFileMarks(editor.getDocument()); if (fmarks == null) return false; Bookmark systemMark = createOrGetSystemMark(ch, lp.line, editor); Mark mark; if (systemMark != null) { mark = new IntellijMark(systemMark, lp.column, editor.getProject()); } else { mark = new VimMark(ch, lp.line, lp.column, vf.getPath(), extractProtocol(vf)); } fmarks.put(ch, mark); Mark oldMark = globalMarks.put(ch, mark); if (oldMark instanceof VimMark) { oldMark.clear(); } } return true; } private @Nullable Bookmark createOrGetSystemMark(char ch, int line, @NotNull Editor editor) { if (!OptionsManager.INSTANCE.getIdeamarks().isSet()) return null; final Project project = editor.getProject(); if (project == null) return null; final BookmarkManager bookmarkManager = BookmarkManager.getInstance(project); Bookmark bookmark = bookmarkManager.findBookmarkForMnemonic(ch); if (bookmark != null && bookmark.getLine() == line) return bookmark; final VirtualFile virtualFile = EditorHelper.getVirtualFile(editor); if (virtualFile == null) return null; bookmark = bookmarkManager.addTextBookmark(virtualFile, line, ""); bookmarkManager.setMnemonic(bookmark, ch); return bookmark; } public static String extractProtocol(@NotNull VirtualFile vf) { return VirtualFileManager.extractProtocol(vf.getUrl()); } public void setVisualSelectionMarks(@NotNull Editor editor, @NotNull TextRange range) { setMark(editor, MARK_VISUAL_START, range.getStartOffset()); setMark(editor, MARK_VISUAL_END, range.getEndOffset()); } public void setChangeMarks(@NotNull Editor editor, @NotNull TextRange range) { setMark(editor, MARK_CHANGE_START, range.getStartOffset()); setMark(editor, MARK_CHANGE_END, range.getEndOffset()); } public @Nullable TextRange getChangeMarks(@NotNull Editor editor) { return getMarksRange(editor, MARK_CHANGE_START, MARK_CHANGE_END); } public @Nullable TextRange getVisualSelectionMarks(@NotNull Editor editor) { return getMarksRange(editor, MARK_VISUAL_START, MARK_VISUAL_END); } private @Nullable TextRange getMarksRange(@NotNull Editor editor, char startMark, char endMark) { final Mark start = getMark(editor, startMark); final Mark end = getMark(editor, endMark); if (start != null && end != null) { final int startOffset = EditorHelper.getOffset(editor, start.getLogicalLine(), start.getCol()); final int endOffset = EditorHelper.getOffset(editor, end.getLogicalLine(), end.getCol()); return new TextRange(startOffset, endOffset); } return null; } public void addJump(@NotNull Editor editor, boolean reset) { addJump(editor, editor.getCaretModel().getOffset(), reset); } private void addJump(@NotNull Editor editor, int offset, boolean reset) { final VirtualFile vf = EditorHelper.getVirtualFile(editor); if (vf == null) { return; } LogicalPosition lp = editor.offsetToLogicalPosition(offset); Jump jump = new Jump(lp.line, lp.column, vf.getPath()); final String filename = jump.getFilepath(); for (int i = 0; i < jumps.size(); i++) { Jump j = jumps.get(i); if (filename.equals(j.getFilepath()) && j.getLogicalLine() == jump.getLogicalLine()) { jumps.remove(i); break; } } jumps.add(jump); if (reset) { jumpSpot = -1; } else { jumpSpot++; } if (jumps.size() > SAVE_JUMP_COUNT) { jumps.remove(0); } } public void resetAllMarks() { globalMarks.clear(); fileMarks.clear(); jumps.clear(); } public void removeMark(char ch, @NotNull Mark mark) { if (FILE_MARKS.indexOf(ch) >= 0) { HashMap fmarks = getFileMarks(mark.getFilename()); fmarks.remove(ch); } else if (GLOBAL_MARKS.indexOf(ch) >= 0) { // Global marks are added to global and file marks HashMap fmarks = getFileMarks(mark.getFilename()); fmarks.remove(ch); globalMarks.remove(ch); } mark.clear(); } public @NotNull List<Mark> getMarks(@NotNull Editor editor) { HashSet<Mark> res = new HashSet<>(); final FileMarks<Character, Mark> marks = getFileMarks(editor.getDocument()); if (marks != null) { res.addAll(marks.values()); } res.addAll(globalMarks.values()); ArrayList<Mark> list = new ArrayList<>(res); list.sort(Mark.KeySorter.INSTANCE); return list; } public @NotNull List<Jump> getJumps() { return jumps; } public int getJumpSpot() { return jumpSpot; } /** * Gets the map of marks for the specified file * * @param doc The editor to get the marks for * @return The map of marks. The keys are <code>Character</code>s of the mark names, the values are * <code>Mark</code>s. */ private @Nullable FileMarks<Character, Mark> getFileMarks(final @NotNull Document doc) { VirtualFile vf = FileDocumentManager.getInstance().getFile(doc); if (vf == null) { return null; } return getFileMarks(vf.getPath()); } private @Nullable HashMap<Character, Mark> getAllFileMarks(final @NotNull Document doc) { VirtualFile vf = FileDocumentManager.getInstance().getFile(doc); if (vf == null) { return null; } HashMap<Character, Mark> res = new HashMap<>(); FileMarks<Character, Mark> fileMarks = getFileMarks(doc); if (fileMarks != null) { res.putAll(fileMarks); } for (Character ch : globalMarks.keySet()) { Mark mark = globalMarks.get(ch); if (vf.getPath().equals(mark.getFilename())) { res.put(ch, mark); } } return res; } /** * Gets the map of marks for the specified file * * @param filename The file to get the marks for * @return The map of marks. The keys are <code>Character</code>s of the mark names, the values are * <code>Mark</code>s. */ private FileMarks<Character, Mark> getFileMarks(String filename) { FileMarks<Character, Mark> marks = fileMarks.get(filename); if (marks == null) { marks = new FileMarks<>(); fileMarks.put(filename, marks); } return marks; } public void saveData(@NotNull Element element) { Element marksElem = new Element("globalmarks"); if (!OptionsManager.INSTANCE.getIdeamarks().isSet()) { for (Mark mark : globalMarks.values()) { if (!mark.isClear()) { Element markElem = new Element("mark"); markElem.setAttribute("key", Character.toString(mark.getKey())); markElem.setAttribute("line", Integer.toString(mark.getLogicalLine())); markElem.setAttribute("column", Integer.toString(mark.getCol())); markElem.setAttribute("filename", StringUtil.notNullize(mark.getFilename())); markElem.setAttribute("protocol", StringUtil.notNullize(mark.getProtocol(), "file")); marksElem.addContent(markElem); if (logger.isDebugEnabled()) { logger.debug("saved mark = " + mark); } } } } element.addContent(marksElem); Element fileMarksElem = new Element("filemarks"); List<FileMarks<Character, Mark>> files = new ArrayList<>(fileMarks.values()); files.sort(Comparator.comparing(o -> o.timestamp)); if (files.size() > SAVE_MARK_COUNT) { files = files.subList(files.size() - SAVE_MARK_COUNT, files.size()); } for (String file : fileMarks.keySet()) { FileMarks<Character, Mark> marks = fileMarks.get(file); if (!files.contains(marks)) { continue; } if (marks.size() > 0) { Element fileMarkElem = new Element("file"); fileMarkElem.setAttribute("name", file); fileMarkElem.setAttribute("timestamp", Long.toString(marks.timestamp.getTime())); for (Mark mark : marks.values()) { if (!mark.isClear() && !Character.isUpperCase(mark.getKey()) && SAVE_FILE_MARKS.indexOf(mark.getKey()) >= 0) { Element markElem = new Element("mark"); markElem.setAttribute("key", Character.toString(mark.getKey())); markElem.setAttribute("line", Integer.toString(mark.getLogicalLine())); markElem.setAttribute("column", Integer.toString(mark.getCol())); fileMarkElem.addContent(markElem); } } fileMarksElem.addContent(fileMarkElem); } } element.addContent(fileMarksElem); Element jumpsElem = new Element("jumps"); for (Jump jump : jumps) { Element jumpElem = new Element("jump"); jumpElem.setAttribute("line", Integer.toString(jump.getLogicalLine())); jumpElem.setAttribute("column", Integer.toString(jump.getCol())); jumpElem.setAttribute("filename", StringUtil.notNullize(jump.getFilepath())); jumpsElem.addContent(jumpElem); if (logger.isDebugEnabled()) { logger.debug("saved jump = " + jump); } } element.addContent(jumpsElem); } public void readData(@NotNull Element element) { // We need to keep the filename for now and create the virtual file later. Any attempt to call // LocalFileSystem.getInstance().findFileByPath() results in the following error: // Read access is allowed from event dispatch thread or inside read-action only // (see com.intellij.openapi.application.Application.runReadAction()) Element marksElem = element.getChild("globalmarks"); if (marksElem != null && !OptionsManager.INSTANCE.getIdeamarks().isSet()) { List markList = marksElem.getChildren("mark"); for (Object aMarkList : markList) { Element markElem = (Element)aMarkList; Mark mark = VimMark.create(markElem.getAttributeValue("key").charAt(0), Integer.parseInt(markElem.getAttributeValue("line")), Integer.parseInt(markElem.getAttributeValue("column")), markElem.getAttributeValue("filename"), markElem.getAttributeValue("protocol")); if (mark != null) { globalMarks.put(mark.getKey(), mark); HashMap<Character, Mark> fmarks = getFileMarks(mark.getFilename()); fmarks.put(mark.getKey(), mark); } } } if (logger.isDebugEnabled()) { logger.debug("globalMarks=" + globalMarks); } Element fileMarksElem = element.getChild("filemarks"); if (fileMarksElem != null) { List fileList = fileMarksElem.getChildren("file"); for (Object aFileList : fileList) { Element fileElem = (Element)aFileList; String filename = fileElem.getAttributeValue("name"); Date timestamp = new Date(); try { long date = Long.parseLong(fileElem.getAttributeValue("timestamp")); timestamp.setTime(date); } catch (NumberFormatException e) { // ignore } FileMarks<Character, Mark> fmarks = getFileMarks(filename); List markList = fileElem.getChildren("mark"); for (Object aMarkList : markList) { Element markElem = (Element)aMarkList; Mark mark = VimMark.create(markElem.getAttributeValue("key").charAt(0), Integer.parseInt(markElem.getAttributeValue("line")), Integer.parseInt(markElem.getAttributeValue("column")), filename, markElem.getAttributeValue("protocol")); if (mark != null) fmarks.put(mark.getKey(), mark); } fmarks.setTimestamp(timestamp); } } if (logger.isDebugEnabled()) { logger.debug("fileMarks=" + fileMarks); } jumps.clear(); Element jumpsElem = element.getChild("jumps"); if (jumpsElem != null) { List jumpList = jumpsElem.getChildren("jump"); for (Object aJumpList : jumpList) { Element jumpElem = (Element)aJumpList; Jump jump = new Jump(Integer.parseInt(jumpElem.getAttributeValue("line")), Integer.parseInt(jumpElem.getAttributeValue("column")), jumpElem.getAttributeValue("filename")); jumps.add(jump); } } if (logger.isDebugEnabled()) { logger.debug("jumps=" + jumps); } } /** * This updates all the marks for a file whenever text is deleted from the file. If the line that contains a mark * is completely deleted then the mark is deleted too. If the deleted text is before the marked line, the mark is * moved up by the number of deleted lines. * * @param editor The modified editor * @param marks The editor's marks to update * @param delStartOff The offset within the editor where the deletion occurred * @param delLength The length of the deleted text */ public static void updateMarkFromDelete(@Nullable Editor editor, @Nullable HashMap<Character, Mark> marks, int delStartOff, int delLength) { // Skip all this work if there are no marks if (marks != null && marks.size() > 0 && editor != null) { // Calculate the logical position of the start and end of the deleted text int delEndOff = delStartOff + delLength - 1; LogicalPosition delStart = editor.offsetToLogicalPosition(delStartOff); LogicalPosition delEnd = editor.offsetToLogicalPosition(delEndOff + 1); if (logger.isDebugEnabled()) logger.debug("mark delete. delStart = " + delStart + ", delEnd = " + delEnd); // Now analyze each mark to determine if it needs to be updated or removed for (Character ch : marks.keySet()) { Mark myMark = marks.get(ch); if (!(myMark instanceof VimMark)) continue; VimMark mark = (VimMark) myMark; if (logger.isDebugEnabled()) logger.debug("mark = " + mark); // If the end of the deleted text is prior to the marked line, simply shift the mark up by the // proper number of lines. if (delEnd.line < mark.getLogicalLine()) { int lines = delEnd.line - delStart.line; if (logger.isDebugEnabled()) logger.debug("Shifting mark by " + lines + " lines"); mark.setLogicalLine(mark.getLogicalLine() - lines); } // If the deleted text begins before the mark and ends after the mark then it may be shifted or deleted else if (delStart.line <= mark.getLogicalLine() && delEnd.line >= mark.getLogicalLine()) { int markLineStartOff = EditorHelper.getLineStartOffset(editor, mark.getLogicalLine()); int markLineEndOff = EditorHelper.getLineEndOffset(editor, mark.getLogicalLine(), true); Command command = CommandState.getInstance(editor).getExecutingCommand(); // If text is being changed from the start of the mark line (a special case for mark deletion) boolean changeFromMarkLineStart = command != null && command.getType() == Command.Type.CHANGE && delStartOff == markLineStartOff; // If the marked line is completely within the deleted text, remove the mark (except the special case) if (delStartOff <= markLineStartOff && delEndOff >= markLineEndOff && !changeFromMarkLineStart) { VimPlugin.getMark().removeMark(ch, mark); logger.debug("Removed mark"); } // The deletion only covers part of the marked line so shift the mark only if the deletion begins // on a line prior to the marked line (which means the deletion must end on the marked line). else if (delStart.line < mark.getLogicalLine()) { // shift mark mark.setLogicalLine(delStart.line); if (logger.isDebugEnabled()) logger.debug("Shifting mark to line " + delStart.line); } } } } } /** * This updates all the marks for a file whenever text is inserted into the file. If the line that contains a mark * that is after the start of the insertion point, shift the mark by the number of new lines added. * * @param editor The editor that was updated * @param marks The editor's marks * @param insStartOff The insertion point * @param insLength The length of the insertion */ public static void updateMarkFromInsert(@Nullable Editor editor, @Nullable HashMap<Character, Mark> marks, int insStartOff, int insLength) { if (marks != null && marks.size() > 0 && editor != null) { int insEndOff = insStartOff + insLength; LogicalPosition insStart = editor.offsetToLogicalPosition(insStartOff); LogicalPosition insEnd = editor.offsetToLogicalPosition(insEndOff); if (logger.isDebugEnabled()) logger.debug("mark insert. insStart = " + insStart + ", insEnd = " + insEnd); int lines = insEnd.line - insStart.line; if (lines == 0) return; for (VimMark mark : marks.values().stream().filter(VimMark.class::isInstance).map(VimMark.class::cast).collect(Collectors.toList())) { if (logger.isDebugEnabled()) logger.debug("mark = " + mark); // Shift the mark if the insertion began on a line prior to the marked line. if (insStart.line < mark.getLogicalLine()) { mark.setLogicalLine(mark.getLogicalLine() + lines); if (logger.isDebugEnabled()) logger.debug("Shifting mark by " + lines + " lines"); } } } } private static class FileMarks<K, V> extends HashMap<K, V> { public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } @Override public V put(K key, V value) { timestamp = new Date(); return super.put(key, value); } private Date timestamp = new Date(); } /** * This class is used to listen to editor document changes */ public static class MarkUpdater implements DocumentListener { public static MarkUpdater INSTANCE = new MarkUpdater(); /** * Creates the listener for the supplied editor */ private MarkUpdater() { } /** * This event indicates that a document is about to be changed. We use this event to update all the * editor's marks if text is about to be deleted. * * @param event The change event */ @Override public void beforeDocumentChange(@NotNull DocumentEvent event) { if (!VimPlugin.isEnabled()) return; if (logger.isDebugEnabled()) logger.debug("MarkUpdater before, event = " + event); if (event.getOldLength() == 0) return; Document doc = event.getDocument(); updateMarkFromDelete(getAnEditor(doc), VimPlugin.getMark().getAllFileMarks(doc), event.getOffset(), event.getOldLength()); // TODO - update jumps } /** * This event indicates that a document was just changed. We use this event to update all the editor's * marks if text was just added. * * @param event The change event */ @Override public void documentChanged(@NotNull DocumentEvent event) { if (!VimPlugin.isEnabled()) return; if (logger.isDebugEnabled()) logger.debug("MarkUpdater after, event = " + event); if (event.getNewLength() == 0 || (event.getNewLength() == 1 && event.getNewFragment().charAt(0) != '\n')) return; Document doc = event.getDocument(); updateMarkFromInsert(getAnEditor(doc), VimPlugin.getMark().getAllFileMarks(doc), event.getOffset(), event.getNewLength()); // TODO - update jumps } private @Nullable Editor getAnEditor(@NotNull Document doc) { Editor[] editors = EditorFactory.getInstance().getEditors(doc); if (editors.length > 0) { return editors[0]; } else { return null; } } } public static class MarkListener implements BookmarksListener { private WeakReference<Project> project; private Bookmark bookmarkTemplate = null; @Contract(pure = true) public MarkListener(Project project) { this.project = new WeakReference<>(project); } @Override public void bookmarkAdded(@NotNull Bookmark b) { if (!OptionsManager.INSTANCE.getIdeamarks().isSet()) return; bookmarkTemplate = b; } @Override public void bookmarkRemoved(@NotNull Bookmark b) { if (!OptionsManager.INSTANCE.getIdeamarks().isSet()) return; char ch = b.getMnemonic(); if (GLOBAL_MARKS.indexOf(ch) != -1) { FileMarks<Character, Mark> fmarks = VimPlugin.getMark().getFileMarks(b.getFile().getPath()); fmarks.remove(ch); VimPlugin.getMark().globalMarks.remove(ch); // No need to call mark.clear() } } @Override public void bookmarkChanged(@NotNull Bookmark b) { /* IJ sets named marks in two steps. Firstly it creates an unnamed mark, then adds a mnemonic */ if (!OptionsManager.INSTANCE.getIdeamarks().isSet()) return; if (b != bookmarkTemplate) return; bookmarkTemplate = null; char ch = b.getMnemonic(); if (GLOBAL_MARKS.indexOf(ch) != -1) { int col = 0; Editor editor = EditorHelper.getEditor(b.getFile()); if (editor != null) col = editor.getCaretModel().getCurrentCaret().getLogicalPosition().column; IntellijMark mark = new IntellijMark(b, col, project.get()); FileMarks<Character, Mark> fmarks = VimPlugin.getMark().getFileMarks(b.getFile().getPath()); fmarks.put(ch, mark); VimPlugin.getMark().globalMarks.put(ch, mark); } } } private final @NotNull HashMap<String, FileMarks<Character, Mark>> fileMarks = new HashMap<>(); private final @NotNull HashMap<Character, Mark> globalMarks = new HashMap<>(); private final @NotNull List<Jump> jumps = new ArrayList<>(); private int jumpSpot = -1; private static final int SAVE_MARK_COUNT = 20; private static final int SAVE_JUMP_COUNT = 100; public static final String WR_GLOBAL_MARKS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String WR_REGULAR_FILE_MARKS = "abcdefghijklmnopqrstuvwxyz"; /** Marks: abcdefghijklmnopqrstuvwxyz' */ private static final String WR_FILE_MARKS = WR_REGULAR_FILE_MARKS + "'"; public static final String RO_GLOBAL_MARKS = "0123456789"; private static final String RO_FILE_MARKS = ".[]<>^{}()"; private static final String DEL_CONTEXT_FILE_MARKS = ".^[]\""; /** Marks: .^[]"abcdefghijklmnopqrstuvwxyz */ public static final String DEL_FILE_MARKS = DEL_CONTEXT_FILE_MARKS + WR_REGULAR_FILE_MARKS; /** Marks: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*/ private static final String DEL_GLOBAL_MARKS = RO_GLOBAL_MARKS + WR_GLOBAL_MARKS; /** Marks: .^[]"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ */ public static final String DEL_MARKS = DEL_FILE_MARKS + DEL_GLOBAL_MARKS; /** Marks: abcdefghijklmnopqrstuvwxyz'.^[]" */ private static final String SAVE_FILE_MARKS = WR_FILE_MARKS + DEL_CONTEXT_FILE_MARKS; /** Marks: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 */ private static final String GLOBAL_MARKS = WR_GLOBAL_MARKS + RO_GLOBAL_MARKS; /** Marks: abcdefghijklmnopqrstuvwxyz'[]<>^{}() */ private static final String FILE_MARKS = WR_FILE_MARKS + RO_FILE_MARKS; /** Marks: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' */ private static final String WRITE_MARKS = WR_GLOBAL_MARKS + WR_FILE_MARKS; /** Marks: 0123456789.[]<>^{}() */ private static final String READONLY_MARKS = RO_GLOBAL_MARKS + RO_FILE_MARKS; /** Marks: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' */ private static final String VALID_SET_MARKS = WRITE_MARKS; /** Marks: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'0123456789.[]<>^{}() */ private static final String VALID_GET_MARKS = WRITE_MARKS + READONLY_MARKS; private static final Logger logger = Logger.getInstance(MarkGroup.class.getName()); }
package com.opencms.examples.news; import com.opencms.file.*; import com.opencms.core.*; import com.opencms.util.*; import com.opencms.template.*; import com.opencms.workplace.*; import java.util.*; import javax.servlet.http.*; public class CmsNewsAdmin extends CmsAdminNews implements I_CmsConstants { /** Name of the file parameter in the URL */ public static final String C_NEWS_PARAM_FILE = "file"; /** Name of the date parameter in the HTTP get request */ public static final String C_NEWS_PARAM_DATE = "date"; /** Name of the headline parameter in the HTTP get request */ public static final String C_NEWS_PARAM_HEADLINE = "headline"; /** Name of the shorttext parameter in the HTTP get request */ public static final String C_NEWS_PARAM_SHORTTEXT = "shorttext"; /** Name of the text parameter in the HTTP get request */ public static final String C_NEWS_PARAM_TEXT = "text"; /** Name of the external link parameter in the HTTP get request */ public static final String C_NEWS_PARAM_EXTLINK = "extlink"; /** Name of the state parameter in the HTTP get request */ public static final String C_NEWS_PARAM_STATE = "state"; /** Template selector of the "done" page */ public static final String C_NEWS_DONE = "done"; /** Filelist datablock for news state value */ private final static String C_NEWS_STATE_VALUE = "NEWS_STATE_VALUE"; /** Filelist datablock for news author value */ private final static String C_NEWS_AUTHOR_VALUE = "NEWS_AUTHOR_VALUE"; /** * Indicates if the results of this class are cacheable. * * @param cms A_CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } /** * Gets the content of a defined section in a given template file and its subtemplates * with the given parameters. * * @see getContent(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters) * @param cms A_CmsObject Object for accessing system resources. * @param templateFile Filename of the template file. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. */ public byte[] getContent(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { HttpServletRequest orgReq = (HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest(); HttpSession session = orgReq.getSession(true); // read the parameters String file = (String)parameters.get(C_NEWS_PARAM_FILE); if(file == null) { file = (String)session.getValue(C_NEWS_PARAM_FILE); } else { session.putValue("file", file); } String action = (String)parameters.get("action"); if(action == null) { action = (String)session.getValue("action"); } else { session.putValue("action", action); } String newDate = (String)parameters.get(C_NEWS_PARAM_DATE); String newHeadline = (String)parameters.get(C_NEWS_PARAM_HEADLINE); String newShorttext = (String)parameters.get(C_NEWS_PARAM_SHORTTEXT); String newText = (String)parameters.get(C_NEWS_PARAM_TEXT); String newExternalLink = (String)parameters.get(C_NEWS_PARAM_EXTLINK); String newState = (String)parameters.get(C_NEWS_PARAM_STATE); // load the template file of the news admin screen CmsXmlWpTemplateFile xmlTemplateDocument = (CmsXmlWpTemplateFile)getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector); // Only go on, if the "edit" action was requested if("edit".equals(action)) { // Calendar object used to get the actual date GregorianCalendar cal = new GregorianCalendar(); if(newHeadline == null && newShorttext == null && newText == null && newExternalLink == null) { if(file != null && ! "".equals(file)) { // the user wants to edit an old article CmsNewsTemplateFile newsFile = getNewsContentFile(cms, cms.readFile(file)); A_CmsResource newsContentFileObject = cms.readFileHeader(newsFile.getAbsoluteFilename()); if (!newsContentFileObject.isLocked()) { cms.lockResource(newsFile.getAbsoluteFilename()); } parameters.put(C_NEWS_PARAM_DATE, Utils.getNiceShortDate(newsFile.getNewsDate())); parameters.put(C_NEWS_PARAM_HEADLINE, newsFile.getNewsHeadline()); parameters.put(C_NEWS_PARAM_SHORTTEXT, newsFile.getNewsShortText()); parameters.put(C_NEWS_PARAM_TEXT, newsFile.getNewsText()); parameters.put(C_NEWS_PARAM_EXTLINK, newsFile.getNewsExternalLink()); parameters.put(C_NEWS_PARAM_STATE, new Boolean(newsFile.isNewsActive())); xmlTemplateDocument.setXmlData("author", newsFile.getNewsAuthor()); session.putValue("author", newsFile.getNewsAuthor()); } else { // the user requested a new article // Get the currently logged in user A_CmsUser author = cms.getRequestContext().currentUser(); // Get the String for the author String authorText = null; String initials = getInitials(author); String firstName = author.getFirstname(); String lastName = author.getLastname(); if((firstName == null || "".equals(firstName)) && (lastName == null || "".equals(lastName))) { authorText = initials; } else { authorText = firstName + " " + lastName; authorText = authorText.trim(); authorText = authorText + " (" + initials + ")"; } session.putValue("author", authorText); xmlTemplateDocument.setXmlData("author", authorText); // Get the Sting for the actual date String dateText = Utils.getNiceShortDate(cal.getTime().getTime()); parameters.put(C_NEWS_PARAM_DATE, dateText); } } else { // this is the POST result of an user input CmsNewsTemplateFile newsContentFile = null; if(file == null || "".equals(file)) { // we have to create a new new file // Get the currently logged in user A_CmsUser author = cms.getRequestContext().currentUser(); // Build the new article filename String dateFileText = getDateFileText(cal); String newsNumber = this.getNewArticleNumber(cms, dateFileText); String initials = getInitials(author); String newsFileName = dateFileText + "-" + newsNumber + "-" + initials.toLowerCase(); parameters.put(C_NEWS_PARAM_FILE, newsFileName); newsContentFile = createNewsFile(cms, newsFileName); //, authorText, dateText, newHeadline, newShorttext, newText, newExternalLink); createPageFile(cms, newsFileName); // check the date parameter if(newDate == null || "".equals(newDate)) { newDate = Utils.getNiceShortDate(cal.getTime().getTime()); } // Create task CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms); HttpServletRequest req = (HttpServletRequest)(cms.getRequestContext().getRequest().getOriginalRequest()); String taskUrl = req.getScheme() + "://" + req.getHeader("HOST") + req.getServletPath() + C_NEWS_FOLDER_PAGE + newsFileName + "/index.html"; String taskcomment = "<A HREF=\"javascript:openwinfull('" + taskUrl + "', 'preview', 0, 0);\"> " + taskUrl + "</A>"; CmsTaskAction.create(cms, C_NEWS_USER, C_NEWS_ROLE, lang.getLanguageValue("task.label.news"), taskcomment, Utils.getNiceShortDate(new Date().getTime() + 345600000), "1", "", "", "", ""); } else { newsContentFile = getNewsContentFile(cms, cms.readFile(file)); } setNewsFileContent(newsContentFile, (String)session.getValue("author"), newDate, newHeadline, newShorttext, newText, newExternalLink, newState); cms.unlockResource(newsContentFile.getAbsoluteFilename()); session.removeValue("file"); templateSelector = C_NEWS_DONE; } } // Finally start the processing return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector); } public String getDate(A_CmsObject cms, CmsXmlLanguageFile lang, Hashtable parameters) { String result = (String)parameters.get(C_NEWS_PARAM_DATE); if(result == null) { result = ""; } return result; } public String getHeadline(A_CmsObject cms, CmsXmlLanguageFile lang, Hashtable parameters) { String result = (String)parameters.get(C_NEWS_PARAM_HEADLINE); if(result == null) { result = ""; } return result; } public String getShorttext(A_CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) { Hashtable parameters = (Hashtable)userObject; String result = (String)parameters.get(C_NEWS_PARAM_SHORTTEXT); if(result == null) { result = ""; } return result; } public String getText(A_CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) { Hashtable parameters = (Hashtable)userObject; String result = (String)parameters.get(C_NEWS_PARAM_TEXT); if(result == null) { result = ""; } return result; } public String getExternalLink(A_CmsObject cms, CmsXmlLanguageFile lang, Hashtable parameters) { String result = (String)parameters.get(C_NEWS_PARAM_EXTLINK); if(result == null || "".equals(result)) { result = "http: } return result; } /** * Gets the resources displayed in the Radiobutton group on the new resource dialog. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources (used for optional images). * @param values The links that are connected with each resource. * @param descriptions Description that will be displayed for the new resource. * @param parameters Hashtable of parameters (not used yet). * @returns The vectors names and values are filled with the information found in the * workplace.ini. * @exception Throws CmsException if something goes wrong. */ public Integer getStates(A_CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Vector descriptions, Hashtable parameters) throws CmsException { Boolean state = (Boolean)parameters.get(C_NEWS_PARAM_STATE); names.addElement(""); names.addElement(""); values.addElement("active"); values.addElement("inactive"); descriptions.addElement(lang.getLanguageValue(C_LANG_LABEL + ".active")); descriptions.addElement(lang.getLanguageValue(C_LANG_LABEL + ".inactive")); if(state != null && state.equals(Boolean.TRUE)) { return new Integer(0); } else { return new Integer(1); } } /** * Collects all folders and files that are displayed in the file list. * @param cms The CmsObject. * @return A vector of folder and file objects. * @exception Throws CmsException if something goes wrong. */ public Vector getFiles(A_CmsObject cms) throws CmsException { Vector newsFiles = new Vector(); Vector newsFolders = cms.getSubFolders(C_NEWS_FOLDER_PAGE); int numNewsFolders = newsFolders.size(); for(int i=0; i<numNewsFolders; i++) { A_CmsResource currFolder = (A_CmsResource)newsFolders.elementAt(i); CmsFile newsPageFile = null; try { newsPageFile = cms.readFile(currFolder.getAbsolutePath(), "index.html"); } catch(Exception e) { // Oh... we expected an index file here. // Do nothing instead continue; } newsFiles.addElement(newsPageFile); } return newsFiles; } /** * Used to modify the bit pattern for hiding and showing columns in * the file list. * @param cms Cms object for accessing system resources. * @param prefs Old bit pattern. * @return New modified bit pattern. * @see I_CmsFileListUsers */ public int modifyDisplayedColumns(A_CmsObject cms, int prefs) { prefs = ((prefs & C_FILELIST_TITLE) == 0) ? prefs : (prefs - C_FILELIST_TITLE); prefs = ((prefs & C_FILELIST_TYPE) == 0) ? prefs : (prefs - C_FILELIST_TYPE); return prefs; } /** * Fills all customized columns with the appropriate settings for the given file * list entry. Any column filled by this method may be used in the customized template * for the file list. * @param cms Cms object for accessing system resources. * @param filelist Template file containing the definitions for the file list together with * the included customized defintions. * @param res A_CmsResource Object of the current file list entry. * @param lang Current language file. * @exception CmsException if access to system resources failed. * @see I_CmsFileListUsers */ public void getCustomizedColumnValues(A_CmsObject cms, CmsXmlWpTemplateFile filelistTemplate, A_CmsResource res, CmsXmlLanguageFile lang) throws CmsException { String state = lang.getLanguageValue(C_LANG_LABEL + ".notavailable"); String author = state; String name = null; if(res instanceof CmsFile) { CmsNewsTemplateFile newsContentFile = getNewsContentFile(cms, res); state = newsContentFile.isNewsActive() ? lang.getLanguageValue(C_LANG_LABEL + ".active") : lang.getLanguageValue(C_LANG_LABEL + ".inactive"); author = newsContentFile.getNewsAuthor(); name = newsContentFile.getNewsHeadline(); } filelistTemplate.setData(C_NEWS_STATE_VALUE, state); filelistTemplate.setData(C_NEWS_AUTHOR_VALUE, author); if(name != null) { filelistTemplate.setData(C_FILELIST_NAME_VALUE, name); } } protected CmsNewsTemplateFile getNewsContentFile(A_CmsObject cms, A_CmsResource file) throws CmsException { CmsFile newsContentFileObject = null; CmsNewsTemplateFile newsContentFile = null; // The given file object contains the news page file. // we have to read out the article CmsXmlControlFile newsPageFile = new CmsXmlControlFile(cms, (CmsFile)file); String readParam = newsPageFile.getElementParameter("body", "read"); String newsfolderParam = newsPageFile.getElementParameter("body", "newsfolder"); if(readParam != null && !"".equals(readParam)) { // there is a read parameter given. // so we know which news file should be read. if(newsfolderParam == null || "".equals(newsfolderParam)) { newsfolderParam = C_NEWS_FOLDER_CONTENT; } try { newsContentFileObject = cms.readFile(newsfolderParam, readParam); } catch(Exception e) { // Ooops. The news content file could not be read. newsContentFileObject = null; } if(newsContentFileObject != null) { newsContentFile = new CmsNewsTemplateFile(cms, newsContentFileObject); } } return newsContentFile; } /** * Get the new article number by scanning all existing articles * of the given date and inreasing the maximum number. * @param cms A_CmsObject for accessing system resources * @param dateFileText String containing the date used in news file names * @return new article number. * @exception CmsException */ private String getNewArticleNumber(A_CmsObject cms, String dateFileText) throws CmsException { String numberText = null; // Get all files in the news folder Vector allNews = cms.getFilesInFolder(C_NEWS_FOLDER_CONTENT); int numNews = allNews.size(); int max = -1; for(int i=0; i<numNews; i++) { // Scan all files in the news folder beginning with the // current date String. // The old maximum number will be stored in "max" CmsFile file = (CmsFile)allNews.elementAt(i); String filename = file.getName(); if(filename.startsWith(dateFileText)) { int index1 = filename.indexOf("-"); int index2 = filename.indexOf("-", index1+1); numberText = filename.substring(index1+1, index2); int noOfDay = new Integer(numberText).intValue(); if(noOfDay > max) { max = noOfDay; } } } // Build a 3 digit String representation of the new number // (with leading 0) max++; numberText = "00" + max; if(numberText.length() > 3) { numberText = numberText.substring(1,4); } return numberText; } /** * Get the initials of the current user. * If both firstname and lastname of the user are not set, * the login name will be returned instead. * @author A_CmsUser object of the currently logged in user. * @return initials of the user. */ private String getInitials(A_CmsUser author) { String firstname = author.getFirstname(); String lastname = author.getLastname(); String initials = ""; if(firstname.length() >= 1) { initials = initials + firstname.substring(0,1).toLowerCase(); } if(lastname.length() >= 1) { initials = initials + lastname.substring(0,1).toLowerCase(); } if("".equals(initials)) { initials = author.getName(); } return initials; } /** * Get a String representation of the date given by the <code>cal</code> * object, that can be used to build filenames for news files. * <P> * The date will be written like <code>YYMMDD</code>. * @param cal Calendar object representig the date * @return Date String */ private String getDateFileText(GregorianCalendar cal) { String day="0"+new Integer(cal.get(Calendar.DAY_OF_MONTH)).intValue(); String month="0"+new Integer(cal.get(Calendar.MONTH)+1).intValue(); String year="0"+new Integer(cal.get(Calendar.YEAR) % 100).toString(); if (day.length() > 2) { day=day.substring(1,3); } if (month.length() > 2) { month=month.substring(1,3); } if (year.length() > 2) { year=year.substring(1,3); } return year + month + day; } /** * Create a news content file. * * @param cms A_CmsObject for accessing system resources. * @param newsFileName filename to be used * @param author Author * @param date Date * @param headline Headline * @param shorttext Short news text * @param test Complete news text * @param extlink External link * @exception CmsException */ private CmsNewsTemplateFile createNewsFile(A_CmsObject cms, String newsFileName) throws CmsException { //, String author, String date, String headline, //String shorttext, String text, String extlink) throws CmsException { String fullFilename = C_NEWS_FOLDER_CONTENT + newsFileName; CmsNewsTemplateFile newsTempDoc = new CmsNewsTemplateFile(); newsTempDoc.createNewFile(cms, fullFilename, "plain"); cms.chmod(fullFilename, C_ACCESS_DEFAULT_FLAGS); return newsTempDoc; } private void setNewsFileContent(CmsNewsTemplateFile newsFile, String author, String date, String headline, String shorttext, String text, String extlink, String state) throws CmsException { newsFile.setNewsAuthor(author); if(date != null && !"".equals(date)) { // only set date if given newsFile.setNewsDate(date); } newsFile.setNewsHeadline(headline); newsFile.setNewsShortText(shorttext); newsFile.setNewsText(text); newsFile.setNewsExternalLink(extlink); newsFile.setNewsActive("active".equals(state)); newsFile.write(); } /** * Create a new page file for displayin a given news content file. * * @param cms A_CmsObject for accessing system resources. * @param newsFileName filename to be used * @exception CmsException */ private void createPageFile(A_CmsObject cms, String newsFileName) throws CmsException { // Create the news folder cms.createFolder(C_NEWS_FOLDER_PAGE, newsFileName); /*String fullFolderName = C_NEWS_FOLDER_PAGE + newsFileName + "/"; cms.lockResource(fullFolderName); cms.chmod(fullFolderName, C_ACCESS_DEFAULT_FLAGS); cms.unlockResource(fullFolderName);*/ // Create an index file in this folder String fullFilename = C_NEWS_FOLDER_PAGE + newsFileName + "/index.html"; CmsXmlControlFile pageFile = new CmsXmlControlFile(); pageFile.createNewFile(cms, fullFilename, "newspage"); pageFile.setTemplateClass("com.opencms.template.CmsXmlTemplate"); pageFile.setMasterTemplate("/content/templates/xDemoTemplate1"); pageFile.setElementClass("body", "com.opencms.examples.news.CmsNewsTemplate"); pageFile.setElementTemplate("body", C_PATH_INTERNAL_TEMPLATES + "newsTemplate"); pageFile.setElementParameter("body", "newsfolder", C_NEWS_FOLDER_CONTENT); pageFile.setElementParameter("body", "read", newsFileName); pageFile.write(); cms.chmod(fullFilename, C_ACCESS_DEFAULT_FLAGS); cms.unlockResource(fullFilename); } }
package com.quollwriter.text; import java.util.*; public class TextBlockIterator implements Iterator<TextBlock> { private TextBlock current = null; private boolean firstDone = false; public TextBlockIterator (String t) { if (t == null) { return; } TextIterator ti = new TextIterator (t); this.current = ti.getFirstParagraph (); } public TextBlockIterator (TextIterator ti) { if (ti == null) { return; } this.current = ti.getFirstParagraph (); } public TextBlockIterator (Sentence s) { this.current = s; } public TextBlockIterator (Paragraph p) { this.current = p; } public boolean hasNext () { if (this.current == null) { return false; } if (this.current instanceof Sentence) { Sentence n = (Sentence) this.current.getNext (); if (n == null) { n = (Sentence) this.current; return (Paragraph) n.getParagraph ().getNext () != null; } } return true; } public boolean hasPrevious () { if (this.current == null) { return false; } if (this.current instanceof Sentence) { Sentence n = (Sentence) this.current.getPrevious (); if (n == null) { n = (Sentence) this.current; return (Paragraph) n.getParagraph ().getPrevious () != null; } } return true; } public boolean hasNextSentence () { if (this.current == null) { return false; } if (this.current instanceof Sentence) { Sentence n = (Sentence) this.current.getNext (); if (n == null) { n = (Sentence) this.current; return (Paragraph) n.getParagraph ().getNext () != null; } } return true; } public boolean hasPreviousSentence () { if (this.current == null) { return false; } if (this.current instanceof Sentence) { Sentence n = (Sentence) this.current.getPrevious (); if (n == null) { n = (Sentence) this.current; return (Paragraph) n.getParagraph ().getPrevious () != null; } } return true; } public boolean hasNextParagraph () { if (this.current == null) { return false; } if (this.current instanceof Sentence) { Sentence n = (Sentence) this.current; return (Paragraph) n.getParagraph ().getNext () != null; } if (this.current instanceof Paragraph) { return ((Paragraph) this.current).getNext () != null; } return false; } public boolean hasPreviousParagraph () { if (this.current == null) { return false; } if (this.current instanceof Sentence) { Sentence n = (Sentence) this.current; return (Paragraph) n.getParagraph ().getPrevious () != null; } if (this.current instanceof Paragraph) { return ((Paragraph) this.current).getPrevious () != null; } return false; } public TextBlock current () { return this.current; } public TextBlock next () { if (!this.firstDone) { this.firstDone = true; return this.current; } if (this.current instanceof Sentence) { Sentence n = (Sentence) this.current.getNext (); if (n == null) { n = (Sentence) this.current; this.current = (Paragraph) n.getParagraph ().getNext (); } else { this.current = n; } } if (this.current instanceof Paragraph) { this.current = ((Paragraph) this.current).getFirstSentence (); } return this.current; } public TextBlock previous () { if (!this.firstDone) { this.firstDone = true; return this.current; } if (this.current instanceof Sentence) { Sentence n = ((Sentence) this.current).getPrevious (); if (n == null) { n = (Sentence) this.current; this.current = n.getParagraph ().getPrevious (); } else { this.current = n; } } if (this.current instanceof Paragraph) { this.current = ((Paragraph) this.current).getPrevious ().getLastSentence (); } return this.current; } public Sentence previousSentence () { TextBlock prev = this.previous (); if (prev instanceof Paragraph) { this.current = ((Paragraph) prev).getLastSentence (); } return (Sentence) this.current; } public Sentence nextSentence () { TextBlock next = this.next (); if (next instanceof Paragraph) { this.current = ((Paragraph) next).getFirstSentence (); } return (Sentence) this.current; } public Paragraph nextParagraph () { TextBlock next = this.next (); if (next instanceof Sentence) { this.current = ((Sentence) next).getParagraph ().getNext (); } return (Paragraph) this.current; } public Paragraph previousParagraph () { TextBlock prev = this.previous (); if (prev instanceof Sentence) { this.current = ((Sentence) prev).getParagraph ().getPrevious (); } return (Paragraph) this.current; } public void remove () { throw new UnsupportedOperationException ("Not supported."); } }
package com.ralitski.util.math.geom.d3; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import com.ralitski.util.io.Streamable; import com.ralitski.util.math.geom.n.Point; public class Point3d implements Cloneable, Streamable { public static Point3d midpoint(Point3d p1, Point3d p2) { return new Point3d((p1.x + p2.x) / 2F, (p1.y + p2.y) / 2F, (p1.z + p2.z) / 2F); } public static Point3d origin() { return ORIGIN.clone(); } public static Point3d ORIGIN = new Point3d() { //add, get, set public void addX(float x) { throw new UnsupportedOperationException("Origin can't be edited"); } public void setX(float x) { throw new UnsupportedOperationException("Origin can't be edited"); } public float getX() { return 0; } public void addY(float y) { throw new UnsupportedOperationException("Origin can't be edited"); } public void setY(float y) { throw new UnsupportedOperationException("Origin can't be edited"); } public float getY() { return 0; } public void addZ(float z) { throw new UnsupportedOperationException("Origin can't be edited"); } public void setZ(float z) { throw new UnsupportedOperationException("Origin can't be edited"); } public float getZ() { return 0; } //translation public void translate(Point3d p) { } public void translate(float x, float y, float z) { } //length public float length() { return 0; } public float lengthSquared() { return 0; } public float length(Point3d center) { return center.length(); } public float lengthSquared(Point3d center) { return center.lengthSquared(); } public float length(float ox, float oy, float oz) { return (float)Math.sqrt(lengthSquared(ox, oy, oz)); } public float lengthSquared(float ox, float oy, float oz) { return ox * ox + oy * oy + oz * oz; } //misc public Point3d negative() { return new Point3d(0, 0, 0); } }; private float x; private float y; private float z; public Point3d() {} public Point3d(Point point) { this(point.get(1), point.get(2), point.get(3)); } public Point3d(Vector3d v) { this(v.getX(), v.getY(), v.getZ()); } public Point3d(Point3d p) { this(p.getX(), p.getY(), p.getZ()); } public Point3d(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } //add, get, set public void addX(float x) { this.setX(getX() + x); } public void setX(float x) { this.x = x; } public float getX() { return x; } public void addY(float y) { this.setY(getY() + y); } public void setY(float y) { this.y = y; } public float getY() { return y; } public void addZ(float z) { this.setZ(getZ() + z); } public void setZ(float z) { this.z = z; } public float getZ() { return z; } //translation, scaling public void translate(Point3d p) { translate(p.getX(), p.getY(), p.getZ()); } public void translate(Vector3d v) { translate(v.getX(), v.getY(), v.getZ()); } public void translate(float x, float y, float z) { this.addX(x); this.addY(y); this.addZ(z); } public void multiply(float scale) { setX(getX() * scale); setY(getY() * scale); setZ(getZ() * scale); } //length public float length() { return (float)Math.sqrt(lengthSquared()); } public float lengthSquared() { float x = getX(); float y = getY(); float z = getZ(); return x * x + y * y + z * z; } public float length(Point3d center) { return (float)Math.sqrt(lengthSquared(center)); } public float lengthSquared(Point3d center) { return lengthSquared(center.getX(), center.getY(), center.getZ()); } public float length(float ox, float oy, float oz) { return (float)Math.sqrt(lengthSquared(ox, oy, oz)); } public float lengthSquared(float ox, float oy, float oz) { float x = this.getX() - ox; float y = this.getY() - oy; float z = this.getZ() - oz; return x * x + y * y + z * z; } public void setLength(float length) { float l = length(); if(l == 0) throw new IllegalStateException("Cannot rescale the origin"); multiply(length / l); } public void setLength(Point3d center, float length) { translate(-center.getX(), -center.getY(), -center.getZ()); setLength(length); translate(center); } //rotate public float getAngleX() { return (float)Math.atan2(y, -z); } public float getAngleXDegrees() { return (float)Math.toDegrees(getAngleX()); } public float getAngleY() { return (float)Math.atan2(-z, x); } public float getAngleYDegrees() { return (float)Math.toDegrees(getAngleY()); } public float getAngleZ() { return (float)Math.atan2(y, x); } public float getAngleZDegrees() { return (float)Math.toDegrees(getAngleZ()); } public void rotateXDegrees(float angle) { rotateX((float)Math.toRadians(angle)); } public void rotateX(float angle) { float cos = (float)Math.cos(angle); float sin = (float)Math.sin(angle); float yPrime = cos * y - sin * z; float zPrime = sin * y + cos * z; y = yPrime; z = zPrime; } public void rotateYDegrees(float angle) { rotateY((float)Math.toRadians(angle)); } public void rotateY(float angle) { float cos = (float)Math.cos(angle); float sin = (float)Math.sin(angle); float xPrime = cos * x + sin * z; float zPrime = cos * z - sin * x; x = xPrime; z = zPrime; } public void rotateZDegrees(float angle) { rotateZ((float)Math.toRadians(angle)); } public void rotateZ(float angle) { float cos = (float)Math.cos(angle); float sin = (float)Math.sin(angle); float xPrime = cos * x - sin * y; float yPrime = sin * x + cos * y; x = xPrime; y = yPrime; } public float getAngleAround(Line3d axis) { return new Vector3d(axis.getClosestPointTo(this), this).getAngleAround(axis.getSlope()); } public void rotateAround(Line3d axis, float angle) { Point3d p = axis.getClosestPointTo(this); Vector3d v = new Vector3d(p, this); v.rotateAround(axis.getSlope(), angle); p.translate(v); setX(p.getX()); setY(p.getY()); setZ(p.getZ()); } //misc public Surface3d getAsSurface(Vector3d orthogonalVector) { return new SurfacePoint3d(this, new Plane(this, orthogonalVector)); } public Point3d clone() { return new Point3d(getX(), getY(), getZ()); } public Point3d negative() { return new Point3d(-getX(), -getY(), -getZ()); } public String toString() { return "(" + getX() + ", " + getY() + ", " + getZ() + ")"; } @Override public boolean equals(Object o) { if(this == o) return true; if(o instanceof Point3d) { Point3d p = (Point3d)o; return p.getX() == getX() && p.getY() == getY() && p.getZ() == getZ(); } return false; } // @Override // public int hashCode() { // //uses the lowest bits of each part // return (Float.floatToIntBits(this.getX()) << 16) + (Float.floatToIntBits(this.getY()) & 65535); @Override public void write(DataOutputStream out) throws IOException { out.writeFloat(getX()); out.writeFloat(getY()); out.writeFloat(getZ()); } @Override public void read(DataInputStream in) throws IOException { setX(in.readFloat()); setY(in.readFloat()); setZ(in.readFloat()); } private static class SurfacePoint3d extends Point3d implements Surface3d { private Plane plane; SurfacePoint3d(Point3d p, Plane plane) { super(p); this.plane = plane; } @Override public Line3d getIntersection(Line3d line) { return line.contains(this) ? new Line3d(this) : null; } @Override public boolean contains(Point3d point) { return equals(point); } @Override public Point3d getClosestPointTo(Point3d point) { return point; } //return intersection.isPoint() ? (contains(line.getBase()) ? intersection : null) : getIntersectionInternal(intersection); @Override public Surface3d project(Plane plane, Vector3d direction) { Line3d line = plane.getIntersection(new Line3d(this, direction)); return line.isPoint() ? new SurfacePoint3d(line.getBase(), plane) : null; } @Override public Surface3d crossSection(Plane plane) { return plane.contains(this) ? this : null; } @Override public Plane getPlane() { return plane; } } }
package com.roscopeco.ormdroid; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; public class ListTypeMapping implements TypeMapping { private static final String TAG = "ListTypeMapping"; public Class<?> javaType() { return List.class; } // TODO make sure concreteType is not List, it should be the List's element, or change the argument to List<Class<?>>... public String sqlType(Class<?> concreteType) { // TODO basic typed lists not supported yet if(Number.class.isAssignableFrom(concreteType)) { return "BLOB"; // Raw packed numbers } else if(String.class.isAssignableFrom(concreteType)) { return "BLOB"; // Packed null-terminated strings } // Should never be reached, as Entity Lists must be inversed return "NONE"; } public String encodeValue(SQLiteDatabase db, Object value) { Log.d(TAG, "encoding... " + value); @SuppressWarnings("unchecked") List<Entity> model = (List<Entity>)value; for(Entity entity : model) { if (entity.isTransient()) { if (db == null) { throw new IllegalArgumentException("Transient object doesn't make sense here"); } else { TypeMapper.encodeValue(db, entity.save(db)); } } else { TypeMapper.encodeValue(db, entity.getPrimaryKeyValue()); } } return "<list>"; } // TODO columnIndex == primaryKey for inverse fields... (+ many more dots...) public Object decodeValue(SQLiteDatabase db, Field field, Cursor c, int columnIndex, ArrayList<Entity> precursors) { Log.d(TAG, "decoding... " + field); Class<?> type = field.getType(); if (List.class.isAssignableFrom(type)) { ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); @SuppressWarnings("unchecked") Class<? extends Entity> expEntityType = (Class<? extends Entity>) parameterizedType.getActualTypeArguments()[0]; // TODO parameterizedType.getActualTypeArguments().length should check to always == 1 // TODO could use Query here? Maybe Query could have a primaryKey() method to select by prikey? Entity.EntityMapping map = Entity.getEntityMappingEnsureSchema(db, expEntityType); List list; try { list = (List) type.newInstance(); } catch (IllegalAccessException e) { Log.e(TAG, "IllegalAccessExpression thrown"); e.printStackTrace(); return null; } catch (InstantiationException e) { Log.e(TAG, "InstantiationException thrown"); e.printStackTrace(); return null; } String inverseColumnName = field.getAnnotation(Column.class).inverse(); // TODO non-inverse Lists (i.e. basic types) are not yet implemented if("".equals(inverseColumnName)) return list; Log.d(TAG, "map.mTableName: " + map.mTableName); String sql = "SELECT * FROM " + map.mTableName + " WHERE " + inverseColumnName + "=" + columnIndex; Log.v(TAG, sql); Cursor valc = db.rawQuery(sql, null); if (valc.moveToFirst()) { do { list.add(map.load(db, valc, precursors)); } while(valc.moveToNext()); } valc.close(); return list; } else { throw new IllegalArgumentException("ListTypeMapping can only be used with List subclasses"); } } }
package com.tactfactory.harmony.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.output.support.AbstractXMLOutputProcessor; import org.jdom2.output.support.FormatStack; /** * Utility class for manipulating XML files. */ public abstract class XMLUtils { /** * Open an XML file. * @param fileName The name of the file. * @return The openened Document object. Or null if nothing found. */ public static Document openXMLFile(final String fileName) { Document doc = null; // Make engine final SAXBuilder builder = new SAXBuilder(); final File xmlFile = TactFileUtils.makeFile(fileName); try { // Load XML File doc = builder.build(xmlFile); } catch (JDOMException e) { ConsoleUtils.displayError(e); } catch (IOException e) { ConsoleUtils.displayError(e); } return doc; } /** * Open an XML file. * @param fileName The name of the file. * @return The openened Document object. Or null if nothing found. */ public static Document openXML(final String fileName) { Document doc = null; try { // Make engine final SAXBuilder builder = new SAXBuilder(); final File xmlFile = new File(fileName); if (!xmlFile.exists()) { doc = new Document(); } else { // Load XML File doc = builder.build(xmlFile); } } catch (JDOMException e) { ConsoleUtils.displayError(e); } catch (IOException e) { ConsoleUtils.displayError(e); } return doc; } /** * Write an XML Document to the given file. * @param doc The XML document to write * @param xmlFileName The name of the file */ public static void writeXMLToFile(final Document doc, final String xmlFileName) { try { final File xmlFile = TactFileUtils.makeFile(xmlFileName); final XMLOutputter xmlOutput = new XMLOutputter(); // Write to File // Make beautiful file with indent !!! xmlOutput.setFormat(Format.getPrettyFormat().setIndent(" ")); xmlOutput.setXMLOutputProcessor(new TactXMLOutputter()); FileOutputStream fos = new FileOutputStream( xmlFile.getAbsoluteFile()); xmlOutput.output( doc, new OutputStreamWriter( fos, TactFileUtils.DEFAULT_ENCODING)); fos.close(); } catch (IOException e) { ConsoleUtils.displayError(e); } } /** * Add a node to the XML node if it doesn't contains it already. * @param newNode The node to add * @param id The attribute name to compare * @param baseNode The node to add the new node to. * @return True if the node was added successfully. * False if the node already exists before. */ public static boolean addValue(final Element newNode, final String id, final Element baseNode) { Element findElement = null; // Debug Log ConsoleUtils.displayDebug( "Update String : " + newNode.getAttributeValue(id)); findElement = findNode(baseNode, newNode, id); // If not found Node, create it if (findElement == null) { baseNode.addContent(newNode); return true; } else { newNode.setText(findElement.getText()); return false; } } /** * Find a node in the given node. * @param baseNode The node in whom to search. * @param newNode The node to search. * @param id The attribute name used for the comparison * @return The found node or null if the node doesn't exists */ public static Element findNode(final Element baseNode, final Element newNode, final String id) { Element result = null; final List<Element> nodes = baseNode.getChildren(newNode.getName()); // Look in the children nodes if one node // has the corresponding key/value couple for (final Element node : nodes) { if (node.hasAttributes() && node.getAttributeValue(id) .equals(newNode.getAttributeValue(id))) { result = node; } } return result; } /** * Open a remote XML file. * @param url The url of the xml file. * @return The Element corresponding to the XML. */ public static Document getRemoteXML(final String url) { Document result = null; try { SAXBuilder builder = new SAXBuilder(); result = builder.build(new URL(url)); } catch (MalformedURLException e) { ConsoleUtils.displayError(e); } catch (JDOMException e) { ConsoleUtils.displayError(e); } catch (IOException e) { ConsoleUtils.displayError(e); } return result; } public static class TactXMLOutputter extends AbstractXMLOutputProcessor { @Override protected void printAttribute(final Writer out, final FormatStack fstack, final Attribute attribute) throws IOException { if (!attribute.isSpecified() && fstack.isSpecifiedAttributesOnly()) { return; } if (attribute.getParent().getAttributes().size() > 1) { write(out, fstack.getLineSeparator()); write(out, fstack.getLevelIndent() + fstack.getIndent()); } else { write(out, " "); } write(out, attribute.getQualifiedName()); write(out, "="); write(out, "\""); attributeEscapedEntitiesFilter(out, fstack, attribute.getValue()); write(out, "\""); } protected void printNamespace(Writer out, FormatStack fstack, Namespace ns) throws java.io.IOException { if (ns == Namespace.NO_NAMESPACE) { return; } else { super.printNamespace(out, fstack, ns); } } } }
package com.thaiopensource.relaxng; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.relaxng.datatype.ValidationContext; class ListPattern extends Pattern { Pattern p; Locator locator; ListPattern(Pattern p, Locator locator) { super(false, DATA_CONTENT_TYPE, combineHashCode(LIST_HASH_CODE, p.hashCode())); this.p = p; this.locator = locator; } Pattern expand(PatternBuilder b) { Pattern ep = p.expand(b); if (ep != p) return b.makeList(ep, locator); else return this; } void checkRecursion(int depth) throws SAXException { p.checkRecursion(depth); } boolean samePattern(Pattern other) { return (other instanceof ListPattern && p == ((ListPattern)other).p); } void accept(PatternVisitor visitor) { visitor.visitList(p); } Pattern residual(PatternBuilder b, Atom a) { if (a.matchesList(b, p)) return b.makeEmptySequence(); else return b.makeEmptyChoice(); } void checkRestrictions(int context, DuplicateAttributeDetector dad, Alphabet alpha) throws RestrictionViolationException { switch (context) { case DATA_EXCEPT_CONTEXT: throw new RestrictionViolationException("data_except_contains_list"); case START_CONTEXT: throw new RestrictionViolationException("start_contains_list"); case LIST_CONTEXT: throw new RestrictionViolationException("list_contains_list"); } try { p.checkRestrictions(LIST_CONTEXT, dad, null); } catch (RestrictionViolationException e) { e.maybeSetLocator(locator); throw e; } } }
package com.trendrr.strest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.netty.handler.codec.http.HttpResponseStatus; /** * @author Dustin Norlander * @created Jan 16, 2011 * */ public class StrestHttpException extends StrestException { private static final long serialVersionUID = -1361952863157674845L; protected Log log = LogFactory.getLog(StrestHttpException.class); public static final StrestHttpException BAD_REQUEST() { return new StrestHttpException(400, "Bad Request"); } public static final StrestHttpException BAD_REQUEST(String message) { return new StrestHttpException(400, message); } public static final StrestHttpException UNAUTHORIZED() { return new StrestHttpException(401, "Unauthorized"); } public static final StrestHttpException UNAUTHORIZED(String message) { return new StrestHttpException(401, message); } public static final StrestHttpException PAYMENT_REQUIRED() { return new StrestHttpException(402, "Payment Required"); } public static final StrestHttpException PAYMENT_REQUIRED(String message) { return new StrestHttpException(402, message); } public static final StrestHttpException FORBIDDEN() { return new StrestHttpException(403, "Forbidden"); } public static final StrestHttpException FORBIDDEN(String message) { return new StrestHttpException(403, message); } public static final StrestHttpException NOT_FOUND() { return new StrestHttpException(404, "Not found"); } public static final StrestHttpException NOT_FOUND(String message) { return new StrestHttpException(404, message); } public static final StrestHttpException METHOD_NOT_ALLOWED() { return new StrestHttpException(405, "Method Not Allowed"); } public static final StrestHttpException METHOD_NOT_ALLOWED(String message) { return new StrestHttpException(405, message); } public static final StrestHttpException NOT_ACCEPTABLE() { return new StrestHttpException(406, "Not Acceptable"); } public static final StrestHttpException NOT_ACCEPTABLE(String message) { return new StrestHttpException(406, message); } public static final StrestHttpException CONFLICT() { return new StrestHttpException(409, "Conflict"); } public static final StrestHttpException CONFLICT(String message) { return new StrestHttpException(409, message); } public static final StrestHttpException RATE_LIMITED() { return new StrestHttpException(420, "Rate Limited"); } public static final StrestHttpException RATE_LIMITED(String message) { return new StrestHttpException(420, message); } public static final StrestHttpException INTERNAL_SERVER_ERROR() { return new StrestHttpException(500, "Internal Server Error"); } public static final StrestHttpException INTERNAL_SERVER_ERROR(String message) { return new StrestHttpException(500, message); } public static final StrestHttpException MOVED() { return new StrestHttpException(301, "Moved"); } public static final StrestHttpException MOVED(String message) { return new StrestHttpException(301, message); } int code; public StrestHttpException(int code, String message) { this.code = code; this.message = message; } public StrestHttpException(HttpResponseStatus status) { this(status.getCode(), status.getReasonPhrase()); } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }
package com.vaadin.data.util; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import com.vaadin.data.Container; import com.vaadin.data.Container.Filterable; import com.vaadin.data.Container.Indexed; import com.vaadin.data.Container.ItemSetChangeNotifier; import com.vaadin.data.Container.Sortable; import com.vaadin.data.Property; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.Property.ValueChangeNotifier; /** * An in-memory container for JavaBeans. * * <p> * The properties of the container are determined automatically by introspecting * the used JavaBean class. Only beans of the same type can be added to the * container. * </p> * * <p> * BeanItemContainer uses the beans themselves as identifiers. The * {@link Object#hashCode()} of a bean is used when storing and looking up beans * so it must not change during the lifetime of the bean (it should not depend * on any part of the bean that can be modified). Typically this restricts the * implementation of {@link Object#equals(Object)} as well in order for it to * fulfill the contract between {@code equals()} and {@code hashCode()}. * </p> * * <p> * It is not possible to add additional properties to the container and nested * bean properties are not supported. * </p> * * @param <BT> * The type of the Bean * * @since 5.4 */ @SuppressWarnings("serial") public class BeanItemContainer<BT> implements Indexed, Sortable, Filterable, ItemSetChangeNotifier, ValueChangeListener { /** * The filteredItems variable contains the items that are visible outside * the container. If filters are enabled this contains a subset of allItems, * if no filters are set this contains the same items as allItems. */ private ListSet<BT> filteredItems = new ListSet<BT>(); /** * The allItems variable always contains all the items in the container. * Some or all of these are also in the filteredItems list. */ private ListSet<BT> allItems = new ListSet<BT>(); /** * Maps all beans (item ids) in the container (including filtered) to their * corresponding BeanItem. This requires the beans to implement * {@link Object#equals(Object)} and {@link Object#hashCode()} so it is not * affected by the contents of the bean. */ private final Map<BT, BeanItem<BT>> beanToItem = new HashMap<BT, BeanItem<BT>>(); /** * The type of the beans in the container. */ private final Class<? extends BT> type; /** * A description of the properties found in beans of type {@link #type}. * Determines the property ids that are present in the container. */ private transient LinkedHashMap<String, PropertyDescriptor> model; /** * Collection of listeners interested in * {@link Container.ItemSetChangeEvent ItemSetChangeEvent} events. */ private List<ItemSetChangeListener> itemSetChangeListeners; /** * Filters currently applied to the container. */ private Set<Filter> filters = new HashSet<Filter>(); /** * The item sorter which is used for sorting the container. */ private ItemSorter itemSorter = new DefaultItemSorter(); /** * A special deserialization method that resolves {@link #model} is needed * as PropertyDescriptor is not {@link Serializable}. */ private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); model = BeanItem.getPropertyDescriptors(type); } public BeanItemContainer(Class<? extends BT> type) { if (type == null) { throw new IllegalArgumentException( "The type passed to BeanItemContainer must not be null"); } this.type = type; model = BeanItem.getPropertyDescriptors(type); } @SuppressWarnings("unchecked") public BeanItemContainer(Collection<? extends BT> collection) throws IllegalArgumentException { if (collection == null || collection.isEmpty()) { throw new IllegalArgumentException( "The collection passed to BeanItemContainer must not be null or empty"); } type = (Class<? extends BT>) collection.iterator().next().getClass(); model = BeanItem.getPropertyDescriptors(type); addAll(collection); } /** * Adds all the beans in {@code collection} in one go. More efficient than * adding them one by one. * * @param collection * The collection of beans to add. Must not be null. */ private void addAll(Collection<? extends BT> collection) { // Pre-allocate space for the collection allItems.ensureCapacity(allItems.size() + collection.size()); int idx = size(); for (BT bean : collection) { if (internalAddAt(idx, bean) != null) { idx++; } } // Filter the contents when all items have been added filterAll(); } /** * Unsupported operation. Beans should be added through * {@link #addItemAt(int, Object)}. */ public Object addItemAt(int index) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Adds a new bean at the given index. * * The bean is used both as the item contents and as the item identifier. * * @param index * Index at which the bean should be added. * @param newItemId * The bean to add to the container. * @return Returns the new BeanItem or null if the operation fails. */ public BeanItem<BT> addItemAt(int index, Object newItemId) throws UnsupportedOperationException { if (index < 0 || index > size()) { return null; } else if (index == 0) { // add before any item, visible or not return addItemAtInternalIndex(0, newItemId); } else { // if index==size(), adds immediately after last visible item return addItemAfter(getIdByIndex(index - 1), newItemId); } } /** * Adds a bean at the given index of the internal (unfiltered) list. * <p> * The item is also added in the visible part of the list if it passes the * filters. * </p> * * @param index * Internal index to add the new item. * @param newItemId * Id of the new item to be added. * @return Returns new item or null if the operation fails. */ private BeanItem<BT> addItemAtInternalIndex(int index, Object newItemId) { BeanItem<BT> beanItem = internalAddAt(index, (BT) newItemId); if (beanItem != null) { filterAll(); } return beanItem; } /** * Adds the bean to all internal data structures at the given position. * Fails if the bean is already in the container or is not assignable to the * correct type. Returns a new BeanItem if the bean was added successfully. * * <p> * Caller should call {@link #filterAll()} after calling this method to * ensure the filtered list is updated. * </p> * * @param position * The position at which the bean should be inserted * @param bean * The bean to insert * * @return true if the bean was added successfully, false otherwise */ private BeanItem<BT> internalAddAt(int position, BT bean) { // Make sure that the item has not been added previously if (allItems.contains(bean)) { return null; } if (!type.isAssignableFrom(bean.getClass())) { return null; } // "filteredList" will be updated in filterAll() which should be invoked // by the caller after calling this method. allItems.add(position, bean); BeanItem<BT> beanItem = new BeanItem<BT>(bean, model); beanToItem.put(bean, beanItem); // add listeners to be able to update filtering on property // changes for (Filter filter : filters) { // addValueChangeListener avoids adding duplicates addValueChangeListener(beanItem, filter.propertyId); } return beanItem; } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Indexed#getIdByIndex(int) */ public BT getIdByIndex(int index) { return filteredItems.get(index); } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Indexed#indexOfId(java.lang.Object) */ public int indexOfId(Object itemId) { return filteredItems.indexOf(itemId); } /** * Unsupported operation. Use {@link #addItemAfter(Object, Object)}. */ public Object addItemAfter(Object previousItemId) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Adds the bean after the given bean. * * The bean is used both as the item contents and as the item identifier. * * @see com.vaadin.data.Container.Ordered#addItemAfter(Object, Object) */ public BeanItem<BT> addItemAfter(Object previousItemId, Object newItemId) throws UnsupportedOperationException { // only add if the previous item is visible if (previousItemId == null) { return addItemAtInternalIndex(0, newItemId); } else if (containsId(previousItemId)) { return addItemAtInternalIndex(allItems.indexOf(previousItemId) + 1, newItemId); } else { return null; } } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Ordered#firstItemId() */ public BT firstItemId() { if (size() > 0) { return getIdByIndex(0); } else { return null; } } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Ordered#isFirstId(java.lang.Object) */ public boolean isFirstId(Object itemId) { return firstItemId() == itemId; } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Ordered#isLastId(java.lang.Object) */ public boolean isLastId(Object itemId) { return lastItemId() == itemId; } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Ordered#lastItemId() */ public BT lastItemId() { if (size() > 0) { return getIdByIndex(size() - 1); } else { return null; } } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Ordered#nextItemId(java.lang.Object) */ public BT nextItemId(Object itemId) { int index = indexOfId(itemId); if (index >= 0 && index < size() - 1) { return getIdByIndex(index + 1); } else { // out of bounds return null; } } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Ordered#prevItemId(java.lang.Object) */ public BT prevItemId(Object itemId) { int index = indexOfId(itemId); if (index > 0) { return getIdByIndex(index - 1); } else { // out of bounds return null; } } /** * Unsupported operation. Properties are determined by the introspecting the * bean class. */ public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Unsupported operation. Use {@link #addBean(Object)}. * * @see com.vaadin.data.Container#addItem() */ public Object addItem() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Adds the bean to the Container. * * The bean is used both as the item contents and as the item identifier. * * @see com.vaadin.data.Container#addItem(Object) */ public BeanItem<BT> addBean(BT bean) { return addItem(bean); } /** * Adds the bean to the Container. * * The bean is used both as the item contents and as the item identifier. * * @see com.vaadin.data.Container#addItem(Object) */ public BeanItem<BT> addItem(Object itemId) throws UnsupportedOperationException { if (size() > 0) { // add immediately after last visible item int lastIndex = allItems.indexOf(lastItemId()); return addItemAtInternalIndex(lastIndex + 1, itemId); } else { return addItemAtInternalIndex(0, itemId); } } /* * (non-Javadoc) * * @see com.vaadin.data.Container#containsId(java.lang.Object) */ public boolean containsId(Object itemId) { // only look at visible items after filtering return filteredItems.contains(itemId); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getContainerProperty(java.lang.Object, * java.lang.Object) */ public Property getContainerProperty(Object itemId, Object propertyId) { BeanItem<BT> item = getItem(itemId); if (item == null) { return null; } return item.getItemProperty(propertyId); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getContainerPropertyIds() */ public Collection<String> getContainerPropertyIds() { return model.keySet(); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getItem(java.lang.Object) */ public BeanItem<BT> getItem(Object itemId) { return beanToItem.get(itemId); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getItemIds() */ @SuppressWarnings("unchecked") public Collection<BT> getItemIds() { return (Collection<BT>) filteredItems.clone(); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getType(java.lang.Object) */ public Class<?> getType(Object propertyId) { return model.get(propertyId).getPropertyType(); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#removeAllItems() */ public boolean removeAllItems() throws UnsupportedOperationException { allItems.clear(); filteredItems.clear(); // detach listeners from all BeanItems for (BeanItem<BT> item : beanToItem.values()) { removeAllValueChangeListeners(item); } beanToItem.clear(); fireItemSetChange(); return true; } /** * Unsupported operation. Properties are determined by the introspecting the * bean class. */ public boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#removeItem(java.lang.Object) */ public boolean removeItem(Object itemId) throws UnsupportedOperationException { if (!allItems.remove(itemId)) { return false; } // detach listeners from Item removeAllValueChangeListeners(getItem(itemId)); // remove item beanToItem.remove(itemId); filteredItems.remove(itemId); fireItemSetChange(); return true; } /** * Make this container listen to the given property provided it notifies * when its value changes. * * @param beanItem * The BeanItem that contains the property * @param propertyId * The id of the property */ private void addValueChangeListener(BeanItem<BT> beanItem, Object propertyId) { Property property = beanItem.getItemProperty(propertyId); if (property instanceof ValueChangeNotifier) { // avoid multiple notifications for the same property if // multiple filters are in use ValueChangeNotifier notifier = (ValueChangeNotifier) property; notifier.removeListener(this); notifier.addListener(this); } } /** * Remove this container as a listener for the given property. * * @param item * The BeanItem that contains the property * @param propertyId * The id of the property */ private void removeValueChangeListener(BeanItem<BT> item, Object propertyId) { Property property = item.getItemProperty(propertyId); if (property instanceof ValueChangeNotifier) { ((ValueChangeNotifier) property).removeListener(this); } } /** * Remove this contains as a listener for all the properties in the given * BeanItem. * * @param item * The BeanItem that contains the properties */ private void removeAllValueChangeListeners(BeanItem<BT> item) { for (Object propertyId : item.getItemPropertyIds()) { removeValueChangeListener(item, propertyId); } } /* * (non-Javadoc) * * @see com.vaadin.data.Container#size() */ public int size() { return filteredItems.size(); } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Sortable#getSortableContainerPropertyIds() */ public Collection<Object> getSortableContainerPropertyIds() { LinkedList<Object> sortables = new LinkedList<Object>(); for (Object propertyId : getContainerPropertyIds()) { Class<?> propertyType = getType(propertyId); if (Comparable.class.isAssignableFrom(propertyType) || propertyType.isPrimitive()) { sortables.add(propertyId); } } return sortables; } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Sortable#sort(java.lang.Object[], * boolean[]) */ public void sort(Object[] propertyId, boolean[] ascending) { itemSorter.setSortProperties(this, propertyId, ascending); doSort(); // notifies if anything changes in the filtered list, including order filterAll(); } /** * Perform the sorting of the data structures in the container. This is * invoked when the <code>itemSorter</code> has been prepared for the sort * operation. Typically this method calls * <code>Collections.sort(aCollection, getItemSorter())</code> on all arrays * (containing item ids) that need to be sorted. * */ protected void doSort() { Collections.sort(allItems, getItemSorter()); } /* * (non-Javadoc) * * @see * com.vaadin.data.Container.ItemSetChangeNotifier#addListener(com.vaadin * .data.Container.ItemSetChangeListener) */ public void addListener(ItemSetChangeListener listener) { if (itemSetChangeListeners == null) { itemSetChangeListeners = new LinkedList<ItemSetChangeListener>(); } itemSetChangeListeners.add(listener); } /* * (non-Javadoc) * * @see * com.vaadin.data.Container.ItemSetChangeNotifier#removeListener(com.vaadin * .data.Container.ItemSetChangeListener) */ public void removeListener(ItemSetChangeListener listener) { if (itemSetChangeListeners != null) { itemSetChangeListeners.remove(listener); } } /** * Send an ItemSetChange event to all listeners. */ protected void fireItemSetChange() { if (itemSetChangeListeners != null) { final Container.ItemSetChangeEvent event = new Container.ItemSetChangeEvent() { public Container getContainer() { return BeanItemContainer.this; } }; for (ItemSetChangeListener listener : itemSetChangeListeners) { listener.containerItemSetChange(event); } } } /* * (non-Javadoc) * * @see * com.vaadin.data.Container.Filterable#addContainerFilter(java.lang.Object, * java.lang.String, boolean, boolean) */ public void addContainerFilter(Object propertyId, String filterString, boolean ignoreCase, boolean onlyMatchPrefix) { if (filters.isEmpty()) { filteredItems = (ListSet<BT>) allItems.clone(); } // listen to change events to be able to update filtering for (BeanItem<BT> item : beanToItem.values()) { addValueChangeListener(item, propertyId); } Filter f = new Filter(propertyId, filterString, ignoreCase, onlyMatchPrefix); filter(f); filters.add(f); fireItemSetChange(); } /** * Filter the view to recreate the visible item list from the unfiltered * items, and send a notification if the set of visible items changed in any * way. */ protected void filterAll() { // avoid notification if the filtering had no effect List<BT> originalItems = filteredItems; // it is somewhat inefficient to do a (shallow) clone() every time filteredItems = (ListSet<BT>) allItems.clone(); for (Filter f : filters) { filter(f); } // check if exactly the same items are there after filtering to avoid // unnecessary notifications // this may be slow in some cases as it uses BT.equals() if (!originalItems.equals(filteredItems)) { fireItemSetChange(); } } /** * Remove (from the filtered list) any items that do not match the given * filter. * * @param f * The filter used to determine if items should be removed */ protected void filter(Filter f) { Iterator<BT> iterator = filteredItems.iterator(); while (iterator.hasNext()) { BT bean = iterator.next(); if (!f.passesFilter(getItem(bean))) { iterator.remove(); } } } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Filterable#removeAllContainerFilters() */ public void removeAllContainerFilters() { if (!filters.isEmpty()) { filters = new HashSet<Filter>(); // stop listening to change events for any property for (BeanItem<BT> item : beanToItem.values()) { removeAllValueChangeListeners(item); } filterAll(); } } /* * (non-Javadoc) * * @see * com.vaadin.data.Container.Filterable#removeContainerFilters(java.lang * .Object) */ public void removeContainerFilters(Object propertyId) { if (!filters.isEmpty()) { boolean filteringChanged = false; for (Iterator<Filter> iterator = filters.iterator(); iterator .hasNext();) { Filter f = iterator.next(); if (f.propertyId.equals(propertyId)) { iterator.remove(); filteringChanged = true; } } if (filteringChanged) { // stop listening to change events for the property for (BeanItem<BT> item : beanToItem.values()) { removeValueChangeListener(item, propertyId); } filterAll(); } } } /* * (non-Javadoc) * * @see * com.vaadin.data.Property.ValueChangeListener#valueChange(com.vaadin.data * .Property.ValueChangeEvent) */ public void valueChange(ValueChangeEvent event) { // if a property that is used in a filter is changed, refresh filtering filterAll(); } /** * Returns the ItemSorter that is used for sorting the container. * * @see #setItemSorter(ItemSorter) * * @return The ItemSorter that is used for sorting the container */ public ItemSorter getItemSorter() { return itemSorter; } /** * Sets the ItemSorter that is used for sorting the container. The * {@link ItemSorter#compare(Object, Object)} method is called to compare * two beans (item ids). * * @param itemSorter * The ItemSorter to use when sorting the container */ public void setItemSorter(ItemSorter itemSorter) { this.itemSorter = itemSorter; } }
package org.postgresql; import java.io.*; import java.lang.*; import java.net.*; import java.util.*; import java.sql.*; import java.security.*; import org.postgresql.*; import org.postgresql.core.*; import org.postgresql.util.*; /** * $Id: PG_Stream.java,v 1.12 2001/08/26 01:06:20 momjian Exp $ * * This class is used by Connection & PGlobj for communicating with the * backend. * * @see java.sql.Connection */ // This class handles all the Streamed I/O for a org.postgresql connection public class PG_Stream { private Socket connection; private InputStream pg_input; private BufferedOutputStream pg_output; private byte[] byte_buf = new byte[8*1024]; BytePoolDim1 bytePoolDim1 = new BytePoolDim1(); BytePoolDim2 bytePoolDim2 = new BytePoolDim2(); private static class PrivilegedSocket implements PrivilegedExceptionAction { private String host; private int port; PrivilegedSocket(String host, int port) { this.host = host; this.port = port; } public Object run() throws Exception { return new Socket(host, port); } } /** * Constructor: Connect to the PostgreSQL back end and return * a stream connection. * * @param host the hostname to connect to * @param port the port number that the postmaster is sitting on * @exception IOException if an IOException occurs below it. */ public PG_Stream(String host, int port) throws IOException { PrivilegedSocket ps = new PrivilegedSocket(host, port); try { connection = (Socket)AccessController.doPrivileged(ps); } catch(PrivilegedActionException pae){ throw (IOException)pae.getException(); } // Submitted by Jason Venner <jason@idiom.com> adds a 10x speed // improvement on FreeBSD machines (caused by a bug in their TCP Stack) connection.setTcpNoDelay(true); // Buffer sizes submitted by Sverre H Huseby <sverrehu@online.no> pg_input = new BufferedInputStream(connection.getInputStream(), 8192); pg_output = new BufferedOutputStream(connection.getOutputStream(), 8192); } /** * Sends a single character to the back end * * @param val the character to be sent * @exception IOException if an I/O error occurs */ public void SendChar(int val) throws IOException { pg_output.write((byte)val); } /** * Sends an integer to the back end * * @param val the integer to be sent * @param siz the length of the integer in bytes (size of structure) * @exception IOException if an I/O error occurs */ public void SendInteger(int val, int siz) throws IOException { byte[] buf = bytePoolDim1.allocByte(siz); while (siz { buf[siz] = (byte)(val & 0xff); val >>= 8; } Send(buf); } /** * Send an array of bytes to the backend * * @param buf The array of bytes to be sent * @exception IOException if an I/O error occurs */ public void Send(byte buf[]) throws IOException { pg_output.write(buf); } /** * Send an exact array of bytes to the backend - if the length * has not been reached, send nulls until it has. * * @param buf the array of bytes to be sent * @param siz the number of bytes to be sent * @exception IOException if an I/O error occurs */ public void Send(byte buf[], int siz) throws IOException { Send(buf,0,siz); } /** * Send an exact array of bytes to the backend - if the length * has not been reached, send nulls until it has. * * @param buf the array of bytes to be sent * @param off offset in the array to start sending from * @param siz the number of bytes to be sent * @exception IOException if an I/O error occurs */ public void Send(byte buf[], int off, int siz) throws IOException { int i; pg_output.write(buf, off, ((buf.length-off) < siz ? (buf.length-off) : siz)); if((buf.length-off) < siz) { for (i = buf.length-off ; i < siz ; ++i) { pg_output.write(0); } } } /** * Receives a single character from the backend * * @return the character received * @exception SQLException if an I/O Error returns */ public int ReceiveChar() throws SQLException { int c = 0; try { c = pg_input.read(); if (c < 0) throw new PSQLException("postgresql.stream.eof"); } catch (IOException e) { throw new PSQLException("postgresql.stream.ioerror",e); } return c; } /** * Receives an integer from the backend * * @param siz length of the integer in bytes * @return the integer received from the backend * @exception SQLException if an I/O error occurs */ public int ReceiveInteger(int siz) throws SQLException { int n = 0; try { for (int i = 0 ; i < siz ; i++) { int b = pg_input.read(); if (b < 0) throw new PSQLException("postgresql.stream.eof"); n = n | (b << (8 * i)) ; } } catch (IOException e) { throw new PSQLException("postgresql.stream.ioerror",e); } return n; } /** * Receives an integer from the backend * * @param siz length of the integer in bytes * @return the integer received from the backend * @exception SQLException if an I/O error occurs */ public int ReceiveIntegerR(int siz) throws SQLException { int n = 0; try { for (int i = 0 ; i < siz ; i++) { int b = pg_input.read(); if (b < 0) throw new PSQLException("postgresql.stream.eof"); n = b | (n << 8); } } catch (IOException e) { throw new PSQLException("postgresql.stream.ioerror",e); } return n; } /** * Receives a null-terminated string from the backend. If we don't see a * null, then we assume something has gone wrong. * * @param encoding the charset encoding to use. * @return string from back end * @exception SQLException if an I/O error occurs, or end of file */ public String ReceiveString(Encoding encoding) throws SQLException { int s = 0; byte[] rst = byte_buf; try { int buflen = rst.length; boolean done = false; while (!done) { while (s < buflen) { int c = pg_input.read(); if (c < 0) throw new PSQLException("postgresql.stream.eof"); else if (c == 0) { rst[s] = 0; done = true; break; } else { rst[s++] = (byte)c; } if (s >= buflen) { // Grow the buffer buflen = (int)(buflen*2); // 100% bigger byte[] newrst = new byte[buflen]; System.arraycopy(rst, 0, newrst, 0, s); rst = newrst; } } } } catch (IOException e) { throw new PSQLException("postgresql.stream.ioerror",e); } return encoding.decode(rst, 0, s); } /** * Read a tuple from the back end. A tuple is a two dimensional * array of bytes * * @param nf the number of fields expected * @param bin true if the tuple is a binary tuple * @return null if the current response has no more tuples, otherwise * an array of strings * @exception SQLException if a data I/O error occurs */ public byte[][] ReceiveTuple(int nf, boolean bin) throws SQLException { int i, bim = (nf + 7)/8; byte[] bitmask = Receive(bim); byte[][] answer = bytePoolDim2.allocByte(nf); int whichbit = 0x80; int whichbyte = 0; for (i = 0 ; i < nf ; ++i) { boolean isNull = ((bitmask[whichbyte] & whichbit) == 0); whichbit >>= 1; if (whichbit == 0) { ++whichbyte; whichbit = 0x80; } if (isNull) answer[i] = null; else { int len = ReceiveIntegerR(4); if (!bin) len -= 4; if (len < 0) len = 0; answer[i] = Receive(len); } } return answer; } /** * Reads in a given number of bytes from the backend * * @param siz number of bytes to read * @return array of bytes received * @exception SQLException if a data I/O error occurs */ private byte[] Receive(int siz) throws SQLException { byte[] answer = bytePoolDim1.allocByte(siz); Receive(answer,0,siz); return answer; } /** * Reads in a given number of bytes from the backend * * @param buf buffer to store result * @param off offset in buffer * @param siz number of bytes to read * @exception SQLException if a data I/O error occurs */ public void Receive(byte[] b,int off,int siz) throws SQLException { int s = 0; try { while (s < siz) { int w = pg_input.read(b, off+s, siz - s); if (w < 0) throw new PSQLException("postgresql.stream.eof"); s += w; } } catch (IOException e) { throw new PSQLException("postgresql.stream.ioerror",e); } } /** * This flushes any pending output to the backend. It is used primarily * by the Fastpath code. * @exception SQLException if an I/O error occurs */ public void flush() throws SQLException { try { pg_output.flush(); } catch (IOException e) { throw new PSQLException("postgresql.stream.flush",e); } } /** * Closes the connection * * @exception IOException if a IO Error occurs */ public void close() throws IOException { pg_output.close(); pg_input.close(); connection.close(); } }
package ch.unizh.ini.headtracker; import ch.unizh.ini.caviar.chip.AEChip; import ch.unizh.ini.caviar.event.EventPacket; import ch.unizh.ini.caviar.eventprocessing.EventFilter2D; import ch.unizh.ini.caviar.eventprocessing.FilterChain; import ch.unizh.ini.caviar.eventprocessing.tracking.RectangularClusterTracker; import ch.unizh.ini.caviar.graphics.FrameAnnotater; import java.awt.Graphics2D; import javax.media.opengl.GLAutoDrawable; /** * Tracks head and applies active appearance models to extract face parameters. *<p> * * @author alex tureczek */ public class HeadTracker extends EventFilter2D implements FrameAnnotater{ RectangularClusterTracker rectangularClusterTracker; private float headSize=getPrefs().getFloat("HeadTracker.headSize",.1f); /** Creates a new instance of HeadTracker */ public HeadTracker(AEChip chip) { super(chip); rectangularClusterTracker=new RectangularClusterTracker(chip); rectangularClusterTracker.setClusterSize(headSize); FilterChain chain=new FilterChain(chip); setEnclosedFilterChain(chain); getEnclosedFilterChain().add(rectangularClusterTracker); } public EventPacket<?> filterPacket(EventPacket<?> in) { if(!isFilterEnabled()) return in; rectangularClusterTracker.filterPacket(in); return in; } public void resetFilter() { } public void initFilter() { } public Object getFilterState() { return null; } public void annotate(float[][][] frame) { } public void annotate(Graphics2D g) { } public void annotate(GLAutoDrawable drawable) { } public float getHeadSize() { return headSize; } public void setHeadSize(float headSize) { this.headSize = headSize; getPrefs().putFloat("HeadTracker.headSize",headSize); rectangularClusterTracker.setClusterSize(headSize); } }
package kata; import java.util.*; public class BasicCalculator { static int basicCalculator(String exp) { char[] chars = exp.toCharArray(); Stack<Integer> values = new Stack<>(); Stack<Character> ops = new Stack<>(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (Character.isDigit(c)) { int val = c - '0'; int j = i + 1; while (j < chars.length && Character.isDigit(chars[j])) { val = val * 10 + chars[j] - '0'; j++; } values.push(val); i = j - 1; // advance i to the last digit, so the next i++ works } else if (c == '+' || c == '-' || c == '*' || c == '/') { // Only evaluate if there is a previous op while (!ops.isEmpty() && hasPrecedence(ops.peek(), c)) { values.push(evalOp(ops.pop(), values.pop(), values.pop())); } ops.push(c); } else if (c == '(') { ops.push(c); } else if (c == ')') { while (ops.peek() != '(') { values.push(evalOp(ops.pop(), values.pop(), values.pop())); } ops.pop(); // take out '(' } } // the expression is parsed, now just take care of the ops stack while (!ops.isEmpty()) { values.push(evalOp(ops.pop(), values.pop(), values.pop())); } return values.pop(); } // If op1 has higher or equal precedence as op2. static boolean hasPrecedence(char op1, char op2) { if (op1 == '(' || op1 == ')') { return false; } if ((op1 == '+' || op1 == '-') && (op2 == '*' || op2 == '/')) { return false; } return true; } // The operand parameters are reversed so the caller can pass the parameters // in reverse, i.e. stack.pop(), stack.pop(). static int evalOperator(char op, int operand2, int operand1) { if (op == '*') { return operand1 * operand2; } if (op == '+') { return operand1 + operand2; } if (op == '-') { return operand1 - operand2; } if (op == '/') { return operand1 - operand2; } throw new RuntimeException("impossible"); } // My dumb method static int basicCalculator2(String exp) { Stack<Delayed> delayeds = new Stack<Delayed>(); return calculate(exp.toCharArray(), 0, exp.length(), delayeds, /* prevVal= */ 0, /* prevOp= */ '0', /* curVal= */ 0); } static int calculate(char[] chars, int i, int n, Stack<Delayed> delayeds, int prevVal, char prevOp, int curVal) { if (i == n) { return evaluate(prevVal, prevOp, curVal, delayeds); } char c = chars[i]; if (Character.isDigit(c)) { return calculate(chars, i + 1, n, delayeds, prevVal, prevOp, curVal * 10 + (c - '0')); } if (c == '+' || c == '-') { if (prevOp == '*') { Delayed delayed = delayeds.pop(); curVal = evalOp(delayed.op, delayed.operand, evalOp(prevOp, prevVal, curVal)); } return evalOpAndContinue(chars, i + 1, n, delayeds, prevVal, /* prevOp= */ prevOp, /* curVal= */ curVal, c); } else if (c == '*') { delayeds.push(new Delayed(prevVal, prevOp)); return calculate(chars, i + 1, n, delayeds, /* prevVal= */ curVal, /* prevOp= */ '*', /* curVal= */ 0); } else if (c == '(') { delayeds.push(new Delayed(prevVal, prevOp)); return calculate(chars, i + 1, n, delayeds, /* prevVal= */ 0, /* prevOp= */ '0', /* curVal= */ 0); } else if (c == ')') { Delayed delayed = delayeds.pop(); int result = evalOp(delayed.op, delayed.operand, evalOp(prevOp, prevVal, curVal)); return calculate(chars, i + 1, n, delayeds, /* prevVal= */ 0, /* prevOp= */ '0', /* curVal= */ result); } throw new RuntimeException("impossible"); } static int evalOpAndContinue(char[] chars, int i, int n, Stack<Delayed> delayeds, int prevVal, char prevOp, int curVal, char curOp) { int val = evalOp(prevOp, prevVal, curVal); return calculate(chars, i, n, delayeds, /* prevVal= */ val, /* prevOp= */ curOp, /* curVal= */ 0); } static int evalOp(char op, int operand1, int operand2) { if (op == '*') { return operand1 * operand2; } if (op == '+') { return operand1 + operand2; } if (op == '-') { return operand1 - operand2; } // special case for "(" happens at the beginning. return operand2; } static int evaluate(int prevVal, char prevOp, int curVal, Stack<Delayed> delayeds) { int result = evalOp(prevOp, prevVal, curVal); if (delayeds.isEmpty()) { return result; } Delayed delayed = delayeds.pop(); return evaluate(delayed.operand, delayed.op, result, delayeds); } static class Delayed { int operand; char op; Delayed(int operand, char op) { this.operand = operand; this.op = op; } } public static void main(String args[]) { runSample("1+2*3"); runSample("1*2+3"); runSample("7-2-3"); runSample("7-(3-1)"); runSample("(1+2)*3"); runSample("((1+2)*(3+4))"); runSample("((10+20)*(19+24))"); } static void runSample(String s) { System.out.printf("%s = %s\n", s, basicCalculator(s)); } }
package de.duenndns.ssl; import android.app.Activity; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.SparseArray; import android.os.Handler; import java.io.File; import java.io.IOException; import java.security.cert.*; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; import java.util.logging.Level; import java.util.logging.Logger; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.Locale; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * A X509 trust manager implementation which asks the user about invalid * certificates and memorizes their decision. * <p> * The certificate validity is checked using the system default X509 * TrustManager, creating a query Dialog if the check fails. * <p> * <b>WARNING:</b> This only works if a dedicated thread is used for * opening sockets! */ public class MemorizingTrustManager implements X509TrustManager { final static String DECISION_INTENT = "de.duenndns.ssl.DECISION"; final static String DECISION_INTENT_ID = DECISION_INTENT + ".decisionId"; final static String DECISION_INTENT_CERT = DECISION_INTENT + ".cert"; final static String DECISION_INTENT_CHOICE = DECISION_INTENT + ".decisionChoice"; private final static Logger LOGGER = Logger.getLogger(MemorizingTrustManager.class.getName()); final static String DECISION_TITLE_ID = DECISION_INTENT + ".titleId"; private final static int NOTIFICATION_ID = 100509; final static String NO_TRUST_ANCHOR = "Trust anchor for certification path not found."; static String KEYSTORE_DIR = "KeyStore"; static String KEYSTORE_FILE = "KeyStore.bks"; Context master; Activity foregroundAct; NotificationManager notificationManager; private static int decisionId = 0; private static SparseArray<MTMDecision> openDecisions = new SparseArray<MTMDecision>(); Handler masterHandler; private File keyStoreFile; private KeyStore appKeyStore; private X509TrustManager defaultTrustManager; private X509TrustManager appTrustManager; /** Creates an instance of the MemorizingTrustManager class that falls back to a custom TrustManager. * * You need to supply the application context. This has to be one of: * - Application * - Activity * - Service * * The context is used for file management, to display the dialog / * notification and for obtaining translated strings. * * @param m Context for the application. * @param defaultTrustManager Delegate trust management to this TM. If null, the user must accept every certificate. */ public MemorizingTrustManager(Context m, X509TrustManager defaultTrustManager) { init(m); this.appTrustManager = getTrustManager(appKeyStore); this.defaultTrustManager = defaultTrustManager; } /** Creates an instance of the MemorizingTrustManager class using the system X509TrustManager. * * You need to supply the application context. This has to be one of: * - Application * - Activity * - Service * * The context is used for file management, to display the dialog / * notification and for obtaining translated strings. * * @param m Context for the application. */ public MemorizingTrustManager(Context m) { init(m); this.appTrustManager = getTrustManager(appKeyStore); this.defaultTrustManager = getTrustManager(null); } void init(Context m) { master = m; masterHandler = new Handler(m.getMainLooper()); notificationManager = (NotificationManager)master.getSystemService(Context.NOTIFICATION_SERVICE); Application app; if (m instanceof Application) { app = (Application)m; } else if (m instanceof Service) { app = ((Service)m).getApplication(); } else if (m instanceof Activity) { app = ((Activity)m).getApplication(); } else throw new ClassCastException("MemorizingTrustManager context must be either Activity or Service!"); File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE); keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE); appKeyStore = loadAppKeyStore(); } /** * Returns a X509TrustManager list containing a new instance of * TrustManagerFactory. * * This function is meant for convenience only. You can use it * as follows to integrate TrustManagerFactory for HTTPS sockets: * * <pre> * SSLContext sc = SSLContext.getInstance("TLS"); * sc.init(null, MemorizingTrustManager.getInstanceList(this), * new java.security.SecureRandom()); * HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); * </pre> * @param c Activity or Service to show the Dialog / Notification */ public static X509TrustManager[] getInstanceList(Context c) { return new X509TrustManager[] { new MemorizingTrustManager(c) }; } /** * Binds an Activity to the MTM for displaying the query dialog. * * This is useful if your connection is run from a service that is * triggered by user interaction -- in such cases the activity is * visible and the user tends to ignore the service notification. * * You should never have a hidden activity bound to MTM! Use this * function in onResume() and @see unbindDisplayActivity in onPause(). * * @param act Activity to be bound */ public void bindDisplayActivity(Activity act) { foregroundAct = act; } /** * Removes an Activity from the MTM display stack. * * Always call this function when the Activity added with * {@link #bindDisplayActivity(Activity)} is hidden. * * @param act Activity to be unbound */ public void unbindDisplayActivity(Activity act) { // do not remove if it was overridden by a different activity if (foregroundAct == act) foregroundAct = null; } /** * Changes the path for the KeyStore file. * * The actual filename relative to the app's directory will be * <code>app_<i>dirname</i>/<i>filename</i></code>. * * @param dirname directory to store the KeyStore. * @param filename file name for the KeyStore. */ public static void setKeyStoreFile(String dirname, String filename) { KEYSTORE_DIR = dirname; KEYSTORE_FILE = filename; } /** * Get a list of all certificate aliases stored in MTM. * * @return an {@link Enumeration} of all certificates */ public Enumeration<String> getCertificates() { try { return appKeyStore.aliases(); } catch (KeyStoreException e) { // this should never happen, however... throw new RuntimeException(e); } } /** * Get a certificate for a given alias. * * @param alias the certificate's alias as returned by {@link #getCertificates()}. * * @return the certificate associated with the alias or <tt>null</tt> if none found. */ public Certificate getCertificate(String alias) { try { return appKeyStore.getCertificate(alias); } catch (KeyStoreException e) { // this should never happen, however... throw new RuntimeException(e); } } /** * Removes the given certificate from MTMs key store. * * <p> * <b>WARNING</b>: this does not immediately invalidate the certificate. It is * well possible that (a) data is transmitted over still existing connections or * (b) new connections are created using TLS renegotiation, without a new cert * check. * </p> * @param alias the certificate's alias as returned by {@link #getCertificates()}. * * @throws KeyStoreException if the certificate could not be deleted. */ public void deleteCertificate(String alias) throws KeyStoreException { appKeyStore.deleteEntry(alias); keyStoreUpdated(); } public HostnameVerifier wrapHostnameVerifier(final HostnameVerifier defaultVerifier) { if (defaultVerifier == null) throw new IllegalArgumentException("The default verifier may not be null"); return new MemorizingHostnameVerifier(defaultVerifier); } X509TrustManager getTrustManager(KeyStore ks) { try { TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(ks); for (TrustManager t : tmf.getTrustManagers()) { if (t instanceof X509TrustManager) { return (X509TrustManager)t; } } } catch (Exception e) { // Here, we are covering up errors. It might be more useful // however to throw them out of the constructor so the // embedding app knows something went wrong. LOGGER.log(Level.SEVERE, "getTrustManager(" + ks + ")", e); } return null; } KeyStore loadAppKeyStore() { KeyStore ks; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { LOGGER.log(Level.SEVERE, "getAppKeyStore()", e); return null; } try { ks.load(null, null); ks.load(new java.io.FileInputStream(keyStoreFile), "MTM".toCharArray()); } catch (java.io.FileNotFoundException e) { LOGGER.log(Level.INFO, "getAppKeyStore(" + keyStoreFile + ") - file does not exist"); } catch (Exception e) { LOGGER.log(Level.SEVERE, "getAppKeyStore(" + keyStoreFile + ")", e); } return ks; } void storeCert(String alias, Certificate cert) { try { appKeyStore.setCertificateEntry(alias, cert); } catch (KeyStoreException e) { LOGGER.log(Level.SEVERE, "storeCert(" + cert + ")", e); return; } keyStoreUpdated(); } void storeCert(X509Certificate cert) { storeCert(cert.getSubjectDN().toString(), cert); } void keyStoreUpdated() { // reload appTrustManager appTrustManager = getTrustManager(appKeyStore); // store KeyStore to file java.io.FileOutputStream fos = null; try { fos = new java.io.FileOutputStream(keyStoreFile); appKeyStore.store(fos, "MTM".toCharArray()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e); } } } } // if the certificate is stored in the app key store, it is considered "known" private boolean isCertKnown(X509Certificate cert) { try { return appKeyStore.getCertificateAlias(cert) != null; } catch (KeyStoreException e) { return false; } } private boolean isExpiredException(Throwable e) { do { if (e instanceof CertificateExpiredException) return true; e = e.getCause(); } while (e != null); return false; } public void checkCertTrusted(X509Certificate[] chain, String authType, boolean isServer) throws CertificateException { LOGGER.log(Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")"); try { LOGGER.log(Level.FINE, "checkCertTrusted: trying appTrustManager"); if (isServer) appTrustManager.checkServerTrusted(chain, authType); else appTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException ae) { LOGGER.log(Level.FINER, "checkCertTrusted: appTrustManager failed", ae); // if the cert is stored in our appTrustManager, we ignore expiredness if (isExpiredException(ae)) { LOGGER.log(Level.INFO, "checkCertTrusted: accepting expired certificate from keystore"); return; } if (isCertKnown(chain[0])) { LOGGER.log(Level.INFO, "checkCertTrusted: accepting cert already stored in keystore"); return; } try { if (defaultTrustManager == null) throw ae; LOGGER.log(Level.FINE, "checkCertTrusted: trying defaultTrustManager"); if (isServer) defaultTrustManager.checkServerTrusted(chain, authType); else defaultTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException e) { LOGGER.log(Level.FINER, "checkCertTrusted: defaultTrustManager failed", e); interactCert(chain, authType, e); } } } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { checkCertTrusted(chain, authType, false); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { checkCertTrusted(chain, authType, true); } public X509Certificate[] getAcceptedIssuers() { LOGGER.log(Level.FINE, "getAcceptedIssuers()"); return defaultTrustManager.getAcceptedIssuers(); } private int createDecisionId(MTMDecision d) { int myId; synchronized(openDecisions) { myId = decisionId; openDecisions.put(myId, d); decisionId += 1; } return myId; } private static String hexString(byte[] data) { StringBuffer si = new StringBuffer(); for (int i = 0; i < data.length; i++) { si.append(String.format("%02x", data[i])); if (i < data.length - 1) si.append(":"); } return si.toString(); } private static String certHash(final X509Certificate cert, String digest) { try { MessageDigest md = MessageDigest.getInstance(digest); md.update(cert.getEncoded()); return hexString(md.digest()); } catch (java.security.cert.CertificateEncodingException e) { return e.getMessage(); } catch (java.security.NoSuchAlgorithmException e) { return e.getMessage(); } } private void certDetails(StringBuffer si, X509Certificate c) { SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd"); si.append("\n"); si.append(c.getSubjectDN().toString()); si.append("\n"); si.append(validityDateFormater.format(c.getNotBefore())); si.append(" - "); si.append(validityDateFormater.format(c.getNotAfter())); si.append("\nSHA-256: "); si.append(certHash(c, "SHA-256")); si.append("\nSHA-1: "); si.append(certHash(c, "SHA-1")); si.append("\nSigned by: "); si.append(c.getIssuerDN().toString()); si.append("\n"); } private String certChainMessage(final X509Certificate[] chain, CertificateException cause) { Throwable e = cause; LOGGER.log(Level.FINE, "certChainMessage for " + e); StringBuffer si = new StringBuffer(); if (e.getCause() != null) { e = e.getCause(); // HACK: there is no sane way to check if the error is a "trust anchor // not found", so we use string comparison. if (NO_TRUST_ANCHOR.equals(e.getMessage())) { si.append(master.getString(R.string.mtm_trust_anchor)); } else si.append(e.getLocalizedMessage()); si.append("\n"); } si.append("\n"); si.append(master.getString(R.string.mtm_connect_anyway)); si.append("\n\n"); si.append(master.getString(R.string.mtm_cert_details)); for (X509Certificate c : chain) { certDetails(si, c); } return si.toString(); } private String hostNameMessage(X509Certificate cert, String hostname) { StringBuffer si = new StringBuffer(); si.append(master.getString(R.string.mtm_hostname_mismatch, hostname)); si.append("\n\n"); try { Collection<List<?>> sans = cert.getSubjectAlternativeNames(); if (sans == null) { si.append(cert.getSubjectDN()); si.append("\n"); } else for (List<?> altName : sans) { Object name = altName.get(1); if (name instanceof String) { si.append("["); si.append((Integer)altName.get(0)); si.append("] "); si.append(name); si.append("\n"); } } } catch (CertificateParsingException e) { e.printStackTrace(); si.append("<Parsing error: "); si.append(e.getLocalizedMessage()); si.append(">\n"); } si.append("\n"); si.append(master.getString(R.string.mtm_connect_anyway)); si.append("\n\n"); si.append(master.getString(R.string.mtm_cert_details)); certDetails(si, cert); return si.toString(); } // We can use Notification.Builder once MTM's minSDK is >= 11 @SuppressWarnings("deprecation") void startActivityNotification(Intent intent, int decisionId, String certName) { Notification n = new Notification(android.R.drawable.ic_lock_lock, master.getString(R.string.mtm_notification), System.currentTimeMillis()); PendingIntent call = PendingIntent.getActivity(master, 0, intent, 0); n.setLatestEventInfo(master.getApplicationContext(), master.getString(R.string.mtm_notification), certName, call); n.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(NOTIFICATION_ID + decisionId, n); } /** * Returns the top-most entry of the activity stack. * * @return the Context of the currently bound UI or the master context if none is bound */ Context getUI() { return (foregroundAct != null) ? foregroundAct : master; } int interact(final String message, final int titleId) { /* prepare the MTMDecision blocker object */ MTMDecision choice = new MTMDecision(); final int myId = createDecisionId(choice); masterHandler.post(new Runnable() { public void run() { Intent ni = new Intent(master, MemorizingActivity.class); ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ni.setData(Uri.parse(MemorizingTrustManager.class.getName() + "/" + myId)); ni.putExtra(DECISION_INTENT_ID, myId); ni.putExtra(DECISION_INTENT_CERT, message); ni.putExtra(DECISION_TITLE_ID, titleId); // we try to directly start the activity and fall back to // making a notification try { getUI().startActivity(ni); } catch (Exception e) { LOGGER.log(Level.FINE, "startActivity(MemorizingActivity)", e); startActivityNotification(ni, myId, message); } } }); LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId); try { synchronized(choice) { choice.wait(); } } catch (InterruptedException e) { LOGGER.log(Level.FINER, "InterruptedException", e); } LOGGER.log(Level.FINE, "finished wait on " + myId + ": " + choice.state); return choice.state; } void interactCert(final X509Certificate[] chain, String authType, CertificateException cause) throws CertificateException { switch (interact(certChainMessage(chain, cause), R.string.mtm_accept_cert)) { case MTMDecision.DECISION_ALWAYS: storeCert(chain[0]); // only store the server cert, not the whole chain case MTMDecision.DECISION_ONCE: break; default: throw (cause); } } boolean interactHostname(X509Certificate cert, String hostname) { switch (interact(hostNameMessage(cert, hostname), R.string.mtm_accept_servername)) { case MTMDecision.DECISION_ALWAYS: storeCert(hostname, cert); case MTMDecision.DECISION_ONCE: return true; default: return false; } } protected static void interactResult(int decisionId, int choice) { MTMDecision d; synchronized(openDecisions) { d = openDecisions.get(decisionId); openDecisions.remove(decisionId); } if (d == null) { LOGGER.log(Level.SEVERE, "interactResult: aborting due to stale decision reference!"); return; } synchronized(d) { d.state = choice; d.notify(); } } class MemorizingHostnameVerifier implements HostnameVerifier { private HostnameVerifier defaultVerifier; public MemorizingHostnameVerifier(HostnameVerifier wrapped) { defaultVerifier = wrapped; } @Override public boolean verify(String hostname, SSLSession session) { LOGGER.log(Level.FINE, "hostname verifier for " + hostname + ", trying default verifier first"); // if the default verifier accepts the hostname, we are done if (defaultVerifier.verify(hostname, session)) { LOGGER.log(Level.FINE, "default verifier accepted " + hostname); return true; } // otherwise, we check if the hostname is an alias for this cert in our keystore try { X509Certificate cert = (X509Certificate)session.getPeerCertificates()[0]; //Log.d(TAG, "cert: " + cert); if (cert.equals(appKeyStore.getCertificate(hostname.toLowerCase(Locale.US)))) { LOGGER.log(Level.FINE, "certificate for " + hostname + " is in our keystore. accepting."); return true; } else { LOGGER.log(Level.FINE, "server " + hostname + " provided wrong certificate, asking user."); return interactHostname(cert, hostname); } } catch (Exception e) { e.printStackTrace(); return false; } } } }
package org.hcjf.log; import org.hcjf.properties.SystemProperties; import org.hcjf.service.Service; import org.hcjf.utils.Strings; import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.PriorityBlockingQueue; import java.util.stream.Stream; /** * Static class that contains the funcionality in order to * maintain and organize a log file with the same records format * The log behavior is affected by the following system properties * <br><b>hcfj_log_path</b>: work directory of the log, by default app work directory * <br><b>hcfj_log_initial_queue_size</b>: initial size of the internal queue, by default 10000; * <br><b>hcfj_log_file_prefix</b>: all the log files start with this prefix, by default hcjf * <br><b>hcfj_log_error_file</b>: if the property is true then log create a particular file for error group only, by default false * <br><b>hcfj_log_warning_file</b>: if the property is true then log create a particular file for warning group only, by default false * <br><b>hcfj_log_info_file</b>: if the property is true then log create a particular file for info group only, by default false * <br><b>hcfj_log_debug_file</b>: if the property is true then log create a particular file for debug group only, by default false * <br><b>hcfj_log_level</b>: min level to write file, by default "I" * <br><b>hcfj_log_date_format</b>: date format to show in the log file, by default "yyyy-mm-dd hh:mm:ss" * @author javaito * @email javaito@gmail.com */ public final class Log extends Service<LogPrinter> { private static final Log instance; static { instance = new Log(); } private final List<LogPrinter> printers; private final Queue<LogRecord> queue; private final Object logMonitor; private Boolean shuttingDown; /** * Private constructor */ private Log() { super(SystemProperties.get(SystemProperties.Log.SERVICE_NAME), SystemProperties.getInteger(SystemProperties.Log.SERVICE_PRIORITY)); this.printers = new ArrayList<>(); this.queue = new PriorityBlockingQueue<>( SystemProperties.getInteger(SystemProperties.Log.QUEUE_INITIAL_SIZE), (o1, o2) -> (int)(o1.getDate().getTime() - o2.getDate().getTime())); this.logMonitor = new Object(); this.shuttingDown = false; } /** * Start the log thread. */ @Override protected void init() { for (int i = 0; i < SystemProperties.getInteger(SystemProperties.Log.LOG_CONSUMERS_SIZE); i++) { fork(new LogRunnable()); } List<String> logConsumers = SystemProperties.getList(SystemProperties.Log.CONSUMERS); logConsumers.forEach(S -> { try { LogPrinter printer = (LogPrinter) Class.forName(S).newInstance(); registerConsumer(printer); } catch (Exception ex){ ex.printStackTrace(); } }); } /** * Only valid with the stage is START * @param stage Shutdown stage. */ @Override protected void shutdown(ShutdownStage stage) { switch (stage) { case START: { shuttingDown = true; synchronized (this.logMonitor) { this.logMonitor.notifyAll(); } break; } } } /** * This method register a printer. * @param consumer Printer. * @throws NullPointerException If the printer is null. */ @Override public void registerConsumer(LogPrinter consumer) { if(consumer == null) { throw new NullPointerException("Log printer null"); } printers.add(consumer); } @Override public void unregisterConsumer(LogPrinter consumer) { printers.remove(consumer); } /** * Add the record to the queue and notify the consumer thread. * @param record Record to add. */ private UUID addRecord(LogRecord record) { if (instance.queue.add(record)) { synchronized (this.logMonitor) { this.logMonitor.notifyAll(); } } return record.getId(); } /** * This method register a printer. * @param printer Printer. * @throws NullPointerException If the printer is null. */ public static void addPrinter(LogPrinter printer) { instance.registerConsumer(printer); } /** * Create a record with debug group ("[D]"). All the places in the messages * are replaced for each param in the natural order. * @param tag Tag of the record * @param message Message to the record. This message use the syntax for class * {@link java.util.Formatter}. * @param params Parameters for the places in the message. * @return Returns the id assigned to the log record created, this id could be null * if the service does not generates any log records */ public static UUID d(String tag, String message, Object... params) { UUID result = null; if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) || instance.printers.size() > 0) { result = instance.addRecord(new LogRecord(LogGroup.DEBUG, tag, message, params)); } return result; } /** * Create a record with debug group ("[D]"). All the places in the messages * are replaced for each param in the natural order. * @param tag Tag of the record * @param message Message to the record. This message use the syntax for class * {@link java.util.Formatter}. * @param throwable Throwable whose message will be printed as part of record * @param params Parameters for the places in the message. * @return Returns the id assigned to the log record created, this id could be null * if the service does not generates any log records */ public static UUID d(String tag, String message, Throwable throwable, Object... params) { UUID result = null; if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) || instance.printers.size() > 0) { result = instance.addRecord(new LogRecord(LogGroup.DEBUG, tag, message, throwable, params)); } return result; } /** * Create a record with info group ("[I]"). All the places in the messages * are replaced for each param in the natural order. * @param tag Tag of the record * @param message Message to the record. This message use the syntax for class * {@link java.util.Formatter}. * @param params Parameters for the places in the message. * @return Returns the id assigned to the log record created, this id could be null * if the service does not generates any log records */ public static UUID i(String tag, String message, Object... params) { UUID result = null; if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) || instance.printers.size() > 0) { result = instance.addRecord(new LogRecord(LogGroup.INFO, tag, message, params)); } return result; } /** * Create a record with info group ("[IN]"). All the places in the messages * are replaced for each param in the natural order. * @param tag Tag of the record * @param message Message to the record. This message use the syntax for class * {@link java.util.Formatter}. * @param params Parameters for the places in the message. * @return Returns the id assigned to the log record created, this id could be null * if the service does not generates any log records */ public static UUID in(String tag, String message, Object... params) { UUID result = null; if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) || instance.printers.size() > 0) { result = instance.addRecord(new LogRecord(LogGroup.INPUT, tag, message, params)); } return result; } /** * Create a record with info group ("[OUT]"). All the places in the messages * are replaced for each param in the natural order. * @param tag Tag of the record * @param message Message to the record. This message use the syntax for class * {@link java.util.Formatter}. * @param params Parameters for the places in the message. * @return Returns the id assigned to the log record created, this id could be null * if the service does not generates any log records */ public static UUID out(String tag, String message, Object... params) { UUID result = null; if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) || instance.printers.size() > 0) { result = instance.addRecord(new LogRecord(LogGroup.OUTPUT, tag, message, params)); } return result; } /** * Create a record with warning group ("[W]"). All the places in the messages * are replaced for each param in the natural order. * @param tag Tag of the record * @param message Message to the record. This message use the syntax for class * {@link java.util.Formatter}. * @param params Parameters for the places in the message. * @return Returns the id assigned to the log record created, this id could be null * if the service does not generates any log records */ public static UUID w(String tag, String message, Object... params) { UUID result = null; if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) || instance.printers.size() > 0) { result = instance.addRecord(new LogRecord(LogGroup.WARNING, tag, message, params)); } return result; } /** * Create a record with warning group ("[W]"). All the places in the messages * are replaced for each param in the natural order. * @param tag Tag of the record * @param message Message to the record. This message use the syntax for class * {@link java.util.Formatter}. * @param throwable Throwable whose message will be printed as part of record * @param params Parameters for the places in the message. * @return Returns the id assigned to the log record created, this id could be null * if the service does not generates any log records */ public static UUID w(String tag, String message, Throwable throwable, Object... params) { UUID result = null; if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) || instance.printers.size() > 0) { result = instance.addRecord(new LogRecord(LogGroup.WARNING, tag, message, throwable, params)); } return result; } /** * Create a record with error group ("[E]"). All the places in the messages * are replaced for each param in the natural order. * @param tag Tag of the record * @param message Message to the record. This message use the syntax for class * {@link java.util.Formatter}. * @param params Parameters for the places in the message. * @return Returns the id assigned to the log record created, this id could be null * if the service does not generates any log records */ public static UUID e(String tag, String message, Object... params) { UUID result = null; if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) || instance.printers.size() > 0) { result = instance.addRecord(new LogRecord(LogGroup.ERROR, tag, message, params)); } return result; } /** * Create a record with error group ("[E]"). All the places in the messages * are replaced for each param in the natural order. * @param tag Tag of the record * @param message Message to the record. This message use the syntax for class * {@link java.util.Formatter}. * @param throwable Throwable whose message will be printed as part of record * @param params Parameters for the places in the message. * @return Returns the id assigned to the log record created, this id could be null * if the service does not generates any log records */ public static UUID e(String tag, String message, Throwable throwable, Object... params) { UUID result = null; if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) || instance.printers.size() > 0) { result = instance.addRecord(new LogRecord(LogGroup.ERROR, tag, message, throwable, params)); } return result; } /** * Return the size of the log queue. * @return Size of the log queue. */ public static Integer getLogQueueSize() { return instance.queue.size(); } private class LogRunnable implements Runnable { /** * Wait to found a recor to print. */ @Override public void run() { try { while(!shuttingDown) { if(instance.queue.isEmpty()) { synchronized (Log.this.logMonitor) { Log.this.logMonitor.wait(); } } try { writeRecord(instance.queue.remove()); } catch (Exception ex) {} } } catch (InterruptedException e) {} } /** * Print the record in all the printers registered and the * syste out printer. * @param record Record to print. */ private void writeRecord(LogRecord record) { if(record.getGroup().getOrder() >= SystemProperties.getInteger(SystemProperties.Log.LEVEL)) { printers.forEach(printer -> printer.print(record)); } if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED)) { System.out.println(record.toString()); System.out.flush(); } } } /** * This class contains all the information to write a record in the log. * The instances of this class will be queued sorted chronologically waiting for * be write */ public static final class LogRecord { private final UUID id; private final Date date; private final LogGroup group; private final String tag; private final String originalMessage; private final String message; private final SimpleDateFormat dateFormat; private final Object[] params; /** * Constructor * @param group Group of the record. * @param tag Tag for the record. * @param message Message with wildcard for the parameters. * @param throwable The error object, could be null * @param params Values that will be put in the each places of the message. */ private LogRecord(LogGroup group, String tag, String message, Throwable throwable, Object... params) { this.id = UUID.randomUUID(); this.date = new Date(); this.group = group; this.tag = tag; this.dateFormat = new SimpleDateFormat(SystemProperties.get(SystemProperties.Log.DATE_FORMAT)); this.originalMessage = message; this.message = createMessage(message, throwable, params); this.params = params; } /** * Constructor * @param group Group of the record. * @param tag Tag for the record. * @param message Message with wildcard for the parameters. * @param params Values that will be put in the each places of the message. */ private LogRecord(LogGroup group, String tag, String message, Object... params) { this(group, tag, message, null, params); } /** * Return the id of log record. * @return Log record id. */ public UUID getId() { return id; } /** * Create a final version of string to print the record. * @param message Message to be format * @param throwable The error object, could be null. * @param params Parameters to format the message. * @return Return the last version of the message. */ private String createMessage(String message, Throwable throwable, Object... params) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); String group = getGroup().getGroup(); String tag = getTag(); if(SystemProperties.getBoolean(SystemProperties.Log.TRUNCATE_TAG)) { int truncateSize = SystemProperties.getInteger(SystemProperties.Log.TRUNCATE_TAG_SIZE); if(truncateSize > tag.length()) { tag = Strings.rightPad(tag, truncateSize); } else if(truncateSize < tag.length()) { tag = tag.substring(0, truncateSize); } } printWriter.print(dateFormat.format(getDate())); printWriter.print(" ["); printWriter.print(group); printWriter.print("]["); printWriter.print(tag); printWriter.print("] "); printWriter.printf(message, params); if(throwable != null) { printWriter.print("\r\n"); throwable.printStackTrace(printWriter); } printWriter.flush(); printWriter.close(); return stringWriter.toString(); } /** * Return the record date * @return Record date. */ public Date getDate() { return date; } /** * Return the record group. * @return Record group. */ public LogGroup getGroup() { return group; } /** * Return the log record tag. * @return Log record tag. */ public String getTag() { return tag; } /** * Return the last version of the message. * @return Record message. */ public String getMessage() { return message; } /** * Return the original message. * @return Original message. */ public String getOriginalMessage() { return originalMessage; } /** * Return de format message. * @return Format message. */ @Override public String toString() { return getMessage(); } /** * Return the log record params. * @return Log record params. */ public Object[] getParams() { return params; } } /** * This enum contains all the possible groups for the records */ public static enum LogGroup { DEBUG("D", 0), INPUT("A", 1), OUTPUT("O", 1), INFO("I", 1), WARNING("W", 2), ERROR("E", 3); private Integer order; private String group; LogGroup(String tag, Integer order) { this.order = order; this.group = tag; } /** * Return the group order. * @return Tag order. */ public Integer getOrder() { return order; } /** * Return the group label. * @return Tag label. */ public String getGroup() { return group; } /** * Return the group instance that correspond with the parameter. * @param tagString String group * @return Tag instance founded or null if the instance is not exist. */ public LogGroup valueOfByTag(String tagString) { LogGroup result = null; try { result = Stream.of(values()). filter(r -> r.getGroup().equals(tagString)). findFirst().get(); } catch (NoSuchElementException ex) {} return result; } } }
package com.creedon.cordova.plugin.captioninput; import android.app.Activity; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.media.ExifInterface; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Vibrator; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.facebook.common.executors.CallerThreadExecutor; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.DataSource; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.core.ImagePipeline; import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.kaopiz.kprogresshud.KProgressHUD; import com.rengwuxian.materialedittext.MaterialEditText; import com.zhihu.matisse.Matisse; import com.zhihu.matisse.MimeType; import com.zhihu.matisse.engine.impl.GlideEngine; 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.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.ref.WeakReference; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static android.view.View.GONE; import static com.creedon.cordova.plugin.captioninput.Constants.KEY_CAPTIONS; import static com.creedon.cordova.plugin.captioninput.Constants.KEY_IMAGES; import static com.creedon.cordova.plugin.captioninput.Constants.KEY_INVALIDIMAGES; import static com.creedon.cordova.plugin.captioninput.Constants.KEY_METADATAS; import static com.creedon.cordova.plugin.captioninput.Constants.KEY_PRESELECTS; public class PhotoCaptionInputViewActivity extends AppCompatActivity implements RecyclerItemClickListener.OnItemClickListener, RecyclerViewAdapter.RecyclerViewAdapterListener { private static final String TAG = PhotoCaptionInputViewActivity.class.getSimpleName(); private static final String KEY_LABEL = "label"; private static final String KEY_TYPE = "type"; private static final int MAX_CHARACTOR = 160; private static final int REQUEST_CODE_PICKER = 0x111; private static final int REQUEST_CODE_CHOOSE = 0x111; private FakeR fakeR; private ArrayList<String> captions; private int currentPosition; private ViewPager mPager; private ScreenSlidePagerAdapter mPagerAdapter; private MaterialEditText mEditText; private LinearLayoutManager linearLayoutManager; private RecyclerViewAdapter recyclerViewAdapter; private KProgressHUD kProgressHUD; private ArrayList<String> imageList; private int width, height; private JSONArray buttonOptions; ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() { Boolean first = true; public void onPageScrollStateChanged(int state) { } public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { mPagerAdapter.stopVideoPlayback(position); if (first && positionOffset == 0 && positionOffsetPixels == 0) { onPageSelected(0); first = false; } else { onPageSelected(position); } } public void onPageSelected(int position) { runOnUiThread(new Runnable() { @Override public void run() { currentPosition = mPager.getCurrentItem(); mPagerAdapter.stopVideoPlayback(currentPosition); setActionBarTitle(imageList, currentPosition); if(isVideo(imageList.get(currentPosition))){ mEditText.setText(""); mEditText.setVisibility(View.INVISIBLE); }else { mEditText.setText(captions.get(currentPosition)); mEditText.setVisibility(View.VISIBLE); } linearLayoutManager.scrollToPositionWithOffset(currentPosition, -1); if (recyclerViewAdapter != null) { recyclerViewAdapter.notifyDataSetChanged(); } } }); } }; private ViewPager.OnAdapterChangeListener onAdapterChangeListener = new ViewPager.OnAdapterChangeListener() { @Override public void onAdapterChanged(@NonNull ViewPager viewPager, @Nullable PagerAdapter oldAdapter, @Nullable PagerAdapter newAdapter) { } }; private ArrayList<String> preSelectedAssets = new ArrayList<String>(); private int maxImages; @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override protected void onCreate(@Nullable Bundle savedInstanceState) { if (!Fresco.hasBeenInitialized()) { Fresco.initialize(this); } getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY); super.onCreate(savedInstanceState); fakeR = new FakeR(this.getApplicationContext()); setContentView(fakeR.getId("layout", "activity_photoscaptioninput")); setupToolBar(); SharedPreferences sharedPrefs = getSharedPreferences("group.com.creedon.Nixplay", Context.MODE_PRIVATE); boolean isOptimizeSize = false; try { isOptimizeSize = sharedPrefs.getBoolean("nixSettings.settings.resolution", false); } catch (Exception e) { try { String ret = sharedPrefs.getString("nixSettings.settings.resolution", ""); isOptimizeSize = Boolean.parseBoolean(ret); } catch (Exception e1) { e1.printStackTrace(); } } if (isOptimizeSize) { this.width = 1820; this.height = 1820; } if (getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); String optionsJsonString = bundle.getString("options"); this.maxImages = bundle.getInt("MAX_IMAGES"); try { JSONObject jsonObject = new JSONObject(optionsJsonString); try { this.buttonOptions = jsonObject.getJSONArray("buttons"); } catch (Exception e) { e.printStackTrace(); } JSONArray imagesJsonArray = jsonObject.getJSONArray("images"); JSONArray preSelectedAssetsJsonArray = jsonObject.getJSONArray("preSelectedAssets"); if (preSelectedAssetsJsonArray != null) { for (int i = 0; i < preSelectedAssetsJsonArray.length(); i++) { preSelectedAssets.add(preSelectedAssetsJsonArray.getString(i)); } } ArrayList<String> stringArray = new ArrayList<String>(); captions = new ArrayList<String>(); for (int i = 0, count = imagesJsonArray.length(); i < count; i++) { try { String jsonObj = imagesJsonArray.getString(i); if (jsonObj.contains("file: stringArray.add(jsonObj); } else { stringArray.add(Uri.fromFile(new File(jsonObj)).toString()); } captions.add(i, ""); } catch (JSONException e) { e.printStackTrace(); } } currentPosition = 0; imageList = stringArray; mEditText = (MaterialEditText) findViewById(fakeR.getId("id", "etDescription")); mEditText.setHint(fakeR.getId("string", "ADD_CAPTION")); mEditText.setFloatingLabelText(getString(fakeR.getId("string", "ADD_CAPTION"))); InputFilter[] filterArray = new InputFilter[1]; filterArray[0] = new InputFilter.LengthFilter(MAX_CHARACTOR); mEditText.setFilters(filterArray); mEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { mEditText.setFloatingLabelText(getString(fakeR.getId("string", "ADD_CAPTION")) + "(" + charSequence.length() + "/" + MAX_CHARACTOR + ")"); } @Override public void afterTextChanged(Editable editable) { if (editable.length() > 0) { if (editable.charAt(editable.length() - 1) == '\n') { editable.delete(editable.length() - 1, editable.length()); mEditText.clearFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); } captions.set(currentPosition, editable.toString()); } } }); mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { Log.d("onEditorAction", " TextView " + v.toString() + " actionId " + actionId + " event " + event); return false; } }); if (this.buttonOptions != null) { for (int i = 0; i < this.buttonOptions.length(); i++) { JSONObject obj = (JSONObject) this.buttonOptions.get(i); String label = obj.getString(KEY_LABEL); final String type = obj.getString(KEY_TYPE); if (i == 0) { if (this.buttonOptions.length() == 1) { findViewById(fakeR.getId("id", "button1")).setVisibility(GONE); Button button = (Button) findViewById(fakeR.getId("id", "button2")); button.setText(label); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { finishWithResult(type); } catch (JSONException e) { e.printStackTrace(); finishActivity(-1); } } }); } else { Button button1 = (Button) findViewById(fakeR.getId("id", "button1")); button1.setText(label); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { finishWithResult(type); } catch (JSONException e) { e.printStackTrace(); finishActivity(-1); } } }); } } else if (i == 1) { Button button2 = (Button) findViewById(fakeR.getId("id", "button2")); button2.setText(label); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { finishWithResult(type); } catch (JSONException e) { e.printStackTrace(); finishActivity(-1); } } }); } } } mPager = (ViewPager) findViewById(fakeR.getId("id", "pager")); mPager.addOnPageChangeListener(onPageChangeListener); mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), stringArray); mPager.setAdapter(mPagerAdapter); RecyclerView recyclerView = (RecyclerView) findViewById(fakeR.getId("id", "recycleview")); linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerViewAdapter = new RecyclerViewAdapter(this, stringArray); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(recyclerViewAdapter); recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, this)); setActionBarTitle(imageList, currentPosition); (findViewById(fakeR.getId("id", "btnAdd"))).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ArrayList<Uri> serialPreselectedAssets = new ArrayList<Uri>(); //content uri all the way for (String s : preSelectedAssets) { serialPreselectedAssets.add(Uri.parse(s)); } Matisse.from(PhotoCaptionInputViewActivity.this) .choose(MimeType.of( MimeType.JPEG, MimeType.PNG, MimeType.MP4 ), false) .countable(true) .maxSelectable(PhotoCaptionInputViewActivity.this.maxImages) .gridExpectedSize((int) convertDpToPixel(120, PhotoCaptionInputViewActivity.this)) .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) .thumbnailScale(0.85f) .imageEngine(new GlideEngine()) .enablePreview(false) .showUseOrigin(false) .forResult(REQUEST_CODE_CHOOSE, serialPreselectedAssets); } }); //show image view } catch (Exception e) { e.printStackTrace(); //TODO setresult failed Intent intent = new Intent(); setResult(RESULT_CANCELED, intent); finish(); } } else { //TODO setresult failed Intent intent = new Intent(); setResult(RESULT_CANCELED, intent); finish(); } } public static Uri getImageContentUri(Context context, File imageFile) { String filePath = imageFile.getAbsolutePath(); Cursor cursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{filePath}, null); if (cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); cursor.close(); return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id); } else { if (imageFile.exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, filePath); return context.getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } } private static boolean isVideo(String filePath) { filePath = filePath.toLowerCase(); return filePath.endsWith(".mp4"); } /** * Get a file path from a Uri. This will get the the path for Storage Access * Framework Documents, as well as the _data field for the MediaStore and * other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @author paulburke */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static String getPath(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } // TODO handle non-primary volumes } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[]{ split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } protected void setupToolBar() { try { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(fakeR.getId("drawable", "ic_close_gray_24dp")); } } catch (NullPointerException e) { e.printStackTrace(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(fakeR.getId("menu", "menu_photoscaptioninput"), menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection int id = item.getItemId(); if (id == android.R.id.home) { setResult(Activity.RESULT_CANCELED); finish(); return true; } else if (id == fakeR.getId("id", "btnTrash")) { //delete current page image if (imageList.size() > 0) { imageList.remove(currentPosition); preSelectedAssets.remove(currentPosition); captions.remove(currentPosition); recyclerViewAdapter.notifyItemRemoved(currentPosition); currentPosition = Math.max(0, Math.min(currentPosition, imageList.size() - 1)); recyclerViewAdapter.notifyItemChanged(currentPosition); if (imageList.size() == 0) { finishActivity(RESULT_CANCELED); finish(); return false; } else { ArrayList<String> clonedPoster = new ArrayList<String>(imageList); ArrayList<String> clonedPoster2 = new ArrayList<String>(imageList); mPagerAdapter.swap(clonedPoster); recyclerViewAdapter.swap(clonedPoster2); linearLayoutManager.scrollToPositionWithOffset(currentPosition, -1); setActionBarTitle(imageList, currentPosition); mEditText.setText(captions.get(currentPosition)); } } else { finishActivity(RESULT_CANCELED); return false; } return true; } return onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); setResult(Activity.RESULT_CANCELED); finish(); } @Override public boolean dispatchTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { View v = getCurrentFocus(); if (v instanceof EditText) { Rect outRect = new Rect(); v.getGlobalVisibleRect(outRect); if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) { v.clearFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } } return super.dispatchTouchEvent(event); } @Override public void onItemClick(View view, int position) { try { currentPosition = (position > 0 && position < imageList.size()) ? position : 0; mPager.setCurrentItem(currentPosition); setActionBarTitle(imageList, currentPosition); mEditText.setText(captions.get(currentPosition)); if (recyclerViewAdapter.getItemCount() > 0 || recyclerViewAdapter != null) { recyclerViewAdapter.notifyDataSetChanged(); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onItemLongClick(View view, int position) { try { currentPosition = (position > 0 && position < imageList.size()) ? position : 0; mPager.setCurrentItem(currentPosition); setActionBarTitle(imageList, currentPosition); mEditText.setText(captions.get(currentPosition)); Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE); // Vibrate for 500 milliseconds v.vibrate(500); if (recyclerViewAdapter.getItemCount() > 0 || recyclerViewAdapter != null) { recyclerViewAdapter.notifyDataSetChanged(); } } catch (Exception e) { e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE) { ArrayList<String> newImages = new ArrayList<String>(); ArrayList<String> newPreselectedAssets = new ArrayList<String>(); ArrayList<String> newCaptions = new ArrayList<String>(); List<Uri> result = Matisse.obtainResult(data); List<String> fileActualPaths = Matisse.obtainPathResult(data); for (int i = 0; i < result.size(); i++) { String fileActualPath = fileActualPaths.get(i); String uriString = result.get(i).toString(); int index = preSelectedAssets.indexOf(uriString); if (fileActualPath.contains("file: newImages.add(fileActualPath); } else { newImages.add(Uri.fromFile(new File(fileActualPath)).toString()); } newPreselectedAssets.add(uriString); if (preSelectedAssets.contains(uriString)) { if (index > 0 && index < captions.size()) { newCaptions.add(captions.get(index)); } else { newCaptions.add(""); } } else { newCaptions.add(""); } } imageList = newImages; preSelectedAssets = newPreselectedAssets; captions = newCaptions; refreshList(); } } } public void setActionBarTitle(ArrayList<String> actionBarTitle, int index) { try { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle((index + 1) + "/" + actionBarTitle.size()); } mEditText.setText(captions.get(index)); } catch (NullPointerException e) { e.printStackTrace(); } } private void finishWithResult(final String type) throws JSONException { // Bundle conData = new Bundle(); // try { // JSONObject jsonObject = new JSONObject(); // JSONArray array = new JSONArray(imageList); // jsonObject.put(KEY_IMAGES, array); // jsonObject.put(KEY_CAPTIONS, new JSONArray(captions)); // jsonObject.put(KEY_PRESELECTS, new JSONArray()); // jsonObject.put(KEY_INVALIDIMAGES, new JSONArray()); // conData.putString(Constants.RESULT, jsonObject.toString()); // } catch (JSONException e) { // e.printStackTrace(); // Intent intent = new Intent(); // intent.putExtras(conData); // setResult(RESULT_OK, intent); // finishActivity(Constants.REQUEST_SUBMIT); // finish(); //for testing james 20170615 recyclerViewAdapter = null; if (mPager != null) { mPager.removeOnPageChangeListener(onPageChangeListener); mPager.removeOnAdapterChangeListener(onAdapterChangeListener); } mPager = null; mPagerAdapter = null; if (kProgressHUD != null) { if (kProgressHUD.isShowing()) { kProgressHUD.dismiss(); } } runOnUiThread(new Runnable() { @Override public void run() { kProgressHUD = KProgressHUD.create(PhotoCaptionInputViewActivity.this) .setStyle(KProgressHUD.Style.PIE_DETERMINATE) .setDetailsLabel("") .setCancellable(false) .setAnimationSpeed(2) .setDimAmount(0.5f) .setMaxProgress(imageList.size()) .show(); } }); ImageResizer imageResizer = new ImageResizer(this, imageList); imageResizer.run(); // ImageResizeTask task = new ImageResizeTask(); imageResizer.setCallback(new ResizeCallback() { @Override public void onResizeSuccess(ArrayList<String> outList, JSONArray jsonArray) { kProgressHUD.dismiss(); Bundle conData = new Bundle(); try { JSONObject jsonObject = new JSONObject(); JSONArray array = new JSONArray(outList); jsonObject.put(KEY_IMAGES, array); jsonObject.put(KEY_CAPTIONS, new JSONArray(captions)); jsonObject.put(KEY_PRESELECTS, new JSONArray()); jsonObject.put(KEY_INVALIDIMAGES, new JSONArray()); jsonObject.put(KEY_TYPE, type); jsonObject.put(KEY_METADATAS, jsonArray); conData.putString(Constants.RESULT, jsonObject.toString()); } catch (JSONException e) { e.printStackTrace(); } Intent intent = new Intent(); intent.putExtras(conData); setResult(RESULT_OK, intent); finishActivity(Constants.REQUEST_SUBMIT); finish(); } @Override public void onResizePrecess(final Integer process) { runOnUiThread(new Runnable() { @Override public void run() { kProgressHUD.setProgress(process); } }); } @Override public void onResizeFailed(String s) { kProgressHUD.dismiss(); Log.e(TAG, s); Intent intent = new Intent(); setResult(RESULT_CANCELED, intent); finish(); } }); // task.execute(imageResizer); } protected String storeImage(String inFilePath, String inFileName) throws JSONException, IOException, URISyntaxException { String outFilePath = System.getProperty("java.io.tmpdir") + "/"; if (!(inFilePath + File.separator + inFileName).equals(outFilePath + inFileName)) { copyFile(inFilePath + File.separator, inFileName, outFilePath); try { copyExif(inFilePath + File.separator + inFileName, outFilePath + inFileName); } catch (Exception e) { e.printStackTrace(); } return outFilePath + inFileName; } return inFilePath + File.separator + inFileName; } protected String storeImage(String inFileName, Bitmap bmp) throws JSONException, IOException, URISyntaxException { String filename = inFileName; filename.replace("bmp", "jpg"); String filePath = System.getProperty("java.io.tmpdir") + "/" + filename; // exif.writeExif(bmp, filePath, 100); FileOutputStream out = null; try { out = new FileOutputStream(filePath); bmp.compress(Bitmap.CompressFormat.JPEG, 100, out); // bmp is your Bitmap instance // PNG is a lossless format, the compression factor (100) is ignored } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return filePath; } protected String storeImageWithExif(String inFileName, Bitmap bmp, ExifInterface exif) throws JSONException, IOException, URISyntaxException { String filename = inFileName; filename.replace("bmp", "jpg"); String filePath = System.getProperty("java.io.tmpdir") + "/" + filename; // exif.writeExif(bmp, filePath, 100); FileOutputStream out = null; try { out = new FileOutputStream(filePath); bmp.compress(Bitmap.CompressFormat.JPEG, 100, out); // bmp is your Bitmap instance // PNG is a lossless format, the compression factor (100) is ignored } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } copyExif(exif, filePath); return filePath; } private void copyFile(String inputPath, String inputFile, String outputPath) { FileInputStream in = null; OutputStream out = null; try { //create output directory if it doesn't exist File dir = new File(outputPath); if (!dir.exists()) { dir.mkdirs(); } in = new FileInputStream(inputPath + inputFile); out = new FileOutputStream(outputPath + inputFile); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); in = null; // write the output file (You have now copied the file) out.flush(); out.close(); out = null; } catch (FileNotFoundException fnfe1) { Log.e("tag", fnfe1.getMessage()); } catch (Exception e) { Log.e("tag", e.getMessage()); } } public static void copyExif(String oldPath, String newPath) throws IOException { ExifInterface oldExif = new ExifInterface(oldPath); String[] attributes = new String[] { ExifInterface.TAG_APERTURE, ExifInterface.TAG_DATETIME, ExifInterface.TAG_DATETIME_DIGITIZED, ExifInterface.TAG_EXPOSURE_TIME, ExifInterface.TAG_FLASH, ExifInterface.TAG_FOCAL_LENGTH, ExifInterface.TAG_GPS_ALTITUDE, ExifInterface.TAG_GPS_ALTITUDE_REF, ExifInterface.TAG_GPS_DATESTAMP, ExifInterface.TAG_GPS_LATITUDE, ExifInterface.TAG_GPS_LATITUDE_REF, ExifInterface.TAG_GPS_LONGITUDE, ExifInterface.TAG_GPS_LONGITUDE_REF, ExifInterface.TAG_GPS_PROCESSING_METHOD, ExifInterface.TAG_GPS_TIMESTAMP, ExifInterface.TAG_IMAGE_LENGTH, ExifInterface.TAG_IMAGE_WIDTH, ExifInterface.TAG_ISO, ExifInterface.TAG_MAKE, ExifInterface.TAG_MODEL, ExifInterface.TAG_ORIENTATION, ExifInterface.TAG_SUBSEC_TIME, ExifInterface.TAG_SUBSEC_TIME_DIG, ExifInterface.TAG_SUBSEC_TIME_ORIG, ExifInterface.TAG_WHITE_BALANCE }; ExifInterface newExif = new ExifInterface(newPath); for (int i = 0; i < attributes.length; i++) { String value = oldExif.getAttribute(attributes[i]); if (value != null) newExif.setAttribute(attributes[i], value); } newExif.saveAttributes(); } public static void copyExif(ExifInterface oldExif, String newPath) throws IOException { String[] attributes = new String[] { ExifInterface.TAG_APERTURE, ExifInterface.TAG_DATETIME, ExifInterface.TAG_DATETIME_DIGITIZED, ExifInterface.TAG_EXPOSURE_TIME, ExifInterface.TAG_FLASH, ExifInterface.TAG_FOCAL_LENGTH, ExifInterface.TAG_GPS_ALTITUDE, ExifInterface.TAG_GPS_ALTITUDE_REF, ExifInterface.TAG_GPS_DATESTAMP, ExifInterface.TAG_GPS_LATITUDE, ExifInterface.TAG_GPS_LATITUDE_REF, ExifInterface.TAG_GPS_LONGITUDE, ExifInterface.TAG_GPS_LONGITUDE_REF, ExifInterface.TAG_GPS_PROCESSING_METHOD, ExifInterface.TAG_GPS_TIMESTAMP, ExifInterface.TAG_IMAGE_LENGTH, ExifInterface.TAG_IMAGE_WIDTH, ExifInterface.TAG_ISO, ExifInterface.TAG_MAKE, ExifInterface.TAG_MODEL, ExifInterface.TAG_ORIENTATION, ExifInterface.TAG_SUBSEC_TIME, ExifInterface.TAG_SUBSEC_TIME_DIG, ExifInterface.TAG_SUBSEC_TIME_ORIG, ExifInterface.TAG_WHITE_BALANCE }; ExifInterface newExif = new ExifInterface(newPath); for (int i = 0; i < attributes.length; i++) { String value = oldExif.getAttribute(attributes[i]); if (value != null) newExif.setAttribute(attributes[i], value); } newExif.saveAttributes(); } void refreshList() { ArrayList<String> clonedPoster = new ArrayList<String>(imageList); mPagerAdapter.swap(clonedPoster); ArrayList<String> clonedPoster2 = new ArrayList<String>(imageList); recyclerViewAdapter.swap(clonedPoster); mPagerAdapter.swap(clonedPoster2); setActionBarTitle(imageList, currentPosition); } @Override public boolean isPhotoSelected(int position) { return currentPosition == position; } @Override public boolean isPhotoSelectionMode() { return false; } private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { private ArrayList<String> itemList; private SparseArray<WeakReference<ScreenSlidePageFragment>> mPageReferenceMap = new SparseArray<WeakReference<ScreenSlidePageFragment>>(); ScreenSlidePagerAdapter(FragmentManager fm, ArrayList<String> itemList) { super(fm); this.itemList = itemList; } @Override public Fragment getItem(int position) { return getFragment(position); } @NonNull @Override public Object instantiateItem(ViewGroup container, int position) { ScreenSlidePageFragment myFragment = ScreenSlidePageFragment.newInstance(itemList.get(position)); mPageReferenceMap.put(position, new WeakReference<ScreenSlidePageFragment>(myFragment)); return super.instantiateItem(container, position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { super.destroyItem(container, position, object); mPageReferenceMap.remove(position); } public ScreenSlidePageFragment getFragment(int position) { WeakReference<ScreenSlidePageFragment> weakReference = mPageReferenceMap.get(position); if (null != weakReference) { return (ScreenSlidePageFragment) weakReference.get(); } else { return null; } } @Override public int getCount() { return itemList.size(); } public void swap(ArrayList<String> poster) { itemList = poster; if (recyclerViewAdapter.getItemCount() > 0 || recyclerViewAdapter != null) { if (itemList.size() > 0) { notifyDataSetChanged(); } } } @Override public int getItemPosition(Object object) { return POSITION_NONE; } public void stopVideoPlayback(int position) { ScreenSlidePageFragment fragment = getFragment(position); if (fragment != null) { fragment.stopVideoPlayback(); } } } private interface ResizeCallback { void onResizeSuccess(ArrayList<String> outList, JSONArray jsonArray); void onResizePrecess(Integer process); void onResizeFailed(String s); } private class ImageResizeTask extends AsyncTask<ImageResizer, Void, Void> { protected Void doInBackground(ImageResizer... imageResizers) { int count = imageResizers.length; long totalSize = 0; for (int i = 0; i < count; i++) { imageResizers[i].run(); } return null; } protected void onProgressUpdate(Void... voids) { } protected void onPostExecute(Void result) { } } public class ImageResizer { private final Context context; private final ArrayList<String> files; private ResizeCallback callback; private ArrayList<String> outList; private JSONArray outMetaList; OnImageResized onImageResizedCallback = new OnImageResized() { @Override public void resizeProcessed(Integer index) { callback.onResizePrecess(index); processFile(onImageResizedCallback, index); } @Override public void resizeCompleted(ArrayList<String> outList) { if (callback != null) { onDone(); } } }; private String originalFileName; private String subfileName; private String previewBitmapFileName; private String thumbnailBitmapFileName; public ImageResizer(Context context, ArrayList<String> files) { this.context = context; this.files = files; this.outList = new ArrayList<String>(); this.outMetaList = new JSONArray(); } public void run() { processFiles(); } private void processFiles() { try { //start progress processFile( onImageResizedCallback , 0); } catch (Exception e) { e.printStackTrace(); } } private void processFile( final OnImageResized onImageResized, Integer index) { if (files.size() > 0) { String fileName = files.get(0); Uri src = Uri.parse(fileName); if ((width != 0 && height != 0) || MimeType.BMP.checkType(getContentResolver(), src)) { try { URI uri = new URI(fileName); final File imageFile = new File(uri); ImageRequest request = null; if (width != 0 && height != 0) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options); float scale = 1.0f; if (options.outWidth > options.outHeight) { scale = (width * 1.0f) / (options.outWidth * 1.0f); } else { scale = (height * 1.0f) / (options.outHeight * 1.0f); } if (scale > 1 || scale <= 0) { scale = 1; } float reqWidth = options.outWidth * scale; float reqHeight = options.outHeight * scale; request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(fileName)) .setResizeOptions(new ResizeOptions((int) reqWidth, (int) reqHeight)) .build(); } else { request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(fileName)) .build(); } ImagePipeline imagePipeline = Fresco.getImagePipeline(); DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(request, this); CallerThreadExecutor executor = CallerThreadExecutor.getInstance(); final Integer[] copyindex = {index}; dataSource.subscribe( new BaseBitmapDataSubscriber() { @Override protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { callback.onResizeFailed("Failed to resize at onFailureImpl " + imageFile.getAbsolutePath()); } @Override protected void onNewResultImpl(Bitmap bmp) { ExifInterface exif = null; try { if (imageFile.getName().toLowerCase().endsWith("jpg") || imageFile.getName().toLowerCase().endsWith("jpeg")) { exif = new ExifInterface(imageFile.getAbsolutePath()); exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_NORMAL)); } } catch (IOException e) { e.printStackTrace(); } try { Log.d("processFile", "storeImageWithExif " + imageFile); String outFilePath; if (exif != null) { outFilePath = storeImageWithExif(imageFile.getName(), bmp, exif); } else { outFilePath = storeImage(imageFile.getParentFile().getAbsolutePath(), imageFile.getName()); } addData(Uri.fromFile(new File(outFilePath)).toString(), new JSONObject()); } catch (JSONException e) { e.printStackTrace(); callback.onResizeFailed("JSONException " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); callback.onResizeFailed("IOException " + e.getMessage()); } catch (URISyntaxException e) { e.printStackTrace(); callback.onResizeFailed("URISyntaxException " + e.getMessage()); } finally { files.remove(0); if(files.size() == 0) { //if filesize = 0 end progress onImageResized.resizeCompleted(outList); }else { //if filesize > 0 continue progress Integer nextIndex = copyindex[0]+1; onImageResized.resizeProcessed( nextIndex); } } } } , executor); } catch (URISyntaxException e) { e.printStackTrace(); callback.onResizeFailed("URISyntaxException " + e.getMessage()); } } else if (MimeType.MP4.checkType(getContentResolver(), src)) { URI uri = null; try { uri = new URI(fileName); File inFile = new File(uri); Log.d("processFile", "storeImage " + uri); MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(PhotoCaptionInputViewActivity.this, src); // Bitmap previewBitmap = mediaMetadataRetriever.getFrameAtTime(0); // Bitmap thumbnailBitmap = (previewBitmap.getWidth() >= previewBitmap.getHeight()) ? // Bitmap.createBitmap( // previewBitmap, // previewBitmap.getWidth() / 2 - previewBitmap.getHeight() / 2, // previewBitmap.getHeight(), // previewBitmap.getHeight() // Bitmap.createBitmap( // previewBitmap, // previewBitmap.getHeight() / 2 - previewBitmap.getWidth() / 2, // previewBitmap.getWidth(), // previewBitmap.getWidth() // originalFileName = temp.get(0).substring(temp.get(0).lastIndexOf("/") + 1); // subfileName = temp.get(0).substring(temp.get(0).lastIndexOf(".") + 1); // previewBitmapFileName = originalFileName.replace(subfileName, "-preview.jpg"); // thumbnailBitmapFileName = originalFileName.replace(subfileName, "-thumbnail.jpg"); // String previewBitmapFilePath = storeImage(previewBitmapFileName, previewBitmap); // String thumbnailBitmapFilePath = storeImage(thumbnailBitmapFileName, thumbnailBitmap); // Log.d("previewBitmapFilePath", previewBitmapFilePath); // Log.d("thumbnailBitmapFilePath", thumbnailBitmapFilePath); JSONObject metaData = new JSONObject(); long durationMs = Long.parseLong(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); long videoWidth = Long.parseLong(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); long videoHeight = Long.parseLong(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); /* testing only */ metaData.put("start", 0L); metaData.put("duration", 15000L > durationMs ? durationMs : 15000L); metaData.put("width", videoWidth); metaData.put("height", videoHeight); metaData.put("originalDuration", durationMs); metaData.put("edited", "auto"); addData(Uri.fromFile(inFile).toString(), metaData); } catch (URISyntaxException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { files.remove(0); if(files.size() == 0) { //if filesize = 0 end progress onImageResized.resizeCompleted(outList); }else { Integer nextIndex = index+1; onImageResized.resizeProcessed(nextIndex); } } } else if (MimeType.JPEG.checkType(getContentResolver(), src) || MimeType.PNG.checkType(getContentResolver(), src)) { try { URI uri = new URI(files.get(0)); File inFile = new File(uri); Log.d("processFile", "storeImage " + uri); String outFilePath = storeImage(inFile.getParentFile().getAbsolutePath(), inFile.getName()); addData(Uri.fromFile(new File(outFilePath)).toString(), new JSONObject()); } catch (URISyntaxException e) { e.printStackTrace(); callback.onResizeFailed("URISyntaxException storeImage " + e.getMessage()); } catch (JSONException e) { e.printStackTrace(); callback.onResizeFailed("JSONException storeImage " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); callback.onResizeFailed("IOException storeImage " + e.getMessage()); } finally { files.remove(0); if(files.size() == 0) { //if filesize = 0 end progress onImageResized.resizeCompleted(outList); }else { //if filesize > 0 continue progress Integer nextIndex = index+1; onImageResized.resizeProcessed(nextIndex); } } } else { addData("", new JSONObject()); files.remove(0); Integer nextIndex = index+1; if(files.size() == 0) { //if filesize = 0 end progress onImageResized.resizeCompleted(outList); }else { onImageResized.resizeProcessed(nextIndex); } } } } private void addData(String s, JSONObject jsonObject) { outList.add(s); outMetaList.put(jsonObject); } private void onDone() { try { if (callback != null) { ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { callback.onResizeSuccess(outList, outMetaList); } }); } } catch (NullPointerException e) { e.printStackTrace(); } } public void setCallback(ResizeCallback callback) { this.callback = callback; } } private interface OnImageResized { void resizeProcessed(Integer index); void resizeCompleted(ArrayList<String> outList); } /** * This method converts dp unit to equivalent pixels, depending on device density. * * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels * @param context Context to get resources and device specific display metrics * @return A float value to represent px equivalent to dp depending on device density */ public static float convertDpToPixel(float dp, Context context) { Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return px; } }
package org.postgresql.largeobject; import java.io.*; import java.lang.*; import java.net.*; import java.util.*; import java.sql.*; import org.postgresql.fastpath.*; import org.postgresql.util.*; public class LargeObjectManager { // the fastpath api for this connection private Fastpath fp; /** * This mode indicates we want to write to an object */ public static final int WRITE = 0x00020000; /** * This mode indicates we want to read an object */ public static final int READ = 0x00040000; /** * This mode is the default. It indicates we want read and write access to * a large object */ public static final int READWRITE = READ | WRITE; private LargeObjectManager() { } /** * Constructs the LargeObject API. * * <p><b>Important Notice</b> * <br>This method should only be called by org.postgresql.Connection * * <p>There should only be one LargeObjectManager per Connection. The * org.postgresql.Connection class keeps track of the various extension API's * and it's advised you use those to gain access, and not going direct. */ public LargeObjectManager(org.postgresql.Connection conn) throws SQLException { // We need Fastpath to do anything this.fp = conn.getFastpathAPI(); // Now get the function oid's for the api // This is an example of Fastpath.addFunctions(); java.sql.ResultSet res = (java.sql.ResultSet)conn.createStatement().executeQuery("select proname, oid from pg_proc" + " where proname = 'lo_open'" + " or proname = 'lo_close'" + " or proname = 'lo_creat'" + " or proname = 'lo_unlink'" + " or proname = 'lo_lseek'" + " or proname = 'lo_tell'" + " or proname = 'loread'" + " or proname = 'lowrite'"); if(res==null) throw new PSQLException("postgresql.lo.init"); fp.addFunctions(res); res.close(); DriverManager.println("Large Object initialised"); } /* * Added to free resources during garbage collection, * Philip Crotwell <crotwell@seis.sc.edu> */ protected void finalize() { close(); } /** * This opens an existing large object, based on its OID. This method * assumes that READ and WRITE access is required (the default). * * @param oid of large object * @return LargeObject instance providing access to the object * @exception SQLException on error */ public LargeObject open(int oid) throws SQLException { return new LargeObject(fp,oid,READWRITE); } /** * This opens an existing large object, based on its OID * * @param oid of large object * @param mode mode of open * @return LargeObject instance providing access to the object * @exception SQLException on error */ public LargeObject open(int oid,int mode) throws SQLException { return new LargeObject(fp,oid,mode); } /** * This creates a large object, returning its OID. * * <p>It defaults to READWRITE for the new object's attributes. * * @return oid of new object * @exception SQLException on error */ public int create() throws SQLException { FastpathArg args[] = new FastpathArg[1]; args[0] = new FastpathArg(READWRITE); return fp.getInteger("lo_creat",args); } /** * This creates a large object, returning its OID * * @param mode a bitmask describing different attributes of the new object * @return oid of new object * @exception SQLException on error */ public int create(int mode) throws SQLException { FastpathArg args[] = new FastpathArg[1]; args[0] = new FastpathArg(mode); return fp.getInteger("lo_creat",args); } /** * This deletes a large object. * * @param oid describing object to delete * @exception SQLException on error */ public void delete(int oid) throws SQLException { FastpathArg args[] = new FastpathArg[1]; args[0] = new FastpathArg(oid); fp.fastpath("lo_unlink",false,args); } /** * This deletes a large object. * * <p>It is identical to the delete method, and is supplied as the C API uses * unlink. * * @param oid describing object to delete * @exception SQLException on error */ public void unlink(int oid) throws SQLException { delete(oid); } }
package algorithms.correlation; import algorithms.misc.MiscMath0; import algorithms.misc.MiscSorter; import java.util.Arrays; public class Distance { /** * calculates the distance covariance between univariate vectors x and y as * "a weighted distance between the joint characteristic function and * the product of marginal distributions; * it is 0 if and only if two random vectors and are independent. * This measure can detect the presence of a dependence structure when the * sample size is large enough." * * This algorithm is an implementation/port of the Matlab code from * "A fast algorithm for computing distance correlation" * 2019 Chaudhuri & Hu, Computational Statistics And Data Analysis, * Volume 135, July 2019, Pages 15-24. * * Runtime is O(n * lg_2(n)) where n is the number of points in x which is * the same as the number in y. * * NOTE: redundant points are possible in the rankings as "ties" are handled * in the algorithm. This is one advantage over the similar * algorithm of Huo and Szekely (2016). * * @param x sample of univariate observations * @param y second sample of univariate observations * @return */ public static DCov univariateCovariance(double[] x, double[] y) { if (x.length != y.length) { throw new IllegalArgumentException("length of x must equal length of y"); } int n = x.length; x = Arrays.copyOf(x, x.length); y = Arrays.copyOf(y, y.length); // x and y sorted: int[] indexes = MiscSorter.mergeBy1stArgThen2nd(x, y); double[] si = MiscMath0.cumulativeSum(x); assert(si.length == n); double s = si[n - 1]; //NOTE: in matlab, the .' is transpose without conjugation //NOTE: in matlab, the .* is multiplying same element positions by one another //NOTE: in matlab, vector .' * vector is the outer product //%a_x is the vector of row sums of distance matrix of x double[] a_x = new double[n]; for (int i = 1; i <= n; ++i) { a_x[i-1] = ((2.*i - n) * x[i-1]) + (s - 2.*si[i-1]); } double[] b_y = new double[n]; //%Compute Frobenius inner product between the //%distance matrices while finding indexes corresponding //%Weight vectors //nw = size( v, 2 ); // matlab .* is multiplying same element positions by one another int nw = 3; double[][] v = new double[n][nw]; for (int row = 0; row < n; ++row) { v[row][0] = x[row]; v[row][1] = y[row]; v[row][2] = x[row]*y[row]; } //% The columns of idx are buffers to store sort indices and output buffer //%of merge-sort //%we alternate between them and avoid uneccessary copying int[][] idx = new int[n][2]; for (int i = 0; i < n; ++i) { idx[i] = new int[2]; idx[i][0] = i+1; } //% iv1, iv2, iv3, iv4 are used to store sum of weights int[] iv1 = new int[n]; int[] iv2 = new int[n]; int[] iv3 = new int[n]; int[] iv4 = new int[n]; //NOTE: in matlab, the .' is transpose without conjugation //NOTE: in matlab, the .* is multiplying same element positions by one another //NOTE: in matlab, vector .' * vector is the outer product int i, j, k, kf, st1, st2, e1, e2, idx1, idx2, gap, z, zz; int[] idx_r = new int[n]; double[][] csumv = new double[n+1][nw]; double[][] tempv = new double[n][nw]; for (i = 0; i < n; ++i){ tempv[i] = new double[nw]; csumv[i] = new double[nw]; } csumv[n] = new double[nw]; double[][] tempcs; double[][] covterm = new double[n][n]; double[][] c1 = new double[n][n]; double c2; double[][] c3 = new double[n][n]; double[][] c4 = new double[n][n]; double[][] d = new double[n][n]; for (i = 0; i < n; ++i){ covterm[i] = new double[n]; c1[i] = new double[n]; c3[i] = new double[n]; c4[i] = new double[n]; d[i] = new double[n]; } //% The merge sort loop . i = 1; int r = 1; int idx_s = 2; while (i < n) { gap = 2*i; k = 0; //idx_r = idx(:, r); for (z = 0; z < idx.length; ++z) { idx_r[z] = idx[z][r-1]; } // csumv = [ zeros(1, nw); cumsum( v(idx_r, :) ) ] ; // csumv = [ zeros(1, nw); cumsum( v(idx_r, :) ) ] ; // dimensions: row0: nw columns // n rows of nw columns for (z = 0; z < n; ++z) { for (zz = 0; zz < nw; ++zz) { tempv[z][zz] = v[ idx_r[z] -1][zz]; } } tempcs = MiscMath0.cumulativeSumAlongColumns(tempv); Arrays.fill(csumv[0], 0); for (z = 0; z < n; ++z) { for (zz = 0; zz < nw; ++zz) { csumv[z + 1][zz] = tempcs[z][zz]; } } //for j = 1:gap:n; for (j = 1; j <= n; j+=gap) { st1 = j; e1 = Math.min(st1 + i - 1, n); st2 = j + i; e2 = Math.min(st2 + i - 1, n); while (( st1 <= e1 ) && ( st2 <= e2 ) ) { k++; idx1 = idx_r[st1-1]; idx2 = idx_r[st2-1]; if (y[idx1-1] >= y[idx2-1]) { idx[k-1][idx_s-1] = idx1; st1++; } else { idx[k-1][idx_s-1] = idx2; st2++; iv1[idx2-1] += (e1 - st1 + 1); iv2[idx2-1] += (csumv[e1+1-1][0] - csumv[st1-1][0]); iv3[idx2-1] += (csumv[e1+1-1][1] - csumv[st1-1][1]); iv4[idx2-1] += (csumv[e1+1-1][2] - csumv[st1-1][2]); } // end if-else } // end while if (st1 <= e1) { kf = k + e1 - st1 + 1; // note: idx is int[n][2]; idx_r is int[n] //idx( (k+1):kf, s ) = idx_r( st1 : e1, : ); int c = st1; for (z = (k+1); z <= kf; ++z) { idx[z-1][idx_s-1] = idx_r[c-1]; c++; } k = kf; } else if (st2 <= e2) { kf = k + e2 - st2 + 1; //idx( ( k+1):kf, s ) = idx_r( st2 : e2, : ); int c = st2; for (z = (k+1); z <= kf; ++z) { idx[z-1][idx_s-1] = idx_r[c-1]; c++; } k = kf; } } // end for j= i = gap; r = 3 - r; idx_s = 3 - idx_s; } System.out.println("iv1=" + Arrays.toString(iv1)); System.out.println("iv2=" + Arrays.toString(iv2)); System.out.println("iv3=" + Arrays.toString(iv3)); System.out.println("iv4=" + Arrays.toString(iv4)); //% d is the Frobenius inner product of the distance matrices // vector .' * is outer product: nX1 * 1Xn = nxn double[] mx = MiscMath0.mean(x, 1); assert(mx.length == 1); double[] my = MiscMath0.mean(y, 1); assert(my.length == 1); for (z = 0; z < n; ++z) { for (zz = 0; zz < n; ++zz) { covterm[z][zz] = n * ( (x[z] - mx[0]) * (y[zz] - my[0]) ); } } //NOTE v is double[n][nw]; //c2 = sum( iv4 ); c2 = 0; for (z = 0; z < n; ++z) { c2 += iv4[z]; for (zz = 0; zz < n; ++zz) { c1[z][zz] = iv1[z] * v[zz][2]; c3[z][zz] = iv2[z] * y[zz]; c4[z][zz] = iv3[z] * x[zz]; } } // c1, c3, c4, covterm are nxn // c2 is 1x1 for (z = 0; z < n; ++z) { for (zz = 0; zz < n; ++zz) { d[z][zz] = (4.*((c1[z][zz] + c2) - (c3[z][zz] + c4[z][zz]))) - 2.*covterm[z][zz]; } } double[] ySorted = new double[n]; //% b_y is the vector of row sums of distance matrix of y int c = 0; for (z = n; z >=1; z ySorted[c] = y[ idx[z-1][r-1] -1]; c++; } //si = cumsum( ySorted ); si = MiscMath0.cumulativeSum(ySorted); s = si[n-1]; //b_y = zeros( n , 1 ); Arrays.fill(b_y, 0); c = 0; double cc = -(n-2.); System.out.printf("cc=%.4f", cc); for (z = n; z >=1; z b_y[ idx[z-1][r-1] -1] = (cc * ySorted[c]) + (s - (2.*si[c])); c++; cc += 2; } System.out.printf("to %.4f\n", cc); System.out.printf("b_y=%s\n", Arrays.toString(b_y)); //%covsq equals V^2_n(x, y) the square of the distance covariance //%between x and y double nsq = (double)(n*n); double ncb = (double)(nsq*n); double nq = (double)(ncb*n); //term1 = d / nsq; double[][] term1 = new double[n][]; double[][] term2 = new double[n][n]; double term3A = 0; double term3B = 0; for (z = 0; z < n; ++z) { term1[z] = Arrays.copyOf(d[z], n); term2[z] = new double[n]; term3A += a_x[z]; term3B += b_y[z]; for (zz = 0; zz < n; ++zz) { term1[z][zz] /= nsq; term2[z][zz] = (2./ncb) * (a_x[z] * b_y[zz]); } } double term3 = (term3A * term3B) / nq; double[][] covsq = new double[n][n]; for (z = 0; z < n; ++z) { for (zz = 0; zz < n; ++zz) { covsq[z][zz] = (term1[z][zz] + term3) - term2[z][zz]; } } // for debugging only: System.out.println("d="); for (z = 0; z < n; ++z) { for (zz = 0; zz < n; ++zz) { System.out.printf(" %.3f", d[z][zz]); } System.out.printf("\n"); } DCov dcov = new DCov(); dcov.covsq = covsq; dcov.d = d; dcov.indexes = indexes; dcov.sortedX = x; dcov.sortedX = y; return dcov; } /** * checks the sort algorithm for having ported the code from 1-based array indexes to 0-based indexes. * "A fast algorithm for computing distance correlation" by Chaudhuri and Hu, 2018 * @param x * @param y * @return 2 dimensional array of size double[2][x.length] holding the sorted x and y in each row, respectively */ static double[][] _sortCheck(double[] x, double[] y) { if (x.length != y.length) { throw new IllegalArgumentException("length of x must equal length of y"); } int n = x.length; x = Arrays.copyOf(x, x.length); y = Arrays.copyOf(y, y.length); // x and y sorted: int[] indexes = MiscSorter.mergeBy1stArgThen2nd(x, y); int nw = 3; double[][] v = new double[n][nw]; v[0] = Arrays.copyOf(x, n); v[1] = Arrays.copyOf(y, n); v[2] = Arrays.copyOf(x, n); for (int row = 0; row < n; ++row) { v[2][row] *= y[row]; } //% The columns of idx are buffers to store sort indices and output buffer //%of merge-sort //%we alternate between them and avoid uneccessary copying int[][] idx = new int[n][2]; for (int i = 0; i < n; ++i) { idx[i] = new int[2]; idx[i][0] = i+1; } //NOTE: in matlab, the .' is transpose without conjugation //NOTE: in matlab, the .* is multiplying same element positions by one another //NOTE: in matlab, vector .' * vector is the outer product int i, j, k, kf, st1, st2, e1, e2, idx1, idx2, gap, z, zz; int[] idx_r = new int[n]; //% The merge sort loop . i = 1; int r = 1; // s = 2 in matlab code, was repurposed use of var s which was an integer type due to integer array x's cumulative sum. int idx_s = 2; while (i < n) { gap = 2*i; k = 0; //idx_r = idx(:, r); for (z = 0; z < idx.length; ++z) { idx_r[z] = idx[z][r-1]; } for (j = 1; j <= n; j+=gap) { st1 = j; e1 = Math.min(st1 + i - 1, n); st2 = j + i; e2 = Math.min(st2 + i - 1, n); while (( st1 <= e1 ) && ( st2 <= e2 ) ) { k++; idx1 = idx_r[st1-1]; idx2 = idx_r[st2-1]; if (y[idx1-1] >= y[idx2-1]) { idx[k-1][idx_s-1] = idx1; st1++; } else { idx[k-1][idx_s-1] = idx2; st2++; } // end if-else } // end while if (st1 <= e1) { kf = k + e1 - st1 + 1; // note: idx is int[n][2]; idx_r is int[n] //idx( (k+1):kf, s ) = idx_r( st1 : e1, : ); int c = st1; for (z = (k+1); z <= kf; ++z) { idx[z-1][idx_s-1] = idx_r[c-1]; c++; } k = kf; } else if (st2 <= e2) { kf = k + e2 - st2 + 1; //idx( ( k+1):kf, s ) = idx_r( st2 : e2, : ); int c = st2; for (z = k+1; z <= kf; ++z) { idx[z-1][idx_s-1] = idx_r[c-1]; c++; } k = kf; } } // end for j= i = gap; r = 3 - r; idx_s = 3 - idx_s; //2; 3-2=1 // 3-1=2 } double[][] sorted = new double[2][x.length]; sorted[0] = x; sorted[1] = y; return sorted; } public static class DCov { double[][] covsq; double[][] d; int[] indexes; double[] sortedX; double[] sortedY; double[] dcov; @Override public String toString() { StringBuilder sb = new StringBuilder(); if (indexes != null) { sb.append("indexes=").append(Arrays.toString(indexes)).append("\n"); } if (sortedX != null) { sb.append("sortedX=").append(Arrays.toString(sortedX)).append("\n"); } if (sortedY != null) { sb.append("sortedY=").append(Arrays.toString(sortedY)).append("\n"); } if (dcov != null) { sb.append("dcov=").append(Arrays.toString(dcov)).append("\n"); } if (d != null) { sb.append("d="); for (int i = 0; i < d.length; ++i) { sb.append(" ").append(Arrays.toString(d[i])).append("\n"); } } if (covsq != null) { sb.append("covsq=").append(Arrays.toString(covsq)).append("\n"); } return sb.toString(); } } /** * calculates the distance covariance between univariate vectors x and y as * "a weighted distance between the joint characteristic function and * the product of marginal distributions; * it is 0 if and only if two random vectors and are independent. * This measure can detect the presence of a dependence structure when the * sample size is large enough." * * This algorithm is an implementation/port of the Matlab code from * "A fast algorithm for computing distance correlation" * 2019 Chaudhuri & Hu, Computational Statistics And Data Analysis, * Volume 135, July 2019, Pages 15-24. * * Runtime is O(n^2) where n is the number of points in x which is * the same as the number in y. * * NOTE: redundant points are possible in the rankings as "ties" are handled * in the algorithm. This is one advantage over the similar * algorithm of Huo and Szekely (2016). * * TODO: for use of same ordering on more than 1 pair of univariate samples, * presumably need to overload this method to include sort order indexes * as an argument. * * @param x * @param y * @return */ public static DCov bruteForceUnivariateCovariance(double[] x, double[] y) { if (x.length != y.length) { throw new IllegalArgumentException("length of x must equal length of y"); } int n = x.length; x = Arrays.copyOf(x, x.length); y = Arrays.copyOf(y, y.length); int[][] idx = new int[2][n]; idx[0] = new int[n]; idx[1] = new int[n]; for (int i = 0; i < n; ++i) { idx[0][i] = i + 1; } int[] idx_r = new int[n]; double[] csumT = new double[n + 1]; double[] d = new double[n]; int gap, k, kf, z, j, st1, e1, st2, e2, idx1, idx2; int i = 1; int r = 1; int idx_s = 2; while (i < n) { gap = 2 * i; k = 0; System.arraycopy(idx[r - 1], 0, idx_r, 0, n); //csumT = cusum(y[idx r]); //csumT = (0, csumT ); csumT[0] = 0; for (z = 0; z < n; ++z) { csumT[z + 1] = y[idx_r[z] - 1]; } for (z = 2; z <= n; ++z) { csumT[z] += csumT[z - 1]; } j = 1; while (j < n) { st1 = j; e1 = Math.min(st1 + i - 1, n); st2 = j + i; e2 = Math.min(st2 + i - 1, n); while ((st1 <= e1) && (st2 <= e2)) { k++; idx1 = idx_r[st1 - 1]; idx2 = idx_r[st2 - 1]; if (x[idx1 - 1] >= x[idx2 - 1]) { idx[idx_s - 1][k - 1] = idx1; st1++; } else { idx[idx_s - 1][k - 1] = idx2; st2++; d[idx2 - 1] += (csumT[e1 + 1 - 1] - csumT[st1 - 1]); } // end if-else } // end while if (st1 <= e1) { kf = k + e1 - st1 + 1; int c = st1; for (z = (k + 1); z <= kf; ++z) { idx[idx_s - 1][z - 1] = idx_r[c - 1]; c++; } k = kf; } else if (st2 <= e2) { kf = k + e2 - st2 + 1; int c = st2; for (z = (k + 1); z <= kf; ++z) { idx[idx_s - 1][z - 1] = idx_r[c - 1]; c++; } k = kf; } j += gap; } // end while j i = gap; r = 3 - r; idx_s = 3 - idx_s; } // end while i double[] sortedX = new double[n]; double[] sortedY = new double[n]; int[] indexes = new int[n]; double[] sortedD = new double[n]; for (z = 0; z < n; ++z) { indexes[z] = idx[r - 1][z] - 1; sortedX[z] = x[indexes[z]]; sortedY[z] = y[indexes[z]]; sortedD[z] = d[indexes[z]]; } DCov dcov = new DCov(); dcov.dcov = sortedD; dcov.indexes = indexes; dcov.sortedX = sortedX; dcov.sortedY = sortedY; return dcov; } }
package be.ibridge.kettle.core; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; /** * This class is a container for "Local" enrvironment variables. * This is a singleton. We are going to launch jobs using a customer classloader. * This will make the variables inside it local. * * @author Matt */ public class LocalVariables { ThreadLocal local; private static LocalVariables localVariables; private Map map; /** * Create a new KettleVariables variable map in the local variables map for the specified thread. * @param localThread The local thread to attach to * @param parentThread The parent thread, null if there is no parent thread. The initial value of the variables will be taken from the variables that are attached to this thread. * @param sameNamespace true if you want to use the same namespace as the parent (if any) or false if you want to use a new namespace, create a new KettleVariables object. */ public KettleVariables createKettleVariables(String localThread, String parentThread, boolean sameNamespace) { if (parentThread!=null && parentThread.equals(localThread)) { throw new RuntimeException("local thread can't be the same as the parent thread!"); } // See if the thread already has an entry in the map KettleVariables vars = new KettleVariables(localThread, parentThread); // Copy the initial values from the parent thread if it is specified if (parentThread!=null) { KettleVariables initialValue = getKettleVariables(parentThread); if (initialValue!=null) { if (sameNamespace) { vars = new KettleVariables(localThread, parentThread); vars.setProperties(initialValue.getProperties()); } else { vars.putAll(initialValue.getProperties()); } } else { throw new RuntimeException("No parent Kettle Variables found for thread ["+parentThread+"], local thread is ["+localThread+"]"); } } // Before we add this, for debugging, just see if we're not overwriting anything. // Overwriting is a big No-No KettleVariables checkVars = (KettleVariables) map.get(localThread); if (checkVars!=null) { // throw new RuntimeException("There are already variables in the local variables map for ["+localThread+"]"); } // Put this one in the map, attached to the local thread map.put(localThread, vars); return vars; } public LocalVariables() { map = new Hashtable(); } public static final LocalVariables getInstance() { if (localVariables==null) // Not the first time we call this, see if we have properties for this thread { // System.out.println("Init of new local variables object"); localVariables = new LocalVariables(); } return localVariables; } public Map getMap() { return map; } public static final KettleVariables getKettleVariables() { return getInstance().getVariables(Thread.currentThread().toString()); } public static final KettleVariables getKettleVariables(String thread) { return getInstance().getVariables(thread); } /** * Find the KettleVariables in the map, attached to the specified Thread. * This is not singleton stuff, we return null in case we don't have anything attached to the current thread. * That makes it easier to find the "missing links" * @param localThread The thread to look for * @return The KettleVariables attached to the specified thread. */ private KettleVariables getVariables(String localThread) { KettleVariables kettleVariables = (KettleVariables) map.get(localThread); return kettleVariables; } public void removeKettleVariables(String thread) { removeKettleVariables(thread, 1); } /** * Remove all KettleVariables objects in the map, including the one for this thread, but also the ones with this thread as parent, etc. * @param thread the grand-parent thread to look for to remove */ private void removeKettleVariables(String thread, int level) { LogWriter log = LogWriter.getInstance(); List children = getKettleVariablesWithParent(thread); for (int i=0;i<children.size();i++) { String child = (String)children.get(i); removeKettleVariables(child, level+1); } // See if it was in there in the first place... if (map.get(thread)==null) { // We should not ever arrive here... log.logError("LocalVariables!!!!!!!", "The variables you are trying to remove, do not exist for thread ["+thread+"]"); log.logError("LocalVariables!!!!!!!", "Please report this error to the Kettle developers."); } else { map.remove(thread); } } private List getKettleVariablesWithParent(String parentThread) { List children = new ArrayList(); List values = new ArrayList(map.values()); for (int i=0;i<values.size();i++) { KettleVariables kv = (KettleVariables)values.get(i); if (kv.getParentThread()!=null && kv.getParentThread().equals(parentThread)) { if (kv.getLocalThread().equals(parentThread)) { System.out.println("---> !!!! This should not happen! Thread ["+parentThread+"] is linked to itself!"); } else { children.add(kv.getLocalThread()); } } } return children; } }
package allbegray.slack.type; import allbegray.slack.exception.SlackArgumentException; import allbegray.slack.validation.SlackFieldValidationUtils; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.util.ArrayList; import java.util.List; @JsonInclude(Include.NON_EMPTY) public class Attachment { private static final String HEX_REGEX = "^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"; private static final String PREDEFINED_COLOR_REGEX = "^(good|warning|danger)$"; protected String fallback; protected String color; protected String pretext; protected String author_name; protected String author_link; protected String author_icon; protected String title; protected String title_link; protected String text; protected List<Field> fields; protected String image_url; protected String thumb_url; protected List<String> mrkdwn_in; protected String footer; protected String footer_icon; protected Integer ts; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { if (color != null) { if (color.charAt(0) == ' if (!color.substring(1).matches(HEX_REGEX)) { throw new SlackArgumentException("invalid hex color"); } } else if (!color.matches(PREDEFINED_COLOR_REGEX)) { throw new SlackArgumentException("invalid predefined(good|warning|danger) color"); } } this.color = color; } public void setColor(Color color) { if (color != null) { this.color = color.name().toLowerCase(); } } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthor_name() { return author_name; } public void setAuthor_name(String author_name) { this.author_name = author_name; } public String getAuthor_link() { return author_link; } public void setAuthor_link(String author_link) { SlackFieldValidationUtils.validUrl(author_link, "author_link"); this.author_link = author_link; } public String getAuthor_icon() { return author_icon; } public void setAuthor_icon(String author_icon) { SlackFieldValidationUtils.validUrl(author_icon, "author_icon"); this.author_icon = author_icon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitle_link() { return title_link; } public void setTitle_link(String title_link) { SlackFieldValidationUtils.validUrl(title_link, "title_link"); this.title_link = title_link; } public String getText() { return text; } public void setText(String text) { this.text = text; } public void addField(Field field) { getFields().add(field); } public List<Field> getFields() { if (fields == null) { fields = new ArrayList<Field>(); } return fields; } public void setFields(List<Field> fields) { this.fields = fields; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { SlackFieldValidationUtils.validUrl(image_url, "image_url"); this.image_url = image_url; } public String getThumb_url() { return thumb_url; } public void setThumb_url(String thumb_url) { SlackFieldValidationUtils.validUrl(thumb_url, "thumb_url"); this.thumb_url = thumb_url; } public void addMrkdwn_in(String field) { getMrkdwn_in().add(field); } public List<String> getMrkdwn_in() { if (mrkdwn_in == null) { mrkdwn_in = new ArrayList<String>(); } return mrkdwn_in; } public void setMrkdwn_in(List<String> mrkdwn_in) { this.mrkdwn_in = mrkdwn_in; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooter_icon() { return footer_icon; } public void setFooter_icon(String footer_icon) { this.footer_icon = footer_icon; } public Integer getTs() { return ts; } public void setTs(Integer ts) { this.ts = ts; } @Override public String toString() { return "Attachment{" + "fallback='" + fallback + '\'' + ", color='" + color + '\'' + ", pretext='" + pretext + '\'' + ", author_name='" + author_name + '\'' + ", author_link='" + author_link + '\'' + ", author_icon='" + author_icon + '\'' + ", title='" + title + '\'' + ", title_link='" + title_link + '\'' + ", text='" + text + '\'' + ", fields=" + fields + ", image_url='" + image_url + '\'' + ", thumb_url='" + thumb_url + '\'' + ", mrkdwn_in=" + mrkdwn_in + ", footer='" + footer + '\'' + ", footer_icon='" + footer_icon + '\'' + ", ts=" + ts + '}'; } }
package be.ibridge.kettle.i18n; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; public class GlobalMessages { private static final ThreadLocal threadLocales = new ThreadLocal(); private static final LanguageChoice langChoice = LanguageChoice.getInstance(); private static final String SYSTEM_BUNDLE_PACKAGE = GlobalMessages.class.getPackage().getName(); private static final String BUNDLE_NAME = "messages.messages"; //$NON-NLS-1$ private static final Map locales = Collections.synchronizedMap(new HashMap()); public static final String[] localeCodes = { "en_US", "nl_NL", "zh_CN", "es_ES", "fr_FR", "de_DE" }; public static final String[] localeDescr = { "English (US)", "Nederlands", "Simplified Chinese", "Espa\u00F1iol", "Fran\u00E7ais", "Deutsch" }; protected static Map getLocales() { return locales; } public static Locale getLocale() { Locale rtn = (Locale) threadLocales.get(); if (rtn != null) { return rtn; } setLocale(langChoice.getDefaultLocale()); return langChoice.getDefaultLocale(); } public static void setLocale(Locale newLocale) { threadLocales.set(newLocale); } private static String getLocaleString(Locale locale) { String locString = locale.toString(); if (locString.length()==5 && locString.charAt(2)=='_') // Force upper-lowercase format { locString=locString.substring(0,2).toLowerCase()+"_"+locString.substring(3).toUpperCase(); // System.out.println("locString="+locString); } return locString; } private static String buildHashKey(Locale locale, String packageName) { return packageName + "_" + getLocaleString(locale); } private static String buildBundleName(String packageName) { return packageName + "." + BUNDLE_NAME; } private static ResourceBundle getBundle(Locale locale, String packageName) throws MissingResourceException { String filename = buildHashKey(locale, packageName); filename = "/"+filename.replace('.', '/') + ".properties"; try { ResourceBundle bundle = (ResourceBundle) locales.get(filename); if (bundle == null) { InputStream inputStream = LanguageChoice.getInstance().getClass().getResourceAsStream(filename); if (inputStream!=null) { bundle = new PropertyResourceBundle(inputStream); locales.put(filename, bundle); } else { throw new MissingResourceException("Unable to find properties file ["+filename+"]", locale.toString(), packageName); } } return bundle; } catch(IOException e) { throw new MissingResourceException("Unable to find properties file ["+filename+"] : "+e.toString(), locale.toString(), packageName); } } public static String getSystemString(String key) { try { ResourceBundle bundle = getBundle(langChoice.getDefaultLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)); return bundle.getString(key); } catch (MissingResourceException e) { // OK, try to find the key in the alternate failover locale try { ResourceBundle bundle = getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)); return bundle.getString(key); } catch (MissingResourceException fe) { fe.printStackTrace(); return '!' + key + '!'; } } } public static String getSystemString(String key, String param1) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getDefaultLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1); } catch (MissingResourceException e) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1); } catch (MissingResourceException fe) { fe.printStackTrace(); return '!' + key + '!'; } } } public static String getSystemString(String key, String param1, String param2) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2); } catch (MissingResourceException e) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2); } catch (MissingResourceException fe) { fe.printStackTrace(); return '!' + key + '!'; } } } public static String getSystemString(String key, String param1, String param2, String param3) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2, param3); } catch (MissingResourceException e) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2, param3); } catch (MissingResourceException fe) { fe.printStackTrace(); return '!' + key + '!'; } } } public static String getSystemString(String key, String param1, String param2, String param3, String param4) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2, param3, param4); } catch (MissingResourceException e) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2, param3, param4); } catch (MissingResourceException fe) { fe.printStackTrace(); return '!' + key + '!'; } } } public static String getSystemString(String key, String param1, String param2, String param3, String param4, String param5) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2, param3, param4, param5); } catch (MissingResourceException e) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2, param3, param4, param5); } catch (MissingResourceException fe) { fe.printStackTrace(); return '!' + key + '!'; } } } public static String getSystemString(String key, String param1, String param2, String param3, String param4, String param5, String param6) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2, param3, param4, param5, param6); } catch (MissingResourceException e) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), buildBundleName(SYSTEM_BUNDLE_PACKAGE)), key, param1, param2, param3, param4, param5, param6); } catch (MissingResourceException fe) { fe.printStackTrace(); return '!' + key + '!'; } } } public static String getString(String packageName, String key) { try { ResourceBundle bundle = getBundle(langChoice.getDefaultLocale(), packageName + "." + BUNDLE_NAME); return bundle.getString(key); } catch(MissingResourceException e) { ResourceBundle bundle = getBundle(langChoice.getFailoverLocale(), packageName + "." + BUNDLE_NAME); return bundle.getString(key); } } public static String getString(String packageName, String key, String param1) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getDefaultLocale(), packageName + "." + BUNDLE_NAME), key, param1); } catch(MissingResourceException e) { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), packageName + "." + BUNDLE_NAME), key, param1); } } public static String getString(String packageName, String key, String param1, String param2) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getDefaultLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2); } catch(MissingResourceException e) { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2); } } public static String getString(String packageName, String key, String param1, String param2, String param3) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getDefaultLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2, param3); } catch(MissingResourceException e) { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2, param3); } } public static String getString(String packageName, String key, String param1, String param2, String param3,String param4) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getDefaultLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2, param3, param4); } catch(MissingResourceException e) { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2, param3, param4); } } public static String getString(String packageName, String key, String param1, String param2, String param3, String param4, String param5) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getDefaultLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2, param3, param4, param5); } catch(MissingResourceException e) { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2, param3, param4, param5); } } public static String getString(String packageName, String key, String param1, String param2, String param3,String param4,String param5,String param6) { try { return GlobalMessageUtil.getString(getBundle(langChoice.getDefaultLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2, param3,param4,param5, param6); } catch(MissingResourceException e) { return GlobalMessageUtil.getString(getBundle(langChoice.getFailoverLocale(), packageName + "." + BUNDLE_NAME), key, param1, param2, param3,param4,param5,param6); } } }
package be.nille.http; import be.nille.http.route.MethodNotAllowedException; import be.nille.http.route.Request; import be.nille.http.route.ResourceNotFoundException; import be.nille.http.route.Response; import be.nille.http.route.Route; import be.nille.http.route.RouteRegistry; import be.nille.http.route.SimpleResponse; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.Cookie; import io.netty.handler.codec.http.CookieDecoder; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContent; import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpHeaderNames.COOKIE; import static io.netty.handler.codec.http.HttpHeaderNames.SET_COOKIE; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.codec.http.ServerCookieEncoder; import io.netty.util.CharsetUtil; import java.util.Map; import java.util.Set; import lombok.extern.slf4j.Slf4j; /** * * @author nholvoet */ @Slf4j public class HttpServerHandler extends SimpleChannelInboundHandler<Object> { private final RouteRegistry registry; private HttpRequest httpRequest; private HttpContent httpContent; public HttpServerHandler(final RouteRegistry registry){ this.registry = registry; } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { this.httpRequest = (HttpRequest) msg; } if (msg instanceof HttpContent) { log.info("HTTP Content received through channel"); this.httpContent = (HttpContent) msg; if (msg instanceof LastHttpContent) { LastHttpContent trailer = (LastHttpContent) msg; Request request = new Request(httpRequest, httpContent); StringBuilder sb = new StringBuilder(); Response response; try{ Route route = registry.find(request); response = route.getHandler().handle(request); }catch(MethodNotAllowedException ex){ log.info(ex.getMessage()); response = new SimpleResponse("","text/html; charset=utf-8",405); sb.append("METHOD NOT ALLOWED"); } catch(ResourceNotFoundException ex){ log.info(ex.getMessage()); response = new SimpleResponse("","text/html; charset=utf-8",404); } if (!writeResponse(trailer, ctx, response)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } } private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx, Response resp) { // Decide whether to close the connection or not. boolean keepAlive = HttpHeaders.isKeepAlive(httpRequest); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, currentObj.decoderResult().isSuccess()? OK : BAD_REQUEST, Unpooled.copiedBuffer(resp.getContent(), CharsetUtil.UTF_8)); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } response.setStatus(new HttpResponseStatus(resp.getStatusCode(), "")); for(Map.Entry<String,String> header : resp.getHeaders().entrySet()){ response.headers().set(header.getKey(),header.getValue()); } // Write the response. ctx.write(response); return keepAlive; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
package ch.bind.philib.lang; /** * Provides helper methods for object comparison. * * @author Philipp Meinen */ public abstract class CompareUtil { protected CompareUtil() { } public static boolean equals(final Object a, final Object b) { if (a == b) return true; if (a == null) { // b is not null -> not equal return false; } // this check could be simplified by only invoking a.equals(b) and // leaving it up to the specific equals implementation to check for // nulls. on the other hand, here we are with the power to find out // right here and now if (b == null) { return false; } return a.equals(b); } public static <T> int compare(final Comparable<T> a, final T b) { if (a == b) return 0; if (a == null) { // b is not null return -1; // a < b } if (b == null) { return 1; // a > b } return a.compareTo(b); } public static final int normalize(int diff) { return diff < 0 ? -1 : (diff == 0 ? 0 : 1); } public static final int normalize(long diff) { return (diff < 0 ? -1 : (diff == 0 ? 0 : 1)); } public static int diff(boolean a, boolean b) { return (a == b ? 0 : (a ? 1 : -1)); } public static final int diff(byte a, byte b) { return diff(a & 0xFF, b & 0xFF); } public static final int diff(char a, char b) { return a == b ? 0 : (a < b ? -1 : 1); } public static final int diff(short a, short b) { return a == b ? 0 : (a < b ? -1 : 1); } public static final int diff(int a, int b) { return a == b ? 0 : (a < b ? -1 : 1); } public static final int diff(long a, long b) { return a == b ? 0 : (a < b ? -1 : 1); } public static final int diff(float a, float b) { return a == b ? 0 : (a < b ? -1 : 1); } public static final int diff(double a, double b) { return a == b ? 0 : (a < b ? -1 : 1); } }
package com.beamofsoul.bip.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * @ClassName Login * @Description * @author MingshuJian * @Date 2017531 10:27:23 * @version 1.0.0 */ @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper=false) @Data @Entity @Table(name = "T_LOGIN") public class Login extends BaseAbstractEntity { private static final long serialVersionUID = 1336473767251163468L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") protected Long id; @ManyToOne @JoinColumn(name = "user_id") private User user; @Column(name = "ip_address") private String ipAddress; @Column(name = "brand") private String brand; @Column(name = "model") private String model; @Column(name = "screen_size") private String screenSize; @Column(name = "operating_system") private String operatingSystem; @Column(name = "browser") private String browser; }
package com.carlosefonseca.common; import android.app.ActivityManager; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.os.Environment; import com.carlosefonseca.common.utils.CodeUtils; import com.carlosefonseca.common.utils.Log; import java.io.File; import static com.carlosefonseca.common.utils.CodeUtils.getTag; /** * Base Class for the Application class. * Does the context management and sets up the test device. * Utils also access this class for its context. */ public class CFApp extends Application { private static final String TAG = getTag(CFApp.class); public static final String VERSION_KEY = "VERSION"; public static Context context; public static boolean test; private static final boolean ALLOW_TEST_DEVICE = true; private static Boolean isTestDevice = null; @Override public void onCreate() { super.onCreate(); context = this; setTestDevice(isTest()); final SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE); final int stored = sharedPreferences.getInt(VERSION_KEY, -1); final int current = CodeUtils.getAppVersionCode(); if (stored != current) { Log.put("App Update", "" + stored + " -> " + current); sharedPreferences.edit().putInt(VERSION_KEY, current).apply(); } else { Log.i("App Version: " + current); } init(current, stored); } protected void init(int currentVersion, int previousVersion) {} public static boolean testIfTestDevice() { if (isTestDevice == null) isTestDevice = isEmulator() || checkForceLogFile(); return isTestDevice; } private static boolean isEmulator() {return Build.FINGERPRINT.startsWith("generic");} private static boolean checkForceLogFile() { return new File(Environment.getExternalStorageDirectory(), "logbw.txt").exists(); } public static Context getContext() { if (context == null) Log.w(TAG, "Please setup a CFApp subclass!"); return context; } /** * You should override this and return com.yourapp.BuildConfig.DEBUG */ protected boolean isTest() { return test; } public static boolean isTestDevice() { return test; } public static void setTestDevice(boolean testDevice) { CFApp.test = testDevice; Log.setConsoleLogging(testDevice || testIfTestDevice()); if (testDevice) Log.w(TAG, "TEST DEVICE!"); } /** * @return {@link android.app.ActivityManager.MemoryInfo#availMem} * @see android.app.ActivityManager#getMemoryInfo(android.app.ActivityManager.MemoryInfo) */ public static long availableMemory() { ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE); activityManager.getMemoryInfo(mi); long availableMegs = mi.availMem / 1048576L; Log.i(TAG, "RAM \"Available\": " + availableMegs + " MB"); return mi.availMem; } @Override public void onTerminate() { context = null; super.onTerminate(); } public static SharedPreferences getUserPreferences() {return getUserPreferences("default");} public static SharedPreferences getUserPreferences(String name) { return context.getSharedPreferences(name, Context.MODE_PRIVATE); } }
package com.cidic.design; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.DisabledAccountException; import org.apache.shiro.authc.ExcessiveAttemptsException; import org.apache.shiro.authc.ExpiredCredentialsException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.UnauthorizedException; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.cidic.design.exception.ServerException; import com.cidic.design.model.News; import com.cidic.design.model.ResultModel; import com.cidic.design.service.JudgeService; import com.cidic.design.service.NewsService; import com.cidic.design.service.UserService; import com.cidic.design.util.ConfigInfo; /** * Handles requests for the application home page. */ @Controller public class HomeController extends DcController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @Autowired @Qualifier(value = "newsServiceImpl") private NewsService newsServiceImpl; @Autowired @Qualifier(value = "userServiceImpl") private UserService userServiceImpl; @Autowired @Qualifier(value = "judgeServiceImpl") private JudgeService judgeServiceImpl; @Autowired @Qualifier(value = "configInfo") private ConfigInfo configInfo; /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView home(Locale locale, Model model) { try { List<News> newsList = newsServiceImpl.getTopThreeNews(); ModelAndView modelView = new ModelAndView(); modelView.setViewName("/frontend/index"); modelView.addObject(newsList); return modelView; } catch (Exception e) { throw new ServerException(400, ""); } } @RequestMapping(value = "/login") public String login(HttpServletRequest request, Model model) { return "/frontend/login"; } @RequestMapping(value = "/error") public String error(HttpServletRequest request, Model model) { return "error"; } @RequestMapping(value = "/index") public ModelAndView index(HttpServletRequest request, Model model) { try { List<News> newsList = newsServiceImpl.getTopThreeNews(); ModelAndView modelView = new ModelAndView(); modelView.setViewName("/frontend/index"); modelView.addObject(newsList); return modelView; } catch (Exception e) { throw new ServerException(400, ""); } } @RequestMapping(value = "/dologin") public String doLogin(HttpServletRequest request, Model model) { String msg = ""; String username = request.getParameter("username"); String password = request.getParameter("password"); UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(true); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); if (subject.isAuthenticated()) { try { subject.checkRole(""); return "redirect:/news/newsMgr"; } catch (AuthorizationException e) { try{ subject.checkRole(""); return "redirect:/review/judgeIndex"; } catch (AuthorizationException ex) { return "redirect:/production/works"; } } } else { return "/frontend/login"; } } catch (IncorrectCredentialsException e) { msg = "."; model.addAttribute("error", msg); System.out.println(msg); } catch (ExcessiveAttemptsException e) { msg = ""; model.addAttribute("error", msg); System.out.println(msg); } catch (LockedAccountException e) { msg = "."; model.addAttribute("error", msg); System.out.println(msg); } catch (DisabledAccountException e) { msg = ". "; model.addAttribute("error", msg); System.out.println(msg); } catch (ExpiredCredentialsException e) { msg = "."; model.addAttribute("error", msg); System.out.println(msg); } catch (UnknownAccountException e) { msg = "."; model.addAttribute("error", msg); System.out.println(msg); } catch (UnauthorizedException e) { msg = ""; model.addAttribute("error", msg); System.out.println(msg); } return "/frontend/login"; } @RequestMapping(value = "/reviewLogin") public String reviewLogin(HttpServletRequest request, Model model) { String msg = ""; String username = request.getParameter("email"); String validCode = request.getParameter("validCode"); String password = judgeServiceImpl.findJudgePwdByEmail(username,validCode); int round = Integer.parseInt(request.getParameter("round").toString()); UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(true); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); if (subject.isAuthenticated()) { try{ subject.checkRole(""); System.out.println(""); return "redirect:/review/judgeIndex/"+round; } catch (AuthorizationException ex) { return "error"; } } else { return "/frontend/login"; } } catch (IncorrectCredentialsException e) { msg = "."; model.addAttribute("error", msg); } catch (ExcessiveAttemptsException e) { msg = ""; model.addAttribute("error", msg); } catch (LockedAccountException e) { msg = "."; model.addAttribute("error", msg); } catch (DisabledAccountException e) { msg = ". "; model.addAttribute("error", msg); } catch (ExpiredCredentialsException e) { msg = "."; model.addAttribute("error", msg); } catch (UnknownAccountException e) { msg = "."; model.addAttribute("error", msg); } catch (UnauthorizedException e) { msg = ""; model.addAttribute("error", msg); } catch(AuthorizationException e){ msg = ""; model.addAttribute("error", msg); } return "/frontend/login"; } @RequestMapping(value = "/logout") public String doLogout(HttpServletRequest request, Model model) { Subject subject = SecurityUtils.getSubject(); subject.logout(); return "/frontend/login"; } @RequestMapping(value = "/countDown") public ResultModel countDown(HttpServletRequest request, Model model) { ResultModel resultModel = new ResultModel(); int countDown = 0; resultModel.setObject(countDown); return resultModel; } }
package com.codeborne.selenide; import com.codeborne.selenide.ex.DialogTextMismatch; import com.codeborne.selenide.ex.JavaScriptErrorsFound; import com.codeborne.selenide.impl.*; import org.openqa.selenium.*; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.logging.LogEntry; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.FluentWait; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static com.codeborne.selenide.Configuration.dismissModalDialogs; import static com.codeborne.selenide.Configuration.timeout; import static com.codeborne.selenide.WebDriverRunner.*; import static com.codeborne.selenide.impl.WebElementProxy.wrap; import static java.lang.System.currentTimeMillis; import static java.util.Collections.emptyList; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * The main starting point of Selenide. * * You start with methods {@link #open(String)} for opening the tested application page and * {@link #$(String)} for searching web elements. */ public class Selenide { private static final Logger log = Logger.getLogger(Selenide.class.getName()); public static Navigator navigator = new Navigator(); public static void open(String relativeOrAbsoluteUrl) { navigator.open(relativeOrAbsoluteUrl); mockModalDialogs(); } /** * @see Selenide#open(String) */ public static void open(URL absoluteUrl) { navigator.open(absoluteUrl); mockModalDialogs(); } private static boolean doDismissModalDialogs() { return !supportsModalDialogs() || dismissModalDialogs; } private static void mockModalDialogs() { if (doDismissModalDialogs()) { String jsCode = " window._selenide_modalDialogReturnValue = true;\n" + " window.alert = function(message) {};\n" + " window.confirm = function(message) {\n" + " return window._selenide_modalDialogReturnValue;\n" + " };"; try { executeJavaScript(jsCode); } catch (UnsupportedOperationException cannotExecuteJsAgainstPlainTextPage) { log.warning(cannotExecuteJsAgainstPlainTextPage.toString()); } } } /** * Open a web page and create PageObject for it. * @return PageObject of given class */ public static <PageObjectClass> PageObjectClass open(String relativeOrAbsoluteUrl, Class<PageObjectClass> pageObjectClassClass) { open(relativeOrAbsoluteUrl); return page(pageObjectClassClass); } public static <PageObjectClass> PageObjectClass open(URL absoluteUrl, Class<PageObjectClass> pageObjectClassClass) { open(absoluteUrl); return page(pageObjectClassClass); } /** * Close the browser if it's open */ public static void close() { closeWebDriver(); } /** * Reload current page */ public static void refresh() { navigator.open(url()); } /** * Navigate browser back to previous page */ public static void back() { navigator.back(); } /** * Navigate browser forward to next page */ public static void forward() { navigator.forward(); } public static String title() { return getWebDriver().getTitle(); } /** * Not recommended. Test should not sleep, but should wait for some condition instead. * @param milliseconds Time to sleep in milliseconds */ public static void sleep(long milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } /** * Take the screenshot of current page and save to file fileName.html and fileName.png * @param fileName Name of file (without extension) to save HTML and PNG to * @return The name of resulting file */ public static String screenshot(String fileName) { return Screenshots.takeScreenShot(fileName); } /** * Wrap standard Selenium WebElement into SelenideElement * to use additional methods like shouldHave(), selectOption() etc. * * @param webElement standard Selenium WebElement * @return given WebElement wrapped into SelenideElement */ public static SelenideElement $(WebElement webElement) { return wrap(webElement); } /** * Find the first element matching given CSS selector * @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message" * @return SelenideElement * @throws NoSuchElementException if element was no found */ public static SelenideElement $(String cssSelector) { return getElement(By.cssSelector(cssSelector)); } /** * Find the first element matching given CSS selector * @param seleniumSelector any Selenium selector like By.id(), By.name() etc. * @return SelenideElement * @throws NoSuchElementException if element was no found */ public static SelenideElement $(By seleniumSelector) { return getElement(seleniumSelector); } /** * @see #getElement(By, int) */ public static SelenideElement $(By seleniumSelector, int index) { return getElement(seleniumSelector, index); } /** * Find the first element matching given CSS selector * @param parent the WebElement to search elements in * @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message" * @return SelenideElement * @throws NoSuchElementException if element was no found */ public static SelenideElement $(WebElement parent, String cssSelector) { return WaitingSelenideElement.wrap($(parent), By.cssSelector(cssSelector), 0); } /** * Find the Nth element matching given criteria * @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message" * @param index 0..N * @return SelenideElement * @throws NoSuchElementException if element was no found */ public static SelenideElement $(String cssSelector, int index) { return WaitingSelenideElement.wrap(null, By.cssSelector(cssSelector), index); } /** * Find the Nth element matching given criteria * @param parent the WebElement to search elements in * @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message" * @param index 0..N * @return SelenideElement * @throws NoSuchElementException if element was no found */ public static SelenideElement $(WebElement parent, String cssSelector, int index) { return WaitingSelenideElement.wrap($(parent), By.cssSelector(cssSelector), index); } public static SelenideElement $(WebElement parent, By selector) { return WaitingSelenideElement.wrap($(parent), selector, 0); } public static SelenideElement $(WebElement parent, By selector, int index) { return WaitingSelenideElement.wrap($(parent), selector, index); } public static ElementsCollection $$(Collection<? extends WebElement> elements) { return new ElementsCollection(new WebElementsCollectionWrapper(elements)); } /** * Find all elements matching given CSS selector. * Methods returns an ElementsCollection which is a list of WebElement objects that can be iterated, * and at the same time is implementation of WebElement interface, * meaning that you can call methods .sendKeys(), click() etc. on it. * * @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message" * @return empty list if element was no found */ public static ElementsCollection $$(String cssSelector) { return new ElementsCollection(new BySelectorCollection(By.cssSelector(cssSelector))); } /** * Find all elements matching given CSS selector. * Methods returns an ElementsCollection which is a list of WebElement objects that can be iterated, * and at the same time is implementation of WebElement interface, * meaning that you can call methods .sendKeys(), click() etc. on it. * * @param seleniumSelector any Selenium selector like By.id(), By.name() etc. * @return empty list if element was no found */ public static ElementsCollection $$(By seleniumSelector) { return new ElementsCollection(new BySelectorCollection(seleniumSelector)); } /** * Find all elements matching given CSS selector inside given parent element * Methods returns an ElementsCollection which is a list of WebElement objects that can be iterated, * and at the same time is implementation of WebElement interface, * meaning that you can call methods .sendKeys(), click() etc. on it. * * @param parent the WebElement to search elements in * @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message" * @return empty list if element was no found */ public static ElementsCollection $$(WebElement parent, String cssSelector) { return new ElementsCollection(new BySelectorCollection(parent, By.cssSelector(cssSelector))); } /** * Find all elements matching given criteria inside given parent element * @see Selenide#$$(WebElement, String) */ public static ElementsCollection $$(WebElement parent, By seleniumSelector) { return new ElementsCollection(new BySelectorCollection(parent, seleniumSelector)); } /** * Find the first element matching given criteria * @param criteria instance of By: By.id(), By.className() etc. * @return SelenideElement * @throws NoSuchElementException if element was no found */ public static SelenideElement getElement(By criteria) { return WaitingSelenideElement.wrap(null, criteria, 0); } /** * Find the Nth element matching given criteria * @param criteria instance of By: By.id(), By.className() etc. * @param index 0..N * @return SelenideElement * @throws NoSuchElementException if element was no found */ public static SelenideElement getElement(By criteria, int index) { return WaitingSelenideElement.wrap(null, criteria, index); } /** * Find all elements matching given CSS selector * @param criteria instance of By: By.id(), By.className() etc. * @return empty list if element was no found */ public static ElementsCollection getElements(By criteria) { return $$(criteria); } @SuppressWarnings("unchecked") public static <T> T executeJavaScript(String jsCode, Object... arguments) { return (T) ((JavascriptExecutor) getWebDriver()).executeScript(jsCode, arguments); } /** * Not recommended. It's better to use method {@code $(radioField).selectRadio(value);} * * Select radio field by value * @param radioField any By selector for finding radio field * @param value value to select (should match an attribute "value") * @return the selected radio field */ public static SelenideElement selectRadio(By radioField, String value) { return $(radioField).selectRadio(value); } public static SelenideElement getSelectedRadio(By radioField) { for (WebElement radio : $$(radioField)) { if (radio.getAttribute("checked") != null) { return wrap(radio); } } return null; } public static void onConfirmReturn(boolean confirmReturnValue) { if (doDismissModalDialogs()) { executeJavaScript("window._selenide_modalDialogReturnValue = " + confirmReturnValue + ';'); } } /** * Accept (Click "Yes" or "Ok") in the confirmation dialog (javascript 'alert' or 'confirm'). * Method does nothing in case of HtmlUnit browser (since HtmlUnit does not support alerts). * * @param expectedDialogText if not null, check that confirmation dialog displays this message (case-sensitive) * @throws DialogTextMismatch if confirmation message differs from expected message */ public static void confirm(String expectedDialogText) { if (!doDismissModalDialogs()) { Alert alert = waitForAlert(); String actualDialogText = alert.getText(); alert.accept(); checkDialogText(expectedDialogText, actualDialogText); } } private static Alert waitForAlert() { final long startTime = currentTimeMillis(); NoAlertPresentException lastError; do { try { Alert alert = getWebDriver().switchTo().alert(); alert.getText(); // check that alert actually exists return alert; } catch (NoAlertPresentException e) { lastError = e; } } while (currentTimeMillis() - startTime <= timeout); throw lastError; } /** * Dismiss (click "No" or "Cancel") in the confirmation dialog (javascript 'alert' or 'confirm'). * Method does nothing in case of HtmlUnit browser (since HtmlUnit does not support alerts). * * @param expectedDialogText if not null, check that confirmation dialog displays this message (case-sensitive) * @throws DialogTextMismatch if confirmation message differs from expected message */ public static void dismiss(String expectedDialogText) { if (!doDismissModalDialogs()) { Alert alert = waitForAlert(); String actualDialogText = alert.getText(); alert.dismiss(); checkDialogText(expectedDialogText, actualDialogText); } } private static void checkDialogText(String expectedDialogText, String actualDialogText) { if (expectedDialogText != null && !expectedDialogText.equals(actualDialogText)) { Screenshots.takeScreenShot(Selenide.class.getName(),Thread.currentThread().getName()); throw new DialogTextMismatch(actualDialogText, expectedDialogText); } } public static SelenideTargetLocator switchTo() { return new SelenideTargetLocator(getWebDriver().switchTo()); } public static WebElement getFocusedElement() { return (WebElement) executeJavaScript("return document.activeElement"); } /** * Create a Page Object instance. * @see PageFactory#initElements(WebDriver, Class) */ public static <PageObjectClass> PageObjectClass page(Class<PageObjectClass> pageObjectClass) { try { return page(pageObjectClass.getConstructor().newInstance()); } catch (Exception e) { throw new RuntimeException("Failed to create new instance of " + pageObjectClass, e); } } /** * Create a Page Object instance. * @see PageFactory#initElements(WebDriver, Class) */ public static <PageObjectClass, T extends PageObjectClass> PageObjectClass page(T pageObject) { PageFactory.initElements(new SelenideFieldDecorator(getWebDriver()), pageObject); return pageObject; } public static FluentWait<WebDriver> Wait() { return new FluentWait<WebDriver>(getWebDriver()) .withTimeout(timeout, MILLISECONDS) .pollingEvery(Configuration.pollingInterval, MILLISECONDS); } public static Actions actions() { return new Actions(getWebDriver()); } /** * Switch to window/tab by title * @deprecated Same as switchTo().window(title) */ @Deprecated public static void switchToWindow(String title) { switchTo().window(title); } /** * @deprecated The same as {@code switchTo().window(index);} * @param index index of window (0-based) */ @Deprecated public static void switchToWindow(int index) { switchTo().window(index); } public static List<String> getJavascriptErrors() { if (!WebDriverRunner.webdriverContainer.hasWebDriverStarted()) { return emptyList(); } try { List<Object> errors = executeJavaScript("return window._selenide_jsErrors"); if (errors == null || errors.isEmpty()) { return emptyList(); } List<String> result = new ArrayList<String>(errors.size()); for (Object error : errors) { result.add(error.toString()); } return result; } catch (WebDriverException cannotExecuteJs) { log.severe(cannotExecuteJs.toString()); return emptyList(); } } /** * Check if there is not JS errors on the page * @throws JavaScriptErrorsFound */ public static void assertNoJavascriptErrors() throws JavaScriptErrorsFound { List<String> jsErrors = getJavascriptErrors(); if (jsErrors != null && !jsErrors.isEmpty()) { throw new JavaScriptErrorsFound(jsErrors); } } /** * Zoom current page (in or out). * @param factor e.g. 1.1 or 2.0 or 0.5 */ public static void zoom(double factor) { executeJavaScript( "document.body.style.transform = 'scale(' + arguments[0] + ')';" + "document.body.style.transformOrigin = '0 0';", factor ); } /** * Same as com.codeborne.selenide.Selenide#getWebDriverLogs(java.lang.String, java.util.logging.Level) * * EXPERIMENTAL! Use with caution. */ public static List<String> getWebDriverLogs(String logType) { return getWebDriverLogs(logType, Level.ALL); } public static List<String> getWebDriverLogs(String logType, Level logLevel) { return listToString(getLogEntries(logType, logLevel)); } private static List<LogEntry> getLogEntries(String logType, Level logLevel) { try { return getWebDriver().manage().logs().get(logType).filter(logLevel); } catch (UnsupportedOperationException ignore) { return emptyList(); } } private static <T> List<String> listToString(List<T> objects) { if (objects == null || objects.isEmpty()) { return emptyList(); } List<String> result = new ArrayList<String>(objects.size()); for (T object : objects) { result.add(object.toString()); } return result; } }
package com.demigodsrpg.chitchatbot; import com.demigodsrpg.chitchat.Chitchat; import com.demigodsrpg.chitchatbot.ai.Brain; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; public class Bot implements Listener { private static final Random RANDOM = new Random(); private static final String SAVE_PATH = BotPlugin.INST.getDataFolder().getPath() + "/bots/"; private final Cache<String, Integer> SPAM_CACHE = CacheBuilder.newBuilder(). expireAfterWrite(8, TimeUnit.SECONDS). build(); private final List<String> listensTo; private final Brain brain; private final String name, prefix; private final boolean talks; private final long freqTicks; public Bot(String name, String prefix, boolean talks, long freqTicks, String... listensTo) { this(name, prefix, talks, freqTicks, Arrays.asList(listensTo)); } public Bot(String name, String prefix, boolean talks, long freqTicks, List<String> listensTo) { this.name = name; this.prefix = prefix; this.talks = talks; this.freqTicks = freqTicks; this.listensTo = listensTo; this.brain = tryLoadFromFile(); } public Brain getBrain() { return brain; } public String getName() { return name; } public String getPrefix() { return prefix; } public boolean getTalks() { return talks; } public long getFreqTicks() { return freqTicks; } public int getSpamAmount(String replyTo) { int amount = SPAM_CACHE.asMap().getOrDefault(replyTo, 0); SPAM_CACHE.put(replyTo, amount + 1); return amount; } private void createFile(File file) { try { file.getParentFile().mkdirs(); file.createNewFile(); } catch (Exception oops) { oops.printStackTrace(); } } public void saveToFile() { File file = new File(SAVE_PATH + name + ".json"); if (!(file.exists())) { createFile(file); } Gson gson = new GsonBuilder().create(); String json = gson.toJson(brain); try { PrintWriter writer = new PrintWriter(file); writer.print(json); writer.close(); } catch (Exception oops) { oops.printStackTrace(); } } public Brain tryLoadFromFile() { Gson gson = new GsonBuilder().create(); try { File file = new File(SAVE_PATH + name + ".json"); if (file.exists()) { FileInputStream inputStream = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(inputStream); Brain brain = gson.fromJson(reader, Brain.class); reader.close(); return brain; } } catch (Exception oops) { oops.printStackTrace(); } return new Brain(); } private String lastPlayer = ""; private Long lastTime = 0L; private String lastMessage = ""; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onChat(AsyncPlayerChatEvent event) { String message = event.getMessage(); if (message.toLowerCase().contains("@" + getName().toLowerCase())) { int spamAmount = getSpamAmount(event.getPlayer().getName()); if (spamAmount < 1) { String[] parts = message.toLowerCase().trim().split("\\s+"); String word = parts[RANDOM.nextInt(parts.length)]; String[] sentence = getBrain().getSentence(!word.toLowerCase().contains("@" + getName().toLowerCase()) ? word : null).split("" + (char) 10); Bukkit.getScheduler().scheduleAsyncDelayedTask(BotPlugin.INST, () -> { if (!"".equals(sentence[0])) { for (String part : sentence) { Chitchat.sendMessage(getPrefix() + part); } } else { Chitchat.sendMessage(getPrefix() + "beep. boop. beep."); } }, 10 * (1 + RANDOM.nextInt(2))); } else { // Let them know the bot doesn't like spam event.setCancelled(true); event.getPlayer().sendMessage(event.getFormat()); if (spamAmount % 5 == 0) { event.getPlayer().sendMessage(ChatColor.DARK_GRAY + "PM from" + " <" + ChatColor.DARK_AQUA + getName() + ChatColor.DARK_GRAY + ">: " + ChatColor.GRAY + "Please don't spam me. :C"); } } } else if (!message.contains("@")) { if (listensTo.isEmpty()) { if (lastTime > System.currentTimeMillis() - 4000 && lastPlayer.equals(event.getPlayer().getName())) { lastMessage += ((char) 10) + message; lastTime = System.currentTimeMillis(); } else { getBrain().add(lastMessage); lastMessage = message; lastPlayer = event.getPlayer().getName(); } } else if (listensTo.contains(event.getPlayer().getName())) { getBrain().add(message); } } } }
package com.epictodo.util; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TimeValidator { private Pattern _pattern; private Matcher _matcher; private static final String TIME24HOURS_PATTERN = "([01]?[0-9]|2[0-3]):[0-5][0-9]"; //"([01]?[0-9]|2[0-3]):[0-5][0-9]\\S+"; public TimeValidator() { _pattern = Pattern.compile(TIME24HOURS_PATTERN); } public boolean validate(final String _time) { assert _time.length() == 5; _matcher = _pattern.matcher(_time); // String time = _time; // time = time.replaceAll(TIME24HOURS_PATTERN, ""); // /** // * Algorithm to provide a natural response when a negative input was entered. // * Time validation will ask users if that was the correct input, otherwise users can correct the error. // */ // if (_matcher.matches() == true) { // return _matcher.matches(); // } else if (!_time.matches(TIME24HOURS_PATTERN)) { // System.out.println("Did you meant " + time + "hrs?"); return _matcher.matches(); } }
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class _1087 { public static class Solution1 { public String[] expand(String S) { List<char[]> letters = parse(S); List<String> result = backtracking(letters, 0, new StringBuilder(), new ArrayList<>()); String[] r = result.stream().toArray(String[]::new); Arrays.sort(r); return r; } private List<String> backtracking(List<char[]> letters, int start, StringBuilder sb, List<String> result) { if (start >= letters.size()) { result.add(sb.toString()); return result; } char[] chars = letters.get(start); for (int i = 0; i < chars.length; i++) { sb.append(chars[i]); backtracking(letters, start + 1, sb, result); sb.setLength(sb.length() - 1); } return result; } private List<char[]> parse(String s) { List<char[]> result = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '{') { int start = ++i; while (i < s.length() && s.charAt(i) != '}') { i++; } String[] strings = s.substring(start, i).split(","); char[] chars = new char[strings.length]; for (int j = 0; j < strings.length; j++) { chars[j] = strings[j].charAt(0); } result.add(chars); } else { char[] chars = new char[1]; chars[0] = s.charAt(i); result.add(chars); } } return result; } } }
package functionalTests.timit.timers.basic; import org.junit.After; import org.objectweb.proactive.api.ProActiveObject; import org.objectweb.proactive.api.ProDeployment; import org.objectweb.proactive.benchmarks.timit.util.basic.TimItBasicReductor; import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.node.Node; import functionalTests.FunctionalTest; import static junit.framework.Assert.assertTrue; public class Test extends FunctionalTest { private ActiveObjectClass a1; private ActiveObjectClass a1bis; private ActiveObjectClass a2; private ProActiveDescriptor descriptorPad; //private TimItBasicReductor t; public void initTest() throws Exception { // Access the nodes of the descriptor file descriptorPad = ProDeployment.getProactiveDescriptor(this.getClass() .getResource("/functionalTests/timit/timers/basic/descriptor.xml") .getPath()); descriptorPad.activateMappings(); VirtualNode vnode = descriptorPad.getVirtualNodes()[0]; Node[] nodes = vnode.getNodes(); this.a1 = (ActiveObjectClass) ProActiveObject.newActive(ActiveObjectClass.class.getName(), new Object[] { "a1" }, nodes[0]); this.a1bis = (ActiveObjectClass) ProActiveObject.newActive(ActiveObjectClass.class.getName(), new Object[] { "a1bis" }, nodes[1]); // Provide the remote reference of a1 and a1bis to a2 this.a2 = (ActiveObjectClass) ProActiveObject.newActive(ActiveObjectClass.class.getName(), new Object[] { this.a1, this.a1bis, "a2" }, nodes[1]); // In order to test the value of the WaitForRequest timer // the main will wait a WAITING_TIME, therefore the a2 will be in // WaitForRequest for at // least 100 Thread.sleep(100); } public boolean preConditions() throws Exception { return ((this.a1 != null) && (this.a1bis != null)) && ((this.a2 != null) && this.a2.checkRemoteAndLocalReference()); } @org.junit.Test public void action() throws Exception { // Create active objects this.initTest(); // Check their creation assertTrue("Problem with the creation of active objects for this test !", this.preConditions()); // Check if the Total timer is started String reason = this.a2.checkIfTotalIsStarted(); assertTrue(reason, reason == null); // Check if the WaitForRequest timer is stopped during a service of a // request reason = this.a2.checkIfWfrIsStopped(); assertTrue(reason, reason == null); // Check if the Serve timer is started during a service of a request reason = this.a2.checkIfServeIsStarted(); assertTrue(reason, reason == null); // For the next requests a2 is going to use timers // SendRequest, BeforeSerialization, Serialization and // AfterSerialization timers must be used reason = this.a2.performSyncCallOnRemote(); assertTrue(reason, reason == null); // SendRequest and LocalCopy timers must be used reason = this.a2.performSyncCallOnLocal(); assertTrue(reason, reason == null); // SendRequest and WaitByNecessity timers must be used reason = this.a2.performAsyncCallWithWbnOnLocal(); assertTrue(reason, reason == null); // disable the result output // this.t = TimItBasicManager.getInstance().getTimItCommonReductor(); // t.setGenerateOutputFile(false); // t.setPrintOutput(false); } @After public void endTest() throws Exception { this.descriptorPad.killall(true); Thread.sleep(300); this.a1 = null; this.a1bis = null; this.a2 = null; this.descriptorPad = null; //this.t = null; } public static void main(String[] args) { Test test = new Test(); try { test.action(); } catch (Throwable e) { e.printStackTrace(); } finally { System.exit(0); } } }
package com.github.acc15.version; import java.util.Comparator; public class Tokens { public static abstract class TokenMatcher implements Comparator<String> { private final int priority; public TokenMatcher() { this(0); } public TokenMatcher(int priority) { this.priority = priority; } public abstract boolean matches(String str); public int compare(String o1, String o2) { return 0; } } public static TokenMatcher empty() { return new TokenMatcher() { @Override public boolean matches(String str) { return str.isEmpty(); } }; } public static TokenMatcher value(String val) { return new TokenMatcher(1) { @Override public boolean matches(String str) { return val.equals(str); } }; } public static TokenMatcher other() { return new TokenMatcher(-1) { @Override public boolean matches(String str) { return true; } @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }; } public static TokenMatcher numeric() { return new TokenMatcher() { @Override public boolean matches(String str) { try { int val = Integer.parseInt(str); return true; } catch (NumberFormatException e) { return false; } } @Override public int compare(String o1, String o2) { return Integer.compare(Integer.parseInt(o1), Integer.parseInt(o2)); } }; } private static int findMatcher(String str, TokenMatcher[] matchers) { int found = -1; for (int i = 0; i < matchers.length; i++) { if (matchers[i].matches(str) && (found < 0 || matchers[found].priority < matchers[i].priority)) { found = i; } } return found; } public static Comparator<String> toComparator(TokenMatcher... matchers) { return (a, b) -> { int m1 = findMatcher(a, matchers); int m2 = findMatcher(b, matchers); int c = Integer.compare(m1, m2); return c == 0 ? matchers[m1].compare(a, b) : c; }; } }
package com.harrison.pubsub; import com.harrison.pubsub.interfaces.Publisher; import com.harrison.pubsub.interfaces.Subscriber; import javax.swing.JPanel; import java.util.List; public abstract class PubSubPanel extends JPanel implements Publisher, Subscriber{ private static final long serialVersionUID = 6289206719300193485L; private PubSubInterface psi; public PubSubPanel(List<String> args){ psi = new PubSubComponent(args); } public PubSubPanel(boolean allowPublishLoopback){ psi = new PubSubComponent(allowPublishLoopback); } public PubSubPanel(){ psi = new PubSubComponent(); } public void subscribe(Class<?> clazz){ psi.subscribe(clazz); } public void publish(Object data){ psi.publish(data); } public abstract void receive(Object data); @Override public boolean isPublishLoopbackAllowed() { return psi.isPublishLoopbackAllowed(); } private class PubSubComponent extends PubSubInterface{ public PubSubComponent(List<String> args){ super(args); } public PubSubComponent(boolean allowPublishLoopback){ super(allowPublishLoopback); } public PubSubComponent(){ super(); } @Override public void receive(Object data) { PubSubPanel.this.receive(data); } } }