answer
stringlengths
17
10.2M
package com.platypii.baseline.jarvis; import com.platypii.baseline.Services; import com.platypii.baseline.measurements.MLocation; import android.os.Handler; import android.support.annotation.NonNull; import android.util.Log; /** * Automatically stop logging when landing is detected (after a known jump) */ public class AutoStop { private static final String TAG = "AutoStop"; // Detection parameters private static final double alpha1 = 0.6; // Freefall param private static final double alpha2 = 0.02; // Canopy param private static final double beta = 0.5; // Landing param private static final double minHeight = 60; // meters public static boolean preferenceEnabled = true; // Jump detection state private static final int STATE_STOPPED = 0; private static final int STATE_STARTED = 1; private static final int STATE_EXITED = 2; private int state = STATE_STOPPED; // When auto stop is enabled, if we haven't detected landing in 1 hour, stop recording private final Handler handler = new Handler(); private static final long autoTimeout = 3600000; // 1 hour private double prExited = 0; private double prLanded = 0; // Stats private long lastMillis = 0; private double altMin = Double.NaN; private double altMax = Double.NaN; void update(@NonNull MLocation loc) { if (loc.millis - lastMillis >= 1000) { lastMillis = loc.millis; update1hz(loc); } } /** * Update to be called at most once per second */ private void update1hz(@NonNull MLocation loc) { final double alt = loc.altitude_gps; // Update altitude range if (!Double.isNaN(alt)) { if (!(altMin < alt)) altMin = alt; if (!(alt < altMax)) altMax = alt; } // Update state if (state == STATE_STARTED) { // Look for flight / freefall if (loc.climb < -15 && altMax - alt > minHeight) { prExited += (1 - prExited) * alpha1; } else if (FlightMode.getMode(loc) == FlightMode.MODE_CANOPY && altMax - alt > minHeight) { prExited += (1 - prExited) * alpha2; } else { prExited -= prExited * alpha1; } if (prExited > 0.85) { Log.i(TAG, "Exit detected"); state = STATE_EXITED; } } else if (state == STATE_EXITED) { // Look for landing final double altNormalized = (alt - altMin) / (altMax - altMin); if (FlightMode.getMode(loc) == FlightMode.MODE_GROUND && !(loc.groundSpeed() > 5) && altMax - altMin > minHeight && altNormalized < 0.1) { prLanded += (1 - prLanded) * beta; } else { prLanded -= (1 - prLanded) * 0.25; } if (prLanded > 0.95) { Log.i(TAG, "Landing detected"); landed(); } } } void start() { if (state == STATE_STOPPED) { // Reset state state = STATE_STARTED; prExited = 0; prLanded = 0; // TODO: Should we reset altitude range per recording or per app session? altMin = Double.NaN; altMax = Double.NaN; // When auto stop is enabled, timeout after 1 hour handler.postDelayed(stopRunnable, autoTimeout); } else { Log.e(TAG, "Autostop should not be started twice"); } } void stop() { if (state != STATE_STOPPED) { state = STATE_STOPPED; // Stop timeout thread handler.removeCallbacks(stopRunnable); } else { Log.e(TAG, "Autostop should not be stopped twice"); } } private void landed() { state = STATE_STOPPED; // If audible enabled, say landing detected if (preferenceEnabled) { // If audible enabled, disable if (Services.audible.isEnabled()) { Services.audible.disableAudible(); } // If logging enabled, disable if (Services.logger.isLogging()) { Services.logger.stopLogging(); } else { Log.e(TAG, "Landing detected, but logger not logging"); } } } /** * A thread that stops recording after 1 hour */ private final Runnable stopRunnable = () -> { Log.i(TAG, "Auto-stop timeout"); landed(); }; }
package com.samourai.wallet.send; import android.app.Activity; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.Editable; import android.text.InputFilter; import android.text.Selection; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; import com.google.android.material.button.MaterialButton; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.slider.Slider; import com.google.android.material.snackbar.Snackbar; import com.google.common.base.Splitter; import com.samourai.boltzmann.beans.BoltzmannSettings; import com.samourai.boltzmann.beans.Txos; import com.samourai.boltzmann.linker.TxosLinkerOptionEnum; import com.samourai.boltzmann.processor.TxProcessor; import com.samourai.boltzmann.processor.TxProcessorResult; import com.samourai.http.client.AndroidHttpClient; import com.samourai.http.client.IHttpClient; import com.samourai.wallet.R; import com.samourai.wallet.SamouraiActivity; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.TxAnimUIActivity; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.SendNotifTxFactory; import com.samourai.wallet.bip47.rpc.PaymentAddress; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.cahoots.Cahoots; import com.samourai.wallet.cahoots.CahootsMode; import com.samourai.wallet.cahoots.CahootsType; import com.samourai.wallet.cahoots.psbt.PSBTUtil; import com.samourai.wallet.fragments.CameraFragmentBottomSheet; import com.samourai.wallet.fragments.PaynymSelectModalFragment; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.paynym.paynymDetails.PayNymDetailsActivity; import com.samourai.wallet.ricochet.RicochetActivity; import com.samourai.wallet.ricochet.RicochetMeta; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.segwit.bech32.Bech32Util; import com.samourai.wallet.send.batch.BatchSpendActivity; import com.samourai.wallet.send.cahoots.ManualCahootsActivity; import com.samourai.wallet.send.cahoots.SelectCahootsType; import com.samourai.wallet.send.soroban.meeting.SorobanMeetingSendActivity; import com.samourai.wallet.tor.TorManager; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.DecimalDigitsInputFilter; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.LogUtil; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.SendAddressUtil; import com.samourai.wallet.util.WebUtil; import com.samourai.wallet.utxos.PreSelectUtil; import com.samourai.wallet.utxos.UTXOSActivity; import com.samourai.wallet.utxos.models.UTXOCoin; import com.samourai.wallet.whirlpool.WhirlpoolConst; import com.samourai.wallet.whirlpool.WhirlpoolMeta; import com.samourai.wallet.widgets.SendTransactionDetailsView; import com.samourai.xmanager.client.XManagerClient; import com.samourai.xmanager.protocol.XManagerService; import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.tuple.Triple; import org.bitcoinj.core.Address; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.script.Script; import org.bouncycastle.util.encoders.Hex; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URLDecoder; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Vector; import java.util.concurrent.TimeUnit; import androidx.appcompat.widget.SwitchCompat; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.constraintlayout.widget.Group; import androidx.core.content.ContextCompat; import ch.boye.httpclientandroidlib.protocol.HttpProcessorBuilder; import io.matthewnelson.topl_service.TorServiceController; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class SendActivity extends SamouraiActivity { private final static int SCAN_QR = 2012; private final static int RICOCHET = 2013; private static final String TAG = "SendActivity"; private SendTransactionDetailsView sendTransactionDetailsView; private ViewSwitcher amountViewSwitcher; private EditText toAddressEditText, btcEditText, satEditText; private TextView tvMaxAmount, tvReviewSpendAmount, tvReviewSpendAmountInSats, tvTotalFee, tvToAddress, tvEstimatedBlockWait, tvSelectedFeeRate, tvSelectedFeeRateLayman, ricochetTitle, ricochetDesc, cahootsStatusText, cahootsNotice, satbText; private MaterialButton btnReview, btnSend; private SwitchCompat ricochetHopsSwitch, ricochetStaggeredDelivery; private ViewGroup totalMinerFeeLayout; private SwitchCompat cahootsSwitch; private Slider feeSeekBar; private Group ricochetStaggeredOptionGroup; private boolean shownWalletLoadingMessage = false; private long balance = 0L; private long selectableBalance = 0L; private String strDestinationBTCAddress = null; private ProgressBar progressBar; private final static int FEE_LOW = 0; private final static int FEE_NORMAL = 1; private final static int FEE_PRIORITY = 2; private final static int FEE_CUSTOM = 3; private int FEE_TYPE = FEE_LOW; public final static int SPEND_SIMPLE = 0; public final static int SPEND_BOLTZMANN = 1; public final static int SPEND_RICOCHET = 2; private int SPEND_TYPE = SPEND_BOLTZMANN; private boolean openedPaynym = false; private String strPCode = null; private String strPcodeCounterParty = null; private long feeLow, feeMed, feeHigh; private String strPrivacyWarning; private String strCannotDoBoltzmann; private ArrayList<UTXO> selectedUTXO; private long _change; private HashMap<String, BigInteger> receivers; private int changeType; private ConstraintLayout cahootsGroup; private ConstraintLayout premiumAddons; private TextView addonsNotAvailableMessage; private String address; private String message; private long amount; private int change_index; private String ricochetMessage; private JSONObject ricochetJsonObj = null; private boolean stoneWallChecked = true; private int idxBIP44Internal = 0; private int idxBIP49Internal = 0; private int idxBIP84Internal = 0; private int idxBIP84PostMixInternal = 0; //stub address for entropy calculation public static String[] stubAddress = {"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", "12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX", "1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1", "1FvzCLoTPGANNjWoUo6jUGuAG3wg1w4YjR", "15ubicBBWFnvoZLT7GiU2qxjRaKJPdkDMG", "1JfbZRwdDHKZmuiZgYArJZhcuuzuw2HuMu", "1GkQmKAmHtNfnD3LHhTkewJxKHVSta4m2a", "16LoW7y83wtawMg5XmT4M3Q7EdjjUmenjM", "1J6PYEzr4CUoGbnXrELyHszoTSz3wCsCaj", "12cbQLTFMXRnSzktFkuoG3eHoMeFtpTu3S", "15yN7NPEpu82sHhB6TzCW5z5aXoamiKeGy ", "1dyoBoF5vDmPCxwSsUZbbYhA5qjAfBTx9", "1PYELM7jXHy5HhatbXGXfRpGrgMMxmpobu", "17abzUBJr7cnqfnxnmznn8W38s9f9EoXiq", "1DMGtVnRrgZaji7C9noZS3a1QtoaAN2uRG", "1CYG7y3fukVLdobqgUtbknwWKUZ5p1HVmV", "16kktFTqsruEfPPphW4YgjktRF28iT8Dby", "1LPBetDzQ3cYwqQepg4teFwR7FnR1TkMCM", "1DJkjSqW9cX9XWdU71WX3Aw6s6Mk4C3TtN", "1P9VmZogiic8d5ZUVZofrdtzXgtpbG9fop", "15ubjFzmWVvj3TqcpJ1bSsb8joJ6gF6dZa"}; private CompositeDisposable compositeDisposables = new CompositeDisposable(); private SelectCahootsType.type selectedCahootsType = SelectCahootsType.type.NONE; private final DecimalFormat decimalFormatSatPerByte = new DecimalFormat(" private List<UTXOCoin> preselectedUTXOs = null; @Override protected void onCreate(Bundle savedInstanceState) { //Switch themes based on accounts (blue theme for whirlpool account) setSwitchThemes(true); super.onCreate(savedInstanceState); setContentView(R.layout.activity_send); setSupportActionBar(findViewById(R.id.toolbar_send)); Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); setTitle(""); //CustomView for showing and hiding body of th UI sendTransactionDetailsView = findViewById(R.id.sendTransactionDetailsView); //ViewSwitcher Element for toolbar section of the UI. //we can switch between Form and review screen with this element amountViewSwitcher = findViewById(R.id.toolbar_view_switcher); //Input elements from toolbar section of the UI toAddressEditText = findViewById(R.id.edt_send_to); btcEditText = findViewById(R.id.amountBTC); satEditText = findViewById(R.id.amountSat); tvToAddress = findViewById(R.id.to_address_review); tvReviewSpendAmount = findViewById(R.id.send_review_amount); tvReviewSpendAmountInSats = findViewById(R.id.send_review_amount_in_sats); tvMaxAmount = findViewById(R.id.totalBTC); //view elements from review segment and transaction segment can be access through respective //methods which returns root viewGroup btnReview = sendTransactionDetailsView.getTransactionView().findViewById(R.id.review_button); cahootsSwitch = sendTransactionDetailsView.getTransactionView().findViewById(R.id.cahoots_switch); ricochetHopsSwitch = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_hops_switch); ricochetTitle = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_desc); ricochetDesc = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_title); ricochetStaggeredDelivery = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_staggered_option); ricochetStaggeredOptionGroup = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_staggered_option_group); tvSelectedFeeRate = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.selected_fee_rate); tvSelectedFeeRateLayman = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.selected_fee_rate_in_layman); tvTotalFee = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.total_fee); btnSend = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.send_btn); tvEstimatedBlockWait = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.est_block_time); feeSeekBar = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.fee_seekbar); cahootsGroup = sendTransactionDetailsView.findViewById(R.id.cohoots_options); premiumAddons = sendTransactionDetailsView.findViewById(R.id.premium_addons); addonsNotAvailableMessage = sendTransactionDetailsView.findViewById(R.id.addons_not_available_message); cahootsStatusText = sendTransactionDetailsView.findViewById(R.id.cahoot_status_text); totalMinerFeeLayout = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.total_miner_fee_group); cahootsNotice = sendTransactionDetailsView.findViewById(R.id.cahoots_not_enabled_notice); progressBar = findViewById(R.id.send_activity_progress); btcEditText.addTextChangedListener(BTCWatcher); btcEditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(8, 8)}); satEditText.addTextChangedListener(satWatcher); toAddressEditText.addTextChangedListener(AddressWatcher); btnReview.setOnClickListener(v -> review()); btnSend.setOnClickListener(v -> initiateSpend()); View.OnClickListener clipboardCopy = view -> { ClipboardManager cm = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clipData = android.content.ClipData .newPlainText("Miner fee", tvTotalFee.getText()); if (cm != null) { cm.setPrimaryClip(clipData); Toast.makeText(this, getString(R.string.copied_to_clipboard), Toast.LENGTH_SHORT).show(); } }; tvTotalFee.setOnClickListener(clipboardCopy); tvSelectedFeeRate.setOnClickListener(clipboardCopy); SPEND_TYPE = SPEND_BOLTZMANN; saveChangeIndexes(); setUpRicochet(); setUpCahoots(); setUpFee(); setBalance(); enableReviewButton(false); setUpBoltzman(); validateSpend(); checkDeepLinks(); if (getIntent().getExtras().containsKey("preselected")) { preselectedUTXOs = PreSelectUtil.getInstance().getPreSelected(getIntent().getExtras().getString("preselected")); setBalance(); if (ricochetHopsSwitch.isChecked()) { SPEND_TYPE = SPEND_RICOCHET; } else { SPEND_TYPE = SPEND_SIMPLE; } if (preselectedUTXOs != null && preselectedUTXOs.size() > 0 && balance < 1000000L) { premiumAddons.setVisibility(View.GONE); cahootsGroup.setVisibility(View.GONE); addonsNotAvailableMessage.setVisibility(View.VISIBLE); } } else { Disposable disposable = APIFactory.getInstance(getApplicationContext()) .walletBalanceObserver .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aLong -> setBalance(), Throwable::printStackTrace); compositeDisposables.add(disposable); // Update fee Disposable feeDisposable = Observable.fromCallable(() -> APIFactory.getInstance(getApplicationContext()).getDynamicFees()) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(t -> { setUpFee(); }, Throwable::printStackTrace); compositeDisposables.add(feeDisposable); if (getIntent().getExtras() != null) { if (!getIntent().getExtras().containsKey("balance")) { return; } balance = getIntent().getExtras().getLong("balance"); } } } private void setUpCahoots() { if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) { cahootsNotice.setVisibility(View.VISIBLE); } cahootsSwitch.setOnCheckedChangeListener((compoundButton, b) -> { // to check whether bottomsheet is closed or selected a value final boolean[] chosen = {false}; if (b) { SelectCahootsType cahootsType = new SelectCahootsType(); cahootsType.show(getSupportFragmentManager(), cahootsType.getTag()); cahootsType.setOnSelectListener(new SelectCahootsType.OnSelectListener() { @Override public void onSelect(SelectCahootsType.type type, String pcode) { if (pcode != null) { strPcodeCounterParty = pcode; if(type.getCahootsType() == CahootsType.STOWAWAY){ strPCode = pcode; } if(type.getCahootsMode() == CahootsMode.SOROBAN){ if(!TorManager.INSTANCE.isConnected()){ TorServiceController.startTor(); PrefsUtil.getInstance(getApplication()).setValue(PrefsUtil.ENABLE_TOR, true); } } } chosen[0] = true; selectedCahootsType = type; switch (selectedCahootsType) { case NONE: { cahootsStatusText.setText("Off"); cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.warning_yellow)); break; } default: { cahootsStatusText.setText(selectedCahootsType.getCahootsType().getLabel()+" "+selectedCahootsType.getCahootsMode().getLabel()); cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.green_ui_2)); if (CahootsType.STOWAWAY.equals(selectedCahootsType.getCahootsType())) { toAddressEditText.setText(getParticipantLabel()); toAddressEditText.setEnabled(false); address = ""; } } } validateSpend(); } @Override public void onDismiss() { if (!chosen[0]) { strPcodeCounterParty = null; compoundButton.setChecked(false); selectedCahootsType = SelectCahootsType.type.NONE; hideToAddressForStowaway(); } validateSpend(); } }); } else { selectedCahootsType = SelectCahootsType.type.NONE; cahootsStatusText.setText("Off"); cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.warning_yellow)); hideToAddressForStowaway(); validateSpend(); enableReviewButton(false); } }); } private void hideToAddressForStowaway() { toAddressEditText.setEnabled(true); toAddressEditText.setText(""); address = ""; } public View createTag(String text) { float scale = getResources().getDisplayMetrics().density; LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); TextView textView = new TextView(getApplicationContext()); textView.setText(text); textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white)); textView.setLayoutParams(lparams); textView.setBackgroundResource(R.drawable.tag_round_shape); textView.setPadding((int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f), (int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f)); textView.setTypeface(Typeface.DEFAULT_BOLD); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11); return textView; } @Override protected void onResume() { super.onResume(); AppUtil.getInstance(SendActivity.this).setIsInForeground(true); AppUtil.getInstance(SendActivity.this).checkTimeOut(); try { new Handler().postDelayed(this::setBalance, 300); } catch (Exception ex) { } } private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = (compoundButton, checked) -> { if (compoundButton.isPressed()) { SPEND_TYPE = checked ? SPEND_BOLTZMANN : SPEND_SIMPLE; stoneWallChecked = checked; compoundButton.setChecked(checked); new Handler().postDelayed(this::prepareSpend, 100); } }; private void setUpBoltzman() { sendTransactionDetailsView.getStoneWallSwitch().setChecked(true); sendTransactionDetailsView.getStoneWallSwitch().setEnabled(WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix() != account); sendTransactionDetailsView.enableStonewall(true); sendTransactionDetailsView.getStoneWallSwitch().setOnCheckedChangeListener(onCheckedChangeListener); } private void checkRicochetPossibility() { double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; return; } double dAmount = btc_amount; amount = Math.round(dAmount * 1e8); if (amount < (balance - (RicochetMeta.samouraiFeeAmountV2.add(BigInteger.valueOf(50000L))).longValue())) { ricochetDesc.setAlpha(1f); ricochetTitle.setAlpha(1f); ricochetHopsSwitch.setAlpha(1f); ricochetHopsSwitch.setEnabled(true); if (ricochetHopsSwitch.isChecked()) { ricochetStaggeredOptionGroup.setVisibility(View.VISIBLE); } } else { ricochetStaggeredOptionGroup.setVisibility(View.GONE); ricochetDesc.setAlpha(.6f); ricochetTitle.setAlpha(.6f); ricochetHopsSwitch.setAlpha(.6f); ricochetHopsSwitch.setEnabled(false); } } private void enableReviewButton(boolean enable) { btnReview.setEnabled(enable); if (enable) { btnReview.setBackgroundColor(getResources().getColor(R.color.blue_ui_2)); } else { btnReview.setBackgroundColor(getResources().getColor(R.color.disabled_grey)); } } private void setUpFee() { int multiplier = 10000; FEE_TYPE = PrefsUtil.getInstance(this).getValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL); feeLow = FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L; feeMed = FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L; feeHigh = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L; float high = ((float) feeHigh / 2) + (float) feeHigh; int feeHighSliderValue = (int) (high * multiplier); int feeMedSliderValue = (int) (feeMed * multiplier); feeSeekBar.setValueTo(feeHighSliderValue - multiplier); if (feeLow == feeMed && feeMed == feeHigh) { feeLow = (long) ((double) feeMed * 0.85); feeHigh = (long) ((double) feeMed * 1.15); SuggestedFee lo_sf = new SuggestedFee(); lo_sf.setDefaultPerKB(BigInteger.valueOf(feeLow * 1000L)); FeeUtil.getInstance().setLowFee(lo_sf); SuggestedFee hi_sf = new SuggestedFee(); hi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L)); FeeUtil.getInstance().setHighFee(hi_sf); } else if (feeLow == feeMed || feeMed == feeMed) { feeMed = (feeLow + feeHigh) / 2L; SuggestedFee mi_sf = new SuggestedFee(); mi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L)); FeeUtil.getInstance().setNormalFee(mi_sf); } else { ; } if (feeLow < 1L) { feeLow = 1L; SuggestedFee lo_sf = new SuggestedFee(); lo_sf.setDefaultPerKB(BigInteger.valueOf(feeLow * 1000L)); FeeUtil.getInstance().setLowFee(lo_sf); } if (feeMed < 1L) { feeMed = 1L; SuggestedFee mi_sf = new SuggestedFee(); mi_sf.setDefaultPerKB(BigInteger.valueOf(feeMed * 1000L)); FeeUtil.getInstance().setNormalFee(mi_sf); } if (feeHigh < 1L) { feeHigh = 1L; SuggestedFee hi_sf = new SuggestedFee(); hi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L)); FeeUtil.getInstance().setHighFee(hi_sf); } // tvEstimatedBlockWait.setText("6 blocks"); tvSelectedFeeRateLayman.setText(getString(R.string.normal)); FeeUtil.getInstance().sanitizeFee(); tvSelectedFeeRate.setText((String.valueOf((int) feeMed)).concat(" sat/b")); feeSeekBar.setValue((feeMedSliderValue - multiplier) + 1); DecimalFormat decimalFormat = new DecimalFormat(" decimalFormat.setDecimalSeparatorAlwaysShown(false); setFeeLabels(); // View.OnClickListener inputFeeListener = v -> { // tvSelectedFeeRate.requestFocus(); // tvSelectedFeeRate.setFocusableInTouchMode(true); // InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); // assert imm != null; // imm.showSoftInput(tvSelectedFeeRate, InputMethodManager.SHOW_FORCED); // tvSelectedFeeRateLayman.setOnClickListener(inputFeeListener); // satbText.setOnClickListener(inputFeeListener); // tvSelectedFeeRate.addTextChangedListener(new TextWatcher() { // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // @Override // public void afterTextChanged(Editable s) { // try { // int i = (int) ((Double.parseDouble(tvSelectedFeeRate.getText().toString())*multiplier) - multiplier); // //feeSeekBar.setMax(feeHighSliderValue - multiplier); // feeSeekBar.setProgress(i); // } catch(NumberFormatException nfe) { // System.out.println("Could not parse " + nfe); //// int position = tvSelectedFeeRate.length(); //// Editable etext = (Editable) tvSelectedFeeRate.getText(); //// Selection.setSelection(etext, position); feeSeekBar.setLabelFormatter(i -> tvSelectedFeeRate.getText().toString()); feeSeekBar.addOnChangeListener((slider, i, fromUser) -> { double value = ((double) i + multiplier) / (double) multiplier; if(selectedCahootsType != SelectCahootsType.type.NONE || SPEND_TYPE == SPEND_RICOCHET){ tvSelectedFeeRate.setText(String.valueOf(decimalFormat.format(value).concat(" sat/b"))); } if (value == 0.0) { value = 1.0; } double pct = 0.0; int nbBlocks = 6; if (value <= (double) feeLow) { pct = ((double) feeLow / value); nbBlocks = ((Double) Math.ceil(pct * 24.0)).intValue(); } else if (value >= (double) feeHigh) { pct = ((double) feeHigh / value); nbBlocks = ((Double) Math.ceil(pct * 2.0)).intValue(); if (nbBlocks < 1) { nbBlocks = 1; } } else { pct = ((double) feeMed / value); nbBlocks = ((Double) Math.ceil(pct * 6.0)).intValue(); } tvEstimatedBlockWait.setText(nbBlocks + " blocks"); setFee(value); setFeeLabels(); restoreChangeIndexes(); }); switch (FEE_TYPE) { case FEE_LOW: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee()); FeeUtil.getInstance().sanitizeFee(); break; case FEE_PRIORITY: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); FeeUtil.getInstance().sanitizeFee(); break; default: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee()); FeeUtil.getInstance().sanitizeFee(); break; } } private void setFeeLabels() { float sliderValue = (((float) feeSeekBar.getValue()) / feeSeekBar.getValueTo()); float sliderInPercentage = sliderValue * 100; if (sliderInPercentage < 33) { tvSelectedFeeRateLayman.setText(R.string.low); } else if (sliderInPercentage > 33 && sliderInPercentage < 66) { tvSelectedFeeRateLayman.setText(R.string.normal); } else if (sliderInPercentage > 66) { tvSelectedFeeRateLayman.setText(R.string.urgent); } } private void setFee(double fee) { double sanitySat = FeeUtil.getInstance().getHighFee().getDefaultPerKB().doubleValue() / 1000.0; final long sanityValue; if (sanitySat < 10.0) { sanityValue = 15L; } else { sanityValue = (long) (sanitySat * 1.5); } // String val = null; double d = FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().doubleValue() / 1000.0; NumberFormat decFormat = NumberFormat.getInstance(Locale.US); decFormat.setMaximumFractionDigits(3); decFormat.setMinimumFractionDigits(0); double customValue = 0.0; try { customValue = (double) fee; } catch (Exception e) { Toast.makeText(this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show(); return; } SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFee.setDefaultPerKB(BigInteger.valueOf((long) (customValue * 1000.0))); FeeUtil.getInstance().setSuggestedFee(suggestedFee); prepareSpend(); } private void setUpRicochet() { ricochetHopsSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { sendTransactionDetailsView.enableForRicochet(isChecked); enableCahoots(!isChecked); ricochetStaggeredOptionGroup.setVisibility(isChecked ? View.VISIBLE : View.GONE); if (isChecked) { SPEND_TYPE = SPEND_RICOCHET; PrefsUtil.getInstance(this).setValue(PrefsUtil.USE_RICOCHET, true); } else { SPEND_TYPE = sendTransactionDetailsView.getStoneWallSwitch().isChecked() ? SPEND_BOLTZMANN : SPEND_SIMPLE; PrefsUtil.getInstance(this).setValue(PrefsUtil.USE_RICOCHET, false); } if (isChecked) { ricochetStaggeredOptionGroup.setVisibility(View.VISIBLE); } else { ricochetStaggeredOptionGroup.setVisibility(View.GONE); } }); ricochetHopsSwitch.setChecked(PrefsUtil.getInstance(this).getValue(PrefsUtil.USE_RICOCHET, false)); if (ricochetHopsSwitch.isChecked()) { ricochetStaggeredOptionGroup.setVisibility(View.VISIBLE); } else { ricochetStaggeredOptionGroup.setVisibility(View.GONE); } ricochetStaggeredDelivery.setChecked(PrefsUtil.getInstance(this).getValue(PrefsUtil.RICOCHET_STAGGERED, false)); ricochetStaggeredDelivery.setOnCheckedChangeListener((compoundButton, isChecked) -> { PrefsUtil.getInstance(this).setValue(PrefsUtil.RICOCHET_STAGGERED, isChecked); // Handle staggered delivery option }); } private Completable setUpRicochetFees() { TorManager torManager = TorManager.INSTANCE; IHttpClient httpClient = new AndroidHttpClient(WebUtil.getInstance(getApplicationContext()), torManager); XManagerClient xManagerClient = new XManagerClient(SamouraiWallet.getInstance().isTestNet(), torManager.isConnected(), httpClient); if (PrefsUtil.getInstance(this).getValue(PrefsUtil.USE_RICOCHET, false)) { Completable completable = Completable.fromCallable(() -> { String feeAddress = xManagerClient.getAddressOrDefault(XManagerService.RICOCHET); RicochetMeta.getInstance(getApplicationContext()).setRicochetFeeAddress(feeAddress); return true; }); //Set BIP47 Fee address if the tx is if (strPCode != null) { Completable pcode = Completable.fromCallable(() -> { String address = xManagerClient.getAddressOrDefault(XManagerService.BIP47); SendNotifTxFactory.getInstance().setAddress(address); return true; }); return Completable.concatArray(completable, pcode); } else { return completable; } } else { return Completable.complete(); } } private void enableCahoots(boolean enable) { if (enable) { cahootsGroup.setVisibility(View.VISIBLE); } else { cahootsGroup.setVisibility(View.GONE); selectedCahootsType = SelectCahootsType.type.NONE; } } private void setBalance() { try { if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { balance = APIFactory.getInstance(SendActivity.this).getXpubPostMixBalance(); selectableBalance = balance; } else { balance = APIFactory.getInstance(SendActivity.this).getXpubBalance(); selectableBalance = balance; } } catch (java.lang.NullPointerException npe) { npe.printStackTrace(); } if (getIntent().getExtras().containsKey("preselected")) { //Reloads preselected utxo's if it changed on last call preselectedUTXOs = PreSelectUtil.getInstance().getPreSelected(getIntent().getExtras().getString("preselected")); if (preselectedUTXOs != null && preselectedUTXOs.size() > 0) { //Checks utxo's state, if the item is blocked it will be removed from preselectedUTXOs for (int i = 0; i < preselectedUTXOs.size(); i++) { UTXOCoin coin = preselectedUTXOs.get(i); if (BlockedUTXO.getInstance().containsAny(coin.hash, coin.idx)) { try { preselectedUTXOs.remove(i); } catch (Exception ex) { } } } long amount = 0; for (UTXOCoin utxo : preselectedUTXOs) { amount += utxo.amount; } balance = amount; } else { ; } } final String strAmount; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMaximumFractionDigits(8); nf.setMinimumFractionDigits(1); nf.setMinimumIntegerDigits(1); strAmount = nf.format(balance / 1e8); if (account == 0) { tvMaxAmount.setOnClickListener(view -> { btcEditText.setText(strAmount); }); } tvMaxAmount.setOnLongClickListener(view -> { setBalance(); return true; }); tvMaxAmount.setText(strAmount + " " + getDisplayUnits()); if(!AppUtil.getInstance(getApplication()).isOfflineMode()) if (balance == 0L && !APIFactory.getInstance(getApplicationContext()).walletInit) { //some time, user may navigate to this activity even before wallet initialization completes //so we will set a delay to reload balance info Disposable disposable = Completable.timer(700, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .subscribe(this::setBalance); compositeDisposables.add(disposable); if (!shownWalletLoadingMessage) { Snackbar.make(tvMaxAmount.getRootView(), "Please wait... your wallet is still loading ", Snackbar.LENGTH_LONG).show(); shownWalletLoadingMessage = true; } } } private void checkDeepLinks() { Bundle extras = getIntent().getExtras(); if (extras != null) { String strUri = extras.getString("uri"); if (extras.containsKey("amount")) { DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US); format.setMaximumFractionDigits(8); btcEditText.setText(format.format(getBtcValue(extras.getDouble("amount")))); } if (extras.getString("pcode") != null) strPCode = extras.getString("pcode"); if (strPCode != null && strPCode.length() > 0) { processPCode(strPCode, null); } else if (strUri != null && strUri.length() > 0) { processScan(strUri); } new Handler().postDelayed(this::validateSpend, 800); } } private TextWatcher BTCWatcher = 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) { } @Override public void afterTextChanged(Editable editable) { satEditText.removeTextChangedListener(satWatcher); btcEditText.removeTextChangedListener(this); try { if (editable.toString().length() == 0) { satEditText.setText("0"); btcEditText.setText(""); satEditText.setSelection(satEditText.getText().length()); satEditText.addTextChangedListener(satWatcher); btcEditText.addTextChangedListener(this); return; } Double btc = Double.parseDouble(String.valueOf(editable)); if (btc > 21000000.0) { btcEditText.setText("0.00"); btcEditText.setSelection(btcEditText.getText().length()); satEditText.setText("0"); satEditText.setSelection(satEditText.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } else { DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US); DecimalFormatSymbols symbols = format.getDecimalFormatSymbols(); String defaultSeparator = Character.toString(symbols.getDecimalSeparator()); int max_len = 8; NumberFormat btcFormat = NumberFormat.getInstance(Locale.US); btcFormat.setMaximumFractionDigits(max_len + 1); try { double d = NumberFormat.getInstance(Locale.US).parse(editable.toString()).doubleValue(); String s1 = btcFormat.format(d); if (s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if (dec.length() > 0) { dec = dec.substring(1); if (dec.length() > max_len) { btcEditText.setText(s1.substring(0, s1.length() - 1)); btcEditText.setSelection(btcEditText.getText().length()); editable = btcEditText.getEditableText(); btc = Double.parseDouble(btcEditText.getText().toString()); } } } } catch (NumberFormatException nfe) { ; } catch (ParseException pe) { ; } Double sats = getSatValue(Double.valueOf(btc)); satEditText.setText(formattedSatValue(sats)); checkRicochetPossibility(); } } catch (NumberFormatException e) { e.printStackTrace(); } satEditText.addTextChangedListener(satWatcher); btcEditText.addTextChangedListener(this); validateSpend(); } }; private TextWatcher AddressWatcher = 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) { } @Override public void afterTextChanged(Editable editable) { if (editable.toString().length() != 0) { validateSpend(); } else { setToAddress(""); } } }; private String formattedSatValue(Object number) { NumberFormat nformat = NumberFormat.getNumberInstance(Locale.US); DecimalFormat decimalFormat = (DecimalFormat) nformat; decimalFormat.applyPattern(" return decimalFormat.format(number).replace(",", " "); } private TextWatcher satWatcher = 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) { } @Override public void afterTextChanged(Editable editable) { satEditText.removeTextChangedListener(this); btcEditText.removeTextChangedListener(BTCWatcher); try { if (editable.toString().length() == 0) { btcEditText.setText("0.00"); satEditText.setText(""); satEditText.addTextChangedListener(this); btcEditText.addTextChangedListener(BTCWatcher); return; } String cleared_space = editable.toString().replace(" ", ""); Double sats = Double.parseDouble(cleared_space); Double btc = getBtcValue(sats); String formatted = formattedSatValue(sats); satEditText.setText(formatted); satEditText.setSelection(formatted.length()); btcEditText.setText(String.format(Locale.ENGLISH, "%.8f", btc)); if (btc > 21000000.0) { btcEditText.setText("0.00"); btcEditText.setSelection(btcEditText.getText().length()); satEditText.setText("0"); satEditText.setSelection(satEditText.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } } catch (NumberFormatException e) { e.printStackTrace(); } satEditText.addTextChangedListener(this); btcEditText.addTextChangedListener(BTCWatcher); checkRicochetPossibility(); validateSpend(); } }; private void setToAddress(String string) { tvToAddress.setText(string); toAddressEditText.removeTextChangedListener(AddressWatcher); toAddressEditText.setText(string); toAddressEditText.setSelection(toAddressEditText.getText().length()); toAddressEditText.addTextChangedListener(AddressWatcher); } private String getToAddress() { if (toAddressEditText.getText().toString().trim().length() != 0) { return toAddressEditText.getText().toString(); } if (tvToAddress.getText().toString().length() != 0) { return tvToAddress.getText().toString(); } return ""; } private Double getBtcValue(Double sats) { return (double) (sats / 1e8); } private Double getSatValue(Double btc) { if (btc == 0) { return (double) 0; } return btc * 1e8; } private void review() { double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } double dAmount = btc_amount; amount = (long) (Math.round(dAmount * 1e8)); if (amount == balance && balance == selectableBalance) { int warningMessage = R.string.full_spend_warning; if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) { warningMessage = R.string.postmix_full_spend; } MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(warningMessage) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); _review(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } } else { _review(); } } private void _review() { setUpBoltzman(); if (validateSpend() && prepareSpend()) { tvReviewSpendAmount.setText(btcEditText.getText().toString().concat(" BTC")); try { tvReviewSpendAmountInSats.setText(formattedSatValue(getSatValue(Double.valueOf(btcEditText.getText().toString()))).concat(" sats")); } catch (Exception ex) { ex.printStackTrace(); } amountViewSwitcher.showNext(); hideKeyboard(); sendTransactionDetailsView.showReview(ricochetHopsSwitch.isChecked()); } } private void hideKeyboard() { InputMethodManager imm = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(amountViewSwitcher.getWindowToken(), 0); } } @Override protected void onDestroy() { super.onDestroy(); PreSelectUtil.getInstance().clear(); if (compositeDisposables != null && !compositeDisposables.isDisposed()) compositeDisposables.dispose(); } synchronized private boolean prepareSpend() { if(SPEND_TYPE == SPEND_SIMPLE && stoneWallChecked){ SPEND_TYPE = SPEND_BOLTZMANN; } restoreChangeIndexes(); double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } double dAmount = btc_amount; amount = (long) (Math.round(dAmount * 1e8)); // Log.i("SendActivity", "amount:" + amount); if (selectedCahootsType.getCahootsType() == CahootsType.STOWAWAY) { setButtonForStowaway(true); return true; } else { setButtonForStowaway(false); } address = strDestinationBTCAddress == null ? toAddressEditText.getText().toString().trim() : strDestinationBTCAddress; if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { changeType = 84; } else if (PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false) { changeType = 84; } else if (FormatsUtil.getInstance().isValidBech32(address) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { changeType = FormatsUtil.getInstance().isValidBech32(address) ? 84 : 49; } else { changeType = 44; } receivers = new HashMap<String, BigInteger>(); receivers.put(address, BigInteger.valueOf(amount)); if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { change_index = idxBIP84PostMixInternal; } else if (changeType == 84) { change_index = idxBIP84Internal; } else if (changeType == 49) { change_index = idxBIP49Internal; } else { change_index = idxBIP44Internal; } // if possible, get UTXO by input 'type': p2pkh, p2sh-p2wpkh or p2wpkh, else get all UTXO long neededAmount = 0L; if (FormatsUtil.getInstance().isValidBech32(address) || account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, 0, UTXOFactory.getInstance().getCountP2WPKH(), 4).longValue(); // Log.d("SendActivity", "segwit:" + neededAmount); } else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, UTXOFactory.getInstance().getCountP2SH_P2WPKH(), 0, 4).longValue(); // Log.d("SendActivity", "segwit:" + neededAmount); } else { neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(UTXOFactory.getInstance().getCountP2PKH(), 0, 0, 4).longValue(); // Log.d("SendActivity", "p2pkh:" + neededAmount); } neededAmount += amount; neededAmount += SamouraiWallet.bDust.longValue(); // get all UTXO List<UTXO> utxos = new ArrayList<>(); if (preselectedUTXOs != null && preselectedUTXOs.size() > 0) { // List<UTXO> utxos = preselectedUTXOs; // sort in descending order by value for (UTXOCoin utxoCoin : preselectedUTXOs) { UTXO u = new UTXO(); List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>(); outs.add(utxoCoin.getOutPoint()); u.setOutpoints(outs); utxos.add(u); } } else { utxos = SpendUtil.getUTXOS(SendActivity.this, address, neededAmount, account); } List<UTXO> utxosP2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllP2WPKH().values()); List<UTXO> utxosP2SH_P2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllP2SH_P2WPKH().values()); List<UTXO> utxosP2PKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllP2PKH().values()); if ((preselectedUTXOs == null || preselectedUTXOs.size() == 0) && account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { utxos = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllPostMix().values()); utxosP2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllPostMix().values()); utxosP2PKH.clear(); utxosP2SH_P2WPKH.clear(); } selectedUTXO = new ArrayList<UTXO>(); long totalValueSelected = 0L; long change = 0L; BigInteger fee = null; boolean canDoBoltzmann = true; // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "balance:" + balance); // insufficient funds if (amount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } if (preselectedUTXOs != null) { canDoBoltzmann = false; if(SPEND_TYPE == SPEND_BOLTZMANN ){ SPEND_TYPE = SPEND_SIMPLE; } } // entire balance (can only be simple spend) else if (amount == balance) { // make sure we are using simple spend SPEND_TYPE = SPEND_SIMPLE; canDoBoltzmann = false; // Log.d("SendActivity", "amount == balance"); // take all utxos, deduct fee selectedUTXO.addAll(utxos); for (UTXO u : selectedUTXO) { totalValueSelected += u.getValue(); } // Log.d("SendActivity", "balance:" + balance); // Log.d("SendActivity", "total value selected:" + totalValueSelected); } else { ; } org.apache.commons.lang3.tuple.Pair<ArrayList<MyTransactionOutPoint>, ArrayList<TransactionOutput>> pair = null; if (SPEND_TYPE == SPEND_RICOCHET) { if(AppUtil.getInstance(getApplicationContext()).isOfflineMode()){ Toast.makeText(getApplicationContext(),"You won't able to compose ricochet when you're on offline mode",Toast.LENGTH_SHORT).show(); return false; } boolean samouraiFeeViaBIP47 = false; if (BIP47Meta.getInstance().getOutgoingStatus(BIP47Meta.strSamouraiDonationPCode) == BIP47Meta.STATUS_SENT_CFM) { samouraiFeeViaBIP47 = true; } ricochetJsonObj = RicochetMeta.getInstance(SendActivity.this).script(amount, FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue(), address, 4, strPCode, samouraiFeeViaBIP47, ricochetStaggeredDelivery.isChecked(), account); if (ricochetJsonObj != null) { try { long totalAmount = ricochetJsonObj.getLong("total_spend"); if (totalAmount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); ricochetHopsSwitch.setChecked(false); return false; } long hop0Fee = ricochetJsonObj.getJSONArray("hops").getJSONObject(0).getLong("fee"); long perHopFee = ricochetJsonObj.getJSONArray("hops").getJSONObject(0).getLong("fee_per_hop"); long ricochetFee = hop0Fee + (RicochetMeta.defaultNbHops * perHopFee); if (selectedCahootsType == SelectCahootsType.type.NONE) { tvTotalFee.setText(Coin.valueOf(ricochetFee).toPlainString().concat(" BTC")); } else { tvTotalFee.setText("__"); } ricochetMessage = getText(R.string.ricochet_spend1) + " " + address + " " + getText(R.string.ricochet_spend2) + " " + Coin.valueOf(totalAmount).toPlainString() + " " + getText(R.string.ricochet_spend3); btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue((double) totalAmount)).concat(" BTC"))); return true; } catch (JSONException je) { return false; } } return true; } else if (SPEND_TYPE == SPEND_BOLTZMANN) { Log.d("SendActivity", "needed amount:" + neededAmount); List<UTXO> _utxos1 = null; List<UTXO> _utxos2 = null; long valueP2WPKH = UTXOFactory.getInstance().getTotalP2WPKH(); long valueP2SH_P2WPKH = UTXOFactory.getInstance().getTotalP2SH_P2WPKH(); long valueP2PKH = UTXOFactory.getInstance().getTotalP2PKH(); if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { valueP2WPKH = UTXOFactory.getInstance().getTotalPostMix(); valueP2SH_P2WPKH = 0L; valueP2PKH = 0L; utxosP2SH_P2WPKH.clear(); utxosP2PKH.clear(); } Log.d("SendActivity", "value P2WPKH:" + valueP2WPKH); Log.d("SendActivity", "value P2SH_P2WPKH:" + valueP2SH_P2WPKH); Log.d("SendActivity", "value P2PKH:" + valueP2PKH); boolean selectedP2WPKH = false; boolean selectedP2SH_P2WPKH = false; boolean selectedP2PKH = false; if ((valueP2WPKH > (neededAmount * 2)) && account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { Log.d("SendActivity", "set 1 P2WPKH 2x"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if ((valueP2WPKH > (neededAmount * 2)) && FormatsUtil.getInstance().isValidBech32(address)) { Log.d("SendActivity", "set 1 P2WPKH 2x"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if (!FormatsUtil.getInstance().isValidBech32(address) && (valueP2SH_P2WPKH > (neededAmount * 2)) && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { Log.d("SendActivity", "set 1 P2SH_P2WPKH 2x"); _utxos1 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } else if (!FormatsUtil.getInstance().isValidBech32(address) && (valueP2PKH > (neededAmount * 2)) && !Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { Log.d("SendActivity", "set 1 P2PKH 2x"); _utxos1 = utxosP2PKH; selectedP2PKH = true; } else if (valueP2WPKH > (neededAmount * 2)) { Log.d("SendActivity", "set 1 P2WPKH 2x"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if (valueP2SH_P2WPKH > (neededAmount * 2)) { Log.d("SendActivity", "set 1 P2SH_P2WPKH 2x"); _utxos1 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } else if (valueP2PKH > (neededAmount * 2)) { Log.d("SendActivity", "set 1 P2PKH 2x"); _utxos1 = utxosP2PKH; selectedP2PKH = true; } else { ; } if (_utxos1 == null || _utxos1.size() == 0) { if (valueP2SH_P2WPKH > neededAmount) { Log.d("SendActivity", "set 1 P2SH_P2WPKH"); _utxos1 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } else if (valueP2WPKH > neededAmount) { Log.d("SendActivity", "set 1 P2WPKH"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if (valueP2PKH > neededAmount) { Log.d("SendActivity", "set 1 P2PKH"); _utxos1 = utxosP2PKH; selectedP2PKH = true; } else { ; } } if (_utxos1 != null && _utxos1.size() > 0) { if (!selectedP2SH_P2WPKH && valueP2SH_P2WPKH > neededAmount) { Log.d("SendActivity", "set 2 P2SH_P2WPKH"); _utxos2 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } if (!selectedP2SH_P2WPKH && !selectedP2WPKH && valueP2WPKH > neededAmount) { Log.d("SendActivity", "set 2 P2WPKH"); _utxos2 = utxosP2WPKH; selectedP2WPKH = true; } if (!selectedP2SH_P2WPKH && !selectedP2WPKH && !selectedP2PKH && valueP2PKH > neededAmount) { Log.d("SendActivity", "set 2 P2PKH"); _utxos2 = utxosP2PKH; selectedP2PKH = true; } else { ; } } if ((_utxos1 == null || _utxos1.size() == 0) && (_utxos2 == null || _utxos2.size() == 0)) { // can't do boltzmann, revert to SPEND_SIMPLE canDoBoltzmann = false; SPEND_TYPE = SPEND_SIMPLE; } else { Log.d("SendActivity", "boltzmann spend"); Collections.shuffle(_utxos1); if (_utxos2 != null && _utxos2.size() > 0) { Collections.shuffle(_utxos2); } // boltzmann spend (STONEWALL) pair = SendFactory.getInstance(SendActivity.this).boltzmann(_utxos1, _utxos2, BigInteger.valueOf(amount), address, account); if (pair == null) { // can't do boltzmann, revert to SPEND_SIMPLE canDoBoltzmann = false; restoreChangeIndexes(); SPEND_TYPE = SPEND_SIMPLE; } else { canDoBoltzmann = true; } } } else { ; } if (SPEND_TYPE == SPEND_SIMPLE && amount == balance && preselectedUTXOs == null) { // do nothing, utxo selection handles above ; } // simple spend (less than balance) else if (SPEND_TYPE == SPEND_SIMPLE) { List<UTXO> _utxos = utxos; // sort in ascending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); Collections.reverse(_utxos); // get smallest 1 UTXO > than spend + fee + dust for (UTXO u : _utxos) { Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(u.getOutpoints())); if (u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 2).longValue())) { selectedUTXO.add(u); totalValueSelected += u.getValue(); Log.d("SendActivity", "spend type:" + SPEND_TYPE); Log.d("SendActivity", "single output"); Log.d("SendActivity", "amount:" + amount); Log.d("SendActivity", "value selected:" + u.getValue()); Log.d("SendActivity", "total value selected:" + totalValueSelected); Log.d("SendActivity", "nb inputs:" + u.getOutpoints().size()); break; } } if (selectedUTXO.size() == 0) { // sort in descending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); int selected = 0; int p2pkh = 0; int p2sh_p2wpkh = 0; int p2wpkh = 0; // get largest UTXOs > than spend + fee + dust for (UTXO u : _utxos) { selectedUTXO.add(u); totalValueSelected += u.getValue(); selected += u.getOutpoints().size(); // Log.d("SendActivity", "value selected:" + u.getValue()); // Log.d("SendActivity", "total value selected/threshold:" + totalValueSelected + "/" + (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 2).longValue())); Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector<MyTransactionOutPoint>(u.getOutpoints())); p2pkh += outpointTypes.getLeft(); p2sh_p2wpkh += outpointTypes.getMiddle(); p2wpkh += outpointTypes.getRight(); if (totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, 2).longValue())) { Log.d("SendActivity", "spend type:" + SPEND_TYPE); Log.d("SendActivity", "multiple outputs"); Log.d("SendActivity", "amount:" + amount); Log.d("SendActivity", "total value selected:" + totalValueSelected); Log.d("SendActivity", "nb inputs:" + selected); break; } } } } else if (pair != null) { selectedUTXO.clear(); receivers.clear(); long inputAmount = 0L; long outputAmount = 0L; for (MyTransactionOutPoint outpoint : pair.getLeft()) { UTXO u = new UTXO(); List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>(); outs.add(outpoint); u.setOutpoints(outs); totalValueSelected += u.getValue(); selectedUTXO.add(u); inputAmount += u.getValue(); } for (TransactionOutput output : pair.getRight()) { try { Script script = new Script(output.getScriptBytes()); if (Bech32Util.getInstance().isP2WPKHScript(Hex.toHexString(output.getScriptBytes()))) { receivers.put(Bech32Util.getInstance().getAddressFromScript(script), BigInteger.valueOf(output.getValue().longValue())); } else { receivers.put(script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), BigInteger.valueOf(output.getValue().longValue())); } outputAmount += output.getValue().longValue(); } catch (Exception e) { Toast.makeText(SendActivity.this, R.string.error_bip126_output, Toast.LENGTH_SHORT).show(); return false; } } fee = BigInteger.valueOf(inputAmount - outputAmount); } else { Toast.makeText(SendActivity.this, R.string.cannot_select_utxo, Toast.LENGTH_SHORT).show(); return false; } if (selectedUTXO.size() > 0) { // estimate fee for simple spend, already done if boltzmann if (SPEND_TYPE == SPEND_SIMPLE) { List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>(); for (UTXO utxo : selectedUTXO) { outpoints.addAll(utxo.getOutpoints()); } Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(outpoints)); if (amount == balance) { fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 1); amount -= fee.longValue(); receivers.clear(); receivers.put(address, BigInteger.valueOf(amount)); // fee sanity check restoreChangeIndexes(); Transaction tx = SendFactory.getInstance(SendActivity.this).makeTransaction(account, outpoints, receivers); tx = SendFactory.getInstance(SendActivity.this).signTransaction(tx, account); byte[] serialized = tx.bitcoinSerialize(); Log.d("SendActivity", "size:" + serialized.length); Log.d("SendActivity", "vsize:" + tx.getVirtualTransactionSize()); Log.d("SendActivity", "fee:" + fee.longValue()); if ((tx.hasWitness() && (fee.longValue() < tx.getVirtualTransactionSize())) || (!tx.hasWitness() && (fee.longValue() < serialized.length))) { Toast.makeText(SendActivity.this, R.string.insufficient_fee, Toast.LENGTH_SHORT).show(); return false; } } else { fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 2); } } Log.d("SendActivity", "spend type:" + SPEND_TYPE); Log.d("SendActivity", "amount:" + amount); Log.d("SendActivity", "total value selected:" + totalValueSelected); Log.d("SendActivity", "fee:" + fee.longValue()); Log.d("SendActivity", "nb inputs:" + selectedUTXO.size()); change = totalValueSelected - (amount + fee.longValue()); // Log.d("SendActivity", "change:" + change); if (change > 0L && change < SamouraiWallet.bDust.longValue() && SPEND_TYPE == SPEND_SIMPLE) { MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.change_is_dust) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } return false; } _change = change; final BigInteger _fee = fee; String dest = null; if (strPCode != null && strPCode.length() > 0) { dest = BIP47Meta.getInstance().getDisplayLabel(strPCode); } else { dest = address; } strCannotDoBoltzmann = ""; if (SendAddressUtil.getInstance().get(address) == 1) { strPrivacyWarning = getString(R.string.send_privacy_warning) + "\n\n"; } else { strPrivacyWarning = ""; } if(SPEND_TYPE == SPEND_BOLTZMANN){ sendTransactionDetailsView.enableStonewall(canDoBoltzmann); sendTransactionDetailsView.getStoneWallSwitch().setChecked(canDoBoltzmann); }else{ sendTransactionDetailsView.enableStonewall(false); } if (!canDoBoltzmann) { restoreChangeIndexes(); if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { strCannotDoBoltzmann = getString(R.string.boltzmann_cannot) + "\n\n"; } } if(account== WhirlpoolConst.WHIRLPOOL_POSTMIX_ACCOUNT){ if(SPEND_TYPE == SPEND_SIMPLE){ strCannotDoBoltzmann = getString(R.string.boltzmann_cannot) + "\n\n"; } } message = strCannotDoBoltzmann + strPrivacyWarning + "Send " + Coin.valueOf(amount).toPlainString() + " to " + dest + " (fee:" + Coin.valueOf(_fee.longValue()).toPlainString() + ")?\n"; if (selectedCahootsType == SelectCahootsType.type.NONE) { tvTotalFee.setText(String.format(Locale.ENGLISH, "%.8f", getBtcValue(fee.doubleValue())).concat(" BTC")); calculateTransactionSize(_fee); } else { tvTotalFee.setText("__"); } double value = Double.parseDouble(String.valueOf(_fee.add(BigInteger.valueOf(amount)))); btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue(value))).concat(" BTC")); switch (selectedCahootsType) { case NONE: { sendTransactionDetailsView.showStonewallx1Layout(null); // for ricochet entropy will be 0 always if (SPEND_TYPE == SPEND_RICOCHET) { break; } if (receivers.size() <= 1) { sendTransactionDetailsView.setEntropyBarStoneWallX1ZeroBits(); break; } if (receivers.size() > 8) { sendTransactionDetailsView.setEntropyBarStoneWallX1(null); break; } CalculateEntropy(selectedUTXO, receivers) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<TxProcessorResult>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(TxProcessorResult entropyResult) { sendTransactionDetailsView.setEntropyBarStoneWallX1(entropyResult); } @Override public void onError(Throwable e) { sendTransactionDetailsView.setEntropyBarStoneWallX1(null); e.printStackTrace(); } @Override public void onComplete() { } }); break; } default: { switch (selectedCahootsType.getCahootsType()) { case STONEWALLX2: sendTransactionDetailsView.showStonewallX2Layout(selectedCahootsType.getCahootsMode(), getParticipantLabel(),1000); btnSend.setBackgroundResource(R.drawable.button_blue); btnSend.setText(getString(R.string.begin_stonewallx2)); break; case STOWAWAY: sendTransactionDetailsView.showStowawayLayout(selectedCahootsType.getCahootsMode(), getParticipantLabel(), null, 1000); btnSend.setBackgroundResource(R.drawable.button_blue); btnSend.setText(getString(R.string.begin_stowaway)); break; default: btnSend.setBackgroundResource(R.drawable.button_green); btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue((double) amount))).concat(" BTC")); } } } return true; } return false; } private String getParticipantLabel() { return strPcodeCounterParty != null ? BIP47Meta.getInstance().getDisplayLabel(strPcodeCounterParty) : null; } private void setButtonForStowaway(boolean prepare) { if (prepare) { // Sets view with stowaway message // also hides overlay push icon from button sendTransactionDetailsView.showStowawayLayout(selectedCahootsType.getCahootsMode(), getParticipantLabel(), null, 1000); btnSend.setBackgroundResource(R.drawable.button_blue); btnSend.setText(getString(R.string.begin_stowaway)); sendTransactionDetailsView.getTransactionReview().findViewById(R.id.transaction_push_icon).setVisibility(View.INVISIBLE); btnSend.setPadding(0, 0, 0, 0); } else { // resets the changes made for stowaway int paddingDp = 12; float density = getResources().getDisplayMetrics().density; int paddingPixel = (int)(paddingDp * density); btnSend.setBackgroundResource(R.drawable.button_green); sendTransactionDetailsView.getTransactionReview().findViewById(R.id.transaction_push_icon).setVisibility(View.VISIBLE); btnSend.setPadding(0,paddingPixel,0,0); } } private void initiateSpend() { if (CahootsMode.MANUAL.equals(selectedCahootsType.getCahootsMode())) { // Cahoots manual Intent intent = ManualCahootsActivity.createIntentSender(this, account, selectedCahootsType.getCahootsType(), amount, address); startActivity(intent); return; } if (CahootsMode.SOROBAN.equals(selectedCahootsType.getCahootsMode())) { // choose Cahoots counterparty Intent intent = SorobanMeetingSendActivity.createIntent(getApplicationContext(), account, selectedCahootsType.getCahootsType(), amount, address, strPcodeCounterParty); startActivity(intent); return; } if (SPEND_TYPE == SPEND_RICOCHET) { progressBar.setVisibility(View.VISIBLE); Disposable disposable = setUpRicochetFees() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(() -> { prepareSpend(); progressBar.setVisibility(View.INVISIBLE); ricochetSpend(ricochetStaggeredDelivery.isChecked()); }, er -> { progressBar.setVisibility(View.INVISIBLE); Toast.makeText(this,"Error ".concat(er.getMessage()),Toast.LENGTH_LONG).show(); }); compositeDisposables.add(disposable); return; } MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(SendActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); final CheckBox cbShowAgain; if (strPrivacyWarning.length() > 0) { cbShowAgain = new CheckBox(SendActivity.this); cbShowAgain.setText(R.string.do_not_repeat_sent_to); cbShowAgain.setChecked(false); builder.setView(cbShowAgain); } else { cbShowAgain = null; } builder.setCancelable(false); builder.setPositiveButton(R.string.yes, (dialog, whichButton) -> { final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for (UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } // add change if (_change > 0L) { if (SPEND_TYPE == SPEND_SIMPLE) { if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix(), AddressFactory.CHANGE_CHAIN, AddressFactory.getInstance(SendActivity.this).getHighestPostChangeIdx()).getBech32AsString(); receivers.put(change_address, BigInteger.valueOf(_change)); } else if (changeType == 84) { String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getBech32AsString(); receivers.put(change_address, BigInteger.valueOf(_change)); } else if (changeType == 49) { String change_address = BIP49Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString(); receivers.put(change_address, BigInteger.valueOf(_change)); } else { String change_address = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddressAt(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx()).getAddressString(); receivers.put(change_address, BigInteger.valueOf(_change)); } } else if (SPEND_TYPE == SPEND_BOLTZMANN) { // do nothing, change addresses included ; } else { ; } } SendParams.getInstance().setParams(outPoints, receivers, strPCode, SPEND_TYPE, _change, changeType, account, address, strPrivacyWarning.length() > 0, cbShowAgain != null ? cbShowAgain.isChecked() : false, amount, change_index ); Intent _intent = new Intent(SendActivity.this, TxAnimUIActivity.class); startActivity(_intent); }); builder.setNegativeButton(R.string.no, (dialog, whichButton) -> SendActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // btSend.setActivated(true); // btSend.setClickable(true); // dialog.dismiss(); } })); builder.create().show(); } private void ricochetSpend(boolean staggered) { MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(ricochetMessage) .setCancelable(false) .setPositiveButton(R.string.yes, (dialog, whichButton) -> { dialog.dismiss(); if (staggered) { // Log.d("SendActivity", "Ricochet staggered:" + ricochetJsonObj.toString()); try { if (ricochetJsonObj.has("hops")) { JSONArray hops = ricochetJsonObj.getJSONArray("hops"); if (hops.getJSONObject(0).has("nTimeLock")) { JSONArray nLockTimeScript = new JSONArray(); for (int i = 0; i < hops.length(); i++) { JSONObject hopObj = hops.getJSONObject(i); int seq = i; long locktime = hopObj.getLong("nTimeLock"); String hex = hopObj.getString("tx"); JSONObject scriptObj = new JSONObject(); scriptObj.put("hop", i); scriptObj.put("nlocktime", locktime); scriptObj.put("tx", hex); nLockTimeScript.put(scriptObj); } JSONObject nLockTimeObj = new JSONObject(); nLockTimeObj.put("script", nLockTimeScript); // Log.d("SendActivity", "Ricochet nLockTime:" + nLockTimeObj.toString()); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); String url = WebUtil.getAPIUrl(SendActivity.this); url += "pushtx/schedule"; try { String result = ""; if (TorManager.INSTANCE.isRequired()) { result = WebUtil.getInstance(SendActivity.this).tor_postURL(url, nLockTimeObj, null); } else { result = WebUtil.getInstance(SendActivity.this).postURL("application/json", url, nLockTimeObj.toString()); } // Log.d("SendActivity", "Ricochet staggered result:" + result); JSONObject resultObj = new JSONObject(result); if (resultObj.has("status") && resultObj.getString("status").equalsIgnoreCase("ok")) { Toast.makeText(SendActivity.this, R.string.ricochet_nlocktime_ok, Toast.LENGTH_LONG).show(); finish(); } else { Toast.makeText(SendActivity.this, R.string.ricochet_nlocktime_ko, Toast.LENGTH_LONG).show(); finish(); } } catch (Exception e) { Log.d("SendActivity", e.getMessage()); Toast.makeText(SendActivity.this, R.string.ricochet_nlocktime_ko, Toast.LENGTH_LONG).show(); finish(); } Looper.loop(); } }).start(); } } } catch (JSONException je) { Log.d("SendActivity", je.getMessage()); } } else { RicochetMeta.getInstance(SendActivity.this).add(ricochetJsonObj); Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivityForResult(intent, RICOCHET); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } } private void backToTransactionView() { if (SPEND_TYPE == SPEND_SIMPLE) SPEND_TYPE = SPEND_BOLTZMANN; //Revert to default selectedUTXO = new ArrayList<>(); receivers = new HashMap<>(); amountViewSwitcher.showPrevious(); sendTransactionDetailsView.showTransaction(); } private void calculateTransactionSize(BigInteger _fee) { Disposable disposable = Single.fromCallable(() -> { final List<MyTransactionOutPoint> outPoints = new ArrayList<>(); for (UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } HashMap<String, BigInteger> _receivers = SerializationUtils.clone(receivers); // add change if (_change > 0L) { if (SPEND_TYPE == SPEND_SIMPLE) { if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix(), AddressFactory.CHANGE_CHAIN, AddressFactory.getInstance(SendActivity.this).getHighestPostChangeIdx()).getBech32AsString(); _receivers.put(change_address, BigInteger.valueOf(_change)); } else if (changeType == 84) { String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getBech32AsString(); _receivers.put(change_address, BigInteger.valueOf(_change)); } else if (changeType == 49) { String change_address = BIP49Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString(); _receivers.put(change_address, BigInteger.valueOf(_change)); } else { String change_address = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddressAt(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx()).getAddressString(); _receivers.put(change_address, BigInteger.valueOf(_change)); } } } final Transaction tx = SendFactory.getInstance(getApplication()).makeTransaction(account, outPoints, _receivers); return SendFactory.getInstance(getApplication()).signTransaction(tx, account); }) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((transaction, throwable) -> { if (throwable == null && transaction != null) { decimalFormatSatPerByte.setDecimalSeparatorAlwaysShown(false); tvSelectedFeeRate.setText(decimalFormatSatPerByte.format((_fee.doubleValue()) / transaction.getVirtualTransactionSize()).concat(" sat/b")); }else{ tvSelectedFeeRate.setText("_"); } }); compositeDisposables.add(disposable); } @Override public void onBackPressed() { if (sendTransactionDetailsView.isReview()) { backToTransactionView(); } else { super.onBackPressed(); } } private void enableAmount(boolean enable) { btcEditText.setEnabled(enable); satEditText.setEnabled(enable); } private void processScan(String data) { strPCode = null; toAddressEditText.setEnabled(true); address = null; strDestinationBTCAddress = null; if (data.contains("https://bitpay.com")) { MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(this) .setTitle(R.string.app_name) .setMessage(R.string.no_bitpay) .setCancelable(false) .setPositiveButton(R.string.learn_more, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.samouraiwallet.com/post/169222582782/bitpay-qr-codes-are-no-longer-valid-important")); startActivity(intent); } }).setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } return; } if (Cahoots.isCahoots(data.trim())) { try { Intent cahootsIntent = ManualCahootsActivity.createIntentResume(this, account, data.trim()); startActivity(cahootsIntent); } catch (Exception e) { Toast.makeText(this,R.string.cannot_process_cahoots,Toast.LENGTH_SHORT).show(); e.printStackTrace(); } return; } if (FormatsUtil.getInstance().isPSBT(data.trim())) { try { PSBTUtil.getInstance(SendActivity.this).doPSBT(data.trim()); } catch(Exception e) { ; } return; } if (FormatsUtil.getInstance().isValidPaymentCode(data)) { processPCode(data, null); return; } if(data.startsWith("BITCOIN:")) { data = "bitcoin:" + data.substring(8); } if (FormatsUtil.getInstance().isBitcoinUri(data)) { String address = FormatsUtil.getInstance().getBitcoinAddress(data); String amount = FormatsUtil.getInstance().getBitcoinAmount(data); setToAddress(address); if (amount != null) { try { NumberFormat btcFormat = NumberFormat.getInstance(Locale.US); btcFormat.setMaximumFractionDigits(8); btcFormat.setMinimumFractionDigits(1); // setToAddress(btcFormat.format(Double.parseDouble(amount) / 1e8)); btcEditText.setText(btcFormat.format(Double.parseDouble(amount) / 1e8)); } catch (NumberFormatException nfe) { // setToAddress("0.0"); } } final String strAmount; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMinimumIntegerDigits(1); nf.setMinimumFractionDigits(1); nf.setMaximumFractionDigits(8); strAmount = nf.format(balance / 1e8); tvMaxAmount.setText(strAmount + " " + getDisplayUnits()); try { if (amount != null && Double.parseDouble(amount) != 0.0) { toAddressEditText.setEnabled(false); // selectPaynymBtn.setEnabled(false); // selectPaynymBtn.setAlpha(0.5f); // Toast.makeText(this, R.string.no_edit_BIP21_scan, Toast.LENGTH_SHORT).show(); enableAmount(false); } } catch (NumberFormatException nfe) { enableAmount(true); } } else if (FormatsUtil.getInstance().isValidBitcoinAddress(data)) { if (FormatsUtil.getInstance().isValidBech32(data)) { setToAddress(data.toLowerCase()); } else { setToAddress(data); } } else if (data.contains("?")) { String pcode = data.substring(0, data.indexOf("?")); // not valid BIP21 but seen often enough if (pcode.startsWith("bitcoin: pcode = pcode.substring(10); } if (pcode.startsWith("bitcoin:")) { pcode = pcode.substring(8); } if (FormatsUtil.getInstance().isValidPaymentCode(pcode)) { processPCode(pcode, data.substring(data.indexOf("?"))); } } else { Toast.makeText(this, R.string.scan_error, Toast.LENGTH_SHORT).show(); } validateSpend(); } public String getDisplayUnits() { return MonetaryUtil.getInstance().getBTCUnits(); } private void processPCode(String pcode, String meta) { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { setBalance(); } }, 2000); if (FormatsUtil.getInstance().isValidPaymentCode(pcode)) { if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_CFM) { try { PaymentCode _pcode = new PaymentCode(pcode); PaymentAddress paymentAddress = BIP47Util.getInstance(this).getSendAddress(_pcode, BIP47Meta.getInstance().getOutgoingIdx(pcode)); if (BIP47Meta.getInstance().getSegwit(pcode)) { SegwitAddress segwitAddress = new SegwitAddress(paymentAddress.getSendECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); strDestinationBTCAddress = segwitAddress.getBech32AsString(); } else { strDestinationBTCAddress = paymentAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } strPCode = _pcode.toString(); setToAddress(BIP47Meta.getInstance().getDisplayLabel(strPCode)); toAddressEditText.setEnabled(false); validateSpend(); } catch (Exception e) { Toast.makeText(this, R.string.error_payment_code, Toast.LENGTH_SHORT).show(); } } else { // Toast.makeText(SendActivity.this, "Payment must be added and notification tx sent", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(this, PayNymDetailsActivity.class); intent.putExtra("pcode", pcode); intent.putExtra("label", ""); if (meta != null && meta.startsWith("?") && meta.length() > 1) { meta = meta.substring(1); if (meta.length() > 0) { String _meta = null; Map<String, String> map = new HashMap<String, String>(); meta.length(); try { _meta = URLDecoder.decode(meta, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } map = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(_meta); intent.putExtra("label", map.containsKey("title") ? map.get("title").trim() : ""); } } if (!openedPaynym) { startActivity(intent); openedPaynym = true; } } } else { Toast.makeText(this, R.string.invalid_payment_code, Toast.LENGTH_SHORT).show(); } } private boolean validateSpend() { boolean isValid = false; boolean insufficientFunds = false; double btc_amount = 0.0; String strBTCAddress = getToAddress(); if (strBTCAddress.startsWith("bitcoin:")) { setToAddress(strBTCAddress.substring(8)); } setToAddress(strBTCAddress); try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } final double dAmount = btc_amount; // Log.i("SendFragment", "amount entered (converted):" + dAmount); final long amount = (long) (Math.round(dAmount * 1e8)); Log.i("SendFragment", "amount entered (converted to long):" + amount); Log.i("SendFragment", "balance:" + balance); if (amount > balance) { insufficientFunds = true; } if (selectedCahootsType != SelectCahootsType.type.NONE) { totalMinerFeeLayout.setVisibility(View.INVISIBLE); } else { totalMinerFeeLayout.setVisibility(View.VISIBLE); } if (selectedCahootsType.getCahootsType() == CahootsType.STOWAWAY && !insufficientFunds && amount != 0) { enableReviewButton(true); return true; } // Log.i("SendFragment", "insufficient funds:" + insufficientFunds); if (amount >= SamouraiWallet.bDust.longValue() && FormatsUtil.getInstance().isValidBitcoinAddress(getToAddress())) { isValid = true; } else if (amount >= SamouraiWallet.bDust.longValue() && strDestinationBTCAddress != null && FormatsUtil.getInstance().isValidBitcoinAddress(strDestinationBTCAddress)) { isValid = true; } else { isValid = false; } if (insufficientFunds) { Toast.makeText(this, getString(R.string.insufficient_funds), Toast.LENGTH_SHORT).show(); } if (!isValid || insufficientFunds) { enableReviewButton(false); return false; } else { enableReviewButton(true); return true; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else if (resultCode == Activity.RESULT_OK && requestCode == RICOCHET) { ; } else if (resultCode == Activity.RESULT_CANCELED && requestCode == RICOCHET) { ; } else { ; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.send_menu, menu); if (account != 0) { menu.findItem(R.id.action_batch).setVisible(false); menu.findItem(R.id.action_ricochet).setVisible(false); menu.findItem(R.id.action_empty_ricochet).setVisible(false); } if(preselectedUTXOs!=null){ menu.findItem(R.id.action_batch).setVisible(false); } if (account == WhirlpoolMeta.getInstance(getApplication()).getWhirlpoolPostmix()) { MenuItem item = menu.findItem(R.id.action_send_menu_account); item.setVisible(true); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); item.setActionView(createTag("POST-MIX")); } 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(); if (item.getItemId() == android.R.id.home) { this.onBackPressed(); return true; } if (item.getItemId() == R.id.select_paynym) { PaynymSelectModalFragment paynymSelectModalFragment = PaynymSelectModalFragment.newInstance(code -> processPCode(code, null),getString(R.string.paynym),false); paynymSelectModalFragment.show(getSupportFragmentManager(), "paynym_select"); return true; } // noinspection SimplifiableIfStatement if (id == R.id.action_scan_qr) { doScan(); } else if (id == R.id.action_ricochet) { Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivity(intent); } else if (id == R.id.action_empty_ricochet) { emptyRicochetQueue(); } else if (id == R.id.action_utxo) { doUTXO(); } else if (id == R.id.action_fees) { doFees(); } else if (id == R.id.action_batch) { doBatchSpend(); } else if (id == R.id.action_support) { doSupport(); } else { ; } return super.onOptionsItemSelected(item); } private void emptyRicochetQueue() { RicochetMeta.getInstance(this).setLastRicochet(null); RicochetMeta.getInstance(this).empty(); new Thread(new Runnable() { @Override public void run() { try { PayloadUtil.getInstance(SendActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(SendActivity.this).getGUID() + AccessFactory.getInstance(SendActivity.this).getPIN())); } catch (Exception e) { ; } } }).start(); } private void doScan() { CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet(); cameraFragmentBottomSheet.show(getSupportFragmentManager(), cameraFragmentBottomSheet.getTag()); cameraFragmentBottomSheet.setQrCodeScanListener(code -> { cameraFragmentBottomSheet.dismissAllowingStateLoss(); processScan(code); }); } private void doSupport() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/section/8-sending-bitcoin")); startActivity(intent); } private void doUTXO() { Intent intent = new Intent(SendActivity.this, UTXOSActivity.class); if (account != 0) { intent.putExtra("_account", account); } startActivity(intent); } private void doBatchSpend() { Intent intent = new Intent(SendActivity.this, BatchSpendActivity.class); startActivity(intent); } private void doFees() { SuggestedFee highFee = FeeUtil.getInstance().getHighFee(); SuggestedFee normalFee = FeeUtil.getInstance().getNormalFee(); SuggestedFee lowFee = FeeUtil.getInstance().getLowFee(); String message = getText(R.string.current_fee_selection) + " " + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_hi_fee_value) + " " + (highFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_mid_fee_value) + " " + (normalFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_lo_fee_value) + " " + (lowFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, (dialog, whichButton) -> dialog.dismiss()); if (!isFinishing()) { dlg.show(); } } private void saveChangeIndexes() { idxBIP84PostMixInternal = AddressFactory.getInstance(SendActivity.this).getHighestPostChangeIdx(); idxBIP84Internal = BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); idxBIP49Internal = BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); idxBIP44Internal = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx(); } private void restoreChangeIndexes() { AddressFactory.getInstance(SendActivity.this).setHighestPostChangeIdx(idxBIP84PostMixInternal); BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(idxBIP84Internal); BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(idxBIP49Internal); HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(idxBIP44Internal); } private Observable<TxProcessorResult> CalculateEntropy(ArrayList<UTXO> selectedUTXO, HashMap<String, BigInteger> receivers) { return Observable.create(emitter -> { Map<String, Long> inputs = new HashMap<>(); Map<String, Long> outputs = new HashMap<>(); for (Map.Entry<String, BigInteger> mapEntry : receivers.entrySet()) { String toAddress = mapEntry.getKey(); BigInteger value = mapEntry.getValue(); outputs.put(toAddress, value.longValue()); } for (int i = 0; i < selectedUTXO.size(); i++) { inputs.put(stubAddress[i], selectedUTXO.get(i).getValue()); } TxProcessor txProcessor = new TxProcessor(BoltzmannSettings.MAX_DURATION_DEFAULT, BoltzmannSettings.MAX_TXOS_DEFAULT); Txos txos = new Txos(inputs, outputs); TxProcessorResult result = txProcessor.processTx(txos, 0.005f, TxosLinkerOptionEnum.PRECHECK, TxosLinkerOptionEnum.LINKABILITY, TxosLinkerOptionEnum.MERGE_INPUTS); emitter.onNext(result); }); } }
package com.samourai.wallet.send; import android.app.Activity; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; import com.google.android.material.button.MaterialButton; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.slider.Slider; import com.google.android.material.snackbar.Snackbar; import com.google.common.base.Splitter; import com.samourai.boltzmann.beans.BoltzmannSettings; import com.samourai.boltzmann.beans.Txos; import com.samourai.boltzmann.linker.TxosLinkerOptionEnum; import com.samourai.boltzmann.processor.TxProcessor; import com.samourai.boltzmann.processor.TxProcessorResult; import com.samourai.http.client.AndroidHttpClient; import com.samourai.http.client.IHttpClient; import com.samourai.wallet.R; import com.samourai.wallet.SamouraiActivity; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.TxAnimUIActivity; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.SendNotifTxFactory; import com.samourai.wallet.bip47.rpc.PaymentAddress; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.cahoots.Cahoots; import com.samourai.wallet.cahoots.CahootsMode; import com.samourai.wallet.cahoots.CahootsType; import com.samourai.wallet.cahoots.psbt.PSBTUtil; import com.samourai.wallet.fragments.CameraFragmentBottomSheet; import com.samourai.wallet.fragments.PaynymSelectModalFragment; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.paynym.paynymDetails.PayNymDetailsActivity; import com.samourai.wallet.ricochet.RicochetActivity; import com.samourai.wallet.ricochet.RicochetMeta; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.segwit.bech32.Bech32Util; import com.samourai.wallet.send.batch.BatchSpendActivity; import com.samourai.wallet.send.cahoots.ManualCahootsActivity; import com.samourai.wallet.send.cahoots.SelectCahootsType; import com.samourai.wallet.send.soroban.meeting.SorobanMeetingSendActivity; import com.samourai.wallet.tor.TorManager; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.DecimalDigitsInputFilter; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.SendAddressUtil; import com.samourai.wallet.util.WebUtil; import com.samourai.wallet.utxos.PreSelectUtil; import com.samourai.wallet.utxos.UTXOSActivity; import com.samourai.wallet.utxos.models.UTXOCoin; import com.samourai.wallet.whirlpool.WhirlpoolConst; import com.samourai.wallet.whirlpool.WhirlpoolMeta; import com.samourai.wallet.widgets.SendTransactionDetailsView; import com.samourai.xmanager.client.XManagerClient; import com.samourai.xmanager.protocol.XManagerService; import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.tuple.Triple; import org.bitcoinj.core.Address; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.script.Script; import org.bouncycastle.util.encoders.Hex; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URLDecoder; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Vector; import java.util.concurrent.TimeUnit; import androidx.appcompat.widget.SwitchCompat; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.constraintlayout.widget.Group; import androidx.core.content.ContextCompat; import ch.boye.httpclientandroidlib.protocol.HttpProcessorBuilder; import io.matthewnelson.topl_service.TorServiceController; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class SendActivity extends SamouraiActivity { private final static int SCAN_QR = 2012; private final static int RICOCHET = 2013; private static final String TAG = "SendActivity"; private SendTransactionDetailsView sendTransactionDetailsView; private ViewSwitcher amountViewSwitcher; private EditText toAddressEditText, btcEditText, satEditText; private TextView tvMaxAmount, tvReviewSpendAmount, tvReviewSpendAmountInSats, tvTotalFee, tvToAddress, tvEstimatedBlockWait, tvSelectedFeeRate, tvSelectedFeeRateLayman, ricochetTitle, ricochetDesc, cahootsStatusText, cahootsNotice, satbText; private MaterialButton btnReview, btnSend; private SwitchCompat ricochetHopsSwitch, ricochetStaggeredDelivery; private ViewGroup totalMinerFeeLayout; private SwitchCompat cahootsSwitch; private Slider feeSeekBar; private Group ricochetStaggeredOptionGroup; private boolean shownWalletLoadingMessage = false; private long balance = 0L; private long selectableBalance = 0L; private String strDestinationBTCAddress = null; private ProgressBar progressBar; private final static int FEE_LOW = 0; private final static int FEE_NORMAL = 1; private final static int FEE_PRIORITY = 2; private final static int FEE_CUSTOM = 3; private int FEE_TYPE = FEE_LOW; public final static int SPEND_SIMPLE = 0; public final static int SPEND_BOLTZMANN = 1; public final static int SPEND_RICOCHET = 2; private int SPEND_TYPE = SPEND_BOLTZMANN; private boolean openedPaynym = false; private String strPCode = null; private String strPcodeCounterParty = null; private long feeLow, feeMed, feeHigh; private String strPrivacyWarning; private String strCannotDoBoltzmann; private ArrayList<UTXO> selectedUTXO; private long _change; private HashMap<String, BigInteger> receivers; private int changeType; private ConstraintLayout cahootsGroup; private ConstraintLayout premiumAddons; private TextView addonsNotAvailableMessage; private String address; private String message; private long amount; private int change_index; private String ricochetMessage; private JSONObject ricochetJsonObj = null; private boolean stoneWallChecked = true; private int idxBIP44Internal = 0; private int idxBIP49Internal = 0; private int idxBIP84Internal = 0; private int idxBIP84PostMixInternal = 0; //stub address for entropy calculation public static String[] stubAddress = {"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", "12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX", "1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1", "1FvzCLoTPGANNjWoUo6jUGuAG3wg1w4YjR", "15ubicBBWFnvoZLT7GiU2qxjRaKJPdkDMG", "1JfbZRwdDHKZmuiZgYArJZhcuuzuw2HuMu", "1GkQmKAmHtNfnD3LHhTkewJxKHVSta4m2a", "16LoW7y83wtawMg5XmT4M3Q7EdjjUmenjM", "1J6PYEzr4CUoGbnXrELyHszoTSz3wCsCaj", "12cbQLTFMXRnSzktFkuoG3eHoMeFtpTu3S", "15yN7NPEpu82sHhB6TzCW5z5aXoamiKeGy ", "1dyoBoF5vDmPCxwSsUZbbYhA5qjAfBTx9", "1PYELM7jXHy5HhatbXGXfRpGrgMMxmpobu", "17abzUBJr7cnqfnxnmznn8W38s9f9EoXiq", "1DMGtVnRrgZaji7C9noZS3a1QtoaAN2uRG", "1CYG7y3fukVLdobqgUtbknwWKUZ5p1HVmV", "16kktFTqsruEfPPphW4YgjktRF28iT8Dby", "1LPBetDzQ3cYwqQepg4teFwR7FnR1TkMCM", "1DJkjSqW9cX9XWdU71WX3Aw6s6Mk4C3TtN", "1P9VmZogiic8d5ZUVZofrdtzXgtpbG9fop", "15ubjFzmWVvj3TqcpJ1bSsb8joJ6gF6dZa"}; private CompositeDisposable compositeDisposables = new CompositeDisposable(); private SelectCahootsType.type selectedCahootsType = SelectCahootsType.type.NONE; private final DecimalFormat decimalFormatSatPerByte = new DecimalFormat(" private List<UTXOCoin> preselectedUTXOs = null; @Override protected void onCreate(Bundle savedInstanceState) { //Switch themes based on accounts (blue theme for whirlpool account) setSwitchThemes(true); super.onCreate(savedInstanceState); setContentView(R.layout.activity_send); setSupportActionBar(findViewById(R.id.toolbar_send)); Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); setTitle(""); //CustomView for showing and hiding body of th UI sendTransactionDetailsView = findViewById(R.id.sendTransactionDetailsView); //ViewSwitcher Element for toolbar section of the UI. //we can switch between Form and review screen with this element amountViewSwitcher = findViewById(R.id.toolbar_view_switcher); //Input elements from toolbar section of the UI toAddressEditText = findViewById(R.id.edt_send_to); btcEditText = findViewById(R.id.amountBTC); satEditText = findViewById(R.id.amountSat); tvToAddress = findViewById(R.id.to_address_review); tvReviewSpendAmount = findViewById(R.id.send_review_amount); tvReviewSpendAmountInSats = findViewById(R.id.send_review_amount_in_sats); tvMaxAmount = findViewById(R.id.totalBTC); //view elements from review segment and transaction segment can be access through respective //methods which returns root viewGroup btnReview = sendTransactionDetailsView.getTransactionView().findViewById(R.id.review_button); cahootsSwitch = sendTransactionDetailsView.getTransactionView().findViewById(R.id.cahoots_switch); ricochetHopsSwitch = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_hops_switch); ricochetTitle = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_desc); ricochetDesc = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_title); ricochetStaggeredDelivery = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_staggered_option); ricochetStaggeredOptionGroup = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_staggered_option_group); tvSelectedFeeRate = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.selected_fee_rate); tvSelectedFeeRateLayman = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.selected_fee_rate_in_layman); tvTotalFee = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.total_fee); btnSend = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.send_btn); tvEstimatedBlockWait = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.est_block_time); feeSeekBar = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.fee_seekbar); cahootsGroup = sendTransactionDetailsView.findViewById(R.id.cohoots_options); premiumAddons = sendTransactionDetailsView.findViewById(R.id.premium_addons); addonsNotAvailableMessage = sendTransactionDetailsView.findViewById(R.id.addons_not_available_message); cahootsStatusText = sendTransactionDetailsView.findViewById(R.id.cahoot_status_text); totalMinerFeeLayout = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.total_miner_fee_group); cahootsNotice = sendTransactionDetailsView.findViewById(R.id.cahoots_not_enabled_notice); progressBar = findViewById(R.id.send_activity_progress); btcEditText.addTextChangedListener(BTCWatcher); btcEditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(8, 8)}); satEditText.addTextChangedListener(satWatcher); toAddressEditText.addTextChangedListener(AddressWatcher); btnReview.setOnClickListener(v -> review()); btnSend.setOnClickListener(v -> initiateSpend()); View.OnClickListener clipboardCopy = view -> { ClipboardManager cm = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clipData = android.content.ClipData .newPlainText("Miner fee", tvTotalFee.getText()); if (cm != null) { cm.setPrimaryClip(clipData); Toast.makeText(this, getString(R.string.copied_to_clipboard), Toast.LENGTH_SHORT).show(); } }; tvTotalFee.setOnClickListener(clipboardCopy); tvSelectedFeeRate.setOnClickListener(clipboardCopy); SPEND_TYPE = SPEND_BOLTZMANN; saveChangeIndexes(); setUpRicochet(); setUpCahoots(); setUpFee(); setBalance(); enableReviewButton(false); setUpBoltzman(); validateSpend(); checkDeepLinks(); if (getIntent().getExtras().containsKey("preselected")) { preselectedUTXOs = PreSelectUtil.getInstance().getPreSelected(getIntent().getExtras().getString("preselected")); setBalance(); if (ricochetHopsSwitch.isChecked()) { SPEND_TYPE = SPEND_RICOCHET; } else { SPEND_TYPE = SPEND_SIMPLE; } if (preselectedUTXOs != null && preselectedUTXOs.size() > 0 && balance < 1000000L) { premiumAddons.setVisibility(View.GONE); cahootsGroup.setVisibility(View.GONE); addonsNotAvailableMessage.setVisibility(View.VISIBLE); } } else { Disposable disposable = APIFactory.getInstance(getApplicationContext()) .walletBalanceObserver .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aLong -> setBalance(), Throwable::printStackTrace); compositeDisposables.add(disposable); // Update fee Disposable feeDisposable = Observable.fromCallable(() -> APIFactory.getInstance(getApplicationContext()).getDynamicFees()) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(t -> { setUpFee(); }, Throwable::printStackTrace); compositeDisposables.add(feeDisposable); if (getIntent().getExtras() != null) { if (!getIntent().getExtras().containsKey("balance")) { return; } balance = getIntent().getExtras().getLong("balance"); } } } private void setUpCahoots() { if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) { cahootsNotice.setVisibility(View.VISIBLE); } cahootsSwitch.setOnCheckedChangeListener((compoundButton, b) -> { // to check whether bottomsheet is closed or selected a value final boolean[] chosen = {false}; if (b) { SelectCahootsType cahootsType = new SelectCahootsType(); cahootsType.show(getSupportFragmentManager(), cahootsType.getTag()); cahootsType.setOnSelectListener(new SelectCahootsType.OnSelectListener() { @Override public void onSelect(SelectCahootsType.type type, String pcode) { if (pcode != null) { strPcodeCounterParty = pcode; if(type.getCahootsType() == CahootsType.STOWAWAY){ strPCode = pcode; } if(type.getCahootsMode() == CahootsMode.SOROBAN){ if(!TorManager.INSTANCE.isConnected()){ TorServiceController.startTor(); PrefsUtil.getInstance(getApplication()).setValue(PrefsUtil.ENABLE_TOR, true); } } } chosen[0] = true; selectedCahootsType = type; switch (selectedCahootsType) { case NONE: { cahootsStatusText.setText("Off"); cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.warning_yellow)); break; } default: { cahootsStatusText.setText(selectedCahootsType.getCahootsType().getLabel()+" "+selectedCahootsType.getCahootsMode().getLabel()); cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.green_ui_2)); if (CahootsType.STOWAWAY.equals(selectedCahootsType.getCahootsType())) { toAddressEditText.setText(getParticipantLabel()); toAddressEditText.setEnabled(false); address = ""; } } } validateSpend(); } @Override public void onDismiss() { if (!chosen[0]) { strPcodeCounterParty = null; compoundButton.setChecked(false); selectedCahootsType = SelectCahootsType.type.NONE; hideToAddressForStowaway(); } validateSpend(); } }); } else { selectedCahootsType = SelectCahootsType.type.NONE; cahootsStatusText.setText("Off"); cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.warning_yellow)); hideToAddressForStowaway(); validateSpend(); enableReviewButton(false); } }); } private void hideToAddressForStowaway() { toAddressEditText.setEnabled(true); toAddressEditText.setText(""); address = ""; } public View createTag(String text) { float scale = getResources().getDisplayMetrics().density; LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); TextView textView = new TextView(getApplicationContext()); textView.setText(text); textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white)); textView.setLayoutParams(lparams); textView.setBackgroundResource(R.drawable.tag_round_shape); textView.setPadding((int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f), (int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f)); textView.setTypeface(Typeface.DEFAULT_BOLD); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11); return textView; } @Override protected void onResume() { super.onResume(); AppUtil.getInstance(SendActivity.this).setIsInForeground(true); AppUtil.getInstance(SendActivity.this).checkTimeOut(); try { new Handler().postDelayed(this::setBalance, 300); } catch (Exception ex) { } } private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = (compoundButton, checked) -> { if (compoundButton.isPressed()) { SPEND_TYPE = checked ? SPEND_BOLTZMANN : SPEND_SIMPLE; stoneWallChecked = checked; compoundButton.setChecked(checked); new Handler().postDelayed(this::prepareSpend, 100); } }; private void setUpBoltzman() { sendTransactionDetailsView.getStoneWallSwitch().setChecked(true); sendTransactionDetailsView.getStoneWallSwitch().setEnabled(WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix() != account); sendTransactionDetailsView.enableStonewall(true); sendTransactionDetailsView.getStoneWallSwitch().setOnCheckedChangeListener(onCheckedChangeListener); } private void checkRicochetPossibility() { double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; return; } double dAmount = btc_amount; amount = Math.round(dAmount * 1e8); if (amount < (balance - (RicochetMeta.samouraiFeeAmountV2.add(BigInteger.valueOf(50000L))).longValue())) { ricochetDesc.setAlpha(1f); ricochetTitle.setAlpha(1f); ricochetHopsSwitch.setAlpha(1f); ricochetHopsSwitch.setEnabled(true); if (ricochetHopsSwitch.isChecked()) { ricochetStaggeredOptionGroup.setVisibility(View.VISIBLE); } } else { ricochetStaggeredOptionGroup.setVisibility(View.GONE); ricochetDesc.setAlpha(.6f); ricochetTitle.setAlpha(.6f); ricochetHopsSwitch.setAlpha(.6f); ricochetHopsSwitch.setEnabled(false); } } private void enableReviewButton(boolean enable) { btnReview.setEnabled(enable); if (enable) { btnReview.setBackgroundColor(getResources().getColor(R.color.blue_ui_2)); } else { btnReview.setBackgroundColor(getResources().getColor(R.color.disabled_grey)); } } private void setUpFee() { int multiplier = 10000; FEE_TYPE = PrefsUtil.getInstance(this).getValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL); feeLow = FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L; feeMed = FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L; feeHigh = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L; float high = ((float) feeHigh / 2) + (float) feeHigh; int feeHighSliderValue = (int) (high * multiplier); int feeMedSliderValue = (int) (feeMed * multiplier); feeSeekBar.setValueTo(feeHighSliderValue - multiplier); if (feeLow == feeMed && feeMed == feeHigh) { feeLow = (long) ((double) feeMed * 0.85); feeHigh = (long) ((double) feeMed * 1.15); SuggestedFee lo_sf = new SuggestedFee(); lo_sf.setDefaultPerKB(BigInteger.valueOf(feeLow * 1000L)); FeeUtil.getInstance().setLowFee(lo_sf); SuggestedFee hi_sf = new SuggestedFee(); hi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L)); FeeUtil.getInstance().setHighFee(hi_sf); } else if (feeLow == feeMed || feeMed == feeMed) { feeMed = (feeLow + feeHigh) / 2L; SuggestedFee mi_sf = new SuggestedFee(); mi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L)); FeeUtil.getInstance().setNormalFee(mi_sf); } else { ; } if (feeLow < 1L) { feeLow = 1L; SuggestedFee lo_sf = new SuggestedFee(); lo_sf.setDefaultPerKB(BigInteger.valueOf(feeLow * 1000L)); FeeUtil.getInstance().setLowFee(lo_sf); } if (feeMed < 1L) { feeMed = 1L; SuggestedFee mi_sf = new SuggestedFee(); mi_sf.setDefaultPerKB(BigInteger.valueOf(feeMed * 1000L)); FeeUtil.getInstance().setNormalFee(mi_sf); } if (feeHigh < 1L) { feeHigh = 1L; SuggestedFee hi_sf = new SuggestedFee(); hi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L)); FeeUtil.getInstance().setHighFee(hi_sf); } // tvEstimatedBlockWait.setText("6 blocks"); tvSelectedFeeRateLayman.setText(getString(R.string.normal)); FeeUtil.getInstance().sanitizeFee(); tvSelectedFeeRate.setText((String.valueOf((int) feeMed)).concat(" sat/b")); feeSeekBar.setValue((feeMedSliderValue - multiplier) + 1); DecimalFormat decimalFormat = new DecimalFormat(" decimalFormat.setDecimalSeparatorAlwaysShown(false); setFeeLabels(); // View.OnClickListener inputFeeListener = v -> { // tvSelectedFeeRate.requestFocus(); // tvSelectedFeeRate.setFocusableInTouchMode(true); // InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); // assert imm != null; // imm.showSoftInput(tvSelectedFeeRate, InputMethodManager.SHOW_FORCED); // tvSelectedFeeRateLayman.setOnClickListener(inputFeeListener); // satbText.setOnClickListener(inputFeeListener); // tvSelectedFeeRate.addTextChangedListener(new TextWatcher() { // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // @Override // public void afterTextChanged(Editable s) { // try { // int i = (int) ((Double.parseDouble(tvSelectedFeeRate.getText().toString())*multiplier) - multiplier); // //feeSeekBar.setMax(feeHighSliderValue - multiplier); // feeSeekBar.setProgress(i); // } catch(NumberFormatException nfe) { // System.out.println("Could not parse " + nfe); //// int position = tvSelectedFeeRate.length(); //// Editable etext = (Editable) tvSelectedFeeRate.getText(); //// Selection.setSelection(etext, position); feeSeekBar.setLabelFormatter(i -> tvSelectedFeeRate.getText().toString()); feeSeekBar.addOnChangeListener((slider, i, fromUser) -> { double value = ((double) i + multiplier) / (double) multiplier; if(selectedCahootsType != SelectCahootsType.type.NONE || SPEND_TYPE == SPEND_RICOCHET){ tvSelectedFeeRate.setText(String.valueOf(decimalFormat.format(value).concat(" sat/b"))); } if (value == 0.0) { value = 1.0; } double pct = 0.0; int nbBlocks = 6; if (value <= (double) feeLow) { pct = ((double) feeLow / value); nbBlocks = ((Double) Math.ceil(pct * 24.0)).intValue(); } else if (value >= (double) feeHigh) { pct = ((double) feeHigh / value); nbBlocks = ((Double) Math.ceil(pct * 2.0)).intValue(); if (nbBlocks < 1) { nbBlocks = 1; } } else { pct = ((double) feeMed / value); nbBlocks = ((Double) Math.ceil(pct * 6.0)).intValue(); } tvEstimatedBlockWait.setText(nbBlocks + " blocks"); setFee(value); setFeeLabels(); restoreChangeIndexes(); }); switch (FEE_TYPE) { case FEE_LOW: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee()); FeeUtil.getInstance().sanitizeFee(); break; case FEE_PRIORITY: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); FeeUtil.getInstance().sanitizeFee(); break; default: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee()); FeeUtil.getInstance().sanitizeFee(); break; } } private void setFeeLabels() { float sliderValue = (((float) feeSeekBar.getValue()) / feeSeekBar.getValueTo()); float sliderInPercentage = sliderValue * 100; if (sliderInPercentage < 33) { tvSelectedFeeRateLayman.setText(R.string.low); } else if (sliderInPercentage > 33 && sliderInPercentage < 66) { tvSelectedFeeRateLayman.setText(R.string.normal); } else if (sliderInPercentage > 66) { tvSelectedFeeRateLayman.setText(R.string.urgent); } } private void setFee(double fee) { double sanitySat = FeeUtil.getInstance().getHighFee().getDefaultPerKB().doubleValue() / 1000.0; final long sanityValue; if (sanitySat < 10.0) { sanityValue = 15L; } else { sanityValue = (long) (sanitySat * 1.5); } // String val = null; double d = FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().doubleValue() / 1000.0; NumberFormat decFormat = NumberFormat.getInstance(Locale.US); decFormat.setMaximumFractionDigits(3); decFormat.setMinimumFractionDigits(0); double customValue = 0.0; try { customValue = (double) fee; } catch (Exception e) { Toast.makeText(this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show(); return; } SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFee.setDefaultPerKB(BigInteger.valueOf((long) (customValue * 1000.0))); FeeUtil.getInstance().setSuggestedFee(suggestedFee); prepareSpend(); } private void setUpRicochet() { ricochetHopsSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { sendTransactionDetailsView.enableForRicochet(isChecked); enableCahoots(!isChecked); ricochetStaggeredOptionGroup.setVisibility(isChecked ? View.VISIBLE : View.GONE); if (isChecked) { SPEND_TYPE = SPEND_RICOCHET; PrefsUtil.getInstance(this).setValue(PrefsUtil.USE_RICOCHET, true); } else { SPEND_TYPE = sendTransactionDetailsView.getStoneWallSwitch().isChecked() ? SPEND_BOLTZMANN : SPEND_SIMPLE; PrefsUtil.getInstance(this).setValue(PrefsUtil.USE_RICOCHET, false); } if (isChecked) { ricochetStaggeredOptionGroup.setVisibility(View.VISIBLE); } else { ricochetStaggeredOptionGroup.setVisibility(View.GONE); } }); ricochetHopsSwitch.setChecked(PrefsUtil.getInstance(this).getValue(PrefsUtil.USE_RICOCHET, false)); if (ricochetHopsSwitch.isChecked()) { ricochetStaggeredOptionGroup.setVisibility(View.VISIBLE); } else { ricochetStaggeredOptionGroup.setVisibility(View.GONE); } ricochetStaggeredDelivery.setChecked(PrefsUtil.getInstance(this).getValue(PrefsUtil.RICOCHET_STAGGERED, false)); ricochetStaggeredDelivery.setOnCheckedChangeListener((compoundButton, isChecked) -> { PrefsUtil.getInstance(this).setValue(PrefsUtil.RICOCHET_STAGGERED, isChecked); // Handle staggered delivery option }); } private Completable setUpRicochetFees() { TorManager torManager = TorManager.INSTANCE; IHttpClient httpClient = new AndroidHttpClient(WebUtil.getInstance(getApplicationContext()), torManager); XManagerClient xManagerClient = new XManagerClient(SamouraiWallet.getInstance().isTestNet(), torManager.isConnected(), httpClient); if (PrefsUtil.getInstance(this).getValue(PrefsUtil.USE_RICOCHET, false)) { Completable completable = Completable.fromCallable(() -> { String feeAddress = xManagerClient.getAddressOrDefault(XManagerService.RICOCHET); RicochetMeta.getInstance(getApplicationContext()).setRicochetFeeAddress(feeAddress); return true; }); //Set BIP47 Fee address if the tx is if (strPCode != null) { Completable pcode = Completable.fromCallable(() -> { String address = xManagerClient.getAddressOrDefault(XManagerService.BIP47); SendNotifTxFactory.getInstance().setAddress(address); return true; }); return Completable.concatArray(completable, pcode); } else { return completable; } } else { return Completable.complete(); } } private void enableCahoots(boolean enable) { if (enable) { cahootsGroup.setVisibility(View.VISIBLE); } else { cahootsGroup.setVisibility(View.GONE); selectedCahootsType = SelectCahootsType.type.NONE; } } private void setBalance() { try { if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { balance = APIFactory.getInstance(SendActivity.this).getXpubPostMixBalance(); selectableBalance = balance; } else { balance = APIFactory.getInstance(SendActivity.this).getXpubBalance(); selectableBalance = balance; } } catch (java.lang.NullPointerException npe) { npe.printStackTrace(); } if (getIntent().getExtras().containsKey("preselected")) { //Reloads preselected utxo's if it changed on last call preselectedUTXOs = PreSelectUtil.getInstance().getPreSelected(getIntent().getExtras().getString("preselected")); if (preselectedUTXOs != null && preselectedUTXOs.size() > 0) { //Checks utxo's state, if the item is blocked it will be removed from preselectedUTXOs for (int i = 0; i < preselectedUTXOs.size(); i++) { UTXOCoin coin = preselectedUTXOs.get(i); if (BlockedUTXO.getInstance().containsAny(coin.hash, coin.idx)) { try { preselectedUTXOs.remove(i); } catch (Exception ex) { } } } long amount = 0; for (UTXOCoin utxo : preselectedUTXOs) { amount += utxo.amount; } balance = amount; } else { ; } } final String strAmount; strAmount = FormatsUtil.formatBTC(balance); if (account == 0) { tvMaxAmount.setOnClickListener(view -> { btcEditText.setText(strAmount.replace("BTC","").trim()); }); } tvMaxAmount.setOnLongClickListener(view -> { setBalance(); return true; }); tvMaxAmount.setText(strAmount); if(!AppUtil.getInstance(getApplication()).isOfflineMode()) if (balance == 0L && !APIFactory.getInstance(getApplicationContext()).walletInit) { //some time, user may navigate to this activity even before wallet initialization completes //so we will set a delay to reload balance info Disposable disposable = Completable.timer(700, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .subscribe(this::setBalance); compositeDisposables.add(disposable); if (!shownWalletLoadingMessage) { Snackbar.make(tvMaxAmount.getRootView(), "Please wait... your wallet is still loading ", Snackbar.LENGTH_LONG).show(); shownWalletLoadingMessage = true; } } } private void checkDeepLinks() { Bundle extras = getIntent().getExtras(); if (extras != null) { String strUri = extras.getString("uri"); if (extras.containsKey("amount")) { DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US); format.setMaximumFractionDigits(8); btcEditText.setText(format.format(getBtcValue(extras.getDouble("amount")))); } if (extras.getString("pcode") != null) strPCode = extras.getString("pcode"); if (strPCode != null && strPCode.length() > 0) { processPCode(strPCode, null); } else if (strUri != null && strUri.length() > 0) { processScan(strUri); } new Handler().postDelayed(this::validateSpend, 800); } } private TextWatcher BTCWatcher = 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) { } @Override public void afterTextChanged(Editable editable) { satEditText.removeTextChangedListener(satWatcher); btcEditText.removeTextChangedListener(this); try { if (editable.toString().length() == 0) { satEditText.setText("0"); btcEditText.setText(""); satEditText.setSelection(satEditText.getText().length()); satEditText.addTextChangedListener(satWatcher); btcEditText.addTextChangedListener(this); return; } Double btc = Double.parseDouble(String.valueOf(editable)); if (btc > 21000000.0) { btcEditText.setText("0.00"); btcEditText.setSelection(btcEditText.getText().length()); satEditText.setText("0"); satEditText.setSelection(satEditText.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } else { DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US); DecimalFormatSymbols symbols = format.getDecimalFormatSymbols(); String defaultSeparator = Character.toString(symbols.getDecimalSeparator()); int max_len = 8; NumberFormat btcFormat = NumberFormat.getInstance(Locale.US); btcFormat.setMaximumFractionDigits(max_len + 1); try { double d = NumberFormat.getInstance(Locale.US).parse(editable.toString()).doubleValue(); String s1 = btcFormat.format(d); if (s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if (dec.length() > 0) { dec = dec.substring(1); if (dec.length() > max_len) { btcEditText.setText(s1.substring(0, s1.length() - 1)); btcEditText.setSelection(btcEditText.getText().length()); editable = btcEditText.getEditableText(); btc = Double.parseDouble(btcEditText.getText().toString()); } } } } catch (NumberFormatException nfe) { ; } catch (ParseException pe) { ; } Double sats = getSatValue(Double.valueOf(btc)); satEditText.setText(formattedSatValue(sats)); checkRicochetPossibility(); } } catch (NumberFormatException e) { e.printStackTrace(); } satEditText.addTextChangedListener(satWatcher); btcEditText.addTextChangedListener(this); validateSpend(); } }; private TextWatcher AddressWatcher = 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) { } @Override public void afterTextChanged(Editable editable) { if (editable.toString().length() != 0) { validateSpend(); } else { setToAddress(""); } } }; private String formattedSatValue(Object number) { NumberFormat nformat = NumberFormat.getNumberInstance(Locale.US); DecimalFormat decimalFormat = (DecimalFormat) nformat; decimalFormat.applyPattern(" return decimalFormat.format(number).replace(",", " "); } private TextWatcher satWatcher = 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) { } @Override public void afterTextChanged(Editable editable) { satEditText.removeTextChangedListener(this); btcEditText.removeTextChangedListener(BTCWatcher); try { if (editable.toString().length() == 0) { btcEditText.setText("0.00"); satEditText.setText(""); satEditText.addTextChangedListener(this); btcEditText.addTextChangedListener(BTCWatcher); return; } String cleared_space = editable.toString().replace(" ", ""); Double sats = Double.parseDouble(cleared_space); Double btc = getBtcValue(sats); String formatted = formattedSatValue(sats); satEditText.setText(formatted); satEditText.setSelection(formatted.length()); btcEditText.setText(String.format(Locale.ENGLISH, "%.8f", btc)); if (btc > 21000000.0) { btcEditText.setText("0.00"); btcEditText.setSelection(btcEditText.getText().length()); satEditText.setText("0"); satEditText.setSelection(satEditText.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } } catch (NumberFormatException e) { e.printStackTrace(); } satEditText.addTextChangedListener(this); btcEditText.addTextChangedListener(BTCWatcher); checkRicochetPossibility(); validateSpend(); } }; private void setToAddress(String string) { tvToAddress.setText(string); toAddressEditText.removeTextChangedListener(AddressWatcher); toAddressEditText.setText(string); toAddressEditText.setSelection(toAddressEditText.getText().length()); toAddressEditText.addTextChangedListener(AddressWatcher); } private String getToAddress() { if (toAddressEditText.getText().toString().trim().length() != 0) { return toAddressEditText.getText().toString(); } if (tvToAddress.getText().toString().length() != 0) { return tvToAddress.getText().toString(); } return ""; } private Double getBtcValue(Double sats) { return (double) (sats / 1e8); } private Double getSatValue(Double btc) { if (btc == 0) { return (double) 0; } return btc * 1e8; } private void review() { double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } double dAmount = btc_amount; amount = (long) (Math.round(dAmount * 1e8)); if (amount == balance && balance == selectableBalance) { int warningMessage = R.string.full_spend_warning; if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) { warningMessage = R.string.postmix_full_spend; } MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(warningMessage) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); _review(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } } else { _review(); } } private void _review() { setUpBoltzman(); if (validateSpend() && prepareSpend()) { tvReviewSpendAmount.setText(btcEditText.getText().toString().concat(" BTC")); try { tvReviewSpendAmountInSats.setText(formattedSatValue(getSatValue(Double.valueOf(btcEditText.getText().toString()))).concat(" sats")); } catch (Exception ex) { ex.printStackTrace(); } amountViewSwitcher.showNext(); hideKeyboard(); hideMenus(true); sendTransactionDetailsView.showReview(ricochetHopsSwitch.isChecked()); } } private void hideKeyboard() { InputMethodManager imm = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(amountViewSwitcher.getWindowToken(), 0); } } private void hideMenus(boolean hide) { Toolbar toolbar = findViewById(R.id.toolbar_send); toolbar.getMenu().findItem(R.id.action_scan_qr).setVisible(!hide); toolbar.getMenu().findItem(R.id.select_paynym).setVisible(!hide); } @Override protected void onDestroy() { super.onDestroy(); PreSelectUtil.getInstance().clear(); if (compositeDisposables != null && !compositeDisposables.isDisposed()) compositeDisposables.dispose(); } synchronized private boolean prepareSpend() { if(SPEND_TYPE == SPEND_SIMPLE && stoneWallChecked){ SPEND_TYPE = SPEND_BOLTZMANN; } restoreChangeIndexes(); double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } double dAmount = btc_amount; amount = (long) (Math.round(dAmount * 1e8)); // Log.i("SendActivity", "amount:" + amount); if (selectedCahootsType.getCahootsType() == CahootsType.STOWAWAY) { setButtonForStowaway(true); return true; } else { setButtonForStowaway(false); } address = strDestinationBTCAddress == null ? toAddressEditText.getText().toString().trim() : strDestinationBTCAddress; if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { changeType = 84; } else if (PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false) { changeType = 84; } else if (FormatsUtil.getInstance().isValidBech32(address) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { changeType = FormatsUtil.getInstance().isValidBech32(address) ? 84 : 49; } else { changeType = 44; } receivers = new HashMap<String, BigInteger>(); receivers.put(address, BigInteger.valueOf(amount)); if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { change_index = idxBIP84PostMixInternal; } else if (changeType == 84) { change_index = idxBIP84Internal; } else if (changeType == 49) { change_index = idxBIP49Internal; } else { change_index = idxBIP44Internal; } // if possible, get UTXO by input 'type': p2pkh, p2sh-p2wpkh or p2wpkh, else get all UTXO long neededAmount = 0L; if (FormatsUtil.getInstance().isValidBech32(address) || account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, 0, UTXOFactory.getInstance().getCountP2WPKH(), 4).longValue(); // Log.d("SendActivity", "segwit:" + neededAmount); } else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, UTXOFactory.getInstance().getCountP2SH_P2WPKH(), 0, 4).longValue(); // Log.d("SendActivity", "segwit:" + neededAmount); } else { neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(UTXOFactory.getInstance().getCountP2PKH(), 0, 0, 4).longValue(); // Log.d("SendActivity", "p2pkh:" + neededAmount); } neededAmount += amount; neededAmount += SamouraiWallet.bDust.longValue(); // get all UTXO List<UTXO> utxos = new ArrayList<>(); if (preselectedUTXOs != null && preselectedUTXOs.size() > 0) { // List<UTXO> utxos = preselectedUTXOs; // sort in descending order by value for (UTXOCoin utxoCoin : preselectedUTXOs) { UTXO u = new UTXO(); List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>(); outs.add(utxoCoin.getOutPoint()); u.setOutpoints(outs); utxos.add(u); } } else { utxos = SpendUtil.getUTXOS(SendActivity.this, address, neededAmount, account); } List<UTXO> utxosP2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllP2WPKH().values()); List<UTXO> utxosP2SH_P2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllP2SH_P2WPKH().values()); List<UTXO> utxosP2PKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllP2PKH().values()); if ((preselectedUTXOs == null || preselectedUTXOs.size() == 0) && account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { utxos = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllPostMix().values()); utxosP2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllPostMix().values()); utxosP2PKH.clear(); utxosP2SH_P2WPKH.clear(); } selectedUTXO = new ArrayList<UTXO>(); long totalValueSelected = 0L; long change = 0L; BigInteger fee = null; boolean canDoBoltzmann = true; // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "balance:" + balance); // insufficient funds if (amount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } if (preselectedUTXOs != null) { canDoBoltzmann = false; if(SPEND_TYPE == SPEND_BOLTZMANN ){ SPEND_TYPE = SPEND_SIMPLE; } } // entire balance (can only be simple spend) else if (amount == balance) { // make sure we are using simple spend SPEND_TYPE = SPEND_SIMPLE; canDoBoltzmann = false; // Log.d("SendActivity", "amount == balance"); // take all utxos, deduct fee selectedUTXO.addAll(utxos); for (UTXO u : selectedUTXO) { totalValueSelected += u.getValue(); } // Log.d("SendActivity", "balance:" + balance); // Log.d("SendActivity", "total value selected:" + totalValueSelected); } else { ; } org.apache.commons.lang3.tuple.Pair<ArrayList<MyTransactionOutPoint>, ArrayList<TransactionOutput>> pair = null; if (SPEND_TYPE == SPEND_RICOCHET) { if(AppUtil.getInstance(getApplicationContext()).isOfflineMode()){ Toast.makeText(getApplicationContext(),"You won't able to compose ricochet when you're on offline mode",Toast.LENGTH_SHORT).show(); return false; } boolean samouraiFeeViaBIP47 = false; if (BIP47Meta.getInstance().getOutgoingStatus(BIP47Meta.strSamouraiDonationPCode) == BIP47Meta.STATUS_SENT_CFM) { samouraiFeeViaBIP47 = true; } ricochetJsonObj = RicochetMeta.getInstance(SendActivity.this).script(amount, FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue(), address, 4, strPCode, samouraiFeeViaBIP47, ricochetStaggeredDelivery.isChecked(), account); if (ricochetJsonObj != null) { try { long totalAmount = ricochetJsonObj.getLong("total_spend"); if (totalAmount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); ricochetHopsSwitch.setChecked(false); return false; } long hop0Fee = ricochetJsonObj.getJSONArray("hops").getJSONObject(0).getLong("fee"); long perHopFee = ricochetJsonObj.getJSONArray("hops").getJSONObject(0).getLong("fee_per_hop"); long ricochetFee = hop0Fee + (RicochetMeta.defaultNbHops * perHopFee); if (selectedCahootsType == SelectCahootsType.type.NONE) { tvTotalFee.setText(Coin.valueOf(ricochetFee).toPlainString().concat(" BTC")); } else { tvTotalFee.setText("__"); } ricochetMessage = getText(R.string.ricochet_spend1) + " " + address + " " + getText(R.string.ricochet_spend2) + " " + Coin.valueOf(totalAmount).toPlainString() + " " + getText(R.string.ricochet_spend3); btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue((double) totalAmount)).concat(" BTC"))); return true; } catch (JSONException je) { return false; } } return true; } else if (SPEND_TYPE == SPEND_BOLTZMANN) { Log.d("SendActivity", "needed amount:" + neededAmount); List<UTXO> _utxos1 = null; List<UTXO> _utxos2 = null; long valueP2WPKH = UTXOFactory.getInstance().getTotalP2WPKH(); long valueP2SH_P2WPKH = UTXOFactory.getInstance().getTotalP2SH_P2WPKH(); long valueP2PKH = UTXOFactory.getInstance().getTotalP2PKH(); if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { valueP2WPKH = UTXOFactory.getInstance().getTotalPostMix(); valueP2SH_P2WPKH = 0L; valueP2PKH = 0L; utxosP2SH_P2WPKH.clear(); utxosP2PKH.clear(); } Log.d("SendActivity", "value P2WPKH:" + valueP2WPKH); Log.d("SendActivity", "value P2SH_P2WPKH:" + valueP2SH_P2WPKH); Log.d("SendActivity", "value P2PKH:" + valueP2PKH); boolean selectedP2WPKH = false; boolean selectedP2SH_P2WPKH = false; boolean selectedP2PKH = false; if ((valueP2WPKH > (neededAmount * 2)) && account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { Log.d("SendActivity", "set 1 P2WPKH 2x"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if ((valueP2WPKH > (neededAmount * 2)) && FormatsUtil.getInstance().isValidBech32(address)) { Log.d("SendActivity", "set 1 P2WPKH 2x"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if (!FormatsUtil.getInstance().isValidBech32(address) && (valueP2SH_P2WPKH > (neededAmount * 2)) && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { Log.d("SendActivity", "set 1 P2SH_P2WPKH 2x"); _utxos1 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } else if (!FormatsUtil.getInstance().isValidBech32(address) && (valueP2PKH > (neededAmount * 2)) && !Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { Log.d("SendActivity", "set 1 P2PKH 2x"); _utxos1 = utxosP2PKH; selectedP2PKH = true; } else if (valueP2WPKH > (neededAmount * 2)) { Log.d("SendActivity", "set 1 P2WPKH 2x"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if (valueP2SH_P2WPKH > (neededAmount * 2)) { Log.d("SendActivity", "set 1 P2SH_P2WPKH 2x"); _utxos1 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } else if (valueP2PKH > (neededAmount * 2)) { Log.d("SendActivity", "set 1 P2PKH 2x"); _utxos1 = utxosP2PKH; selectedP2PKH = true; } else { ; } if (_utxos1 == null || _utxos1.size() == 0) { if (valueP2SH_P2WPKH > neededAmount) { Log.d("SendActivity", "set 1 P2SH_P2WPKH"); _utxos1 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } else if (valueP2WPKH > neededAmount) { Log.d("SendActivity", "set 1 P2WPKH"); _utxos1 = utxosP2WPKH; selectedP2WPKH = true; } else if (valueP2PKH > neededAmount) { Log.d("SendActivity", "set 1 P2PKH"); _utxos1 = utxosP2PKH; selectedP2PKH = true; } else { ; } } if (_utxos1 != null && _utxos1.size() > 0) { if (!selectedP2SH_P2WPKH && valueP2SH_P2WPKH > neededAmount) { Log.d("SendActivity", "set 2 P2SH_P2WPKH"); _utxos2 = utxosP2SH_P2WPKH; selectedP2SH_P2WPKH = true; } if (!selectedP2SH_P2WPKH && !selectedP2WPKH && valueP2WPKH > neededAmount) { Log.d("SendActivity", "set 2 P2WPKH"); _utxos2 = utxosP2WPKH; selectedP2WPKH = true; } if (!selectedP2SH_P2WPKH && !selectedP2WPKH && !selectedP2PKH && valueP2PKH > neededAmount) { Log.d("SendActivity", "set 2 P2PKH"); _utxos2 = utxosP2PKH; selectedP2PKH = true; } else { ; } } if ((_utxos1 == null || _utxos1.size() == 0) && (_utxos2 == null || _utxos2.size() == 0)) { // can't do boltzmann, revert to SPEND_SIMPLE canDoBoltzmann = false; SPEND_TYPE = SPEND_SIMPLE; } else { Log.d("SendActivity", "boltzmann spend"); Collections.shuffle(_utxos1); if (_utxos2 != null && _utxos2.size() > 0) { Collections.shuffle(_utxos2); } // boltzmann spend (STONEWALL) pair = SendFactory.getInstance(SendActivity.this).boltzmann(_utxos1, _utxos2, BigInteger.valueOf(amount), address, account); if (pair == null) { // can't do boltzmann, revert to SPEND_SIMPLE canDoBoltzmann = false; restoreChangeIndexes(); SPEND_TYPE = SPEND_SIMPLE; } else { canDoBoltzmann = true; } } } else { ; } if (SPEND_TYPE == SPEND_SIMPLE && amount == balance && preselectedUTXOs == null) { // do nothing, utxo selection handles above ; } // simple spend (less than balance) else if (SPEND_TYPE == SPEND_SIMPLE) { List<UTXO> _utxos = utxos; // sort in ascending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); Collections.reverse(_utxos); // get smallest 1 UTXO > than spend + fee + dust for (UTXO u : _utxos) { Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(u.getOutpoints())); if (u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 2).longValue())) { selectedUTXO.add(u); totalValueSelected += u.getValue(); Log.d("SendActivity", "spend type:" + SPEND_TYPE); Log.d("SendActivity", "single output"); Log.d("SendActivity", "amount:" + amount); Log.d("SendActivity", "value selected:" + u.getValue()); Log.d("SendActivity", "total value selected:" + totalValueSelected); Log.d("SendActivity", "nb inputs:" + u.getOutpoints().size()); break; } } if (selectedUTXO.size() == 0) { // sort in descending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); int selected = 0; int p2pkh = 0; int p2sh_p2wpkh = 0; int p2wpkh = 0; // get largest UTXOs > than spend + fee + dust for (UTXO u : _utxos) { selectedUTXO.add(u); totalValueSelected += u.getValue(); selected += u.getOutpoints().size(); // Log.d("SendActivity", "value selected:" + u.getValue()); // Log.d("SendActivity", "total value selected/threshold:" + totalValueSelected + "/" + (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 2).longValue())); Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector<MyTransactionOutPoint>(u.getOutpoints())); p2pkh += outpointTypes.getLeft(); p2sh_p2wpkh += outpointTypes.getMiddle(); p2wpkh += outpointTypes.getRight(); if (totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, 2).longValue())) { Log.d("SendActivity", "spend type:" + SPEND_TYPE); Log.d("SendActivity", "multiple outputs"); Log.d("SendActivity", "amount:" + amount); Log.d("SendActivity", "total value selected:" + totalValueSelected); Log.d("SendActivity", "nb inputs:" + selected); break; } } } } else if (pair != null) { selectedUTXO.clear(); receivers.clear(); long inputAmount = 0L; long outputAmount = 0L; for (MyTransactionOutPoint outpoint : pair.getLeft()) { UTXO u = new UTXO(); List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>(); outs.add(outpoint); u.setOutpoints(outs); totalValueSelected += u.getValue(); selectedUTXO.add(u); inputAmount += u.getValue(); } for (TransactionOutput output : pair.getRight()) { try { Script script = new Script(output.getScriptBytes()); if (Bech32Util.getInstance().isP2WPKHScript(Hex.toHexString(output.getScriptBytes()))) { receivers.put(Bech32Util.getInstance().getAddressFromScript(script), BigInteger.valueOf(output.getValue().longValue())); } else { receivers.put(script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), BigInteger.valueOf(output.getValue().longValue())); } outputAmount += output.getValue().longValue(); } catch (Exception e) { Toast.makeText(SendActivity.this, R.string.error_bip126_output, Toast.LENGTH_SHORT).show(); return false; } } fee = BigInteger.valueOf(inputAmount - outputAmount); } else { Toast.makeText(SendActivity.this, R.string.cannot_select_utxo, Toast.LENGTH_SHORT).show(); return false; } if (selectedUTXO.size() > 0) { // estimate fee for simple spend, already done if boltzmann if (SPEND_TYPE == SPEND_SIMPLE) { List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>(); for (UTXO utxo : selectedUTXO) { outpoints.addAll(utxo.getOutpoints()); } Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(outpoints)); if (amount == balance) { fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 1); amount -= fee.longValue(); receivers.clear(); receivers.put(address, BigInteger.valueOf(amount)); // fee sanity check restoreChangeIndexes(); Transaction tx = SendFactory.getInstance(SendActivity.this).makeTransaction(account, outpoints, receivers); tx = SendFactory.getInstance(SendActivity.this).signTransaction(tx, account); byte[] serialized = tx.bitcoinSerialize(); Log.d("SendActivity", "size:" + serialized.length); Log.d("SendActivity", "vsize:" + tx.getVirtualTransactionSize()); Log.d("SendActivity", "fee:" + fee.longValue()); if ((tx.hasWitness() && (fee.longValue() < tx.getVirtualTransactionSize())) || (!tx.hasWitness() && (fee.longValue() < serialized.length))) { Toast.makeText(SendActivity.this, R.string.insufficient_fee, Toast.LENGTH_SHORT).show(); return false; } } else { fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 2); } } Log.d("SendActivity", "spend type:" + SPEND_TYPE); Log.d("SendActivity", "amount:" + amount); Log.d("SendActivity", "total value selected:" + totalValueSelected); Log.d("SendActivity", "fee:" + fee.longValue()); Log.d("SendActivity", "nb inputs:" + selectedUTXO.size()); change = totalValueSelected - (amount + fee.longValue()); // Log.d("SendActivity", "change:" + change); if (change > 0L && change < SamouraiWallet.bDust.longValue() && SPEND_TYPE == SPEND_SIMPLE) { MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.change_is_dust) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } return false; } _change = change; final BigInteger _fee = fee; String dest = null; if (strPCode != null && strPCode.length() > 0) { dest = BIP47Meta.getInstance().getDisplayLabel(strPCode); } else { dest = address; } strCannotDoBoltzmann = ""; if (SendAddressUtil.getInstance().get(address) == 1) { strPrivacyWarning = getString(R.string.send_privacy_warning) + "\n\n"; } else { strPrivacyWarning = ""; } if(SPEND_TYPE == SPEND_BOLTZMANN){ sendTransactionDetailsView.enableStonewall(canDoBoltzmann); sendTransactionDetailsView.getStoneWallSwitch().setChecked(canDoBoltzmann); }else{ sendTransactionDetailsView.enableStonewall(false); } if (!canDoBoltzmann) { restoreChangeIndexes(); if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { strCannotDoBoltzmann = getString(R.string.boltzmann_cannot) + "\n\n"; } } if(account== WhirlpoolConst.WHIRLPOOL_POSTMIX_ACCOUNT){ if(SPEND_TYPE == SPEND_SIMPLE){ strCannotDoBoltzmann = getString(R.string.boltzmann_cannot) + "\n\n"; } } message = strCannotDoBoltzmann + strPrivacyWarning + "Send " + Coin.valueOf(amount).toPlainString() + " to " + dest + " (fee:" + Coin.valueOf(_fee.longValue()).toPlainString() + ")?\n"; if (selectedCahootsType == SelectCahootsType.type.NONE) { tvTotalFee.setText(String.format(Locale.ENGLISH, "%.8f", getBtcValue(fee.doubleValue())).concat(" BTC")); calculateTransactionSize(_fee); } else { tvTotalFee.setText("__"); } double value = Double.parseDouble(String.valueOf(_fee.add(BigInteger.valueOf(amount)))); btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue(value))).concat(" BTC")); switch (selectedCahootsType) { case NONE: { sendTransactionDetailsView.showStonewallx1Layout(null); // for ricochet entropy will be 0 always if (SPEND_TYPE == SPEND_RICOCHET) { break; } if (receivers.size() <= 1) { sendTransactionDetailsView.setEntropyBarStoneWallX1ZeroBits(); break; } if (receivers.size() > 8) { sendTransactionDetailsView.setEntropyBarStoneWallX1(null); break; } CalculateEntropy(selectedUTXO, receivers) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<TxProcessorResult>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(TxProcessorResult entropyResult) { sendTransactionDetailsView.setEntropyBarStoneWallX1(entropyResult); } @Override public void onError(Throwable e) { sendTransactionDetailsView.setEntropyBarStoneWallX1(null); e.printStackTrace(); } @Override public void onComplete() { } }); break; } default: { switch (selectedCahootsType.getCahootsType()) { case STONEWALLX2: sendTransactionDetailsView.showStonewallX2Layout(selectedCahootsType.getCahootsMode(), getParticipantLabel(),1000); btnSend.setBackgroundResource(R.drawable.button_blue); btnSend.setText(getString(R.string.begin_stonewallx2)); break; case STOWAWAY: sendTransactionDetailsView.showStowawayLayout(selectedCahootsType.getCahootsMode(), getParticipantLabel(), null, 1000); btnSend.setBackgroundResource(R.drawable.button_blue); btnSend.setText(getString(R.string.begin_stowaway)); break; default: btnSend.setBackgroundResource(R.drawable.button_green); btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue((double) amount))).concat(" BTC")); } } } return true; } return false; } private String getParticipantLabel() { return strPcodeCounterParty != null ? BIP47Meta.getInstance().getDisplayLabel(strPcodeCounterParty) : null; } private void setButtonForStowaway(boolean prepare) { if (prepare) { // Sets view with stowaway message // also hides overlay push icon from button sendTransactionDetailsView.showStowawayLayout(selectedCahootsType.getCahootsMode(), getParticipantLabel(), null, 1000); btnSend.setBackgroundResource(R.drawable.button_blue); btnSend.setText(getString(R.string.begin_stowaway)); sendTransactionDetailsView.getTransactionReview().findViewById(R.id.transaction_push_icon).setVisibility(View.INVISIBLE); btnSend.setPadding(0, 0, 0, 0); } else { // resets the changes made for stowaway int paddingDp = 12; float density = getResources().getDisplayMetrics().density; int paddingPixel = (int)(paddingDp * density); btnSend.setBackgroundResource(R.drawable.button_green); sendTransactionDetailsView.getTransactionReview().findViewById(R.id.transaction_push_icon).setVisibility(View.VISIBLE); btnSend.setPadding(0,paddingPixel,0,0); } } private void initiateSpend() { if (CahootsMode.MANUAL.equals(selectedCahootsType.getCahootsMode())) { // Cahoots manual Intent intent = ManualCahootsActivity.createIntentSender(this, account, selectedCahootsType.getCahootsType(), amount, address); startActivity(intent); return; } if (CahootsMode.SOROBAN.equals(selectedCahootsType.getCahootsMode())) { // choose Cahoots counterparty Intent intent = SorobanMeetingSendActivity.createIntent(getApplicationContext(), account, selectedCahootsType.getCahootsType(), amount, address, strPcodeCounterParty); startActivity(intent); return; } if (SPEND_TYPE == SPEND_RICOCHET) { progressBar.setVisibility(View.VISIBLE); Disposable disposable = setUpRicochetFees() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(() -> { prepareSpend(); progressBar.setVisibility(View.INVISIBLE); ricochetSpend(ricochetStaggeredDelivery.isChecked()); }, er -> { progressBar.setVisibility(View.INVISIBLE); Toast.makeText(this,"Error ".concat(er.getMessage()),Toast.LENGTH_LONG).show(); }); compositeDisposables.add(disposable); return; } MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(SendActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); final CheckBox cbShowAgain; if (strPrivacyWarning.length() > 0) { cbShowAgain = new CheckBox(SendActivity.this); cbShowAgain.setText(R.string.do_not_repeat_sent_to); cbShowAgain.setChecked(false); builder.setView(cbShowAgain); } else { cbShowAgain = null; } builder.setCancelable(false); builder.setPositiveButton(R.string.yes, (dialog, whichButton) -> { final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for (UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } // add change if (_change > 0L) { if (SPEND_TYPE == SPEND_SIMPLE) { if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix(), AddressFactory.CHANGE_CHAIN, AddressFactory.getInstance(SendActivity.this).getHighestPostChangeIdx()).getBech32AsString(); receivers.put(change_address, BigInteger.valueOf(_change)); } else if (changeType == 84) { String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getBech32AsString(); receivers.put(change_address, BigInteger.valueOf(_change)); } else if (changeType == 49) { String change_address = BIP49Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString(); receivers.put(change_address, BigInteger.valueOf(_change)); } else { String change_address = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddressAt(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx()).getAddressString(); receivers.put(change_address, BigInteger.valueOf(_change)); } } else if (SPEND_TYPE == SPEND_BOLTZMANN) { // do nothing, change addresses included ; } else { ; } } SendParams.getInstance().setParams(outPoints, receivers, strPCode, SPEND_TYPE, _change, changeType, account, address, strPrivacyWarning.length() > 0, cbShowAgain != null ? cbShowAgain.isChecked() : false, amount, change_index ); Intent _intent = new Intent(SendActivity.this, TxAnimUIActivity.class); startActivity(_intent); }); builder.setNegativeButton(R.string.no, (dialog, whichButton) -> SendActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // btSend.setActivated(true); // btSend.setClickable(true); // dialog.dismiss(); } })); builder.create().show(); } private void ricochetSpend(boolean staggered) { MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(ricochetMessage) .setCancelable(false) .setPositiveButton(R.string.yes, (dialog, whichButton) -> { dialog.dismiss(); if (staggered) { // Log.d("SendActivity", "Ricochet staggered:" + ricochetJsonObj.toString()); try { if (ricochetJsonObj.has("hops")) { JSONArray hops = ricochetJsonObj.getJSONArray("hops"); if (hops.getJSONObject(0).has("nTimeLock")) { JSONArray nLockTimeScript = new JSONArray(); for (int i = 0; i < hops.length(); i++) { JSONObject hopObj = hops.getJSONObject(i); int seq = i; long locktime = hopObj.getLong("nTimeLock"); String hex = hopObj.getString("tx"); JSONObject scriptObj = new JSONObject(); scriptObj.put("hop", i); scriptObj.put("nlocktime", locktime); scriptObj.put("tx", hex); nLockTimeScript.put(scriptObj); } JSONObject nLockTimeObj = new JSONObject(); nLockTimeObj.put("script", nLockTimeScript); // Log.d("SendActivity", "Ricochet nLockTime:" + nLockTimeObj.toString()); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); String url = WebUtil.getAPIUrl(SendActivity.this); url += "pushtx/schedule"; try { String result = ""; if (TorManager.INSTANCE.isRequired()) { result = WebUtil.getInstance(SendActivity.this).tor_postURL(url, nLockTimeObj, null); } else { result = WebUtil.getInstance(SendActivity.this).postURL("application/json", url, nLockTimeObj.toString()); } // Log.d("SendActivity", "Ricochet staggered result:" + result); JSONObject resultObj = new JSONObject(result); if (resultObj.has("status") && resultObj.getString("status").equalsIgnoreCase("ok")) { Toast.makeText(SendActivity.this, R.string.ricochet_nlocktime_ok, Toast.LENGTH_LONG).show(); finish(); } else { Toast.makeText(SendActivity.this, R.string.ricochet_nlocktime_ko, Toast.LENGTH_LONG).show(); finish(); } } catch (Exception e) { Log.d("SendActivity", e.getMessage()); Toast.makeText(SendActivity.this, R.string.ricochet_nlocktime_ko, Toast.LENGTH_LONG).show(); finish(); } Looper.loop(); } }).start(); } } } catch (JSONException je) { Log.d("SendActivity", je.getMessage()); } } else { RicochetMeta.getInstance(SendActivity.this).add(ricochetJsonObj); Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivityForResult(intent, RICOCHET); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } } private void backToTransactionView() { if (SPEND_TYPE == SPEND_SIMPLE) SPEND_TYPE = SPEND_BOLTZMANN; //Revert to default selectedUTXO = new ArrayList<>(); receivers = new HashMap<>(); amountViewSwitcher.showPrevious(); sendTransactionDetailsView.showTransaction(); hideMenus(false); } private void calculateTransactionSize(BigInteger _fee) { Disposable disposable = Single.fromCallable(() -> { final List<MyTransactionOutPoint> outPoints = new ArrayList<>(); for (UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } HashMap<String, BigInteger> _receivers = SerializationUtils.clone(receivers); // add change if (_change > 0L) { if (SPEND_TYPE == SPEND_SIMPLE) { if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) { String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix(), AddressFactory.CHANGE_CHAIN, AddressFactory.getInstance(SendActivity.this).getHighestPostChangeIdx()).getBech32AsString(); _receivers.put(change_address, BigInteger.valueOf(_change)); } else if (changeType == 84) { String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getBech32AsString(); _receivers.put(change_address, BigInteger.valueOf(_change)); } else if (changeType == 49) { String change_address = BIP49Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString(); _receivers.put(change_address, BigInteger.valueOf(_change)); } else { String change_address = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddressAt(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx()).getAddressString(); _receivers.put(change_address, BigInteger.valueOf(_change)); } } } final Transaction tx = SendFactory.getInstance(getApplication()).makeTransaction(account, outPoints, _receivers); return SendFactory.getInstance(getApplication()).signTransaction(tx, account); }) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((transaction, throwable) -> { if (throwable == null && transaction != null) { decimalFormatSatPerByte.setDecimalSeparatorAlwaysShown(false); tvSelectedFeeRate.setText(decimalFormatSatPerByte.format((_fee.doubleValue()) / transaction.getVirtualTransactionSize()).concat(" sat/b")); }else{ tvSelectedFeeRate.setText("_"); } }); compositeDisposables.add(disposable); } @Override public void onBackPressed() { if (sendTransactionDetailsView.isReview()) { backToTransactionView(); } else { super.onBackPressed(); } } private void enableAmount(boolean enable) { btcEditText.setEnabled(enable); satEditText.setEnabled(enable); } private void processScan(String data) { strPCode = null; toAddressEditText.setEnabled(true); address = null; strDestinationBTCAddress = null; if (data.contains("https://bitpay.com")) { MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(this) .setTitle(R.string.app_name) .setMessage(R.string.no_bitpay) .setCancelable(false) .setPositiveButton(R.string.learn_more, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.samouraiwallet.com/post/169222582782/bitpay-qr-codes-are-no-longer-valid-important")); startActivity(intent); } }).setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } return; } if (Cahoots.isCahoots(data.trim())) { try { Intent cahootsIntent = ManualCahootsActivity.createIntentResume(this, account, data.trim()); startActivity(cahootsIntent); } catch (Exception e) { Toast.makeText(this,R.string.cannot_process_cahoots,Toast.LENGTH_SHORT).show(); e.printStackTrace(); } return; } if (FormatsUtil.getInstance().isPSBT(data.trim())) { try { PSBTUtil.getInstance(SendActivity.this).doPSBT(data.trim()); } catch(Exception e) { ; } return; } if (FormatsUtil.getInstance().isValidPaymentCode(data)) { processPCode(data, null); return; } if(data.startsWith("BITCOIN:")) { data = "bitcoin:" + data.substring(8); } if (FormatsUtil.getInstance().isBitcoinUri(data)) { String address = FormatsUtil.getInstance().getBitcoinAddress(data); String amount = FormatsUtil.getInstance().getBitcoinAmount(data); setToAddress(address); if (amount != null) { try { NumberFormat btcFormat = NumberFormat.getInstance(Locale.US); btcFormat.setMaximumFractionDigits(8); btcFormat.setMinimumFractionDigits(1); // setToAddress(btcFormat.format(Double.parseDouble(amount) / 1e8)); btcEditText.setText(btcFormat.format(Double.parseDouble(amount) / 1e8)); } catch (NumberFormatException nfe) { // setToAddress("0.0"); } } final String strAmount = FormatsUtil.formatBTCWithoutUnit(balance); tvMaxAmount.setText(strAmount); try { if (amount != null && Double.parseDouble(amount) != 0.0) { toAddressEditText.setEnabled(false); // selectPaynymBtn.setEnabled(false); // selectPaynymBtn.setAlpha(0.5f); // Toast.makeText(this, R.string.no_edit_BIP21_scan, Toast.LENGTH_SHORT).show(); enableAmount(false); } } catch (NumberFormatException nfe) { enableAmount(true); } } else if (FormatsUtil.getInstance().isValidBitcoinAddress(data)) { if (FormatsUtil.getInstance().isValidBech32(data)) { setToAddress(data.toLowerCase()); } else { setToAddress(data); } } else if (data.contains("?")) { String pcode = data.substring(0, data.indexOf("?")); // not valid BIP21 but seen often enough if (pcode.startsWith("bitcoin: pcode = pcode.substring(10); } if (pcode.startsWith("bitcoin:")) { pcode = pcode.substring(8); } if (FormatsUtil.getInstance().isValidPaymentCode(pcode)) { processPCode(pcode, data.substring(data.indexOf("?"))); } } else { Toast.makeText(this, R.string.scan_error, Toast.LENGTH_SHORT).show(); } validateSpend(); } private void processPCode(String pcode, String meta) { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { setBalance(); } }, 2000); if (FormatsUtil.getInstance().isValidPaymentCode(pcode)) { if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_CFM) { try { PaymentCode _pcode = new PaymentCode(pcode); PaymentAddress paymentAddress = BIP47Util.getInstance(this).getSendAddress(_pcode, BIP47Meta.getInstance().getOutgoingIdx(pcode)); if (BIP47Meta.getInstance().getSegwit(pcode)) { SegwitAddress segwitAddress = new SegwitAddress(paymentAddress.getSendECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); strDestinationBTCAddress = segwitAddress.getBech32AsString(); } else { strDestinationBTCAddress = paymentAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } strPCode = _pcode.toString(); setToAddress(BIP47Meta.getInstance().getDisplayLabel(strPCode)); toAddressEditText.setEnabled(false); validateSpend(); } catch (Exception e) { Toast.makeText(this, R.string.error_payment_code, Toast.LENGTH_SHORT).show(); } } else { // Toast.makeText(SendActivity.this, "Payment must be added and notification tx sent", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(this, PayNymDetailsActivity.class); intent.putExtra("pcode", pcode); intent.putExtra("label", ""); if (meta != null && meta.startsWith("?") && meta.length() > 1) { meta = meta.substring(1); if (meta.length() > 0) { String _meta = null; Map<String, String> map = new HashMap<String, String>(); meta.length(); try { _meta = URLDecoder.decode(meta, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } map = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(_meta); intent.putExtra("label", map.containsKey("title") ? map.get("title").trim() : ""); } } if (!openedPaynym) { startActivity(intent); openedPaynym = true; } } } else { Toast.makeText(this, R.string.invalid_payment_code, Toast.LENGTH_SHORT).show(); } } private boolean validateSpend() { boolean isValid = false; boolean insufficientFunds = false; double btc_amount = 0.0; String strBTCAddress = getToAddress(); if (strBTCAddress.startsWith("bitcoin:")) { setToAddress(strBTCAddress.substring(8)); } setToAddress(strBTCAddress); try { btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } final double dAmount = btc_amount; // Log.i("SendFragment", "amount entered (converted):" + dAmount); final long amount = (long) (Math.round(dAmount * 1e8)); Log.i("SendFragment", "amount entered (converted to long):" + amount); Log.i("SendFragment", "balance:" + balance); if (amount > balance) { insufficientFunds = true; } if (selectedCahootsType != SelectCahootsType.type.NONE) { totalMinerFeeLayout.setVisibility(View.INVISIBLE); } else { totalMinerFeeLayout.setVisibility(View.VISIBLE); } if (selectedCahootsType.getCahootsType() == CahootsType.STOWAWAY && !insufficientFunds && amount != 0) { enableReviewButton(true); return true; } // Log.i("SendFragment", "insufficient funds:" + insufficientFunds); if (amount >= SamouraiWallet.bDust.longValue() && FormatsUtil.getInstance().isValidBitcoinAddress(getToAddress())) { isValid = true; } else if (amount >= SamouraiWallet.bDust.longValue() && strDestinationBTCAddress != null && FormatsUtil.getInstance().isValidBitcoinAddress(strDestinationBTCAddress)) { isValid = true; } else { isValid = false; } if (insufficientFunds) { Toast.makeText(this, getString(R.string.insufficient_funds), Toast.LENGTH_SHORT).show(); } if (!isValid || insufficientFunds) { enableReviewButton(false); return false; } else { enableReviewButton(true); return true; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else if (resultCode == Activity.RESULT_OK && requestCode == RICOCHET) { ; } else if (resultCode == Activity.RESULT_CANCELED && requestCode == RICOCHET) { ; } else { ; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.send_menu, menu); if (account != 0) { menu.findItem(R.id.action_batch).setVisible(false); menu.findItem(R.id.action_ricochet).setVisible(false); menu.findItem(R.id.action_empty_ricochet).setVisible(false); } if(preselectedUTXOs!=null){ menu.findItem(R.id.action_batch).setVisible(false); } if (account == WhirlpoolMeta.getInstance(getApplication()).getWhirlpoolPostmix()) { MenuItem item = menu.findItem(R.id.action_send_menu_account); item.setVisible(true); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); item.setActionView(createTag("POST-MIX")); } 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(); if (item.getItemId() == android.R.id.home) { this.onBackPressed(); return true; } if (item.getItemId() == R.id.select_paynym) { PaynymSelectModalFragment paynymSelectModalFragment = PaynymSelectModalFragment.newInstance(code -> processPCode(code, null),getString(R.string.paynym),false); paynymSelectModalFragment.show(getSupportFragmentManager(), "paynym_select"); return true; } // noinspection SimplifiableIfStatement if (id == R.id.action_scan_qr) { doScan(); } else if (id == R.id.action_ricochet) { Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivity(intent); } else if (id == R.id.action_empty_ricochet) { emptyRicochetQueue(); } else if (id == R.id.action_utxo) { doUTXO(); } else if (id == R.id.action_fees) { doFees(); } else if (id == R.id.action_batch) { doBatchSpend(); } else if (id == R.id.action_support) { doSupport(); } else { ; } return super.onOptionsItemSelected(item); } private void emptyRicochetQueue() { RicochetMeta.getInstance(this).setLastRicochet(null); RicochetMeta.getInstance(this).empty(); new Thread(new Runnable() { @Override public void run() { try { PayloadUtil.getInstance(SendActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(SendActivity.this).getGUID() + AccessFactory.getInstance(SendActivity.this).getPIN())); } catch (Exception e) { ; } } }).start(); } private void doScan() { CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet(); cameraFragmentBottomSheet.show(getSupportFragmentManager(), cameraFragmentBottomSheet.getTag()); cameraFragmentBottomSheet.setQrCodeScanListener(code -> { cameraFragmentBottomSheet.dismissAllowingStateLoss(); processScan(code); }); } private void doSupport() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/section/8-sending-bitcoin")); startActivity(intent); } private void doUTXO() { Intent intent = new Intent(SendActivity.this, UTXOSActivity.class); if (account != 0) { intent.putExtra("_account", account); } startActivity(intent); } private void doBatchSpend() { Intent intent = new Intent(SendActivity.this, BatchSpendActivity.class); startActivity(intent); } private void doFees() { SuggestedFee highFee = FeeUtil.getInstance().getHighFee(); SuggestedFee normalFee = FeeUtil.getInstance().getNormalFee(); SuggestedFee lowFee = FeeUtil.getInstance().getLowFee(); String message = getText(R.string.current_fee_selection) + " " + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_hi_fee_value) + " " + (highFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_mid_fee_value) + " " + (normalFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_lo_fee_value) + " " + (lowFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, (dialog, whichButton) -> dialog.dismiss()); if (!isFinishing()) { dlg.show(); } } private void saveChangeIndexes() { idxBIP84PostMixInternal = AddressFactory.getInstance(SendActivity.this).getHighestPostChangeIdx(); idxBIP84Internal = BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); idxBIP49Internal = BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); idxBIP44Internal = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx(); } private void restoreChangeIndexes() { AddressFactory.getInstance(SendActivity.this).setHighestPostChangeIdx(idxBIP84PostMixInternal); BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(idxBIP84Internal); BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(idxBIP49Internal); HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(idxBIP44Internal); } private Observable<TxProcessorResult> CalculateEntropy(ArrayList<UTXO> selectedUTXO, HashMap<String, BigInteger> receivers) { return Observable.create(emitter -> { Map<String, Long> inputs = new HashMap<>(); Map<String, Long> outputs = new HashMap<>(); for (Map.Entry<String, BigInteger> mapEntry : receivers.entrySet()) { String toAddress = mapEntry.getKey(); BigInteger value = mapEntry.getValue(); outputs.put(toAddress, value.longValue()); } for (int i = 0; i < selectedUTXO.size(); i++) { inputs.put(stubAddress[i], selectedUTXO.get(i).getValue()); } TxProcessor txProcessor = new TxProcessor(BoltzmannSettings.MAX_DURATION_DEFAULT, BoltzmannSettings.MAX_TXOS_DEFAULT); Txos txos = new Txos(inputs, outputs); TxProcessorResult result = txProcessor.processTx(txos, 0.005f, TxosLinkerOptionEnum.PRECHECK, TxosLinkerOptionEnum.LINKABILITY, TxosLinkerOptionEnum.MERGE_INPUTS); emitter.onNext(result); }); } }
package io.github.arpankapoor.country; import android.support.annotation.NonNull; import com.google.i18n.phonenumbers.PhoneNumberUtil; import java.io.Serializable; import java.util.Locale; public class Country implements Comparable<Country>, Serializable { private static final long serialVersionUID = 8116297477768564397L; private String name; private String isoCode; private int callingCode; public Country(String isoCode) { setIsoCode(isoCode.toUpperCase()); setName(new Locale("", getIsoCode()).getDisplayCountry()); setCallingCode(PhoneNumberUtil.getInstance().getCountryCodeForRegion(getIsoCode())); } @Override public String toString() { return name + " (+" + callingCode + ")"; } public int getCallingCode() { return callingCode; } public void setCallingCode(int callingCode) { this.callingCode = callingCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsoCode() { return isoCode; } public void setIsoCode(String isoCode) { this.isoCode = isoCode; } @Override public int compareTo(@NonNull Country another) { return this.name.compareTo(another.name); } }
package jp.blanktar.ruumusic; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ArrayAdapter; import android.widget.Toast; import android.widget.AdapterView; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.app.Activity; import android.view.Menu; public class PlaylistFragment extends Fragment { private ArrayAdapter<String> adapter; public File current; private final Stack<DirectoryCache> directoryCache = new Stack<>(); private DirectoryCache currentCache; private class DirectoryCache { public final File path; public final ArrayList<String> files = new ArrayList<>(); public int selection = 0; public DirectoryCache(File path) { this.path = path; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_playlist, container, false); adapter = new ArrayAdapter<>(view.getContext(), R.layout.list_item); final ListView lv = (ListView)view.findViewById(R.id.playlist); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { File file = new File(current, (String) lv.getItemAtPosition(position)); if (file.isDirectory()) { changeDir(file); } else { changeMusic(file.getPath()); } } }); SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity()); if(savedInstanceState == null) { changeDir(new File(preference.getString("root_directory", "/"))); }else{ String currentPath = savedInstanceState.getString("CURRENT_PATH"); if(currentPath != null) { changeDir(new File(currentPath)); }else { changeDir(new File(preference.getString("root_directory", "/"))); } } return view; } @Override public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putString("CURRENT_PATH", current.getPath()); } public void updateTitle(Activity activity) { if(current == null) { activity.setTitle(""); }else{ String newtitle = current.getPath(); SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(activity); String rootDirectory = preference.getString("root_directory", "/"); if (newtitle.equals(rootDirectory)) { newtitle = "/"; } else { newtitle = newtitle.substring(rootDirectory.length()); if (!newtitle.startsWith("/")) { newtitle = "/" + newtitle; } } activity.setTitle(newtitle); } } private void updateTitle() { updateTitle(getActivity()); } public void updateRoot() { updateTitle(); updateMenu(); changeDir(current); } private void changeDir(File dir){ try { dir = dir.getCanonicalFile(); }catch(IOException e) { } SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity()); String rootDirectory = preference.getString("root_directory", "/"); File rootfile = new File(rootDirectory); if(!dir.equals(rootfile) && !dir.getPath().startsWith(rootfile.getPath())) { Toast.makeText(getActivity(), String.format(getString(R.string.out_of_root), dir.getPath()), Toast.LENGTH_LONG).show(); }else if(!dir.isDirectory()) { Toast.makeText(getActivity(), String.format(getString(R.string.is_not_directory), dir.getPath()), Toast.LENGTH_LONG).show(); }else if(!directoryCache.empty() && directoryCache.peek().path.equals(dir)) { currentCache = directoryCache.pop(); current = dir; if(((MainActivity)getActivity()).getCurrentPage() == 1) { updateTitle(); } adapter.clear(); if(current.getParentFile() != null && !current.equals(rootfile)) { adapter.add("../"); } for(String file: currentCache.files) { adapter.add(file); } ((ListView) getActivity().findViewById(R.id.playlist)).setSelection(currentCache.selection); updateMenu(); }else{ File[] files = dir.listFiles(); if(files == null) { Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), dir.getPath()), Toast.LENGTH_LONG).show(); }else { if(!directoryCache.empty() && !currentCache.path.equals(dir.getParentFile())){ while(!directoryCache.empty()) { directoryCache.pop(); } }else if(currentCache != null) { currentCache.selection = ((ListView) getActivity().findViewById(R.id.playlist)).getFirstVisiblePosition(); directoryCache.push(currentCache); } currentCache = new DirectoryCache(dir); current = dir; if(current.getPath().equals("")) { current = new File(rootDirectory); } if(((MainActivity)getActivity()).getCurrentPage() == 1) { updateTitle(); } Arrays.sort(files); adapter.clear(); if(current.getParentFile() != null && !current.equals(rootfile)) { adapter.add("../"); } String before = ""; for (File file : files) { String name = file.getName(); if(name.length() > 0 && name.charAt(0) != '.') { if (file.isDirectory()) { adapter.add(name + "/"); currentCache.files.add(name + "/"); }else if(FileTypeUtil.isSupported(file.getName())) { name = FileTypeUtil.stripExtension(name); if(name != null && !name.equals(before)) { adapter.add(name); currentCache.files.add(name); before = name; } } } } ListView lv = (ListView)getActivity().findViewById(R.id.playlist); if(lv != null) { lv.setSelection(0); } updateMenu(); } } } public void updateMenu(MainActivity activity) { Menu menu = activity.menu; if (menu != null) { SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(activity); File rootDirectory = new File(preference.getString("root_directory", "/")); menu.findItem(R.id.action_set_root).setVisible(!rootDirectory.equals(current)); menu.findItem(R.id.action_unset_root).setVisible(!rootDirectory.equals(new File("/"))); } } private void updateMenu() { updateMenu((MainActivity)getActivity()); } private void changeMusic(String file) { Intent intent = new Intent(getActivity(), RuuService.class); intent.setAction("RUU_PLAY"); intent.putExtra("path", file); getActivity().startService(intent); ((MainActivity)getActivity()).moveToPlayer(); } public boolean onBackKey() { SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity()); if(current.equals(new File(preference.getString("root_directory", "/")))) { return false; }else{ changeDir(current.getParentFile()); return true; } } }
package jp.co.dwango.cbb.db.test; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.webkit.ConsoleMessage; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.Toast; import org.json.JSONArray; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import jp.co.dwango.cbb.db.DataBus; import jp.co.dwango.cbb.db.DataBusHandler; import jp.co.dwango.cbb.db.WebViewDataBus; public class MainActivity extends AppCompatActivity { @TargetApi(Build.VERSION_CODES.KITKAT) @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // KITKAT Chrome if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) { WebView.setWebContentsDebuggingEnabled(true); } setContentView(R.layout.activity_main); WebView webView = (WebView) findViewById(R.id.web_view); assert webView != null; DataBus.logging(true); // WebView webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { Log.d("CrossBorderBridge-js", consoleMessage.message() + " (src=" + consoleMessage.sourceId() + ", line=" + consoleMessage.lineNumber() + ")"); return super.onConsoleMessage(consoleMessage); } }); // WebViewDataBusWebView final WebViewDataBus dataBus = new WebViewDataBus(this, webView, true); // WebView(JavaScript) final DataBusHandler handler = new DataBusHandler() { @Override public void onReceive(JSONArray data) { Log.d("CrossBorderBridge-java", "received-from-js: " + data.toString()); Toast.makeText(MainActivity.this, data.toString(), Toast.LENGTH_SHORT).show(); } }; findViewById(R.id.native_button_add).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dataBus.addHandler(handler); } }); findViewById(R.id.native_button_remove).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dataBus.removeHandler(handler); } }); findViewById(R.id.native_button_send).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dataBus.send(new JSONArray().put("test%10%20%30test").put(2525).put(true)); } }); findViewById(R.id.native_button_destroy).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dataBus.destroy(); } }); // WebView String html = loadTextFromAsset("html/index.html"); webView.loadDataWithBaseURL("", html.replace("$(WEB-VIEW-DATA-BUS)", dataBus.getInjectJavaScript()), "text/html", "UTF-8", null); } // assets private String loadTextFromAsset(String path) { InputStream is = null; BufferedReader br = null; StringBuilder result = new StringBuilder(16384); try { is = getAssets().open(path); br = new BufferedReader(new InputStreamReader(is)); String str; while ((str = br.readLine()) != null) { result.append(str).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { if (null != is) try { is.close(); } catch (IOException e) { e.printStackTrace(); } if (null != br) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return result.toString(); } }
package mx.citydevs.hackcdmx; import android.app.ProgressDialog; import android.content.DialogInterface; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.Locale; import mx.citydevs.hackcdmx.adapters.OfficerListViewAdapter; import mx.citydevs.hackcdmx.beans.Officer; import mx.citydevs.hackcdmx.database.DBHelper; import mx.citydevs.hackcdmx.dialogues.Dialogues; import mx.citydevs.hackcdmx.httpconnection.HttpConnection; import mx.citydevs.hackcdmx.parser.GsonParser; public class OfficersActivity extends ActionBarActivity { private String TAG_CLASS = OfficersActivity.class.getSimpleName(); DBHelper BD = null; SQLiteDatabase bd = null; public static int LOCAL = 0; public static int CONSULTA = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_officers); setSupportActionBar(); getOfficersData(LOCAL); } protected void setSupportActionBar() { Toolbar mToolbar = (Toolbar) findViewById(R.id.actionbar); mToolbar.setTitle(getResources().getString(R.string.app_name)); mToolbar.setTitleTextColor(getResources().getColor(R.color.colorAppBlue)); mToolbar.getBackground().setAlpha(255); mToolbar.setBackgroundColor(getResources().getColor(R.color.colorWhite)); ImageView actionbarIcon = (ImageView) mToolbar.findViewById(R.id.actionbar_icon); actionbarIcon.setVisibility(View.GONE); TextView actionbarTitle = (TextView) mToolbar.findViewById(R.id.actionbar_title); actionbarTitle.setTextColor(getResources().getColor(R.color.colorAppBlue)); ImageView actionbar_reload = (ImageView)mToolbar.findViewById(R.id.actionbar_reload); actionbar_reload.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { getOfficersData(CONSULTA); } }); setSupportActionBar(mToolbar); getSupportActionBar().setElevation(5); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void initUI(ArrayList<Officer> listOfficers) { ListView lvOfficers = (ListView) findViewById(R.id.officers_lv); ArrayList<Officer> newList = new ArrayList(); for (Officer officer : listOfficers) { if (officer.getPlaca() != null) newList.add(officer); } final OfficerListViewAdapter adapter = new OfficerListViewAdapter(this, newList); lvOfficers.setAdapter(adapter); final EditText actvOfficers = (EditText) findViewById(R.id.officers_et_officers); actvOfficers.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { String text = actvOfficers.getText().toString().toLowerCase(Locale.getDefault()); adapter.filter(text); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } private void getOfficersData(int val) { String cops= null; try { BD = new DBHelper(OfficersActivity.this); bd = BD.loadDataBase(OfficersActivity.this, BD); cops = BD.getPolicias(bd); } catch (IOException e1) { e1.printStackTrace(); } if(cops != null && val != CONSULTA){ Log.d("**************", "local"); llenaCops(cops); }else{ Log.d("**************", "consulta"); GetOfficersPublicationsAsyncTask task = new GetOfficersPublicationsAsyncTask(); task.execute(); } } private class GetOfficersPublicationsAsyncTask extends AsyncTask<String, String, String> { private ProgressDialog dialog; public GetOfficersPublicationsAsyncTask() {} @Override protected void onPreExecute() { dialog = new ProgressDialog(OfficersActivity.this); dialog.setMessage(getResources().getString(R.string.getdata_loading_officers)); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(true); dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); dialog.show(); } @Override protected String doInBackground(String... params) { String result = HttpConnection.GET(HttpConnection.OFFICERS); BD.seCops(bd,result); return result; } @Override protected void onPostExecute(String result) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } if (result != null) { llenaCops(result); } } } /** * llena el lista con array de policias * @param result */ public void llenaCops(String result){ try { ArrayList<Officer> listOfficers = (ArrayList<Officer>) GsonParser.getOfficerListFromJSON(result); if (listOfficers != null) { initUI(listOfficers); } } catch (Exception e) { e.printStackTrace(); } BD.close(); } }
package org.webrtc; import android.test.ActivityTestCase; import android.test.suitebuilder.annotation.SmallTest; import java.nio.ByteBuffer; import java.util.Random; import android.opengl.EGL14; import android.opengl.Matrix; import android.opengl.GLES20; public class GlRectDrawerTest extends ActivityTestCase { // Resolution of the test image. private static final int WIDTH = 16; private static final int HEIGHT = 16; // Seed for random pixel creation. private static final int SEED = 42; // When comparing pixels, allow some slack for float arithmetic and integer rounding. final float MAX_DIFF = 1.0f; private static float normalizedByte(byte b) { return (b & 0xFF) / 255.0f; } private static float saturatedConvert(float c) { return 255.0f * Math.max(0, Math.min(c, 1)); } // Assert RGB ByteBuffers are pixel perfect identical. private static void assertEquals(int width, int height, ByteBuffer actual, ByteBuffer expected) { actual.rewind(); expected.rewind(); assertEquals(actual.remaining(), width * height * 3); assertEquals(expected.remaining(), width * height * 3); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { final int actualR = actual.get() & 0xFF; final int actualG = actual.get() & 0xFF; final int actualB = actual.get() & 0xFF; final int expectedR = expected.get() & 0xFF; final int expectedG = expected.get() & 0xFF; final int expectedB = expected.get() & 0xFF; if (actualR != expectedR || actualG != expectedG || actualB != expectedB) { fail("ByteBuffers of size " + width + "x" + height + " not equal at position " + "(" + x + ", " + y + "). Expected color (R,G,B): " + "(" + expectedR + ", " + expectedG + ", " + expectedB + ")" + " but was: " + "(" + actualR + ", " + actualG + ", " + actualB + ")."); } } } } // Convert RGBA ByteBuffer to RGB ByteBuffer. private static ByteBuffer stripAlphaChannel(ByteBuffer rgbaBuffer) { rgbaBuffer.rewind(); assertEquals(rgbaBuffer.remaining() % 4, 0); final int numberOfPixels = rgbaBuffer.remaining() / 4; final ByteBuffer rgbBuffer = ByteBuffer.allocateDirect(numberOfPixels * 3); while (rgbaBuffer.hasRemaining()) { // Copy RGB. for (int channel = 0; channel < 3; ++channel) { rgbBuffer.put(rgbaBuffer.get()); } // Drop alpha. rgbaBuffer.get(); } return rgbBuffer; } @SmallTest public void testRgbRendering() throws Exception { // Create EGL base with a pixel buffer as display output. final EglBase eglBase = new EglBase(EGL14.EGL_NO_CONTEXT, EglBase.ConfigType.PIXEL_BUFFER); eglBase.createPbufferSurface(WIDTH, HEIGHT); eglBase.makeCurrent(); // Create RGB byte buffer plane with random content. final ByteBuffer rgbPlane = ByteBuffer.allocateDirect(WIDTH * HEIGHT * 3); final Random random = new Random(SEED); random.nextBytes(rgbPlane.array()); // Upload the RGB byte buffer data as a texture. final int rgbTexture = GlUtil.generateTexture(GLES20.GL_TEXTURE_2D); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, rgbTexture); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGB, WIDTH, HEIGHT, 0, GLES20.GL_RGB, GLES20.GL_UNSIGNED_BYTE, rgbPlane); GlUtil.checkNoGLES2Error("glTexImage2D"); // Draw the RGB frame onto the pixel buffer. final GlRectDrawer drawer = new GlRectDrawer(); final float[] identityMatrix = new float[16]; Matrix.setIdentityM(identityMatrix, 0); drawer.drawRgb(rgbTexture, identityMatrix); // Download the pixels in the pixel buffer as RGBA. Not all platforms support RGB, e.g. Nexus 9. final ByteBuffer rgbaData = ByteBuffer.allocateDirect(WIDTH * HEIGHT * 4); GLES20.glReadPixels(0, 0, WIDTH, HEIGHT, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, rgbaData); GlUtil.checkNoGLES2Error("glReadPixels"); // Assert rendered image is pixel perfect to source RGB. assertEquals(WIDTH, HEIGHT, stripAlphaChannel(rgbaData), rgbPlane); drawer.release(); GLES20.glDeleteTextures(1, new int[] {rgbTexture}, 0); eglBase.release(); } @SmallTest public void testYuvRendering() throws Exception { // Create EGL base with a pixel buffer as display output. EglBase eglBase = new EglBase(EGL14.EGL_NO_CONTEXT, EglBase.ConfigType.PIXEL_BUFFER); eglBase.createPbufferSurface(WIDTH, HEIGHT); eglBase.makeCurrent(); // Create YUV byte buffer planes with random content. final ByteBuffer[] yuvPlanes = new ByteBuffer[3]; final Random random = new Random(SEED); for (int i = 0; i < 3; ++i) { yuvPlanes[i] = ByteBuffer.allocateDirect(WIDTH * HEIGHT); random.nextBytes(yuvPlanes[i].array()); } // Generate 3 texture ids for Y/U/V. final int yuvTextures[] = new int[3]; for (int i = 0; i < 3; i++) { yuvTextures[i] = GlUtil.generateTexture(GLES20.GL_TEXTURE_2D); } // Upload the YUV byte buffer data as textures. for (int i = 0; i < 3; ++i) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yuvTextures[i]); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, WIDTH, HEIGHT, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, yuvPlanes[i]); GlUtil.checkNoGLES2Error("glTexImage2D"); } // Draw the YUV frame onto the pixel buffer. final GlRectDrawer drawer = new GlRectDrawer(); final float[] texMatrix = new float[16]; Matrix.setIdentityM(texMatrix, 0); drawer.drawYuv(yuvTextures, texMatrix); // Download the pixels in the pixel buffer as RGBA. Not all platforms support RGB, e.g. Nexus 9. final ByteBuffer data = ByteBuffer.allocateDirect(WIDTH * HEIGHT * 4); GLES20.glReadPixels(0, 0, WIDTH, HEIGHT, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, data); GlUtil.checkNoGLES2Error("glReadPixels"); // Compare the YUV data with the RGBA result. for (int y = 0; y < HEIGHT; ++y) { for (int x = 0; x < WIDTH; ++x) { // YUV color space. Y in [0, 1], UV in [-0.5, 0.5]. The constants are taken from the YUV // fragment shader code in GlRectDrawer. final float y_luma = normalizedByte(yuvPlanes[0].get()); final float u_chroma = normalizedByte(yuvPlanes[1].get()) - 0.5f; final float v_chroma = normalizedByte(yuvPlanes[2].get()) - 0.5f; // Expected color in unrounded RGB [0.0f, 255.0f]. final float expectedRed = saturatedConvert(y_luma + 1.403f * v_chroma); final float expectedGreen = saturatedConvert(y_luma - 0.344f * u_chroma - 0.714f * v_chroma); final float expectedBlue = saturatedConvert(y_luma + 1.77f * u_chroma); // Actual color in RGB8888. final int actualRed = data.get() & 0xFF; final int actualGreen = data.get() & 0xFF; final int actualBlue = data.get() & 0xFF; final int actualAlpha = data.get() & 0xFF; // Assert rendered image is close to pixel perfect from source YUV. assertTrue(Math.abs(actualRed - expectedRed) < MAX_DIFF); assertTrue(Math.abs(actualGreen - expectedGreen) < MAX_DIFF); assertTrue(Math.abs(actualBlue - expectedBlue) < MAX_DIFF); assertEquals(actualAlpha, 255); } } drawer.release(); GLES20.glDeleteTextures(3, yuvTextures, 0); eglBase.release(); } }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import processing.app.debug.Compiler; import processing.app.debug.Target; import processing.app.helpers.FileUtils; import processing.app.helpers.filefilters.OnlyDirs; import processing.app.tools.ZipDeflater; import processing.core.*; import static processing.app.I18n._; /** * The base class for the main processing application. * Primary role of this class is for platform identification and * general interaction with the system (launching URLs, loading * files and images, etc) that comes from that. */ public class Base { public static final int REVISION = 105; /** This might be replaced by main() if there's a lib/version.txt file. */ static String VERSION_NAME = "0105"; /** Set true if this a proper release rather than a numbered revision. */ static public boolean RELEASE = false; static HashMap<Integer, String> platformNames = new HashMap<Integer, String>(); static { platformNames.put(PConstants.WINDOWS, "windows"); platformNames.put(PConstants.MACOSX, "macosx"); platformNames.put(PConstants.LINUX, "linux"); } static HashMap<String, Integer> platformIndices = new HashMap<String, Integer>(); static { platformIndices.put("windows", PConstants.WINDOWS); platformIndices.put("macosx", PConstants.MACOSX); platformIndices.put("linux", PConstants.LINUX); } static Platform platform; static private boolean commandLine; // A single instance of the preferences window Preferences preferencesFrame; // set to true after the first time the menu is built. // so that the errors while building don't show up again. boolean builtOnce; static File buildFolder; // these are static because they're used by Sketch static private File examplesFolder; static private File librariesFolder; static private File toolsFolder; static private File hardwareFolder; static HashSet<File> libraries; // maps imported packages to their library folder static HashMap<String, File> importToLibraryTable; // classpath for all known libraries for p5 // (both those in the p5/libs folder and those with lib subfolders // found in the sketchbook) static public String librariesClassPath; static public HashMap<String, Target> targetsTable; // Location for untitled items static File untitledFolder; // p5 icon for the window // static Image icon; // int editorCount; // Editor[] editors; java.util.List<Editor> editors = Collections.synchronizedList(new ArrayList<Editor>()); // ArrayList editors = Collections.synchronizedList(new ArrayList<Editor>()); Editor activeEditor; static public void main(String args[]) { initPlatform(); //setting environment variables Process p; try{ p = Runtime.getRuntime().exec("export PATH=/usr/local/angstrom/arm/bin:$PATH ; export CROSS_COMPILE=arm-angstrom-linux-gnueabi-"); } catch (IOException e) { p=null; } // run static initialization that grabs all the prefs Preferences.init(null); try { File versionFile = getContentFile("lib/version.txt"); if (versionFile.exists()) { String version = PApplet.loadStrings(versionFile)[0]; if (!version.equals(VERSION_NAME)) { VERSION_NAME = version; RELEASE = true; } } } catch (Exception e) { e.printStackTrace(); } // if (System.getProperty("mrj.version") != null) { // //String jv = System.getProperty("java.version"); // String ov = System.getProperty("os.version"); // if (ov.startsWith("10.5")) { // System.setProperty("apple.laf.useScreenMenuBar", "true"); /* commandLine = false; if (args.length >= 2) { if (args[0].startsWith("--")) { commandLine = true; } } if (PApplet.javaVersion < 1.5f) { //System.err.println("no way man"); Base.showError("Need to install Java 1.5", "This version of Processing requires \n" + "Java 1.5 or later to run properly.\n" + "Please visit java.com to upgrade.", null); } */ // // Set the look and feel before opening the window // try { // platform.setLookAndFeel(); // } catch (Exception e) { // System.err.println("Non-fatal error while setting the Look & Feel."); // System.err.println("The error message follows, however Processing should run fine."); // System.err.println(e.getMessage()); // //e.printStackTrace(); // Use native popups so they don't look so crappy on osx JPopupMenu.setDefaultLightWeightPopupEnabled(false); // Don't put anything above this line that might make GUI, // because the platform has to be inited properly first. // Make sure a full JDK is installed //initRequirements(); // setup the theme coloring fun Theme.init(); // Set the look and feel before opening the window try { platform.setLookAndFeel(); } catch (Exception e) { String mess = e.getMessage(); if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) { System.err.println(_("Non-fatal error while setting the Look & Feel.")); System.err.println(_("The error message follows, however Arduino should run fine.")); System.err.println(mess); } } // Create a location for untitled sketches untitledFolder = createTempFolder("untitled"); untitledFolder.deleteOnExit(); new Base(args); } static protected void setCommandLine() { commandLine = true; } static protected boolean isCommandLine() { return commandLine; } static protected void initPlatform() { try { Class<?> platformClass = Class.forName("processing.app.Platform"); if (Base.isMacOS()) { platformClass = Class.forName("processing.app.macosx.Platform"); } else if (Base.isWindows()) { platformClass = Class.forName("processing.app.windows.Platform"); } else if (Base.isLinux()) { platformClass = Class.forName("processing.app.linux.Platform"); } platform = (Platform) platformClass.newInstance(); } catch (Exception e) { Base.showError(_("Problem Setting the Platform"), _("An unknown error occurred while trying to load\n" + "platform-specific code for your machine."), e); } } static protected void initRequirements() { try { Class.forName("com.sun.jdi.VirtualMachine"); } catch (ClassNotFoundException cnfe) { Base.showPlatforms(); Base.showError(_("Please install JDK 1.5 or later"), _("Arduino requires a full JDK (not just a JRE)\n" + "to run. Please install JDK 1.5 or later.\n" + "More information can be found in the reference."), cnfe); } } public Base(String[] args) { platform.init(this); // Get paths for the libraries and examples in the Processing folder //String workingDirectory = System.getProperty("user.dir"); examplesFolder = getContentFile("examples"); librariesFolder = getContentFile("libraries"); toolsFolder = getContentFile("tools"); // Get the sketchbook path, and make sure it's set properly String sketchbookPath = Preferences.get("sketchbook.path"); // If a value is at least set, first check to see if the folder exists. // If it doesn't, warn the user that the sketchbook folder is being reset. if (sketchbookPath != null) { File skechbookFolder = new File(sketchbookPath); if (!skechbookFolder.exists()) { Base.showWarning(_("Sketchbook folder disappeared"), _("The sketchbook folder no longer exists.\n" + "Arduino will switch to the default sketchbook\n" + "location, and create a new sketchbook folder if\n" + "necessary. Arduino will then stop talking about\n" + "himself in the third person."), null); sketchbookPath = null; } } // If no path is set, get the default sketchbook folder for this platform if (sketchbookPath == null) { File defaultFolder = getDefaultSketchbookFolder(); Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath()); if (!defaultFolder.exists()) { defaultFolder.mkdirs(); } } targetsTable = new HashMap<String, Target>(); loadHardware(getHardwareFolder()); loadHardware(getSketchbookHardwareFolder()); // Check if there were previously opened sketches to be restored boolean opened = restoreSketches(); // Check if any files were passed in on the command line for (int i = 0; i < args.length; i++) { String path = args[i]; // Fix a problem with systems that use a non-ASCII languages. Paths are // being passed in with 8.3 syntax, which makes the sketch loader code // unhappy, since the sketch folder naming doesn't match up correctly. if (isWindows()) { try { File file = new File(args[i]); path = file.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } } if (handleOpen(path) != null) { opened = true; } } // Create a new empty window (will be replaced with any files to be opened) if (!opened) { handleNew(); } // check for updates if (Preferences.getBoolean("update.check")) { new UpdateCheck(this); } } /** * Post-constructor setup for the editor area. Loads the last * sketch that was used (if any), and restores other Editor settings. * The complement to "storePreferences", this is called when the * application is first launched. */ protected boolean restoreSketches() { // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); boolean windowPositionValid = true; if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical int screenW = Preferences.getInteger("last.screen.width"); int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { windowPositionValid = false; } /* int windowX = Preferences.getInteger("last.window.x"); int windowY = Preferences.getInteger("last.window.y"); if ((windowX < 0) || (windowY < 0) || (windowX > screenW) || (windowY > screenH)) { windowPositionValid = false; } */ } else { windowPositionValid = false; } // Iterate through all sketches that were open last time p5 was running. // If !windowPositionValid, then ignore the coordinates found for each. // Save the sketch path and window placement for each open sketch int count = Preferences.getInteger("last.sketch.count"); int opened = 0; for (int i = 0; i < count; i++) { String path = Preferences.get("last.sketch" + i + ".path"); int[] location; if (windowPositionValid) { String locationStr = Preferences.get("last.sketch" + i + ".location"); location = PApplet.parseInt(PApplet.split(locationStr, ',')); } else { location = nextEditorLocation(); } // If file did not exist, null will be returned for the Editor if (handleOpen(path, location) != null) { opened++; } } return (opened > 0); } /** * Store list of sketches that are currently open. * Called when the application is quitting and documents are still open. */ protected void storeSketches() { // Save the width and height of the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Preferences.setInteger("last.screen.width", screen.width); Preferences.setInteger("last.screen.height", screen.height); String untitledPath = untitledFolder.getAbsolutePath(); // Save the sketch path and window placement for each open sketch int index = 0; for (Editor editor : editors) { String path = editor.getSketch().getMainFilePath(); // In case of a crash, save untitled sketches if they contain changes. // (Added this for release 0158, may not be a good idea.) if (path.startsWith(untitledPath) && !editor.getSketch().isModified()) { continue; } Preferences.set("last.sketch" + index + ".path", path); int[] location = editor.getPlacement(); String locationStr = PApplet.join(PApplet.str(location), ","); Preferences.set("last.sketch" + index + ".location", locationStr); index++; } Preferences.setInteger("last.sketch.count", index); } // If a sketch is untitled on quit, may need to store the new name // rather than the location from the temp folder. protected void storeSketchPath(Editor editor, int index) { String path = editor.getSketch().getMainFilePath(); String untitledPath = untitledFolder.getAbsolutePath(); if (path.startsWith(untitledPath)) { path = ""; } Preferences.set("last.sketch" + index + ".path", path); } /* public void storeSketch(Editor editor) { int index = -1; for (int i = 0; i < editorCount; i++) { if (editors[i] == editor) { index = i; break; } } if (index == -1) { System.err.println("Problem storing sketch " + editor.sketch.name); } else { String path = editor.sketch.getMainFilePath(); Preferences.set("last.sketch" + index + ".path", path); } } */ // Because of variations in native windowing systems, no guarantees about // changes to the focused and active Windows can be made. Developers must // never assume that this Window is the focused or active Window until this // Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event. protected void handleActivated(Editor whichEditor) { activeEditor = whichEditor; // set the current window to be the console that's getting output EditorConsole.setEditor(activeEditor); } protected int[] nextEditorLocation() { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int defaultWidth = Preferences.getInteger("editor.window.width.default"); int defaultHeight = Preferences.getInteger("editor.window.height.default"); if (activeEditor == null) { // If no current active editor, use default placement return new int[] { (screen.width - defaultWidth) / 2, (screen.height - defaultHeight) / 2, defaultWidth, defaultHeight, 0 }; } else { // With a currently active editor, open the new window // using the same dimensions, but offset slightly. synchronized (editors) { final int OVER = 50; // In release 0160, don't //location = activeEditor.getPlacement(); Editor lastOpened = editors.get(editors.size() - 1); int[] location = lastOpened.getPlacement(); // Just in case the bounds for that window are bad location[0] += OVER; location[1] += OVER; if (location[0] == OVER || location[2] == OVER || location[0] + location[2] > screen.width || location[1] + location[3] > screen.height) { // Warp the next window to a randomish location on screen. return new int[] { (int) (Math.random() * (screen.width - defaultWidth)), (int) (Math.random() * (screen.height - defaultHeight)), defaultWidth, defaultHeight, 0 }; } return location; } } } boolean breakTime = false; String[] months = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; /** * Handle creating a sketch folder, return its base .pde file * or null if the operation was canceled. * @param shift whether shift is pressed, which will invert prompt setting * @param noPrompt disable prompt, no matter the setting */ protected String createNewUntitled() throws IOException { File newbieDir = null; String newbieName = null; // In 0126, untitled sketches will begin in the temp folder, // and then moved to a new location because Save will default to Save As. File sketchbookDir = getSketchbookFolder(); File newbieParentDir = untitledFolder; // Use a generic name like sketch_031008a, the date plus a char int index = 0; //SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd"); //SimpleDateFormat formatter = new SimpleDateFormat("MMMdd"); //String purty = formatter.format(new Date()).toLowerCase(); Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31 int month = cal.get(Calendar.MONTH); // 0..11 String purty = months[month] + PApplet.nf(day, 2); do { if (index == 26) { // In 0159, avoid running past z by sending people outdoors. if (!breakTime) { Base.showWarning(_("Time for a Break"), _("You've reached the limit for auto naming of new sketches\n" + "for the day. How about going for a walk instead?"), null); breakTime = true; } else { Base.showWarning(_("Sunshine"), _("No really, time for some fresh air for you."), null); } return null; } newbieName = "sketch_" + purty + ((char) ('a' + index)); newbieDir = new File(newbieParentDir, newbieName); index++; // Make sure it's not in the temp folder *and* it's not in the sketchbook } while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists()); // Make the directory for the new sketch newbieDir.mkdirs(); // Make an empty pde file File newbieFile = new File(newbieDir, newbieName + ".ino"); new FileOutputStream(newbieFile); // create the file return newbieFile.getAbsolutePath(); } /** * Create a new untitled document in a new sketch window. */ public void handleNew() { try { String path = createNewUntitled(); if (path != null) { Editor editor = handleOpen(path); editor.untitled = true; } } catch (IOException e) { if (activeEditor != null) { activeEditor.statusError(e); } } } /** * Replace the sketch in the current window with a new untitled document. */ public void handleNewReplace() { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); // Actually replace things handleNewReplaceImpl(); } protected void handleNewReplaceImpl() { try { String path = createNewUntitled(); if (path != null) { activeEditor.handleOpenInternal(path); activeEditor.untitled = true; } // return true; } catch (IOException e) { activeEditor.statusError(e); // return false; } } /** * Open a sketch, replacing the sketch in the current window. * @param path Location of the primary pde file for the sketch. */ public void handleOpenReplace(String path) { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); boolean loaded = activeEditor.handleOpenInternal(path); if (!loaded) { // replace the document without checking if that's ok handleNewReplaceImpl(); } } /** * Prompt for a sketch to open, and open it in a new window. */ public void handleOpenPrompt() { // get the frontmost window frame for placing file dialog FileDialog fd = new FileDialog(activeEditor, _("Open an Arduino sketch..."), FileDialog.LOAD); // This was annoying people, so disabled it in 0125. //fd.setDirectory(Preferences.get("sketchbook.path")); //fd.setDirectory(getSketchbookPath()); // Only show .pde files as eligible bachelors fd.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { // TODO this doesn't seem to ever be used. AWESOME. //System.out.println("check filter on " + dir + " " + name); return name.toLowerCase().endsWith(".ino") || name.toLowerCase().endsWith(".pde"); } }); fd.setVisible(true); String directory = fd.getDirectory(); String filename = fd.getFile(); // User canceled selection if (filename == null) return; File inputFile = new File(directory, filename); handleOpen(inputFile.getAbsolutePath()); } /** * Open a sketch in a new window. * @param path Path to the pde file for the sketch in question * @return the Editor object, so that properties (like 'untitled') * can be set by the caller */ public Editor handleOpen(String path) { return handleOpen(path, nextEditorLocation()); } protected Editor handleOpen(String path, int[] location) { // System.err.println("entering handleOpen " + path); File file = new File(path); if (!file.exists()) return null; // System.err.println(" editors: " + editors); // Cycle through open windows to make sure that it's not already open. for (Editor editor : editors) { if (editor.getSketch().getMainFilePath().equals(path)) { editor.toFront(); // System.err.println(" handleOpen: already opened"); return editor; } } // If the active editor window is an untitled, and un-modified document, // just replace it with the file that's being opened. // if (activeEditor != null) { // Sketch activeSketch = activeEditor.sketch; // if (activeSketch.isUntitled() && !activeSketch.isModified()) { // // if it's an untitled, unmodified document, it can be replaced. // // except in cases where a second blank window is being opened. // if (!path.startsWith(untitledFolder.getAbsolutePath())) { // activeEditor.handleOpenUnchecked(path, 0, 0, 0, 0); // return activeEditor; // System.err.println(" creating new editor"); Editor editor = new Editor(this, path, location); // Editor editor = null; // try { // editor = new Editor(this, path, location); // } catch (Exception e) { // e.printStackTrace(); // System.err.flush(); // System.out.flush(); // System.exit(1); // System.err.println(" done creating new editor"); // EditorConsole.systemErr.println(" done creating new editor"); // Make sure that the sketch actually loaded if (editor.getSketch() == null) { // System.err.println("sketch was null, getting out of handleOpen"); return null; // Just walk away quietly } // if (editors == null) { // editors = new Editor[5]; // if (editorCount == editors.length) { // editors = (Editor[]) PApplet.expand(editors); // editors[editorCount++] = editor; editors.add(editor); // if (markedForClose != null) { // Point p = markedForClose.getLocation(); // handleClose(markedForClose, false); // // open the new window in // editor.setLocation(p); // now that we're ready, show the window // (don't do earlier, cuz we might move it based on a window being closed) editor.setVisible(true); // System.err.println("exiting handleOpen"); return editor; } /** * Close a sketch as specified by its editor window. * @param editor Editor object of the sketch to be closed. * @return true if succeeded in closing, false if canceled. */ public boolean handleClose(Editor editor) { // Check if modified // boolean immediate = editors.size() == 1; if (!editor.checkModified()) { return false; } // Close the running window, avoid window boogers with multiple sketches editor.internalCloseRunner(); if (editors.size() == 1) { // For 0158, when closing the last window /and/ it was already an // untitled sketch, just give up and let the user quit. // if (Preferences.getBoolean("sketchbook.closing_last_window_quits") || // (editor.untitled && !editor.getSketch().isModified())) { if (Base.isMacOS()) { Object[] options = { "OK", "Cancel" }; String prompt = _("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Are you sure you want to Quit?</b>" + "<p>Closing the last open sketch will quit Arduino."); int result = JOptionPane.showOptionDialog(editor, prompt, _("Quit"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.NO_OPTION || result == JOptionPane.CLOSED_OPTION) { return false; } } // This will store the sketch count as zero editors.remove(editor); Editor.serialMonitor.closeSerialPort(); storeSketches(); // Save out the current prefs state Preferences.save(); // Since this wasn't an actual Quit event, call System.exit() System.exit(0); } else { // More than one editor window open, // proceed with closing the current window. editor.setVisible(false); editor.dispose(); // for (int i = 0; i < editorCount; i++) { // if (editor == editors[i]) { // for (int j = i; j < editorCount-1; j++) { // editors[j] = editors[j+1]; // editorCount--; // // Set to null so that garbage collection occurs // editors[editorCount] = null; editors.remove(editor); } return true; } /** * Handler for File &rarr; Quit. * @return false if canceled, true otherwise. */ public boolean handleQuit() { // If quit is canceled, this will be replaced anyway // by a later handleQuit() that is not canceled. storeSketches(); Editor.serialMonitor.closeSerialPort(); if (handleQuitEach()) { // make sure running sketches close before quitting for (Editor editor : editors) { editor.internalCloseRunner(); } // Save out the current prefs state Preferences.save(); if (!Base.isMacOS()) { // If this was fired from the menu or an AppleEvent (the Finder), // then Mac OS X will send the terminate signal itself. System.exit(0); } return true; } return false; } /** * Attempt to close each open sketch in preparation for quitting. * @return false if canceled along the way */ protected boolean handleQuitEach() { int index = 0; for (Editor editor : editors) { if (editor.checkModified()) { // Update to the new/final sketch path for this fella storeSketchPath(editor, index); index++; } else { return false; } } return true; } /** * Asynchronous version of menu rebuild to be used on save and rename * to prevent the interface from locking up until the menus are done. */ protected void rebuildSketchbookMenus() { //System.out.println("async enter"); //new Exception().printStackTrace(); SwingUtilities.invokeLater(new Runnable() { public void run() { //System.out.println("starting rebuild"); rebuildSketchbookMenu(Editor.sketchbookMenu); rebuildToolbarMenu(Editor.toolbarMenu); //System.out.println("done with rebuild"); } }); //System.out.println("async exit"); } protected void rebuildToolbarMenu(JMenu menu) { JMenuItem item; menu.removeAll(); //System.out.println("rebuilding toolbar menu"); // Add the single "Open" item item = Editor.newJMenuItem(_("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleOpenPrompt(); } }); menu.add(item); menu.addSeparator(); // Add a list of all sketches and subfolders try { boolean sketches = addSketches(menu, getSketchbookFolder(), true); //boolean sketches = addSketches(menu, getSketchbookFolder()); if (sketches) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); } //System.out.println("rebuilding examples menu"); // Add each of the subfolders of examples directly to the menu try { boolean found = addSketches(menu, examplesFolder, true); if (found) menu.addSeparator(); found = addSketches(menu, getSketchbookLibrariesFolder(), true); if (found) menu.addSeparator(); addSketches(menu, librariesFolder, true); } catch (IOException e) { e.printStackTrace(); } } protected void rebuildSketchbookMenu(JMenu menu) { //System.out.println("rebuilding sketchbook menu"); //new Exception().printStackTrace(); try { menu.removeAll(); addSketches(menu, getSketchbookFolder(), false); //addSketches(menu, getSketchbookFolder()); } catch (IOException e) { e.printStackTrace(); } } public void rebuildImportMenu(JMenu importMenu, final Editor editor) { importMenu.removeAll(); JMenuItem addLibraryMenuItem = new JMenuItem(_("Add Library...")); addLibraryMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.this.handleAddLibrary(editor); Base.this.onBoardOrPortChange(); Base.this.rebuildImportMenu(Editor.importMenu, editor); Base.this.rebuildExamplesMenu(Editor.examplesMenu); } }); importMenu.add(addLibraryMenuItem); importMenu.addSeparator(); // reset the set of libraries libraries = new HashSet<File>(); // reset the table mapping imports to libraries importToLibraryTable = new HashMap<String, File>(); // Add from the "libraries" subfolder in the Processing directory try { addLibraries(importMenu, librariesFolder); } catch (IOException e) { e.printStackTrace(); } // Add libraries found in the sketchbook folder int separatorIndex = importMenu.getItemCount(); try { File sketchbookLibraries = getSketchbookLibrariesFolder(); boolean found = addLibraries(importMenu, sketchbookLibraries); if (found) { JMenuItem contrib = new JMenuItem(_("Contributed")); contrib.setEnabled(false); importMenu.insert(contrib, separatorIndex); importMenu.insertSeparator(separatorIndex); } } catch (IOException e) { e.printStackTrace(); } } public void rebuildExamplesMenu(JMenu menu) { //System.out.println("rebuilding examples menu"); try { menu.removeAll(); boolean found = addSketches(menu, examplesFolder, false); if (found) menu.addSeparator(); found = addSketches(menu, getSketchbookLibrariesFolder(), false); if (found) menu.addSeparator(); addSketches(menu, librariesFolder, false); } catch (IOException e) { e.printStackTrace(); } } public void onBoardOrPortChange() { for (Editor editor : editors) { editor.onBoardOrPortChange(); } } public void rebuildBoardsMenu(JMenu menu, final Editor editor) { //System.out.println("rebuilding boards menu"); menu.removeAll(); ButtonGroup group = new ButtonGroup(); for (Target target : targetsTable.values()) { for (String board : target.getBoards().keySet()) { AbstractAction action = new AbstractAction(target.getBoards().get(board).get("name")) { public void actionPerformed(ActionEvent actionevent) { //System.out.println("Switching to " + target + ":" + board); Preferences.set("target", (String) getValue("target")); Preferences.set("board", (String) getValue("board")); onBoardOrPortChange(); Sketch.buildSettingChanged(); } }; action.putValue("target", target.getName()); action.putValue("board", board); JMenuItem item = new JRadioButtonMenuItem(action); if (target.getName().equals(Preferences.get("target")) && board.equals(Preferences.get("board"))) { item.setSelected(true); } group.add(item); menu.add(item); } } } public void rebuildProgrammerMenu(JMenu menu) { //System.out.println("rebuilding programmer menu"); menu.removeAll(); ButtonGroup group = new ButtonGroup(); for (Target target : targetsTable.values()) { for (String programmer : target.getProgrammers().keySet()) { AbstractAction action = new AbstractAction( target.getProgrammers().get(programmer).get("name")) { public void actionPerformed(ActionEvent actionevent) { Preferences.set("programmer", getValue("target") + ":" + getValue("programmer")); } }; action.putValue("target", target.getName()); action.putValue("programmer", programmer); JMenuItem item = new JRadioButtonMenuItem(action); if (Preferences.get("programmer").equals(target.getName() + ":" + programmer)) { item.setSelected(true); } group.add(item); menu.add(item); } } } /** * Scan a folder recursively, and add any sketches found to the menu * specified. Set the openReplaces parameter to true when opening the sketch * should replace the sketch in the current window, or false when the * sketch should open in a new window. */ protected boolean addSketches(JMenu menu, File folder, final boolean replaceExisting) throws IOException { // skip .DS_Store files, etc (this shouldn't actually be necessary) if (!folder.isDirectory()) return false; String[] list = folder.list(); // If a bad folder or unreadable or whatever, this will come back null if (list == null) return false; // Alphabetize list, since it's not always alpha order Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); //processing.core.PApplet.println("adding sketches " + folder.getAbsolutePath()); //PApplet.println(list); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { String path = e.getActionCommand(); if (new File(path).exists()) { boolean replace = replaceExisting; if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { replace = !replace; } if (replace) { handleOpenReplace(path); } else { handleOpen(path); } } else { showWarning(_("Sketch Does Not Exist"), _("The selected sketch no longer exists.\n" + "You may need to restart Arduino to update\n" + "the sketchbook menu."), null); } } }; // offers no speed improvement //menu.addActionListener(listener); boolean ifound = false; for (int i = 0; i < list.length; i++) { if ((list[i].charAt(0) == '.') || list[i].equals("CVS")) continue; File subfolder = new File(folder, list[i]); if (!subfolder.isDirectory()) continue; File entry = new File(subfolder, list[i] + ".ino"); if (!entry.exists() && (new File(subfolder, list[i] + ".pde")).exists()) { entry = new File(subfolder, list[i] + ".pde"); } // if a .pde file of the same prefix as the folder exists.. if (entry.exists()) { //String sanityCheck = sanitizedName(list[i]); //if (!sanityCheck.equals(list[i])) { if (!Sketch.isSanitaryName(list[i])) { if (!builtOnce) { String complaining = I18n.format( _("The sketch \"{0}\" cannot be used.\n" + "Sketch names must contain only basic letters and numbers\n" + "(ASCII-only with no spaces, " + "and it cannot start with a number).\n" + "To get rid of this message, remove the sketch from\n" + "{1}"), list[i], entry.getAbsolutePath() ); Base.showMessage(_("Ignoring sketch with bad name"), complaining); } continue; } JMenuItem item = new JMenuItem(list[i]); item.addActionListener(listener); item.setActionCommand(entry.getAbsolutePath()); menu.add(item); ifound = true; } else { // don't create an extra menu level for a folder named "examples" if (subfolder.getName().equals("examples")) { boolean found = addSketches(menu, subfolder, replaceExisting); if (found) ifound = true; } else { // not a sketch folder, but maybe a subfolder containing sketches JMenu submenu = new JMenu(list[i]); // needs to be separate var // otherwise would set ifound to false boolean found = addSketches(submenu, subfolder, replaceExisting); //boolean found = addSketches(submenu, subfolder); //, false); if (found) { menu.add(submenu); ifound = true; } } } } return ifound; // actually ignored, but.. } protected boolean addLibraries(JMenu menu, File folder) throws IOException { if (!folder.isDirectory()) return false; String list[] = folder.list(new FilenameFilter() { public boolean accept(File dir, String name) { // skip .DS_Store files, .svn folders, etc if (name.charAt(0) == '.') return false; if (name.equals("CVS")) return false; return (new File(dir, name).isDirectory()); } }); // if a bad folder or something like that, this might come back null if (list == null) return false; // alphabetize list, since it's not always alpha order // replaced hella slow bubble sort with this feller for 0093 Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent event) { String jarPath = event.getActionCommand(); try { activeEditor.getSketch().importLibrary(jarPath); } catch (IOException e) { showWarning(_("Error"), I18n.format("Unable to list header files in {0}", jarPath), e); } } }; boolean ifound = false; for (String potentialName : list) { File subfolder = new File(folder, potentialName); // File libraryFolder = new File(subfolder, "library"); // File libraryJar = new File(libraryFolder, potentialName + ".jar"); // // If a .jar file of the same prefix as the folder exists // // inside the 'library' subfolder of the sketch // if (libraryJar.exists()) { String sanityCheck = Sketch.sanitizeName(potentialName); if (!sanityCheck.equals(potentialName)) { String mess = I18n.format( _("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), potentialName ); Base.showMessage(_("Ignoring bad library name"), mess); continue; } String libraryName = potentialName; // // get the path for all .jar files in this code folder // String libraryClassPath = // Compiler.contentsToClassPath(libraryFolder); // // grab all jars and classes from this folder, // // and append them to the library classpath // librariesClassPath += // File.pathSeparatorChar + libraryClassPath; // // need to associate each import with a library folder // String packages[] = // Compiler.packageListFromClassPath(libraryClassPath); libraries.add(subfolder); try { String packages[] = Compiler.headerListFromIncludePath(subfolder.getAbsolutePath()); for (String pkg : packages) { importToLibraryTable.put(pkg, subfolder); } } catch (IOException e) { showWarning(_("Error"), I18n.format("Unable to list header files in {0}", subfolder), e); } JMenuItem item = new JMenuItem(libraryName); item.addActionListener(listener); item.setActionCommand(subfolder.getAbsolutePath()); menu.add(item); ifound = true; // XXX: DAM: should recurse here so that library folders can be nested // } else { // not a library, but is still a folder, so recurse // JMenu submenu = new JMenu(libraryName); // // needs to be separate var, otherwise would set ifound to false // boolean found = addLibraries(submenu, subfolder); // if (found) { // menu.add(submenu); // ifound = true; } return ifound; } protected void loadHardware(File folder) { if (!folder.isDirectory()) return; String list[] = folder.list(new FilenameFilter() { public boolean accept(File dir, String name) { // skip .DS_Store files, .svn folders, etc if (name.charAt(0) == '.') return false; if (name.equals("CVS")) return false; return (new File(dir, name).isDirectory()); } }); // if a bad folder or something like that, this might come back null if (list == null) return; // alphabetize list, since it's not always alpha order // replaced hella slow bubble sort with this feller for 0093 Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); for (String target : list) { File subfolder = new File(folder, target); targetsTable.put(target, new Target(target, subfolder)); } } /** * Show the About box. */ public void handleAbout() { final Image image = Base.getLibImage("about.jpg", activeEditor); final Window window = new Window(activeEditor) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); g.drawString(Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); int w = image.getWidth(activeEditor); int h = image.getHeight(activeEditor); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h); window.setVisible(true); } /** * Show the Preferences window. */ public void handlePrefs() { if (preferencesFrame == null) preferencesFrame = new Preferences(); preferencesFrame.showFrame(activeEditor); } /** * Get list of platform constants. */ // static public int[] getPlatforms() { // return platforms; // static public int getPlatform() { // String osname = System.getProperty("os.name"); // if (osname.indexOf("Mac") != -1) { // return PConstants.MACOSX; // } else if (osname.indexOf("Windows") != -1) { // return PConstants.WINDOWS; // } else if (osname.equals("Linux")) { // true for the ibm vm // return PConstants.LINUX; // } else { // return PConstants.OTHER; static public Platform getPlatform() { return platform; } static public String getPlatformName() { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { return "macosx"; } else if (osname.indexOf("Windows") != -1) { return "windows"; } else if (osname.equals("Linux")) { // true for the ibm vm return "linux"; } else { return "other"; } } /** * Map a platform constant to its name. * @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX * @return one of "windows", "macosx", or "linux" */ static public String getPlatformName(int which) { return platformNames.get(which); } static public int getPlatformIndex(String what) { Integer entry = platformIndices.get(what); return (entry == null) ? -1 : entry.intValue(); } // These were changed to no longer rely on PApplet and PConstants because // of conflicts that could happen with older versions of core.jar, where // the MACOSX constant would instead read as the LINUX constant. /** * returns true if Processing is running on a Mac OS X machine. */ static public boolean isMacOS() { //return PApplet.platform == PConstants.MACOSX; return System.getProperty("os.name").indexOf("Mac") != -1; } /** * returns true if running on windows. */ static public boolean isWindows() { //return PApplet.platform == PConstants.WINDOWS; return System.getProperty("os.name").indexOf("Windows") != -1; } /** * true if running on linux. */ static public boolean isLinux() { //return PApplet.platform == PConstants.LINUX; return System.getProperty("os.name").indexOf("Linux") != -1; } static public File getSettingsFolder() { File settingsFolder = null; String preferencesPath = Preferences.get("settings.path"); if (preferencesPath != null) { settingsFolder = new File(preferencesPath); } else { try { settingsFolder = platform.getSettingsFolder(); } catch (Exception e) { showError(_("Problem getting data folder"), _("Error getting the Arduino data folder."), e); } } // create the folder if it doesn't exist already if (!settingsFolder.exists()) { if (!settingsFolder.mkdirs()) { showError(_("Settings issues"), _("Arduino cannot run because it could not\n" + "create a folder to store your settings."), null); } } return settingsFolder; } /** * Convenience method to get a File object for the specified filename inside * the settings folder. * For now, only used by Preferences to get the preferences.txt file. * @param filename A file inside the settings folder. * @return filename wrapped as a File object inside the settings folder */ static public File getSettingsFile(String filename) { return new File(getSettingsFolder(), filename); } static public File getBuildFolder() { if (buildFolder == null) { String buildPath = Preferences.get("build.path"); if (buildPath != null) { buildFolder = new File(buildPath); } else { //File folder = new File(getTempFolder(), "build"); //if (!folder.exists()) folder.mkdirs(); buildFolder = createTempFolder("build"); buildFolder.deleteOnExit(); } } return buildFolder; } /** * Get the path to the platform's temporary folder, by creating * a temporary temporary file and getting its parent folder. * <br/> * Modified for revision 0094 to actually make the folder randomized * to avoid conflicts in multi-user environments. (Bug 177) */ static public File createTempFolder(String name) { try { File folder = File.createTempFile(name, null); //String tempPath = ignored.getParent(); //return new File(tempPath); folder.delete(); folder.mkdirs(); return folder; } catch (Exception e) { e.printStackTrace(); } return null; } static public Set<File> getLibraries() { return libraries; } static public String getExamplesPath() { return examplesFolder.getAbsolutePath(); } static public String getLibrariesPath() { return librariesFolder.getAbsolutePath(); } static public File getToolsFolder() { return toolsFolder; } static public String getToolsPath() { return toolsFolder.getAbsolutePath(); } static public File getHardwareFolder() { // calculate on the fly because it's needed by Preferences.init() to find // the boards.txt and programmers.txt preferences files (which happens // before the other folders / paths get cached). return getContentFile("hardware"); } static public String getHardwarePath() { //if(Preferences.get("target") return getHardwareFolder().getAbsolutePath(); } static public String getAvrBasePath() { String path = getHardwarePath() + File.separator + "tools" + File.separator + "avr" + File.separator + "bin" + File.separator; if (Base.isLinux() && !(new File(path)).exists()) { return ""; // use distribution provided avr tools if bundled tools missing } return path; } static public File getBeagleFolder() { return getContentFile("Userspace-Arduino"); } static public String getBeaglePath() { return getBeagleFolder().getAbsolutePath(); } static public File getBeagleLibFolder() { return new File(getBeagleFolder(),"libarduino"); } static public String getBeagleLibPath() { return getBeagleLibFolder().getAbsolutePath(); } static public Target getTarget() { return Base.targetsTable.get(Preferences.get("target")); } static public Map<String, String> getBoardPreferences() { Target target = getTarget(); if (target == null) return new LinkedHashMap(); Map map = target.getBoards(); if (map == null) return new LinkedHashMap(); map = (Map) map.get(Preferences.get("board")); if (map == null) return new LinkedHashMap(); return map; } static public File getSketchbookFolder() { return new File(Preferences.get("sketchbook.path")); } static public File getSketchbookLibrariesFolder() { File libdir = new File(getSketchbookFolder(), "libraries"); if (!libdir.exists()) { try { libdir.mkdirs(); File readme = new File(libdir, "readme.txt"); FileWriter freadme = new FileWriter(readme); freadme.write(_("For information on installing libraries, see: " + "http://arduino.cc/en/Guide/Libraries\n")); freadme.close(); } catch (Exception e) { } } return libdir; } static public String getSketchbookLibrariesPath() { return getSketchbookLibrariesFolder().getAbsolutePath(); } static public File getSketchbookHardwareFolder() { return new File(getSketchbookFolder(), "hardware"); } protected File getDefaultSketchbookFolder() { File sketchbookFolder = null; try { sketchbookFolder = platform.getDefaultSketchbookFolder(); } catch (Exception e) { } if (sketchbookFolder == null) { sketchbookFolder = promptSketchbookLocation(); } // create the folder if it doesn't exist already boolean result = true; if (!sketchbookFolder.exists()) { result = sketchbookFolder.mkdirs(); } if (!result) { showError(_("You forgot your sketchbook"), _("Arduino cannot run because it could not\n" + "create a folder to store your sketchbook."), null); } return sketchbookFolder; } /** * Check for a new sketchbook location. */ static protected File promptSketchbookLocation() { File folder = null; folder = new File(System.getProperty("user.home"), "sketchbook"); if (!folder.exists()) { folder.mkdirs(); return folder; } String prompt = _("Select (or create new) folder for sketches..."); folder = Base.selectFolder(prompt, null, null); if (folder == null) { System.exit(0); } return folder; } /** * Implements the cross-platform headache of opening URLs * TODO This code should be replaced by PApplet.link(), * however that's not a static method (because it requires * an AppletContext when used as an applet), so it's mildly * trickier than just removing this method. */ static public void openURL(String url) { try { platform.openURL(url); } catch (Exception e) { showWarning(_("Problem Opening URL"), I18n.format(_("Could not open the URL\n{0}"), url), e); } } /** * Used to determine whether to disable the "Show Sketch Folder" option. * @return true If a means of opening a folder is known to be available. */ static protected boolean openFolderAvailable() { return platform.openFolderAvailable(); } /** * Implements the other cross-platform headache of opening * a folder in the machine's native file browser. */ static public void openFolder(File file) { try { platform.openFolder(file); } catch (Exception e) { showWarning(_("Problem Opening Folder"), I18n.format(_("Could not open the folder\n{0}"), file.getAbsolutePath()), e); } } static public File selectFolder(String prompt, File folder, Frame frame) { if (Base.isMacOS()) { if (frame == null) frame = new Frame(); //.pack(); FileDialog fd = new FileDialog(frame, prompt, FileDialog.LOAD); if (folder != null) { fd.setDirectory(folder.getParent()); //fd.setFile(folder.getName()); } System.setProperty("apple.awt.fileDialogForDirectories", "true"); fd.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); if (fd.getFile() == null) { return null; } return new File(fd.getDirectory(), fd.getFile()); } else { JFileChooser fc = new JFileChooser(); fc.setDialogTitle(prompt); if (folder != null) { fc.setSelectedFile(folder); } fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returned = fc.showOpenDialog(new JDialog()); if (returned == JFileChooser.APPROVE_OPTION) { return fc.getSelectedFile(); } } return null; } /** * Give this Frame a Processing icon. */ static public void setIcon(Frame frame) { // don't use the low-res icon on Mac OS X; the window should // already have the right icon from the .app file. if (Base.isMacOS()) return; Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE); frame.setIconImage(image); } // someone needs to be slapped //static KeyStroke closeWindowKeyStroke; /** * Return true if the key event was a Ctrl-W or an ESC, * both indicators to close the window. * Use as part of a keyPressed() event handler for frames. */ /* static public boolean isCloseWindowEvent(KeyEvent e) { if (closeWindowKeyStroke == null) { int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); closeWindowKeyStroke = KeyStroke.getKeyStroke('W', modifiers); } return ((e.getKeyCode() == KeyEvent.VK_ESCAPE) || KeyStroke.getKeyStrokeForEvent(e).equals(closeWindowKeyStroke)); } */ /** * Registers key events for a Ctrl-W and ESC with an ActionListener * that will take care of disposing the window. */ static public void registerWindowCloseKeys(JRootPane root, ActionListener disposer) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); stroke = KeyStroke.getKeyStroke('W', modifiers); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); } static public void showReference(String filename) { File referenceFolder = Base.getContentFile("reference"); File referenceFile = new File(referenceFolder, filename); openURL(referenceFile.getAbsolutePath()); } static public void showGettingStarted() { if (Base.isMacOS()) { Base.showReference(_("Guide_MacOSX.html")); } else if (Base.isWindows()) { Base.showReference(_("Guide_Windows.html")); } else { Base.openURL(_("http: } } static public void showReference() { showReference(_("index.html")); } static public void showEnvironment() { showReference(_("Guide_Environment.html")); } static public void showPlatforms() { showReference(_("environment") + File.separator + _("platforms.html")); } static public void showTroubleshooting() { showReference(_("Guide_Troubleshooting.html")); } static public void showFAQ() { showReference(_("FAQ.html")); } /** * "No cookie for you" type messages. Nothing fatal or all that * much of a bummer, but something to notify the user about. */ static public void showMessage(String title, String message) { if (title == null) title = _("Message"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.INFORMATION_MESSAGE); } } /** * Non-fatal error message with optional stack trace side dish. */ static public void showWarning(String title, String message, Exception e) { if (title == null) title = _("Warning"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.WARNING_MESSAGE); } if (e != null) e.printStackTrace(); } /** * Show an error message that's actually fatal to the program. * This is an error that can't be recovered. Use showWarning() * for errors that allow P5 to continue running. */ static public void showError(String title, String message, Throwable e) { if (title == null) title = _("Error"); if (commandLine) { System.err.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.ERROR_MESSAGE); } if (e != null) e.printStackTrace(); System.exit(1); } // incomplete static public int showYesNoCancelQuestion(Editor editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { int result = JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); return result; // if (result == JOptionPane.YES_OPTION) { // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // } else { } else { // Pane formatting adapted from the Quaqua guide JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.CANCEL_OPTION; } else if (result == options[2]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } //if (result == JOptionPane.YES_OPTION) { // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // } else { static public int showYesNoQuestion(Frame editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { return JOptionPane.showConfirmDialog(editor, "<html><body>" + "<b>" + primary + "</b>" + "<br>" + secondary, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } else { // Pane formatting adapted from the Quaqua guide JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>" + primary + "</b>" + "<p>" + secondary + "</p>", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Yes", "No" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } /** * Retrieve a path to something in the Processing folder. Eventually this * may refer to the Contents subfolder of Processing.app, if we bundle things * up as a single .app file with no additional folders. */ // static public String getContentsPath(String filename) { // String basePath = System.getProperty("user.dir"); // /* // // do this later, when moving to .app package // if (PApplet.platform == PConstants.MACOSX) { // basePath = System.getProperty("processing.contents"); // } // */ // return basePath + File.separator + filename; /** * Get a path for something in the Processing lib folder. */ /* static public String getLibContentsPath(String filename) { String libPath = getContentsPath("lib/" + filename); File libDir = new File(libPath); if (libDir.exists()) { return libPath; } // was looking into making this run from Eclipse, but still too much mess // libPath = getContents("build/shared/lib/" + what); // libDir = new File(libPath); // if (libDir.exists()) { // return libPath; // } return null; } */ static public File getContentFile(String name) { String path = System.getProperty("user.dir"); // Get a path to somewhere inside the .app folder if (Base.isMacOS()) { // <key>javaroot</key> // <string>$JAVAROOT</string> String javaroot = System.getProperty("javaroot"); if (javaroot != null) { path = javaroot; } } File working = new File(path); return new File(working, name); } /** * Get an image associated with the current color theme. */ static public Image getThemeImage(String name, Component who) { return getLibImage("theme/" + name, who); } /** * Return an Image object from inside the Processing lib folder. */ static public Image getLibImage(String name, Component who) { Image image = null; Toolkit tk = Toolkit.getDefaultToolkit(); File imageLocation = new File(getContentFile("lib"), name); image = tk.getImage(imageLocation.getAbsolutePath()); MediaTracker tracker = new MediaTracker(who); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { } return image; } /** * Return an InputStream for a file inside the Processing lib folder. */ static public InputStream getLibStream(String filename) throws IOException { return new FileInputStream(new File(getContentFile("lib"), filename)); } /** * Get the number of lines in a file by counting the number of newline * characters inside a String (and adding 1). */ static public int countLines(String what) { int count = 1; for (char c : what.toCharArray()) { if (c == '\n') count++; } return count; } /** * Same as PApplet.loadBytes(), however never does gzip decoding. */ static public byte[] loadBytesRaw(File file) throws IOException { int size = (int) file.length(); FileInputStream input = new FileInputStream(file); byte buffer[] = new byte[size]; int offset = 0; int bytesRead; while ((bytesRead = input.read(buffer, offset, size-offset)) != -1) { offset += bytesRead; if (bytesRead == 0) break; } input.close(); // weren't properly being closed input = null; return buffer; } /** * Read from a file with a bunch of attribute/value pairs * that are separated by = and ignore comments with #. */ static public HashMap<String,String> readSettings(File inputFile) { HashMap<String,String> outgoing = new HashMap<String,String>(); if (!inputFile.exists()) return outgoing; // return empty hash String lines[] = PApplet.loadStrings(inputFile); for (int i = 0; i < lines.length; i++) { int hash = lines[i].indexOf(' String line = (hash == -1) ? lines[i].trim() : lines[i].substring(0, hash).trim(); if (line.length() == 0) continue; int equals = line.indexOf('='); if (equals == -1) { System.err.println("ignoring illegal line in " + inputFile); System.err.println(" " + line); continue; } String attr = line.substring(0, equals).trim(); String valu = line.substring(equals + 1).trim(); outgoing.put(attr, valu); } return outgoing; } static public void copyFile(File sourceFile, File targetFile) throws IOException { InputStream from = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream to = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] buffer = new byte[16 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) { to.write(buffer, 0, bytesRead); } to.flush(); from.close(); from = null; to.close(); to = null; targetFile.setLastModified(sourceFile.lastModified()); } /** * Grab the contents of a file as a string. */ static public String loadFile(File file) throws IOException { String[] contents = PApplet.loadStrings(file); if (contents == null) return null; return PApplet.join(contents, "\n"); } /** * Spew the contents of a String object out to a file. */ static public void saveFile(String str, File file) throws IOException { File temp = File.createTempFile(file.getName(), null, file.getParentFile()); PApplet.saveStrings(temp, new String[] { str }); if (file.exists()) { boolean result = file.delete(); if (!result) { throw new IOException( I18n.format( _("Could not remove old version of {0}"), file.getAbsolutePath() ) ); } } boolean result = temp.renameTo(file); if (!result) { throw new IOException( I18n.format( _("Could not replace {0}"), file.getAbsolutePath() ) ); } } /** * Copy a folder from one place to another. This ignores all dot files and * folders found in the source directory, to avoid copying silly .DS_Store * files and potentially troublesome .svn folders. */ static public void copyDir(File sourceDir, File targetDir) throws IOException { targetDir.mkdirs(); String files[] = sourceDir.list(); for (int i = 0; i < files.length; i++) { // Ignore dot files (.DS_Store), dot folders (.svn) while copying if (files[i].charAt(0) == '.') continue; //if (files[i].equals(".") || files[i].equals("..")) continue; File source = new File(sourceDir, files[i]); File target = new File(targetDir, files[i]); if (source.isDirectory()) { //target.mkdirs(); copyDir(source, target); target.setLastModified(source.lastModified()); } else { copyFile(source, target); } } } /** * Remove all files in a directory and the directory itself. */ static public void removeDir(File dir) { if (dir.exists()) { removeDescendants(dir); if (!dir.delete()) { System.err.println(I18n.format(_("Could not delete {0}"), dir)); } } } /** * Recursively remove all files within a directory, * used with removeDir(), or when the contents of a dir * should be removed, but not the directory itself. * (i.e. when cleaning temp files from lib/build) */ static public void removeDescendants(File dir) { if (!dir.exists()) return; String files[] = dir.list(); for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || files[i].equals("..")) continue; File dead = new File(dir, files[i]); if (!dead.isDirectory()) { if (!Preferences.getBoolean("compiler.save_build_files")) { if (!dead.delete()) { // temporarily disabled System.err.println(I18n.format(_("Could not delete {0}"), dead)); } } } else { removeDir(dead); //dead.delete(); } } } /** * Calculate the size of the contents of a folder. * Used to determine whether sketches are empty or not. * Note that the function calls itself recursively. */ static public int calcFolderSize(File folder) { int size = 0; String files[] = folder.list(); // null if folder doesn't exist, happens when deleting sketch if (files == null) return -1; for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || (files[i].equals("..")) || files[i].equals(".DS_Store")) continue; File fella = new File(folder, files[i]); if (fella.isDirectory()) { size += calcFolderSize(fella); } else { size += (int) fella.length(); } } return size; } /** * Recursively creates a list of all files within the specified folder, * and returns a list of their relative paths. * Ignores any files/folders prefixed with a dot. */ static public String[] listFiles(String path, boolean relative) { return listFiles(new File(path), relative); } static public String[] listFiles(File folder, boolean relative) { String path = folder.getAbsolutePath(); Vector<String> vector = new Vector<String>(); listFiles(relative ? (path + File.separator) : "", path, vector); String outgoing[] = new String[vector.size()]; vector.copyInto(outgoing); return outgoing; } static protected void listFiles(String basePath, String path, Vector<String> vector) { File folder = new File(path); String list[] = folder.list(); if (list == null) return; for (int i = 0; i < list.length; i++) { if (list[i].charAt(0) == '.') continue; File file = new File(path, list[i]); String newPath = file.getAbsolutePath(); if (newPath.startsWith(basePath)) { newPath = newPath.substring(basePath.length()); } vector.add(newPath); if (file.isDirectory()) { listFiles(basePath, newPath, vector); } } } public void handleAddLibrary(Editor editor) { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setDialogTitle(_("Select a zip file or a folder containing the library you'd like to add")); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setFileFilter(new FileNameExtensionFilter(_("ZIP files or folders"), "zip")); Dimension preferredSize = fileChooser.getPreferredSize(); fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200)); int returnVal = fileChooser.showOpenDialog(editor); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File sourceFile = fileChooser.getSelectedFile(); File tmpFolder = null; try { // unpack ZIP if (!sourceFile.isDirectory()) { try { tmpFolder = FileUtils.createTempFolder(); ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder); zipDeflater.deflate(); File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs()); if (foldersInTmpFolder.length != 1) { throw new IOException(_("Zip doesn't contain a library")); } sourceFile = foldersInTmpFolder[0]; } catch (IOException e) { editor.statusError(e); return; } } // is there a valid library? File libFolder = sourceFile; String libName = libFolder.getName(); if (!Sketch.isSanitaryName(libName)) { String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), libName); editor.statusError(mess); return; } // copy folder File destinationFolder = new File(getSketchbookLibrariesFolder(), sourceFile.getName()); if (!destinationFolder.mkdir()) { editor.statusError(I18n.format(_("A library named {0} already exists"), sourceFile.getName())); return; } try { FileUtils.copy(sourceFile, destinationFolder); } catch (IOException e) { editor.statusError(e); return; } editor.statusNotice(_("Library added to your libraries. Check \"Import library\" menu")); } finally { // delete zip created temp folder, if exists FileUtils.recursiveDelete(tmpFolder); } } }
package de.lmu.ifi.dbs.algorithm.clustering.clique; import de.lmu.ifi.dbs.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.algorithm.clustering.Clustering; import de.lmu.ifi.dbs.algorithm.result.clustering.CLIQUEModel; import de.lmu.ifi.dbs.algorithm.result.clustering.ClusteringResult; import de.lmu.ifi.dbs.algorithm.result.clustering.Clusters; import de.lmu.ifi.dbs.data.RealVector; import de.lmu.ifi.dbs.data.SimpleClassLabel; import de.lmu.ifi.dbs.database.Database; import de.lmu.ifi.dbs.math.linearalgebra.Matrix; import de.lmu.ifi.dbs.utilities.Description; import de.lmu.ifi.dbs.utilities.Interval; import de.lmu.ifi.dbs.utilities.Util; import de.lmu.ifi.dbs.utilities.optionhandling.DoubleParameter; import de.lmu.ifi.dbs.utilities.optionhandling.Flag; import de.lmu.ifi.dbs.utilities.optionhandling.IntParameter; import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.utilities.optionhandling.constraints.GreaterConstraint; import de.lmu.ifi.dbs.utilities.optionhandling.constraints.LessConstraint; import de.lmu.ifi.dbs.utilities.optionhandling.constraints.ParameterConstraint; import java.util.*; /** * Implementation of the CLIQUE algorithm, a grid-based algorithm to identify dense clusters * in subspaces of maximum dimensionality.<p> * * The implementation consists of two steps:br> * 1. Identification of subspaces that contain clusters<br> * 2. Identification of clusters<p> * * The third step of the original algorithm (Generation of minimal description * for the clusters) is not (yet) implemented. * * @author Elke Achtert (<a href="mailto:achtert@dbs.ifi.lmu.de">achtert@dbs.ifi.lmu.de</a>) */ public class CLIQUE<V extends RealVector<V, ?>> extends AbstractAlgorithm<V> implements Clustering<V> { /** * Parameter xsi. */ public static final String XSI_P = "xsi"; /** * Description for parameter xsi. */ public static final String XSI_D = "number of intervals (units) in each dimension"; /** * Parameter tau. */ public static final String TAU_P = "tau"; /** * Description for parameter tau. */ public static final String TAU_D = "density threshold for the selectivity of a unit, where the selectivity is" + "the fraction of total feature vectors contained in this unit"; /** * Flag prune. */ public static final String PRUNE_F = "prune"; /** * Description for flag prune. */ public static final String PRUNE_D = "flag indicating that only subspaces with large coverage " + "(i.e. the fraction of the database that is covered by the dense units) " + "are selected, the rest will be pruned, default: no pruning"; /** * Number of units in each dimension. */ private int xsi; /** * Threshold for the selectivity of a unit. */ private double tau; /** * Flag indicating that subspaces with low coverage are pruned. */ private boolean prune; /** * The result of the algorithm; */ private Clusters<V> result; public CLIQUE() { super(); // this.debug = true; //parameter xsi optionHandler.put(new IntParameter(XSI_P, XSI_D, new GreaterConstraint(0))); //parameter tau List<ParameterConstraint<Number>> tauConstraints = new ArrayList<ParameterConstraint<Number>>(); tauConstraints.add(new GreaterConstraint(0)); tauConstraints.add(new LessConstraint(1)); optionHandler.put(new DoubleParameter(TAU_P, TAU_D, tauConstraints)); //flag prune optionHandler.put(new Flag(PRUNE_F, PRUNE_D)); } /** * Returns the result of the algorithm. * * @return the result of the algorithm */ public ClusteringResult<V> getResult() { return result; } /** * Returns a description of the algorithm. * * @return a description of the algorithm */ public Description getDescription() { return new Description("CLIQUE", "Automatic Subspace Clustering of High Dimensional Data for Data Mining Applications", "Grid-based algorithm to identify dense clusters in subspaces of maximum dimensionality. ", "R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan: " + "Automatic Subspace Clustering of High Dimensional Data for Data Mining Applications. " + "In Proc. SIGMOD Conference, Seattle, WA, 1998."); } protected void runInTime(Database<V> database) throws IllegalStateException { Map<CLIQUEModel<V>, Set<Integer>> modelsAndClusters = new HashMap<CLIQUEModel<V>, Set<Integer>>(); // 1. Identification of subspaces that contain clusters if (isVerbose()) { verbose("*** 1. Identification of subspaces that contain clusters ***"); } SortedMap<Integer, SortedSet<CLIQUESubspace<V>>> dimensionToDenseSubspaces = new TreeMap<Integer, SortedSet<CLIQUESubspace<V>>>(); SortedSet<CLIQUESubspace<V>> denseSubspaces = findOneDimensionalDenseSubspaces(database); dimensionToDenseSubspaces.put(0, denseSubspaces); if (isVerbose()) { verbose(" 1-dimensional dense subspaces: " + denseSubspaces.size()); } for (int k = 2; k <= database.dimensionality() && !denseSubspaces.isEmpty(); k++) { denseSubspaces = findDenseSubspaces(database, denseSubspaces); dimensionToDenseSubspaces.put(k - 1, denseSubspaces); if (isVerbose()) { verbose(" " + k + "-dimensional dense subspaces: " + denseSubspaces.size()); } } // 2. Identification of clusters if (isVerbose()) { verbose("\n*** 2. Identification of clusters ***"); } for (Integer dim : dimensionToDenseSubspaces.keySet()) { SortedSet<CLIQUESubspace<V>> subspaces = dimensionToDenseSubspaces.get(dim); Map<CLIQUEModel<V>, Set<Integer>> modelsToClusters = determineClusters(database, subspaces); modelsAndClusters.putAll(modelsToClusters); if (isVerbose()) { verbose(" " + (dim + 1) + "-dimensionional clusters: " + modelsToClusters.size()); } } Integer[][] clusters = new Integer[modelsAndClusters.size()][0]; Iterator<Set<Integer>> valuesIt = modelsAndClusters.values().iterator(); for (int i = 0; i < clusters.length; i++) { Set<Integer> ids = valuesIt.next(); clusters[i] = ids.toArray(new Integer[ids.size()]); } result = new Clusters<V>(clusters, database); // append model Iterator<CLIQUEModel<V>> keysIt = modelsAndClusters.keySet().iterator(); for (int i = 0; i < clusters.length; i++) { SimpleClassLabel label = new SimpleClassLabel(); label.init(result.canonicalClusterLabel(i)); result.appendModel(label, keysIt.next()); } } /** * Sets the parameters xsi, tau and prune additionally to the parameters set * by the super-class' method. * * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[]) */ @Override public String[] setParameters(String[] args) throws ParameterException { String[] remainingParameters = super.setParameters(args); xsi = (Integer) optionHandler.getOptionValue(XSI_P); tau = (Double) optionHandler.getOptionValue(TAU_P); prune = optionHandler.isSet(PRUNE_F); return remainingParameters; } /** * Determines the clusters in the specified dense subspaces. * * @param database the database to run the algorithm on * @param denseSubspaces the dense subspaces * @return the clusters in the specified dense subspaces and the corresponding * cluster models */ private Map<CLIQUEModel<V>, Set<Integer>> determineClusters(Database<V> database, SortedSet<CLIQUESubspace<V>> denseSubspaces) { Map<CLIQUEModel<V>, Set<Integer>> result = new HashMap<CLIQUEModel<V>, Set<Integer>>(); for (CLIQUESubspace<V> subspace : denseSubspaces) { Map<CLIQUEModel<V>, Set<Integer>> clusters = subspace.determineClusters(database); if (debug) { debugFine("Subspace " + subspace + " clusters " + clusters.size()); } result.putAll(clusters); } return result; } /** * Determines the one dimensional dense subspaces and performs * a pruning if this option is chosen. * * @param database the database to run the algorithm on * @return the one dimensional dense subspaces */ private SortedSet<CLIQUESubspace<V>> findOneDimensionalDenseSubspaces(Database<V> database) { SortedSet<CLIQUESubspace<V>> denseSubspaceCandidates = findOneDimensionalDenseSubspaceCandidates(database); if (prune) return pruneDenseSubspaces(denseSubspaceCandidates); return denseSubspaceCandidates; } /** * Determines the k>1 dimensional dense subspaces and performs * a pruning if this option is chosen. * * @param database the database to run the algorithm on * @param denseSubspaces the (k-1)-dimensional dense subspaces * @return the k-dimensional dense subspaces */ private SortedSet<CLIQUESubspace<V>> findDenseSubspaces(Database<V> database, SortedSet<CLIQUESubspace<V>> denseSubspaces) { SortedSet<CLIQUESubspace<V>> denseSubspaceCandidates = findDenseSubspaceCandidates(database, denseSubspaces); if (prune) return pruneDenseSubspaces(denseSubspaceCandidates); return denseSubspaceCandidates; } private Collection<Unit<V>> initOneDimensionalUnits(Database<V> database) { int dimensionality = database.dimensionality(); // initialize minima and maxima double[] minima = new double[dimensionality]; double[] maxima = new double[dimensionality]; for (int d = 0; d < dimensionality; d++) { maxima[d] = -Double.MAX_VALUE; minima[d] = Double.MAX_VALUE; } // update minima and maxima for (Iterator<Integer> it = database.iterator(); it.hasNext();) { V featureVector = database.get(it.next()); updateMinMax(featureVector, minima, maxima); } for (int i = 0; i < maxima.length; i++) { maxima[i] += 0.0001; } // determine the unit length in each dimension double[] unit_lengths = new double[dimensionality]; for (int d = 0; d < dimensionality; d++) { unit_lengths[d] = (maxima[d] - minima[d]) / xsi; } if (debug) { StringBuffer msg = new StringBuffer(); msg.append("\n minima: ").append(Util.format(minima, ", ", 2)); msg.append("\n maxima: ").append(Util.format(maxima, ", ", 2)); msg.append("\n unit lengths: ").append(Util.format(unit_lengths, ", ", 2)); debugFiner(msg.toString()); } // determine the boundaries of the units double[][] unit_bounds = new double[xsi + 1][dimensionality]; for (int x = 0; x <= xsi; x++) { for (int d = 0; d < dimensionality; d++) { if (x < xsi) unit_bounds[x][d] = minima[d] + x * unit_lengths[d]; else unit_bounds[x][d] = maxima[d]; } } if (debug) { StringBuffer msg = new StringBuffer(); msg.append("\n unit bounds ").append(new Matrix(unit_bounds).toString(" ")); debugFiner(msg.toString()); } // build the 1 dimensional units List<Unit<V>> units = new ArrayList<Unit<V>>((xsi * dimensionality)); for (int x = 0; x < xsi; x++) { for (int d = 0; d < dimensionality; d++) { units.add(new Unit<V>(new Interval(d, unit_bounds[x][d], unit_bounds[x + 1][d]))); } } if (debug) { StringBuffer msg = new StringBuffer(); msg.append("\n total number of 1-dim units: ").append(units.size()); debugFiner(msg.toString()); } return units; } /** * Updates the minima and maxima array according to the specified feature vector. * * @param featureVector the feature vector * @param minima the array of minima * @param maxima the array of maxima */ private void updateMinMax(V featureVector, double[] minima, double[] maxima) { if (minima.length != featureVector.getDimensionality()) { throw new IllegalArgumentException("FeatureVectors differ in length."); } for (int d = 1; d <= featureVector.getDimensionality(); d++) { if ((featureVector.getValue(d).doubleValue()) > maxima[d - 1]) { maxima[d - 1] = (featureVector.getValue(d).doubleValue()); } if ((featureVector.getValue(d).doubleValue()) < minima[d - 1]) { minima[d - 1] = (featureVector.getValue(d).doubleValue()); } } } /** * Determines the one-dimensional dense subspace candidates by making a pass over the database. * * @param database the database to run the algorithm on * @return the one-dimensional dense subspace candidates */ private SortedSet<CLIQUESubspace<V>> findOneDimensionalDenseSubspaceCandidates(Database<V> database) { Collection<Unit<V>> units = initOneDimensionalUnits(database); Collection<Unit<V>> denseUnits = new ArrayList<Unit<V>>(); Map<Integer, CLIQUESubspace<V>> denseSubspaces = new HashMap<Integer, CLIQUESubspace<V>>(); // identify dense units double total = database.size(); for (Iterator<Integer> it = database.iterator(); it.hasNext();) { V featureVector = database.get(it.next()); for (Unit<V> unit : units) { unit.addFeatureVector(featureVector); // unit is a dense unit if (!it.hasNext() && unit.selectivity(total) >= tau) { denseUnits.add(unit); // add the dense unit to its subspace int dim = unit.getIntervals().iterator().next().getDimension(); CLIQUESubspace<V> subspace_d = denseSubspaces.get(dim); if (subspace_d == null) { subspace_d = new CLIQUESubspace<V>(dim); denseSubspaces.put(dim, subspace_d); } subspace_d.addDenseUnit(unit); } } } if (debug) { StringBuffer msg = new StringBuffer(); msg.append("\n number of 1-dim dense units: ").append(denseUnits.size()); msg.append("\n number of 1-dim dense subspace candidates: ").append(denseSubspaces.size()); debugFine(msg.toString()); } return new TreeSet<CLIQUESubspace<V>>(denseSubspaces.values()); } /** * Determines the k-dimensional dense subspace candidates. * * @param database the database to run the algorithm on * @param denseSubspaces the (k-1)-dimensional dense subspace * @return the k-dimensional dense subspace candidates */ private SortedSet<CLIQUESubspace<V>> findDenseSubspaceCandidates(Database<V> database, Set<CLIQUESubspace<V>> denseSubspaces) { List<CLIQUESubspace<V>> denseSubspaceList = new ArrayList<CLIQUESubspace<V>>(); for (CLIQUESubspace<V> s : denseSubspaces) { denseSubspaceList.add(s); } Comparator<CLIQUESubspace<V>> comparator = new Comparator<CLIQUESubspace<V>>() { public int compare(CLIQUESubspace<V> s1, CLIQUESubspace<V> s2) { SortedSet<Integer> dims1 = s1.getDimensions(); SortedSet<Integer> dims2 = s2.getDimensions(); if (dims1.size() != dims2.size()) { throw new IllegalArgumentException("different dimensions sizes!"); } Iterator<Integer> it1 = dims1.iterator(); Iterator<Integer> it2 = dims2.iterator(); while (it1.hasNext()) { Integer d1 = it1.next(); Integer d2 = it2.next(); if (d1.equals(d2)) continue; return d1.compareTo(d2); } return 0; } }; Collections.sort(denseSubspaceList, comparator); double all = database.size(); TreeSet<CLIQUESubspace<V>> subspaces = new TreeSet<CLIQUESubspace<V>>(); while (!denseSubspaceList.isEmpty()) { CLIQUESubspace<V> s1 = denseSubspaceList.get(0); for (int j = 1; j < denseSubspaceList.size(); j++) { CLIQUESubspace<V> s2 = denseSubspaceList.get(j); CLIQUESubspace<V> s = s1.join(s2, all, tau); if (s != null) { subspaces.add(s); } } denseSubspaceList.remove(s1); } return subspaces; } /** * Performs a MDL-based pruning of the specified * dense sunspaces as described in the CLIQUE algorithm. * * @param denseSubspaces the subspaces to be pruned * @return the subspaces which are not pruned */ private SortedSet<CLIQUESubspace<V>> pruneDenseSubspaces(SortedSet<CLIQUESubspace<V>> denseSubspaces) { int[][] means = computeMeans(denseSubspaces); double[][] diffs = computeDiffs(denseSubspaces, means[0], means[1]); double[] codeLength = new double[denseSubspaces.size()]; double minCL = Double.MAX_VALUE; int min_i = -1; for (int i = 0; i < denseSubspaces.size(); i++) { int mi = means[0][i]; int mp = means[1][i]; double log_mi = mi == 0 ? 0 : StrictMath.log(mi) / StrictMath.log(2); double log_mp = mp == 0 ? 0 : StrictMath.log(mp) / StrictMath.log(2); double diff_mi = diffs[0][i]; double diff_mp = diffs[1][i]; codeLength[i] = log_mi + diff_mi + log_mp + diff_mp; if (codeLength[i] <= minCL) { minCL = codeLength[i]; min_i = i; } } SortedSet<CLIQUESubspace<V>> result = new TreeSet<CLIQUESubspace<V>>(); Iterator<CLIQUESubspace<V>> it = denseSubspaces.iterator(); for (int i = 0; i <= min_i; i++) { result.add(it.next()); } return result; } /** * The specified sorted set of dense subspaces is divided into the selected set I * and the pruned set P. For each set the mean of the cover fractions * is computed. * * @param denseSubspaces the dense subspaces * @return the mean of the cover fractions, the first value is the mean of the * selected set I, the second value is the mean of the pruned set P. */ private int[][] computeMeans(SortedSet<CLIQUESubspace<V>> denseSubspaces) { int n = denseSubspaces.size() - 1; CLIQUESubspace[] subspaces = denseSubspaces.toArray(new CLIQUESubspace[n + 1]); int[] mi = new int[n + 1]; int[] mp = new int[n + 1]; double resultMI = 0; double resultMP = 0; for (int i = 0; i < subspaces.length; i++) { resultMI += subspaces[i].getCoverage(); resultMP += subspaces[n - i].getCoverage(); //noinspection NumericCastThatLosesPrecision mi[i] = (int) Math.ceil(resultMI / (i + 1)); if (i != n) //noinspection NumericCastThatLosesPrecision mp[n - 1 - i] = (int) Math.ceil(resultMP / (i + 1)); } int[][] result = new int[2][]; result[0] = mi; result[1] = mp; return result; } /** * The specified sorted set of dense subspaces is divided into the selected set I * and the pruned set P. For each set the difference from the specified mean values * is computed. * * @param denseSubspaces the dense subspaces * @param mi the mean of the selected sets I * @param mp the mean of the pruned sets P * @return the difference from the specified mean values, the first value is the * difference from the mean of the selected set I, * the second value is the difference from the mean of the pruned set P. */ private double[][] computeDiffs(SortedSet<CLIQUESubspace<V>> denseSubspaces, int[] mi, int[] mp) { int n = denseSubspaces.size() - 1; CLIQUESubspace[] subspaces = denseSubspaces.toArray(new CLIQUESubspace[n + 1]); double[] diff_mi = new double[n + 1]; double[] diff_mp = new double[n + 1]; double resultMI = 0; double resultMP = 0; for (int i = 0; i < subspaces.length; i++) { double diffMI = Math.abs(subspaces[i].getCoverage() - mi[i]); resultMI += diffMI == 0.0 ? 0 : StrictMath.log(diffMI) / StrictMath.log(2); double diffMP = (i != n) ? Math.abs(subspaces[n - i].getCoverage() - mp[n - 1 - i]) : 0; resultMP += diffMP == 0.0 ? 0 : StrictMath.log(diffMP) / StrictMath.log(2); diff_mi[i] = resultMI; if (i != n) diff_mp[n - 1 - i] = resultMP; } double[][] result = new double[2][]; result[0] = diff_mi; result[1] = diff_mp; return result; } }
package net.idlesoft.android.apps.github.utils; import android.provider.BaseColumns; import net.idlesoft.android.apps.github.ui.activities.BaseActivity; import org.eclipse.egit.github.core.Repository; import org.eclipse.egit.github.core.User; import org.eclipse.egit.github.core.client.GsonUtils; import org.eclipse.egit.github.core.service.RepositoryService; import org.eclipse.egit.github.core.service.UserService; import android.content.Context; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Date; public class RequestCache { private final static String ROOT_DIR = "requests/"; private final static String REPOSITORY_DIR = "repositories/"; private final static String USER_DIR = "users/"; public static Repository getRepository(final BaseActivity context, final String owner, final String name, final boolean forceUpdate) { Repository repo = null; boolean shouldRefresh = false; final File dir = new File(context.getCacheDir(), ROOT_DIR + REPOSITORY_DIR); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } final File f = new File(dir, owner + "_" + name + ".json"); if (!forceUpdate && f.exists()) { /* Check if the cached JSON is really old */ final Date d = new Date(); final long elderCheck = d.getTime() - (15 * 24 * 60 * 60000); if (f.lastModified() < elderCheck) { shouldRefresh = true; } else { try { final FileInputStream in = new FileInputStream(f); repo = GsonUtils.fromJson(new BufferedReader( new InputStreamReader(in)), Repository.class); in.close(); return repo; } catch (Exception e) { shouldRefresh = true; } } } else { shouldRefresh = true; } if (shouldRefresh || forceUpdate) { try { final RepositoryService rs = new RepositoryService(context.getGHClient()); repo = rs.getRepository(owner, name); if (repo != null) { putRepository(context, repo); } } catch (Exception e) { repo = null; e.printStackTrace(); } } return repo; } public static Repository getRepository(final BaseActivity context, final String owner, final String name) { return getRepository(context, owner, name, false); } public static boolean putRepository(final BaseActivity context, final Repository repository) { final File dir = new File(context.getCacheDir(), ROOT_DIR + REPOSITORY_DIR); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } final File f = new File(dir, repository.getOwner().getLogin() + "_" + repository.getName() + ".json"); if (f.exists()) { f.delete(); } try { final FileOutputStream out = new FileOutputStream(f, false); final String outJson = GsonUtils.toJson(repository); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(outJson); writer.flush(); out.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public static User getUser(final BaseActivity context, final String login, final boolean forceUpdate) { User user = null; boolean shouldRefresh = false; final File dir = new File(context.getCacheDir(), ROOT_DIR + USER_DIR); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } final File f = new File(dir, login + ".json"); if (!forceUpdate && f.exists()) { /* Check if the cached JSON is really old (>1 day) */ final Date d = new Date(); /* TODO: The amount of time to keep cache should be a preference, really */ final long elderCheck = d.getTime() - (24 * 60 * 60000); if (f.lastModified() < elderCheck) { shouldRefresh = true; } else { try { final FileInputStream in = new FileInputStream(f); user = GsonUtils.fromJson(new BufferedReader( new InputStreamReader(in)), User.class); in.close(); return user; } catch (Exception e) { shouldRefresh = true; } } } else { shouldRefresh = true; } if (shouldRefresh || forceUpdate) { try { final UserService us = new UserService(context.getGHClient()); user = us.getUser(login); if (user != null) { putUser(context, user); } } catch (Exception e) { user = null; e.printStackTrace(); } } return user; } public static User getUser(final BaseActivity context, final String login) { return getUser(context, login, false); } public static boolean putUser(final BaseActivity context, final User user) { final File dir = new File(context.getCacheDir(), ROOT_DIR + USER_DIR); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } final File f = new File(dir, user.getLogin() + ".json"); if (f.exists()) { f.delete(); } try { final FileOutputStream out = new FileOutputStream(f, false); final String outJson = GsonUtils.toJson(user); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(outJson); writer.flush(); out.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } private static boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } return path.delete(); } else { return false; } } public static boolean clearCache(final Context context) { final File root = new File(context.getCacheDir(), ROOT_DIR); return deleteDirectory(root); } public static boolean clearRepositoryCache(final Context context) { final File repositories = new File(context.getCacheDir(), REPOSITORY_DIR); return deleteDirectory(repositories); } public static boolean clearUserCache(final Context context) { final File users = new File(context.getCacheDir(), USER_DIR); return deleteDirectory(users); } }
package de.mrapp.android.adapter.list; import static de.mrapp.android.adapter.util.Condition.ensureAtLeast; import static de.mrapp.android.adapter.util.Condition.ensureAtMaximum; import static de.mrapp.android.adapter.util.Condition.ensureNotNull; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import android.content.Context; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import de.mrapp.android.adapter.ListAdapter; import de.mrapp.android.adapter.datastructure.SerializableWrapper; import de.mrapp.android.adapter.datastructure.item.Item; import de.mrapp.android.adapter.datastructure.item.ItemIterator; import de.mrapp.android.adapter.datastructure.item.ItemListIterator; import de.mrapp.android.adapter.inflater.Inflater; import de.mrapp.android.adapter.logging.LogLevel; import de.mrapp.android.adapter.logging.Logger; import de.mrapp.android.adapter.util.VisibleForTesting; /** * An abstract base class for all adapters, whose underlying data is managed as * a list of arbitrary items. Such an adapter's purpose is to provide the * underlying data for visualization using a {@link ListView} widget. * * @param <DataType> * The type of the adapter's underlying data * @param <DecoratorType> * The type of the decorator, which allows to customize the * appearance of the views, which are used to visualize the items of * the adapter * * @author Michael Rapp * * @since 1.0.0 */ public abstract class AbstractListAdapter<DataType, DecoratorType> extends BaseAdapter implements ListAdapter<DataType> { /** * The constant serial version UID. */ private static final long serialVersionUID = 1L; /** * The key, which is used to store the adapter's underlying data within a * bundle, if it implements the interface {@link Parcelable}. */ @VisibleForTesting protected static final String PARCELABLE_ITEMS_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::ParcelableItems"; /** * The key, which is used to store the adapter's underlying data within a * bundle, if it implements the interface {@link Serializable}. */ @VisibleForTesting protected static final String SERIALIZABLE_ITEMS_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::SerializableItems"; /** * The key, which is used to store, whether duplicate items should be * allowed, or not, within a bundle. */ @VisibleForTesting protected static final String ALLOW_DUPLICATES_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::AllowDuplicates"; /** * The key, which is used to store, whether the method * <code>notifyDataSetChanged():void</code> should be called automatically * when the adapter's underlying data has been changed, or not, within a * bundle. */ @VisibleForTesting protected static final String NOTIFY_ON_CHANGE_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::NotifyOnChange"; /** * The key, which is used to store the key value pairs, which are stored * within the adapter, within a bundle. */ @VisibleForTesting protected static final String PARAMETERS_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::Parameters"; /** * The key, which is used to store the log level, which is used for logging, * within a bundle. */ @VisibleForTesting protected static final String LOG_LEVEL_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::LogLevel"; /** * The context, the adapter belongs to. */ private final transient Context context; /** * The inflater, which is used to inflate the views, which are used to * visualize the adapter's items. */ private final transient Inflater inflater; /** * The decorator, which allows to customize the appearance of the views, * which are used to visualize the items of the adapter. */ private final transient DecoratorType decorator; /** * The logger, which is used for logging. */ private final transient Logger logger; /** * A set, which contains the listeners, which should be notified, when the * adapter's underlying data has been modified. */ private transient Set<ListAdapterListener<DataType>> adapterListeners; /** * A bundle, which contains key value pairs, which are stored within the * adapter. */ private Bundle parameters; /** * True, if duplicate items are allowed, false otherwise. */ private boolean allowDuplicates; /** * True, if the method <code>notifyDataSetChanged():void</code> is * automatically called when the adapter's underlying data has been changed, * false otherwise. */ private boolean notifyOnChange; /** * A list, which contains the the adapter's underlying data. */ private ArrayList<Item<DataType>> items; /** * Notifies all listeners, which have been registered to be notified, when * the adapter's underlying data has been modified, about an item, which has * been added to the adapter. * * @param item * The item, which has been added to the adapter, as an instance * of the generic type DataType. The item may not be null * @param index * The index of the item, which has been added to the adapter, as * an {@link Integer} value. The index must be between 0 and the * value of the method <code>getNumberOfItems():int</code> - 1 */ private void notifyOnItemAdded(final DataType item, final int index) { for (ListAdapterListener<DataType> listener : adapterListeners) { listener.onItemAdded(this, item, index); } } /** * Notifies all listeners, which have been registered to be notified, when * the adapter's underlying data has been modified, about an item, which has * been removed from the adapter. * * @param item * The item, which has been removed from the adapter, as an * instance of the generic type DataType. The item may not be * null * @param index * The index of the item, which has been removed from the * adapter, as an {@link Integer} value. The index must be * between 0 and the value of the method * <code>getNumberOfItems():int</code> */ private void notifyOnItemRemoved(final DataType item, final int index) { for (ListAdapterListener<DataType> listener : adapterListeners) { listener.onItemRemoved(this, item, index); } } /** * Returns, whether the adapter's underlying data implements the interface * {@link Parcelable}, or not. * * @return True, if the adapter's underlying data implements the interface * {@link Parcelable} or if the adapter is empty, false otherwise */ private boolean isUnderlyingDataParcelable() { if (!isEmpty()) { if (!Parcelable.class.isAssignableFrom(getItem(0).getClass())) { return false; } } return true; } /** * Creates and returns an {@link OnClickListener}, which is invoked, when a * specific item has been clicked. * * @param index * The index of the item, which should cause the listener to be * invoked, when clicked, as an {@link Integer} value * @return The listener, which has been created as an instance of the type * {@link OnClickListener} */ private OnClickListener createItemOnClickListener(final int index) { return new OnClickListener() { @Override public void onClick(final View v) { onItemClicked(index); } }; } /** * Returns, whether the adapter's underlying data implements the interface * {@link Serializable}, or not. * * @return True, if the adapter's underlying data implements the interface * {@link Serializable} or if the adapter is empty, false otherwise */ private boolean isUnderlyingDataSerializable() { if (!isEmpty()) { if (!Serializable.class.isAssignableFrom(getItem(0).getClass())) { return false; } } return true; } /** * Returns, the context, the adapter belongs to. * * @return The context, the adapter belongs to, as an instance of the class * {@link Context}. The context may not be null */ protected final Context getContext() { return context; } /** * Returns the inflater, which is used to inflate the views, which are used * to visualize the adapter's items. * * @return The inflater, which is used to inflate views, which are used to * visualize the adapter's items, as an instance of the type * {@link Inflater}. The inflater may not be null */ protected final Inflater getInflater() { return inflater; } /** * Returns the decorator, which allows to customize the appearance of the * views, which are used to visualize the items of the adapter. * * @return The decorator, which allows to customize the appearance of the * views, which are used to visualize the items of the adapter, as * an instance of the generic type DecoratorType. The decorator may * not be null */ protected final DecoratorType getDecorator() { return decorator; } /** * Returns the logger, which is used for logging. * * @return The logger, which is used for logging, as an instance of the * class {@link Logger}. The logger may not be null */ protected final Logger getLogger() { return logger; } /** * Returns a list, which contains the adapter's underlying data. * * @return A list, which contains the adapters underlying data, as an * instance of the type {@link ArrayList} or an empty list, if the * adapter does not contain any data */ protected final ArrayList<Item<DataType>> getItems() { return items; } /** * Sets the list, which contains the adapter's underlying data. * * @param items * The list, which should be set, as an instance of the type * {@link ArrayList} or an empty list, if the adapter should not * contain any data */ protected final void setItems(final ArrayList<Item<DataType>> items) { ensureNotNull(items, "The items may not be null"); this.items = items; } /** * Creates and returns a deep copy of the list, which contains the adapter's * underlying data. * * @return A deep copy of the list, which contains the adapter's underlying * data, as an instance of the type {@link ArrayList}. The list may * not be null * @throws CloneNotSupportedException * The exception, which is thrown, if cloning is not supported * by the adapter's underlying data */ protected final ArrayList<Item<DataType>> cloneItems() throws CloneNotSupportedException { ArrayList<Item<DataType>> clonedItems = new ArrayList<Item<DataType>>(); for (Item<DataType> item : items) { clonedItems.add(item.clone()); } return clonedItems; } /** * Returns a set, which contains the listeners, which should be notified, * when the adapter's underlying data has been modified. * * @return A set, which contains the listeners, which should be notified, * when the adapter's underlying data has been modified, as an * instance of the type {@link Set} or an empty set, if no listeners * should be notified */ protected final Set<ListAdapterListener<DataType>> getAdapterListeners() { return adapterListeners; } /** * The method, which is invoked, when an item has been clicked. * * @param index * The index of the item, which has been clicked, as an * {@link Integer} value */ protected void onItemClicked(final int index) { return; } /** * Notifies, that the adapter's underlying data has been changed, if * automatically notifying such events is currently enabled. */ protected final void notifyOnDataSetChanged() { if (isNotifiedOnChange()) { notifyDataSetChanged(); } } /** * This method is invoked to apply the decorator, which allows to customize * the view, which is used to visualize a specific item. * * @param context * The context, the adapter belongs to, as an instance of the * class {@link Context}. The context may not be null * @param view * The view, which is used to visualize the item, as an instance * of the class {@link View}. The view may not be null * @param index * The index of the item, which should be visualized, as an * {@link Integer} value */ protected abstract void applyDecorator(final Context context, final View view, final int index); /** * Creates a new adapter, whose underlying data is managed as a list of * arbitrary items. * * @param context * The context, the adapter belongs to, as an instance of the * class {@link Context}. The context may not be null * @param inflater * The inflater, which should be used to inflate the views, which * are used to visualize the adapter's items, as an instance of * the type {@link Inflater}. The inflater may not be null * @param decorator * The decorator, which should be used to customize the * appearance of the views, which are used to visualize the items * of the adapter, as an instance of the generic type * DecoratorType. The decorator may not be null * @param logLevel * The log level, which should be used for logging, as a value of * the enum {@link LogLevel}. The log level may not be null * @param items * A list, which contains the adapter's items, or an empty list, * if the adapter should not contain any items * @param allowDuplicates * True, if duplicate items should be allowed, false otherwise * @param notifyOnChange * True, if the method <code>notifyDataSetChanged():void</code> * should be automatically called when the adapter's underlying * data has been changed, false otherwise * @param adapterListeners * A set, which contains the listeners, which should be notified, * when the adapter's underlying data has been modified, as an * instance of the type {@link Set} or an empty set, if no * listeners should be notified */ protected AbstractListAdapter(final Context context, final Inflater inflater, final DecoratorType decorator, final LogLevel logLevel, final ArrayList<Item<DataType>> items, final boolean allowDuplicates, final boolean notifyOnChange, final Set<ListAdapterListener<DataType>> adapterListeners) { ensureNotNull(context, "The context may not be null"); ensureNotNull(inflater, "The inflater may not be null"); ensureNotNull(decorator, "The decorator may not be null"); ensureNotNull(adapterListeners, "The adapter listeners may not be null"); this.context = context; this.inflater = inflater; this.decorator = decorator; this.logger = new Logger(logLevel); this.items = items; this.parameters = null; this.allowDuplicates = allowDuplicates; this.notifyOnChange = notifyOnChange; this.adapterListeners = adapterListeners; } @Override public final LogLevel getLogLevel() { return getLogger().getLogLevel(); } @Override public final void setLogLevel(final LogLevel logLevel) { getLogger().setLogLevel(logLevel); } @Override public final Bundle getParameters() { return parameters; } @Override public final void setParameters(final Bundle parameters) { this.parameters = parameters; } @Override public final boolean areDuplicatesAllowed() { return allowDuplicates; } @Override public final void allowDuplicates(final boolean allowDuplicates) { this.allowDuplicates = allowDuplicates; String message = "Duplicate items are now " + (allowDuplicates ? "allowed" : "disallowed"); getLogger().logDebug(getClass(), message); } @Override public final boolean isNotifiedOnChange() { return notifyOnChange; } @Override public final void notifyOnChange(final boolean notifyOnChange) { this.notifyOnChange = notifyOnChange; String message = "Changes of the adapter's underlying data are now " + (notifyOnChange ? "" : "not ") + "automatically notified"; getLogger().logDebug(getClass(), message); } @Override public final void addAdapterListener( final ListAdapterListener<DataType> listener) { ensureNotNull(listener, "The listener may not be null"); adapterListeners.add(listener); String message = "Added adapter listener \"" + listener + "\""; getLogger().logDebug(getClass(), message); } @Override public final void removeAdapterListener( final ListAdapterListener<DataType> listener) { ensureNotNull(listener, "The listener may not be null"); adapterListeners.remove(listener); String message = "Removed adapter listener \"" + listener + "\""; getLogger().logDebug(getClass(), message); } @Override public final boolean addItem(final DataType item) { return addItem(getNumberOfItems(), item); } @Override public final boolean addItem(final int index, final DataType item) { ensureNotNull(item, "The item may not be null"); if (!areDuplicatesAllowed() && containsItem(item)) { String message = "Item \"" + item + "\" at index " + index + " not added, because adapter already contains item"; getLogger().logDebug(getClass(), message); return false; } items.add(index, new Item<DataType>(item)); notifyOnItemAdded(item, index); notifyOnDataSetChanged(); String message = "Item \"" + item + "\" added at index " + index; getLogger().logInfo(getClass(), message); return true; } @Override public final boolean addAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); return addAllItems(getNumberOfItems(), items); } @Override public final boolean addAllItems(final int index, final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); boolean result = true; int currentIndex = index; for (DataType item : items) { result &= addItem(currentIndex, item); currentIndex++; } return result; } @Override public final boolean addAllItems(final DataType... items) { return addAllItems(getNumberOfItems(), items); } @Override public final boolean addAllItems(final int index, final DataType... items) { ensureNotNull(items, "The array may not be null"); return addAllItems(index, Arrays.asList(items)); } @Override public final DataType replaceItem(final int index, final DataType item) { ensureNotNull(item, "The item may not be null"); DataType replacedItem = items.set(index, new Item<DataType>(item)) .getData(); notifyOnItemRemoved(replacedItem, index); notifyOnItemAdded(item, index); notifyOnDataSetChanged(); String message = "Replaced item \"" + replacedItem + "\" at index " + index + " with item \"" + item + "\""; getLogger().logInfo(getClass(), message); return replacedItem; } @Override public final DataType removeItem(final int index) { DataType removedItem = items.remove(index).getData(); notifyOnItemRemoved(removedItem, index); notifyOnDataSetChanged(); String message = "Removed item \"" + removedItem + "\" from index " + index; getLogger().logInfo(getClass(), message); return removedItem; } @Override public final boolean removeItem(final DataType item) { ensureNotNull(item, "The item may not be null"); int index = indexOf(item); if (index != -1) { items.remove(index); notifyOnItemRemoved(item, index); notifyOnDataSetChanged(); String message = "Removed item \"" + item + "\" from index " + index; getLogger().logInfo(getClass(), message); return true; } String message = "Item \"" + item + "\" not removed, because adapter does not contain item"; getLogger().logDebug(getClass(), message); return false; } @Override public final boolean removeAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); int numberOfRemovedItems = 0; for (int i = getNumberOfItems() - 1; i >= 0; i if (items.contains(getItem(i))) { removeItem(i); numberOfRemovedItems++; } } return numberOfRemovedItems == items.size(); } @Override public final boolean removeAllItems(final DataType... items) { ensureNotNull(items, "The array may not be null"); return removeAllItems(Arrays.asList(items)); } @Override public final void retainAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); for (int i = getNumberOfItems() - 1; i >= 0; i if (!items.contains(getItem(i))) { removeItem(i); } } } @Override public final void retainAllItems(final DataType... items) { ensureNotNull(items, "The array may not be null"); retainAllItems(Arrays.asList(items)); } @Override public final void clearItems() { for (int i = getNumberOfItems() - 1; i >= 0; i removeItem(i); } getLogger().logInfo(getClass(), "Cleared all items"); } @Override public final Iterator<DataType> iterator() { return new ItemIterator<DataType>(items, this); } @Override public final ListIterator<DataType> listIterator() { return new ItemListIterator<DataType>(items, this); } @Override public final ListIterator<DataType> listIterator(final int index) { return new ItemListIterator<DataType>(items, this, index); } @Override public final Collection<DataType> subList(final int start, final int end) { Collection<DataType> subList = new ArrayList<DataType>(); for (int i = start; i < end; i++) { subList.add(getItem(i)); } return subList; } @Override public final Object[] toArray() { return getAllItems().toArray(); } @Override public final <T> T[] toArray(final T[] array) { return getAllItems().toArray(array); } @Override public final int indexOf(final DataType item) { ensureNotNull(item, "The item may not be null"); return getAllItems().indexOf(item); } @Override public final int lastIndexOf(final DataType item) { ensureNotNull(item, "The item may not be null"); return getAllItems().lastIndexOf(item); } @Override public final boolean containsItem(final DataType item) { ensureNotNull(item, "The item may not be null"); return getAllItems().contains(item); } @Override public final boolean containsAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); return getAllItems().containsAll(items); } @Override public final boolean containsAllItems(final DataType... items) { ensureNotNull(items, "The array may not be null"); return containsAllItems(Arrays.asList(items)); } @Override public final int getNumberOfItems() { return items.size(); } @Override public final DataType getItem(final int index) { return items.get(index).getData(); } @Override public final List<DataType> getAllItems() { List<DataType> result = new ArrayList<DataType>(); for (Item<DataType> item : items) { result.add(item.getData()); } return result; } @Override public final boolean isEmpty() { return items.isEmpty(); } @Override public final int getCount() { return getNumberOfItems(); } @Override public final long getItemId(final int index) { ensureAtLeast(index, 0, "The index must be at least 0"); ensureAtMaximum(index, items.size() - 1, isEmpty() ? "The index must be at maximum " + (items.size() - 1) : "The adapter is empty"); return index; } @Override public final View getView(final int index, final View convertView, final ViewGroup parent) { View view = convertView; if (view == null) { view = getInflater().inflate(getContext(), parent, false); String message = "Inflated view to visualize the item at index " + index; getLogger().logVerbose(getClass(), message); } view.setOnClickListener(createItemOnClickListener(index)); applyDecorator(getContext(), view, index); return view; } @Override public void onSaveInstanceState(final Bundle outState) { if (isUnderlyingDataParcelable()) { outState.putParcelableArrayList(PARCELABLE_ITEMS_BUNDLE_KEY, items); } else if (isUnderlyingDataSerializable()) { SerializableWrapper<ArrayList<Item<DataType>>> wrappedItems = new SerializableWrapper<ArrayList<Item<DataType>>>( getItems()); outState.putSerializable(SERIALIZABLE_ITEMS_BUNDLE_KEY, wrappedItems); } else { String message = "The adapter's items can not be stored, because the " + "underlying data does neither implement the interface \"" + Parcelable.class.getName() + "\", nor the interface \"" + Serializable.class.getName() + "\""; getLogger().logWarn(getClass(), message); } outState.putBundle(PARAMETERS_BUNDLE_KEY, getParameters()); outState.putBoolean(ALLOW_DUPLICATES_BUNDLE_KEY, areDuplicatesAllowed()); outState.putBoolean(NOTIFY_ON_CHANGE_BUNDLE_KEY, isNotifiedOnChange()); outState.putInt(LOG_LEVEL_BUNDLE_KEY, getLogLevel().getRank()); getLogger().logDebug(getClass(), "Saved instance state"); } @SuppressWarnings("unchecked") @Override public void onRestoreInstanceState(final Bundle savedInstanceState) { if (savedInstanceState != null) { if (savedInstanceState.containsKey(PARCELABLE_ITEMS_BUNDLE_KEY)) { items = savedInstanceState .getParcelableArrayList(PARCELABLE_ITEMS_BUNDLE_KEY); } else if (savedInstanceState .containsKey(SERIALIZABLE_ITEMS_BUNDLE_KEY)) { SerializableWrapper<ArrayList<Item<DataType>>> wrappedItems = (SerializableWrapper<ArrayList<Item<DataType>>>) savedInstanceState .getSerializable(SERIALIZABLE_ITEMS_BUNDLE_KEY); items = wrappedItems.getWrappedInstance(); } setParameters(savedInstanceState.getBundle(PARAMETERS_BUNDLE_KEY)); allowDuplicates(savedInstanceState .getBoolean(ALLOW_DUPLICATES_BUNDLE_KEY)); notifyOnChange(savedInstanceState .getBoolean(NOTIFY_ON_CHANGE_BUNDLE_KEY)); setLogLevel(LogLevel.fromRank(savedInstanceState .getInt(LOG_LEVEL_BUNDLE_KEY))); notifyDataSetChanged(); getLogger().logDebug(getClass(), "Restored instance state"); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (allowDuplicates ? 1231 : 1237); result = prime * result + (notifyOnChange ? 1231 : 1237); result = prime * result + items.hashCode(); result = prime * result + getLogLevel().getRank(); result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractListAdapter<?, ?> other = (AbstractListAdapter<?, ?>) obj; if (allowDuplicates != other.allowDuplicates) return false; if (notifyOnChange != other.notifyOnChange) return false; if (!items.equals(other.items)) return false; if (!getLogLevel().equals(other.getLogLevel())) return false; if (parameters == null) { if (other.parameters != null) return false; } else if (!parameters.equals(other.parameters)) return false; return true; } @Override public abstract AbstractListAdapter<DataType, DecoratorType> clone() throws CloneNotSupportedException; }
package net.localizethat.model.jpa; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import net.localizethat.Main; import net.localizethat.model.LocaleContainer; import net.localizethat.model.LocaleFile; /** * This class provides helper methods to interact with LocaleContainer persistence. * * @author rpalomares */ public class LocaleContainerJPAHelper { private static final int DEFAULT_TRANSACT_MAX_COUNT = 50; private int transactMaxCount; private int transactCounter; private final EntityManager em; private boolean isTransactionOpen; private LocaleFileJPAHelper lfHelper; public LocaleContainerJPAHelper(EntityManager em, int transactMaxCount) { transactCounter = 0; if (em == null) { this.em = Main.emf.createEntityManager(); isTransactionOpen = false; } else { this.em = em; // Does the passed EntityManager have a transaction open? isTransactionOpen = this.em.isJoinedToTransaction(); } this.transactMaxCount = transactMaxCount; this.lfHelper = new LocaleFileJPAHelper(this.em, this.transactMaxCount); } public LocaleContainerJPAHelper(EntityManager em) { this(em, LocaleContainerJPAHelper.DEFAULT_TRANSACT_MAX_COUNT); } public boolean removeRecursively(LocaleContainer lc) { return removeRecursively(lc, 0); } private boolean removeRecursively(LocaleContainer lc, int depth) { boolean result = true; try { if (transactCounter == 0 && !em.isJoinedToTransaction()) { em.getTransaction().begin(); } lc = em.merge(lc); // Ensure that the EntityManager is managing the LocaleContainer to be removed // for (Iterator<LocaleContainer> iterator = lc.getChildren().iterator(); iterator.hasNext();) { // LocaleContainer child = iterator.next(); for(LocaleContainer child : lc.getChildren()) { result = removeRecursively(child, depth + 1); if (!result) { break; } lc = em.merge(lc); // Ensure that the EntityManager is managing the LocaleContainer to be removed lc.removeChild(child); } if (result) { for(LocaleFile lfChild : lc.getFileChildren()) { result = lfHelper.removeRecursively(lfChild); // TODO Check if this can be done without affecting the for, as the JPAHelper is changing // the collection traversed by this for. If this fails, maybe the above for for LocaleContainer // will fail, too? } lc.setDefLocaleTwin(null); LocaleContainer parent = (LocaleContainer) lc.getParent(); if (parent != null) { // parent = em.merge(parent); parent.removeChild(lc); lc.setParent(null); } em.remove(lc); transactCounter++; if ((transactCounter > transactMaxCount) && (depth > 0)) { em.getTransaction().commit(); transactCounter = 0; } } } catch (Exception e) { Logger.getLogger(LocaleContainerJPAHelper.class.getName()).log(Level.SEVERE, null, e); if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } result = false; } if (em.isJoinedToTransaction() && transactCounter > 0 && depth > 0) { em.getTransaction().commit(); } if (this.isTransactionOpen && depth > 0) { // If needed, let the EntityManager in the same status we got it // (i.e., with an open transaction) em.getTransaction().begin(); } return result; } }
package edu.cmu.cs.diamond.opendiamond; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; class XDR_attr_name_list implements XDREncodeable { private final String strings[]; public XDR_attr_name_list(Collection<String> list) { strings = list.toArray(new String[0]); } public byte[] encode() { // length + strings ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); try { // length out.writeInt(strings.length); // strings for (String s : strings) { out.write(XDREncoders.encodeString(s)); } } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); } }
package net.x4a42.volksempfaenger.service; import java.io.File; import java.io.FilenameFilter; import net.x4a42.volksempfaenger.Constants; import net.x4a42.volksempfaenger.Log; import android.app.Service; import android.content.Intent; import android.os.AsyncTask; import android.os.IBinder; public class CleanCacheService extends Service { private class CleanCacheTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { final File cacheDir = getExternalCacheDir(); final File images = new File(cacheDir, "images"); // 3 days final long minTime = System.currentTimeMillis() - 3 * 24 * 60 * 60 * 1000; final File[] imageFiles = images.listFiles(); final File[] errorReportFiles = cacheDir .listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename .startsWith(Constants.ERROR_REPORT_PREFIX)) { return true; } else { return false; } } }); try { if (imageFiles != null) { CleanCacheService.removeOldFiles(imageFiles, minTime); } if (errorReportFiles != null) { CleanCacheService.removeOldFiles(errorReportFiles, minTime); } } catch (Exception e) { /* * do not crash everything because removing temporary files * fails. probably just a temporary problem */ Log.w(this, e); e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { stopSelf(); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { new CleanCacheTask().execute(); return START_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } public static void removeOldFiles(File[] files, long minLastModified) { for (File f : files) { if (f.lastModified() < minLastModified) { f.delete(); } } } }
package edu.washington.escience.myria.operator; import java.util.BitSet; import java.util.List; import com.google.common.collect.ImmutableMap; import edu.washington.escience.myria.DbException; import edu.washington.escience.myria.Schema; import edu.washington.escience.myria.TupleBatch; import edu.washington.escience.myria.TupleBuffer; import edu.washington.escience.myria.column.Column; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; /** * Implementation of set difference. Duplicates are not preserved. * * @author whitaker */ public class Difference extends BinaryOperator { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** * This buffer stores tuples to remove from the left operator. */ private transient TupleBuffer tuplesToRemove = null; /** * Mapping from tuple hash code to indices in the tuplesToRemove buffer. * */ private transient TIntObjectMap<TIntList> tupleIndices; /** * Instantiate a set difference operator: left EXCEPT right. * * @param left the operator being subtracted from. * @param right the operator to be subtracted. */ public Difference(final Operator left, final Operator right) { super(left, right); } /** * Mark a particular tuple as seen. * * @param batch A tuple batch * @param rowNum The index of the tuple among the valid tuples in batch. * * @return true if this is the first time this tuple has been encountered. */ private boolean markAsSeen(final TupleBatch batch, final int rowNum) { final int tupleHash = batch.hashCode(rowNum); TIntList tupleIndexList = tupleIndices.get(tupleHash); if (tupleIndexList == null) { tupleIndexList = new TIntArrayList(); tupleIndices.put(tupleHash, tupleIndexList); } // Check whether we've seen this tuple before for (int i = 0; i < tupleIndexList.size(); i++) { if (batch.tupleEquals(rowNum, tuplesToRemove, tupleIndexList.get(i))) { return false; } } // This is a new tuple: add it to the toRemove tuple buffer final int nextToRemoveRow = tuplesToRemove.numTuples(); final int absoluteRowNum = batch.getValidIndices().get(rowNum); final List<Column<?>> columns = batch.getDataColumns(); for (int columnNum = 0; columnNum < batch.numColumns(); columnNum++) { tuplesToRemove.put(columnNum, columns.get(columnNum), absoluteRowNum); } tupleIndexList.add(nextToRemoveRow); return true; } /** * Process a batch of tuples that are removed from the final result. * * @param batch A tuple batch */ private void processRightChildTB(final TupleBatch batch) { final int numValidTuples = batch.numTuples(); for (int row = 0; row < numValidTuples; row++) { markAsSeen(batch, row); } } /** * Process a batch of tuples that are subtracted from to produce the final result. * * @param batch A tuple batch. * * @return A filtered batch of tuples. */ private TupleBatch processLeftChildTB(final TupleBatch batch) { final int numValidTuples = batch.numTuples(); final BitSet toRemove = new BitSet(numValidTuples); for (int row = 0; row < numValidTuples; row++) { if (!markAsSeen(batch, row)) { toRemove.set(row); } } return batch.remove(toRemove); } @Override protected TupleBatch fetchNextReady() throws Exception { final Operator right = getRight(); /* Drain the right child. */ while (!right.eos()) { TupleBatch rightTB = right.nextReady(); if (rightTB == null) { if (right.eos()) { break; } return null; } processRightChildTB(rightTB); } /* Drain the left child */ final Operator left = getLeft(); while (!left.eos()) { TupleBatch leftTB = left.nextReady(); if (leftTB == null) { return null; } return processLeftChildTB(leftTB); } return null; } @Override protected Schema generateSchema() { return getLeft().getSchema(); } @Override public void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { tupleIndices = new TIntObjectHashMap<TIntList>(); tuplesToRemove = new TupleBuffer(getSchema()); } @Override protected void cleanup() throws DbException { tuplesToRemove = null; tupleIndices = null; } }
package org.ow2.chameleon.fuchsia.core; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Instantiate; import org.ow2.chameleon.fuchsia.core.component.ImporterService; import java.util.Map; import java.util.Set; @Component(name = "FuchsiaMediatorFactory", publicFactory = false) @Instantiate(name = "FuchsiaMediator") public interface FuchsiaMediator { /** * System property identifying the host name for this FuchsiaMediator. */ final static String FUCHSIA_MEDIATOR_HOST = "host"; /** * TimeStamp */ final static String FUCHSIA_MEDIATOR_DATE = "date"; enum EndpointListenerInterest { LOCAL, REMOTE, ALL } /** * @return The ImporterService linked to this FuchsiaMediator */ Set<ImporterService> getLinkers(); /** * @return This FuchsiaMediator host. */ String getHost(); /** * @return This FuchsiaMediator properties. */ Map<String, Object> getProperties(); }
package eu.alebianco.intellij.tasks.bugzilla; import com.intellij.openapi.util.IconLoader; import com.intellij.tasks.Comment; import com.intellij.tasks.Task; import com.intellij.tasks.TaskType; import com.j2bugzilla.base.Bug; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Date; public class BugzillaTask extends Task { private final Bug bug; public String baseUrl; public BugzillaTask(Bug bug, String serverUrl) { this.bug = bug; this.baseUrl = serverUrl; } @NotNull @Override public String getId() { return Integer.toString(bug.getID()); } @NotNull @Override public String getSummary() { return bug.getSummary(); } @Nullable @Override public String getDescription() { return ""; // TODO retrieve first comment? } @NotNull @Override public Comment[] getComments() { return Comment.EMPTY_ARRAY; } @NotNull @Override public Icon getIcon() { return IconLoader.getIcon("/bugzilla.png"); } @NotNull @Override public TaskType getType() { return TaskType.BUG; } @Nullable @Override public Date getUpdated() { return bug.getLastChanged(); } @Nullable @Override public Date getCreated() { return null; } @Override public boolean isClosed() { return "resolved".equals(bug.getStatus()) || "verified".equals(bug.getStatus()); } @Override public boolean isIssue() { return !"enhancment".equals(bug.getSeverity()); } @Nullable @Override public String getIssueUrl() { return String.format("%s/show_bug.cgi?id=%s", baseUrl, getId()); } }
package eu.greenlightning.hypercubepdf.container; import java.io.IOException; import java.util.Collection; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import eu.greenlightning.hypercubepdf.HCPElement; /** * Paints multiple {@link HCPElement}s on top of each other. The elements are painted in the order they are * provided in, i.&nbsp;e. the first element is painted first and the last element is painted last * (bottom-to-top ordering). * <p> * The width of the widest and the height of the highest element are used as the size of the stack. * <p> * This class is immutable. * * @author Green Lightning */ public class HCPStack implements HCPElement { private final HCPElements elements; public HCPStack(Collection<HCPElement> elements) { this.elements = new HCPElements(elements); } public HCPStack(HCPElement... elements) { this.elements = new HCPElements(elements); } @Override public float getWidth() throws IOException { return elements.getMaxWidth(); } @Override public float getHeight() throws IOException { return elements.getMaxHeight(); } @Override public void paint(PDPageContentStream content, PDRectangle shape) throws IOException { for (HCPElement element : elements) { element.paint(content, shape); } } }
package com.twitter; import java.util.*; import java.util.regex.*; import java.text.*; /** * A class for adding HTML highlighting in Tweet text (such as would be returned from a Search) */ public class HitHighlighter { /** Default HTML tag for highlight hits */ public static final String DEFAULT_HIGHLIGHT_TAG = "em"; /** the current HTML tag used for hit highlighting */ protected String highlightTag; /** Create a new HitHighlighter object. */ public HitHighlighter() { highlightTag = DEFAULT_HIGHLIGHT_TAG; } /** * Surround the <code>hits</code> in the provided <code>text</code> with an HTML tag. This is used with offsets * from the search API to support the highlighting of query terms. * * @param text of the Tweet to highlight * @param hits A List of highlighting offsets (themselves lists of two elements) * @return text with highlight HTML added */ public String highlight(String text, List<List<Integer>> hits) { if (hits == null || hits.isEmpty()) { return(text); } StringBuilder sb = new StringBuilder(text.length()); CharacterIterator iterator = new StringCharacterIterator(text); boolean isCounting = true; boolean tagOpened = false; int currentIndex = 0; char currentChar = iterator.first(); while (currentChar != CharacterIterator.DONE) { // TODO: this is slow. for (List<Integer> start_end : hits) { if (start_end.get(0) == currentIndex) { sb.append(tag(false)); tagOpened = true; } else if (start_end.get(1) == currentIndex) { sb.append(tag(true)); tagOpened = false; } } if (currentChar == '<') { isCounting = false; } else if (currentChar == '>' && !isCounting) { isCounting = true; } if (isCounting) { currentIndex++; } sb.append(currentChar); currentChar = iterator.next(); } if (tagOpened) { sb.append(tag(true)); } return(sb.toString()); } /** * Format the current <code>highlightTag</code> by adding &lt; and &gt;. If <code>closeTag</code> is <code>true</code> * then the tag returned will include a <code>/</code> to signify a closing tag. * * @param closeTag true if this is a closing tag, false otherwise * @return reformed tag */ protected String tag(boolean closeTag) { StringBuilder sb = new StringBuilder(highlightTag.length() + 3); sb.append("<"); if (closeTag) { sb.append("/"); } sb.append(highlightTag).append(">"); return(sb.toString()); } /** * Get the current HTML tag used for phrase highlighting. * * @return current HTML tag (without &lt; or &gt;) */ public String getHighlightTag() { return highlightTag; } /** * Set the current HTML tag used for phrase highlighting. * * @param highlightTag sets highlighting tag */ public void setHighlightTag(String highlightTag) { this.highlightTag = highlightTag; } }
package org.concord.framework.otrunk.otcore; public interface OTClassProperty { String getName(); OTType getType(); Object getDefault(); boolean isPrimitive(); boolean isList(); boolean isMap(); boolean isOnlyInOverlayProperty(); public boolean isOverriddenProperty(); public OTClassProperty getOnlyInOverlayProperty(); public OTClassProperty getOverriddenProperty(); }
package org.ensembl.healthcheck.testcase.compara; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Map; import java.util.Vector; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Species; import org.ensembl.healthcheck.Team; import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase; /** * Check compara taxon table against core meta ones. */ public class CheckTaxon extends MultiDatabaseTestCase { /** * Create a new instance of MetaCrossSpecies */ public CheckTaxon() { addToGroup("compara_external_foreign_keys"); setDescription("Check that the attributes of the taxon table (genus, species," + " common_name and classification) correspond to the meta data in the core DB and vice versa."); setTeamResponsible(Team.COMPARA); } /** * Check that the attributes of the taxon table (genus, species, common_name and * classification) correspond to the meta data in the core DB and vice versa. * NB: A warning message is displayed if some dnafrags cannot be checked because * there is not any connection to the corresponding core database. * * @param dbr * The database registry containing all the specified databases. * @return true if the all the taxa in compara.taxon table which have a counterpart in * the compara.genome_db table match the corresponding core databases. */ public boolean run(DatabaseRegistry dbr) { boolean result = true; // Get compara DB connection DatabaseRegistryEntry[] allComparaDBs = dbr.getAll(DatabaseType.COMPARA); if (allComparaDBs.length == 0) { result = false; ReportManager.problem(this, "", "Cannot find compara database"); usage(); return false; } Map speciesDbrs = getSpeciesDatabaseMap(dbr, true); for (int i = 0; i < allComparaDBs.length; i++) { result &= checkTaxon(allComparaDBs[i], speciesDbrs); } return result; } /** * Check that the attributes of the taxon table (genus, species, common_name and * classification) correspond to the meta data in the core DB and vice versa. * NB: A warning message is displayed if some dnafrags cannot be checked because * there is not any connection to the corresponding core database. * * @param comparaDbre * The database registry entry for Compara DB * @param Map * HashMap of DatabaseRegistryEntry[], one key/value pair for each Species. * @return true if the all the taxa in compara.taxon table which have a counterpart in * the compara.genome_db table match the corresponding core databases. */ public boolean checkTaxon(DatabaseRegistryEntry comparaDbre, Map speciesDbrs) { boolean result = true; Connection comparaCon = comparaDbre.getConnection(); // Get list of species in compara Vector comparaSpecies = new Vector(); String sql = "SELECT DISTINCT genome_db.name FROM genome_db WHERE assembly_default = 1" + " AND name <> 'ancestral_sequences'"; try { Statement stmt = comparaCon.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { comparaSpecies.add(Species.resolveAlias(rs.getString(1).toLowerCase().replace(' ', '_'))); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } //Check that don't have duplicate entries in the ncbi_taxa_name table String useful_sql = "SELECT taxon_id,name,name_class,count(*) FROM ncbi_taxa_name GROUP BY taxon_id,name,name_class HAVING count(*) > 1;"; String[] failures = getColumnValues(comparaCon, useful_sql); if (failures.length > 0) { ReportManager.problem(this, comparaCon, "FAILED ncbi_taxa_name contains duplicate entries "); ReportManager.problem(this, comparaCon, "FAILURE DETAILS: There are " + failures.length + " ncbi_taxa_names with more than 1 entry"); ReportManager.problem(this, comparaCon, "USEFUL SQL: " + useful_sql); result = false; } else { result = true; } boolean allSpeciesFound = true; for (int i = 0; i < comparaSpecies.size(); i++) { Species species = (Species) comparaSpecies.get(i); DatabaseRegistryEntry[] speciesDbr = (DatabaseRegistryEntry[]) speciesDbrs.get(species); if (speciesDbr != null) { Connection speciesCon = speciesDbr[0].getConnection(); String sql1, sql2; /* Get taxon_id */ String taxon_id = getRowColumnValue(speciesCon, "SELECT meta_value FROM meta WHERE meta_key = \"species.taxonomy_id\""); /* Check name ++ compara scientific name := last two entries in the species classification in the core meta table */ sql1 = "SELECT \"name\", name " + " FROM ncbi_taxa_name WHERE name_class = \"scientific name\" AND taxon_id = " + taxon_id; sql2 = "SELECT \"name\", GROUP_CONCAT(meta_value ORDER BY meta_id DESC SEPARATOR \" \") " + " FROM (SELECT meta_id, meta_key, meta_value FROM meta " + " WHERE meta_key = \"species.classification\" ORDER BY meta_id LIMIT 2) AS name " + " GROUP BY meta_key"; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); /* Check common_name */ sql1 = "SELECT \"common_name\", name " + " FROM ncbi_taxa_name WHERE name_class = \"genbank common name\" AND taxon_id = " + taxon_id; sql2 = "SELECT \"common_name\", meta_value FROM meta" + " WHERE meta_key = \"species.common_name\" and meta_value != \"\""; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); /* Check ensembl_common_name */ sql1 = "SELECT \"ensembl_common_name\", name " + " FROM ncbi_taxa_name WHERE name_class = \"ensembl common name\" AND taxon_id = " + taxon_id; sql2 = "SELECT \"ensembl_common_name\", meta_value FROM meta" + " WHERE meta_key = \"species.ensembl_common_name\" and meta_value != \"\""; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); /* Check ensembl_alias_name */ sql1 = "SELECT \"ensembl_alias_name\", name " + " FROM ncbi_taxa_name WHERE name_class = \"ensembl alias name\" AND taxon_id = " + taxon_id; sql2 = "SELECT \"ensembl_alias_name\", meta_value FROM meta" + " WHERE meta_key = \"species.ensembl_alias_name\" and meta_value != \"\""; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); /* Check classification */ /* This check is quite complex as the axonomy is stored in very different ways in compara and core DBs. In compara, the tree structure is stored in the ncbi_taxa_node table while the names are in the ncbi_taxa_name table. In the core DB, the taxonomy is stored in the meta table as values of the key "species.classification" and they should be sorted by meta_id. In the core DB, only the abbreviated lineage is described which means that we have to ignore ncbi_taxa_node with the genbank_hidden_flag set. On top of that, we want to compare the classification in one single SQL. Therefore, we are getting the results recursivelly and then execute a dumb SQL query with result itself */ String comparaClassification = ""; String values1[] = getRowValues(comparaCon, "SELECT rank, parent_id, genbank_hidden_flag FROM ncbi_taxa_node WHERE taxon_id = " + taxon_id); if (values1.length == 0) { /* if no rows are fetched, this taxon is missing from compara DB */ ReportManager.problem(this, comparaCon, "No taxon for " + species.toString()); } else { String this_taxon_id = values1[1]; while (!this_taxon_id.equals("0")) { values1 = getRowValues(comparaCon, "SELECT rank, parent_id, genbank_hidden_flag FROM ncbi_taxa_node WHERE taxon_id = " + this_taxon_id); if ( // values1[2].equals("0") && // we used to filter out entries with genbank_hidden_flag, we don't anymore !this_taxon_id.equals("33154") && // "Fungi/Metazoa" node (under various names) has to be excluded !values1[1].equals("1") && !values1[1].equals("0") && !values1[0].equals("subgenus") && !values1[0].equals("subspecies") ) { String taxonName = getRowColumnValue(comparaCon, "SELECT name FROM ncbi_taxa_name " + "WHERE name_class = \"scientific name\" AND taxon_id = " + this_taxon_id); // spaces within taxa are not allowed by the script that loads taxonomy into core: if (taxonName.indexOf(' ')==-1) { comparaClassification += " " + taxonName; } } this_taxon_id = values1[1]; } sql1 = "SELECT \"classification\", \"" + comparaClassification + "\""; /* It will be much better to run this using GROUP_CONCAT() but our MySQL server does not support it yet */ sql2 = "SELECT \"classification\", \""; String[] values2 = getColumnValues(speciesCon, "SELECT meta_value FROM meta WHERE meta_key = \"species.classification\"" + " ORDER BY meta_id"); /* Skip first value as it is part of the species name and not the lineage */ for (int a = 1; a < values2.length; a++) { sql2 += " " + values2[a]; } sql2 += "\""; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); } } else { ReportManager.problem(this, comparaCon, "No connection for " + species.toString()); allSpeciesFound = false; } } if (!allSpeciesFound) { usage(); } return result; } /** * Prints the usage through the ReportManager * * @param * The database registry containing all the specified databases. * @return true if the all the dnafrags are top_level seq_regions in their corresponding * core database. */ private void usage() { ReportManager.problem(this, "USAGE", "run-healthcheck.sh -d ensembl_compara_.+ " + " -d2 .+_core_.+ CheckTaxon"); } } // CheckTopLevelDnaFrag
package org.game_host.hebo.nullpomino.gui.net; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.Locale; import java.util.zip.Adler32; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.ListSelectionModel; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.game_host.hebo.nullpomino.game.component.RuleOptions; import org.game_host.hebo.nullpomino.game.net.NetBaseClient; import org.game_host.hebo.nullpomino.game.net.NetMessageListener; import org.game_host.hebo.nullpomino.game.net.NetPlayerClient; import org.game_host.hebo.nullpomino.game.net.NetPlayerInfo; import org.game_host.hebo.nullpomino.game.net.NetRoomInfo; import org.game_host.hebo.nullpomino.game.net.NetUtil; import org.game_host.hebo.nullpomino.util.CustomProperties; import org.game_host.hebo.nullpomino.util.GeneralUtil; public class NetLobbyFrame extends JFrame implements ActionListener, NetMessageListener { private static final long serialVersionUID = 1L; public static final String[] ROOMTABLE_COLUMNNAMES = { "RoomTable_ID", "RoomTable_Name", "RoomTable_RuleName", "RoomTable_Status", "RoomTable_Players", "RoomTable_Spectators" }; public static final String[] STATTABLE_COLUMNNAMES = { "StatTable_Rank", "StatTable_Name", "StatTable_Attack", "StatTable_APM", "StatTable_Lines", "StatTable_LPM", "StatTable_Piece", "StatTable_PPS", "StatTable_Time", "StatTable_KO", "StatTable_Wins", "StatTable_Games" }; public static final String[] COMBOBOX_SPINBONUS_NAMES = {"CreateRoom_TSpin_Disable", "CreateRoom_TSpin_TOnly", "CreateRoom_TSpin_All"}; /** Names for spin check types */ public static final String[] COMBOBOX_SPINCHECKTYPE_NAMES = {"CreateRoom_SpinCheck_4Point", "CreateRoom_SpinCheck_Immobile"}; public static final int SCREENCARD_SERVERSELECT = 0, SCREENCARD_LOBBY = 1, SCREENCARD_ROOM = 2, SCREENCARD_SERVERADD = 3, SCREENCARD_CREATEROOM = 4; public static final String[] SCREENCARD_NAMES = {"ServerSelect", "Lobby", "Room", "ServerAdd", "CreateRoom"}; static final Logger log = Logger.getLogger(NetLobbyFrame.class); public NetPlayerClient netPlayerClient; public RuleOptions ruleOpt; protected LinkedList<NetLobbyListener> listeners = new LinkedList<NetLobbyListener>(); protected CustomProperties propConfig; /** Swing */ protected CustomProperties propSwingConfig; protected CustomProperties propObserver; /** Default language file */ protected CustomProperties propLangDefault; protected CustomProperties propLang; protected int currentScreenCardNumber; protected int currentViewDetailRoomID = -1; /** NetRoomInfo */ protected NetRoomInfo backupRoomInfo; /** PrintWriter */ protected PrintWriter writerChatLog; protected CardLayout contentPaneCardLayout; protected JTextField txtfldPlayerName; protected JTextField txtfldPlayerTeam; protected JList listboxServerList; protected DefaultListModel listmodelServerList; protected JButton btnServerConnect; protected JSplitPane splitLobby; protected CardLayout roomListTopBarCardLayout; protected JPanel subpanelRoomListTopBar; protected JButton btnRoomListQuickStart; protected JButton btnRoomListRoomCreate; protected JButton btnRoomListTeamChange; protected JTextField txtfldRoomListTeam; protected JTable tableRoomList; protected String[] strTableColumnNames; protected DefaultTableModel tablemodelRoomList; protected JSplitPane splitLobbyChat; protected JTextPane txtpaneLobbyChatLog; protected JList listboxLobbyChatPlayerList; protected DefaultListModel listmodelLobbyChatPlayerList; protected JTextField txtfldLobbyChatInput; protected JButton btnLobbyChatSend; protected JButton btnRoomButtonsJoin; protected JButton btnRoomButtonsSitOut; protected JButton btnRoomButtonsTeamChange; protected JSplitPane splitRoom; protected CardLayout roomTopBarCardLayout; protected JPanel subpanelRoomTopBar; protected JTable tableGameStat; protected String[] strGameStatTableColumnNames; protected DefaultTableModel tablemodelGameStat; protected JSplitPane splitRoomChat; protected JTextPane txtpaneRoomChatLog; protected JList listboxRoomChatPlayerList; protected DefaultListModel listmodelRoomChatPlayerList; protected LinkedList<NetPlayerInfo> sameRoomPlayerInfoList; protected JTextField txtfldRoomChatInput; protected JButton btnRoomChatSend; protected JTextField txtfldRoomTeam; protected JTextField txtfldServerAddHost; protected JButton btnServerAddOK; protected JTextField txtfldCreateRoomName; protected JSpinner spinnerCreateRoomMaxPlayers; protected JSpinner spinnerCreateRoomAutoStartSeconds; protected JSpinner spinnerCreateRoomGravity; protected JSpinner spinnerCreateRoomDenominator; /** ARE() */ protected JSpinner spinnerCreateRoomARE; /** ARE() */ protected JSpinner spinnerCreateRoomARELine; protected JSpinner spinnerCreateRoomLineDelay; protected JSpinner spinnerCreateRoomLockDelay; protected JSpinner spinnerCreateRoomDAS; /** Hurryup() */ protected JSpinner spinnerCreateRoomHurryupSeconds; /** Hurryup() */ protected JSpinner spinnerCreateRoomHurryupInterval; protected JSpinner spinnerCreateRoomMapSetID; /** Rate of change of garbage holes */ protected JSpinner spinnerCreateRoomGarbagePercent; protected JCheckBox chkboxCreateRoomUseMap; protected JCheckBox chkboxCreateRoomRuleLock; protected JComboBox comboboxCreateRoomTSpinEnableType; /** Spin recognition type (4-point, immobile, etc.) */ protected JComboBox comboboxCreateRoomSpinCheckType; /** B2B() */ protected JCheckBox chkboxCreateRoomB2B; protected JCheckBox chkboxCreateRoomCombo; /** Allow Rensa/Combo Block */ protected JCheckBox chkboxCreateRoomRensaBlock; /** Allow countering */ protected JCheckBox chkboxCreateRoomCounter; /** Enable bravo bonus */ protected JCheckBox chkboxCreateRoomBravo; /** Allow EZ spins */ protected JCheckBox chkboxCreateRoomTSpinEnableEZ; protected JCheckBox chkboxCreateRoomReduceLineSend; /** Set garbage type */ protected JCheckBox chkboxCreateRoomGarbageChangePerAttack; /** B2B chunk type */ protected JCheckBox chkboxCreateRoomB2BChunk; protected JCheckBox chkboxCreateRoomUseFractionalGarbage; /** TNET2() */ protected JCheckBox chkboxCreateRoomAutoStartTNET2; protected JCheckBox chkboxCreateRoomDisableTimerAfterSomeoneCancelled; protected JButton btnCreateRoomOK; protected JButton btnCreateRoomJoin; protected JButton btnCreateRoomWatch; /** Cancel Button (Create room screen) */ protected JButton btnCreateRoomCancel; public NetLobbyFrame() { super(); } public void init() { propConfig = new CustomProperties(); try { FileInputStream in = new FileInputStream("config/setting/netlobby.cfg"); propConfig.load(in); in.close(); } catch(IOException e) {} // Swing propSwingConfig = new CustomProperties(); try { FileInputStream in = new FileInputStream("config/setting/swing.cfg"); propSwingConfig.load(in); in.close(); } catch(IOException e) {} propObserver = new CustomProperties(); try { FileInputStream in = new FileInputStream("config/setting/netobserver.cfg"); propObserver.load(in); in.close(); } catch(IOException e) {} propLangDefault = new CustomProperties(); try { FileInputStream in = new FileInputStream("config/lang/netlobby_default.properties"); propLangDefault.load(in); in.close(); } catch (Exception e) { log.error("Couldn't load default UI language file", e); } propLang = new CustomProperties(); try { FileInputStream in = new FileInputStream("config/lang/netlobby_" + Locale.getDefault().getCountry() + ".properties"); propLang.load(in); in.close(); } catch(IOException e) {} // Look&Feel if(propSwingConfig.getProperty("option.usenativelookandfeel", true) == true) { try { UIManager.getInstalledLookAndFeels(); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { log.warn("Failed to set native look&feel", e); } } // WindowListener addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { shutdown(); } }); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setTitle(getUIText("Title_NetLobby")); initUI(); this.setSize(propConfig.getProperty("mainwindow.width", 500), propConfig.getProperty("mainwindow.height", 450)); this.setLocation(propConfig.getProperty("mainwindow.x", 0), propConfig.getProperty("mainwindow.y", 0)); // Listener if(listeners != null) { for(NetLobbyListener l: listeners) { if(l != null) l.netlobbyOnInit(this); } } } protected void initUI() { contentPaneCardLayout = new CardLayout(); this.getContentPane().setLayout(contentPaneCardLayout); initServerSelectUI(); initLobbyUI(); initRoomUI(); initServerAddUI(); initCreateRoomUI(); changeCurrentScreenCard(SCREENCARD_SERVERSELECT); } protected void initServerSelectUI() { JPanel mainpanelServerSelect = new JPanel(new BorderLayout()); this.getContentPane().add(mainpanelServerSelect, SCREENCARD_NAMES[SCREENCARD_SERVERSELECT]); JPanel subpanelNames = new JPanel(); subpanelNames.setLayout(new BoxLayout(subpanelNames, BoxLayout.Y_AXIS)); mainpanelServerSelect.add(subpanelNames, BorderLayout.NORTH); JPanel subpanelNameEntry = new JPanel(new BorderLayout()); subpanelNames.add(subpanelNameEntry); JLabel labelNameEntry = new JLabel(getUIText("ServerSelect_LabelName")); subpanelNameEntry.add(labelNameEntry, BorderLayout.WEST); txtfldPlayerName = new JTextField(); txtfldPlayerName.setComponentPopupMenu(new TextComponentPopupMenu(txtfldPlayerName)); txtfldPlayerName.setText(propConfig.getProperty("serverselect.txtfldPlayerName.text", "")); subpanelNameEntry.add(txtfldPlayerName, BorderLayout.CENTER); JPanel subpanelTeamEntry = new JPanel(new BorderLayout()); subpanelNames.add(subpanelTeamEntry); JLabel labelTeamEntry = new JLabel(getUIText("ServerSelect_LabelTeam")); subpanelTeamEntry.add(labelTeamEntry, BorderLayout.WEST); txtfldPlayerTeam = new JTextField(); txtfldPlayerTeam.setComponentPopupMenu(new TextComponentPopupMenu(txtfldPlayerTeam)); txtfldPlayerTeam.setText(propConfig.getProperty("serverselect.txtfldPlayerTeam.text", "")); subpanelTeamEntry.add(txtfldPlayerTeam, BorderLayout.CENTER); listmodelServerList = new DefaultListModel(); if(!loadListToDefaultListModel(listmodelServerList, "config/setting/netlobby_serverlist.cfg")) { loadListToDefaultListModel(listmodelServerList, "config/list/netlobby_serverlist_default.lst"); saveListFromDefaultListModel(listmodelServerList, "config/setting/netlobby_serverlist.cfg"); } listboxServerList = new JList(listmodelServerList); listboxServerList.setComponentPopupMenu(new ServerSelectListBoxPopupMenu()); listboxServerList.addMouseListener(new ServerSelectListBoxMouseAdapter()); listboxServerList.setSelectedValue(propConfig.getProperty("serverselect.listboxServerList.value", ""), true); JScrollPane spListboxServerSelect = new JScrollPane(listboxServerList); mainpanelServerSelect.add(spListboxServerSelect, BorderLayout.CENTER); JPanel subpanelServerAdd = new JPanel(); subpanelServerAdd.setLayout(new BoxLayout(subpanelServerAdd, BoxLayout.Y_AXIS)); mainpanelServerSelect.add(subpanelServerAdd, BorderLayout.EAST); JButton btnServerAdd = new JButton(getUIText("ServerSelect_ServerAdd")); btnServerAdd.setMaximumSize(new Dimension(Short.MAX_VALUE, btnServerAdd.getMaximumSize().height)); btnServerAdd.addActionListener(this); btnServerAdd.setActionCommand("ServerSelect_ServerAdd"); btnServerAdd.setMnemonic('A'); subpanelServerAdd.add(btnServerAdd); JButton btnServerDelete = new JButton(getUIText("ServerSelect_ServerDelete")); btnServerDelete.setMaximumSize(new Dimension(Short.MAX_VALUE, btnServerDelete.getMaximumSize().height)); btnServerDelete.addActionListener(this); btnServerDelete.setActionCommand("ServerSelect_ServerDelete"); btnServerDelete.setMnemonic('D'); subpanelServerAdd.add(btnServerDelete); JButton btnSetObserver = new JButton(getUIText("ServerSelect_SetObserver")); btnSetObserver.setMaximumSize(new Dimension(Short.MAX_VALUE, btnSetObserver.getMaximumSize().height)); btnSetObserver.addActionListener(this); btnSetObserver.setActionCommand("ServerSelect_SetObserver"); btnSetObserver.setMnemonic('S'); subpanelServerAdd.add(btnSetObserver); JButton btnUnsetObserver = new JButton(getUIText("ServerSelect_UnsetObserver")); btnUnsetObserver.setMaximumSize(new Dimension(Short.MAX_VALUE, btnUnsetObserver.getMaximumSize().height)); btnUnsetObserver.addActionListener(this); btnUnsetObserver.setActionCommand("ServerSelect_UnsetObserver"); btnUnsetObserver.setMnemonic('U'); subpanelServerAdd.add(btnUnsetObserver); JPanel subpanelServerSelectButtons = new JPanel(); subpanelServerSelectButtons.setLayout(new BoxLayout(subpanelServerSelectButtons, BoxLayout.X_AXIS)); mainpanelServerSelect.add(subpanelServerSelectButtons, BorderLayout.SOUTH); btnServerConnect = new JButton(getUIText("ServerSelect_Connect")); btnServerConnect.setMaximumSize(new Dimension(Short.MAX_VALUE, btnServerConnect.getMaximumSize().height)); btnServerConnect.addActionListener(this); btnServerConnect.setActionCommand("ServerSelect_Connect"); btnServerConnect.setMnemonic('C'); subpanelServerSelectButtons.add(btnServerConnect); JButton btnServerExit = new JButton(getUIText("ServerSelect_Exit")); btnServerExit.setMaximumSize(new Dimension(Short.MAX_VALUE, btnServerExit.getMaximumSize().height)); btnServerExit.addActionListener(this); btnServerExit.setActionCommand("ServerSelect_Exit"); btnServerExit.setMnemonic('X'); subpanelServerSelectButtons.add(btnServerExit); } protected void initLobbyUI() { JPanel mainpanelLobby = new JPanel(new BorderLayout()); this.getContentPane().add(mainpanelLobby, SCREENCARD_NAMES[SCREENCARD_LOBBY]); splitLobby = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitLobby.setDividerLocation(propConfig.getProperty("lobby.splitLobby.location", 200)); mainpanelLobby.add(splitLobby, BorderLayout.CENTER); JPanel subpanelRoomList = new JPanel(new BorderLayout()); subpanelRoomList.setMinimumSize(new Dimension(0,0)); splitLobby.setTopComponent(subpanelRoomList); roomListTopBarCardLayout = new CardLayout(); subpanelRoomListTopBar = new JPanel(roomListTopBarCardLayout); subpanelRoomList.add(subpanelRoomListTopBar, BorderLayout.NORTH); JPanel subpanelRoomListButtons = new JPanel(); subpanelRoomListTopBar.add(subpanelRoomListButtons, "Buttons"); //subpanelRoomList.add(subpanelRoomListButtons, BorderLayout.NORTH); btnRoomListQuickStart = new JButton(getUIText("Lobby_QuickStart")); btnRoomListQuickStart.addActionListener(this); btnRoomListQuickStart.setActionCommand("Lobby_QuickStart"); btnRoomListQuickStart.setMnemonic('Q'); btnRoomListQuickStart.setVisible(false); subpanelRoomListButtons.add(btnRoomListQuickStart); btnRoomListRoomCreate = new JButton(getUIText("Lobby_RoomCreate")); btnRoomListRoomCreate.addActionListener(this); btnRoomListRoomCreate.setActionCommand("Lobby_RoomCreate"); btnRoomListRoomCreate.setMnemonic('C'); subpanelRoomListButtons.add(btnRoomListRoomCreate); btnRoomListTeamChange = new JButton(getUIText("Lobby_TeamChange")); btnRoomListTeamChange.addActionListener(this); btnRoomListTeamChange.setActionCommand("Lobby_TeamChange"); btnRoomListTeamChange.setMnemonic('T'); subpanelRoomListButtons.add(btnRoomListTeamChange); JButton btnRoomListDisconnect = new JButton(getUIText("Lobby_Disconnect")); btnRoomListDisconnect.addActionListener(this); btnRoomListDisconnect.setActionCommand("Lobby_Disconnect"); btnRoomListDisconnect.setMnemonic('D'); subpanelRoomListButtons.add(btnRoomListDisconnect); JPanel subpanelRoomListTeam = new JPanel(new BorderLayout()); subpanelRoomListTopBar.add(subpanelRoomListTeam, "Team"); txtfldRoomListTeam = new JTextField(); subpanelRoomListTeam.add(txtfldRoomListTeam, BorderLayout.CENTER); JPanel subpanelRoomListTeamButtons = new JPanel(); subpanelRoomListTeam.add(subpanelRoomListTeamButtons, BorderLayout.EAST); JButton btnRoomListTeamOK = new JButton(getUIText("Lobby_TeamChange_OK")); btnRoomListTeamOK.addActionListener(this); btnRoomListTeamOK.setActionCommand("Lobby_TeamChange_OK"); btnRoomListTeamOK.setMnemonic('O'); subpanelRoomListTeamButtons.add(btnRoomListTeamOK); JButton btnRoomListTeamCancel = new JButton(getUIText("Lobby_TeamChange_Cancel")); btnRoomListTeamCancel.addActionListener(this); btnRoomListTeamCancel.setActionCommand("Lobby_TeamChange_Cancel"); btnRoomListTeamCancel.setMnemonic('C'); subpanelRoomListTeamButtons.add(btnRoomListTeamCancel); strTableColumnNames = new String[ROOMTABLE_COLUMNNAMES.length]; for(int i = 0; i < strTableColumnNames.length; i++) { strTableColumnNames[i] = getUIText(ROOMTABLE_COLUMNNAMES[i]); } tablemodelRoomList = new DefaultTableModel(strTableColumnNames, 0); tableRoomList = new JTable(tablemodelRoomList); tableRoomList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tableRoomList.setDefaultEditor(Object.class, null); tableRoomList.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); tableRoomList.getTableHeader().setReorderingAllowed(false); tableRoomList.setComponentPopupMenu(new RoomTablePopupMenu()); tableRoomList.addMouseListener(new RoomTableMouseAdapter()); tableRoomList.addKeyListener(new RoomTableKeyAdapter()); TableColumnModel tm = tableRoomList.getColumnModel(); tm.getColumn(0).setPreferredWidth(propConfig.getProperty("tableRoomList.width.id", 35)); tm.getColumn(1).setPreferredWidth(propConfig.getProperty("tableRoomList.width.name", 155)); tm.getColumn(2).setPreferredWidth(propConfig.getProperty("tableRoomList.width.rulename", 105)); tm.getColumn(3).setPreferredWidth(propConfig.getProperty("tableRoomList.width.status", 55)); tm.getColumn(4).setPreferredWidth(propConfig.getProperty("tableRoomList.width.players", 65)); tm.getColumn(5).setPreferredWidth(propConfig.getProperty("tableRoomList.width.spectators", 65)); JScrollPane spTableRoomList = new JScrollPane(tableRoomList); subpanelRoomList.add(spTableRoomList, BorderLayout.CENTER); JPanel subpanelLobbyChat = new JPanel(new BorderLayout()); subpanelLobbyChat.setMinimumSize(new Dimension(0,0)); splitLobby.setBottomComponent(subpanelLobbyChat); splitLobbyChat = new JSplitPane(); splitLobbyChat.setDividerLocation(propConfig.getProperty("lobby.splitLobbyChat.location", 350)); subpanelLobbyChat.add(splitLobbyChat, BorderLayout.CENTER); txtpaneLobbyChatLog = new JTextPane(); txtpaneLobbyChatLog.setComponentPopupMenu(new LogPopupMenu(txtpaneLobbyChatLog)); txtpaneLobbyChatLog.addKeyListener(new LogKeyAdapter()); JScrollPane spTxtpaneLobbyChatLog = new JScrollPane(txtpaneLobbyChatLog); spTxtpaneLobbyChatLog.setMinimumSize(new Dimension(0,0)); splitLobbyChat.setLeftComponent(spTxtpaneLobbyChatLog); listmodelLobbyChatPlayerList = new DefaultListModel(); listboxLobbyChatPlayerList = new JList(listmodelLobbyChatPlayerList); listboxLobbyChatPlayerList.setComponentPopupMenu(new ListBoxPopupMenu(listboxLobbyChatPlayerList)); JScrollPane spListboxLobbyChatPlayerList = new JScrollPane(listboxLobbyChatPlayerList); spListboxLobbyChatPlayerList.setMinimumSize(new Dimension(0, 0)); splitLobbyChat.setRightComponent(spListboxLobbyChatPlayerList); JPanel subpanelLobbyChatInputArea = new JPanel(new BorderLayout()); subpanelLobbyChat.add(subpanelLobbyChatInputArea, BorderLayout.SOUTH); txtfldLobbyChatInput = new JTextField(); txtfldLobbyChatInput.setComponentPopupMenu(new TextComponentPopupMenu(txtfldLobbyChatInput)); subpanelLobbyChatInputArea.add(txtfldLobbyChatInput, BorderLayout.CENTER); btnLobbyChatSend = new JButton(getUIText("Lobby_ChatSend")); btnLobbyChatSend.addActionListener(this); btnLobbyChatSend.setActionCommand("Lobby_ChatSend"); btnLobbyChatSend.setMnemonic('S'); subpanelLobbyChatInputArea.add(btnLobbyChatSend, BorderLayout.EAST); } protected void initRoomUI() { JPanel mainpanelRoom = new JPanel(new BorderLayout()); this.getContentPane().add(mainpanelRoom, SCREENCARD_NAMES[SCREENCARD_ROOM]); splitRoom = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitRoom.setDividerLocation(propConfig.getProperty("room.splitRoom.location", 200)); mainpanelRoom.add(splitRoom, BorderLayout.CENTER); JPanel subpanelRoomTop = new JPanel(new BorderLayout()); subpanelRoomTop.setMinimumSize(new Dimension(0,0)); splitRoom.setTopComponent(subpanelRoomTop); roomTopBarCardLayout = new CardLayout(); subpanelRoomTopBar = new JPanel(roomTopBarCardLayout); subpanelRoomTop.add(subpanelRoomTopBar, BorderLayout.NORTH); JPanel subpanelRoomButtons = new JPanel(); subpanelRoomTopBar.add(subpanelRoomButtons, "Buttons"); JButton btnRoomButtonsLeave = new JButton(getUIText("Room_Leave")); btnRoomButtonsLeave.addActionListener(this); btnRoomButtonsLeave.setActionCommand("Room_Leave"); btnRoomButtonsLeave.setMnemonic('L'); subpanelRoomButtons.add(btnRoomButtonsLeave); btnRoomButtonsJoin = new JButton(getUIText("Room_Join")); btnRoomButtonsJoin.addActionListener(this); btnRoomButtonsJoin.setActionCommand("Room_Join"); btnRoomButtonsJoin.setMnemonic('J'); btnRoomButtonsJoin.setVisible(false); subpanelRoomButtons.add(btnRoomButtonsJoin); btnRoomButtonsSitOut = new JButton(getUIText("Room_SitOut")); btnRoomButtonsSitOut.addActionListener(this); btnRoomButtonsSitOut.setActionCommand("Room_SitOut"); btnRoomButtonsSitOut.setMnemonic('O'); btnRoomButtonsSitOut.setVisible(false); subpanelRoomButtons.add(btnRoomButtonsSitOut); btnRoomButtonsTeamChange = new JButton(getUIText("Room_TeamChange")); btnRoomButtonsTeamChange.addActionListener(this); btnRoomButtonsTeamChange.setActionCommand("Room_TeamChange"); btnRoomButtonsTeamChange.setMnemonic('T'); subpanelRoomButtons.add(btnRoomButtonsTeamChange); JPanel subpanelRoomTeam = new JPanel(new BorderLayout()); subpanelRoomTopBar.add(subpanelRoomTeam, "Team"); txtfldRoomTeam = new JTextField(); subpanelRoomTeam.add(txtfldRoomTeam, BorderLayout.CENTER); JPanel subpanelRoomTeamButtons = new JPanel(); subpanelRoomTeam.add(subpanelRoomTeamButtons, BorderLayout.EAST); JButton btnRoomTeamOK = new JButton(getUIText("Room_TeamChange_OK")); btnRoomTeamOK.addActionListener(this); btnRoomTeamOK.setActionCommand("Room_TeamChange_OK"); btnRoomTeamOK.setMnemonic('O'); subpanelRoomTeamButtons.add(btnRoomTeamOK); JButton btnRoomTeamCancel = new JButton(getUIText("Room_TeamChange_Cancel")); btnRoomTeamCancel.addActionListener(this); btnRoomTeamCancel.setActionCommand("Room_TeamChange_Cancel"); btnRoomTeamCancel.setMnemonic('C'); subpanelRoomTeamButtons.add(btnRoomTeamCancel); JButton btnRoomButtonViewSetting = new JButton(getUIText("Room_ViewSetting")); btnRoomButtonViewSetting.addActionListener(this); btnRoomButtonViewSetting.setActionCommand("Room_ViewSetting"); btnRoomButtonViewSetting.setMnemonic('V'); subpanelRoomButtons.add(btnRoomButtonViewSetting); strGameStatTableColumnNames = new String[STATTABLE_COLUMNNAMES.length]; for(int i = 0; i < strGameStatTableColumnNames.length; i++) { strGameStatTableColumnNames[i] = getUIText(STATTABLE_COLUMNNAMES[i]); } tablemodelGameStat = new DefaultTableModel(strGameStatTableColumnNames, 0); tableGameStat = new JTable(tablemodelGameStat); tableGameStat.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tableGameStat.setDefaultEditor(Object.class, null); tableGameStat.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); tableGameStat.getTableHeader().setReorderingAllowed(false); TableColumnModel tm = tableGameStat.getColumnModel(); tm.getColumn(0).setPreferredWidth(propConfig.getProperty("tableGameStat.width.rank", 30)); tm.getColumn(1).setPreferredWidth(propConfig.getProperty("tableGameStat.width.name", 100)); tm.getColumn(2).setPreferredWidth(propConfig.getProperty("tableGameStat.width.attack", 55)); tm.getColumn(3).setPreferredWidth(propConfig.getProperty("tableGameStat.width.apm", 55)); // APM tm.getColumn(4).setPreferredWidth(propConfig.getProperty("tableGameStat.width.lines", 55)); tm.getColumn(5).setPreferredWidth(propConfig.getProperty("tableGameStat.width.lpm", 55)); // LPM tm.getColumn(6).setPreferredWidth(propConfig.getProperty("tableGameStat.width.piece", 55)); tm.getColumn(7).setPreferredWidth(propConfig.getProperty("tableGameStat.width.pps", 55)); // PPS tm.getColumn(8).setPreferredWidth(propConfig.getProperty("tableGameStat.width.time", 65)); tm.getColumn(9).setPreferredWidth(propConfig.getProperty("tableGameStat.width.ko", 40)); tm.getColumn(10).setPreferredWidth(propConfig.getProperty("tableGameStat.width.wins", 55)); tm.getColumn(11).setPreferredWidth(propConfig.getProperty("tableGameStat.width.games", 55)); JScrollPane spTableGameStat = new JScrollPane(tableGameStat); subpanelRoomTop.add(spTableGameStat, BorderLayout.CENTER); JPanel subpanelRoomChat = new JPanel(new BorderLayout()); subpanelRoomChat.setMinimumSize(new Dimension(0,0)); splitRoom.setBottomComponent(subpanelRoomChat); splitRoomChat = new JSplitPane(); splitRoomChat.setDividerLocation(propConfig.getProperty("room.splitRoomChat.location", 350)); subpanelRoomChat.add(splitRoomChat, BorderLayout.CENTER); txtpaneRoomChatLog = new JTextPane(); txtpaneRoomChatLog.setComponentPopupMenu(new LogPopupMenu(txtpaneRoomChatLog)); txtpaneRoomChatLog.addKeyListener(new LogKeyAdapter()); JScrollPane spTxtpaneRoomChatLog = new JScrollPane(txtpaneRoomChatLog); spTxtpaneRoomChatLog.setMinimumSize(new Dimension(0,0)); splitRoomChat.setLeftComponent(spTxtpaneRoomChatLog); sameRoomPlayerInfoList = new LinkedList<NetPlayerInfo>(); listmodelRoomChatPlayerList = new DefaultListModel(); listboxRoomChatPlayerList = new JList(listmodelRoomChatPlayerList); listboxRoomChatPlayerList.setComponentPopupMenu(new ListBoxPopupMenu(listboxRoomChatPlayerList)); JScrollPane spListboxRoomChatPlayerList = new JScrollPane(listboxRoomChatPlayerList); spListboxRoomChatPlayerList.setMinimumSize(new Dimension(0,0)); splitRoomChat.setRightComponent(spListboxRoomChatPlayerList); JPanel subpanelRoomChatInputArea = new JPanel(new BorderLayout()); subpanelRoomChat.add(subpanelRoomChatInputArea, BorderLayout.SOUTH); txtfldRoomChatInput = new JTextField(); txtfldRoomChatInput.setComponentPopupMenu(new TextComponentPopupMenu(txtfldRoomChatInput)); subpanelRoomChatInputArea.add(txtfldRoomChatInput, BorderLayout.CENTER); btnRoomChatSend = new JButton(getUIText("Room_ChatSend")); btnRoomChatSend.addActionListener(this); btnRoomChatSend.setActionCommand("Room_ChatSend"); btnRoomChatSend.setMnemonic('S'); subpanelRoomChatInputArea.add(btnRoomChatSend, BorderLayout.EAST); } protected void initServerAddUI() { JPanel mainpanelServerAdd = new JPanel(new BorderLayout()); this.getContentPane().add(mainpanelServerAdd, SCREENCARD_NAMES[SCREENCARD_SERVERADD]); JPanel containerpanelServerAdd = new JPanel(); containerpanelServerAdd.setLayout(new BoxLayout(containerpanelServerAdd, BoxLayout.Y_AXIS)); mainpanelServerAdd.add(containerpanelServerAdd, BorderLayout.NORTH); JPanel subpanelHost = new JPanel(new BorderLayout()); containerpanelServerAdd.add(subpanelHost); JLabel labelHost = new JLabel(getUIText("ServerAdd_Host")); subpanelHost.add(labelHost, BorderLayout.WEST); txtfldServerAddHost = new JTextField(); txtfldServerAddHost.setComponentPopupMenu(new TextComponentPopupMenu(txtfldServerAddHost)); subpanelHost.add(txtfldServerAddHost, BorderLayout.CENTER); JPanel subpanelButtons = new JPanel(); subpanelButtons.setLayout(new BoxLayout(subpanelButtons, BoxLayout.X_AXIS)); containerpanelServerAdd.add(subpanelButtons); btnServerAddOK = new JButton(getUIText("ServerAdd_OK")); btnServerAddOK.addActionListener(this); btnServerAddOK.setActionCommand("ServerAdd_OK"); btnServerAddOK.setMnemonic('O'); btnServerAddOK.setMaximumSize(new Dimension(Short.MAX_VALUE, btnServerAddOK.getMaximumSize().height)); subpanelButtons.add(btnServerAddOK); JButton btnServerAddCancel = new JButton(getUIText("ServerAdd_Cancel")); btnServerAddCancel.addActionListener(this); btnServerAddCancel.setActionCommand("ServerAdd_Cancel"); btnServerAddCancel.setMnemonic('C'); btnServerAddCancel.setMaximumSize(new Dimension(Short.MAX_VALUE, btnServerAddCancel.getMaximumSize().height)); subpanelButtons.add(btnServerAddCancel); } protected void initCreateRoomUI() { JPanel mainpanelCreateRoom = new JPanel(new BorderLayout()); this.getContentPane().add(mainpanelCreateRoom, SCREENCARD_NAMES[SCREENCARD_CREATEROOM]); JTabbedPane tabbedPane = new JTabbedPane(); mainpanelCreateRoom.add(tabbedPane, BorderLayout.CENTER); // tabs JPanel containerpanelCreateRoomMainOwner = new JPanel(new BorderLayout()); tabbedPane.addTab(getUIText("CreateRoom_Tab_Main"), containerpanelCreateRoomMainOwner); JPanel containerpanelCreateRoomSpeedOwner = new JPanel(new BorderLayout()); tabbedPane.addTab(getUIText("CreateRoom_Tab_Speed"), containerpanelCreateRoomSpeedOwner); // * Bonus tab JPanel containerpanelCreateRoomBonusOwner = new JPanel(new BorderLayout()); tabbedPane.addTab(getUIText("CreateRoom_Tab_Bonus"), containerpanelCreateRoomBonusOwner); // * Garbage tab JPanel containerpanelCreateRoomGarbageOwner = new JPanel(new BorderLayout()); tabbedPane.addTab(getUIText("CreateRoom_Tab_Garbage"), containerpanelCreateRoomGarbageOwner); // * Miscellaneous tab JPanel containerpanelCreateRoomMiscOwner = new JPanel(new BorderLayout()); tabbedPane.addTab(getUIText("CreateRoom_Tab_Misc"), containerpanelCreateRoomMiscOwner); // general tab JPanel containerpanelCreateRoomMain = new JPanel(); containerpanelCreateRoomMain.setLayout(new BoxLayout(containerpanelCreateRoomMain, BoxLayout.Y_AXIS)); containerpanelCreateRoomMainOwner.add(containerpanelCreateRoomMain, BorderLayout.NORTH); JPanel subpanelName = new JPanel(new BorderLayout()); containerpanelCreateRoomMain.add(subpanelName); JLabel labelName = new JLabel(getUIText("CreateRoom_Name")); subpanelName.add(labelName, BorderLayout.WEST); txtfldCreateRoomName = new JTextField(); txtfldCreateRoomName.setComponentPopupMenu(new TextComponentPopupMenu(txtfldCreateRoomName)); txtfldCreateRoomName.setToolTipText(getUIText("CreateRoom_Name_Tip")); subpanelName.add(txtfldCreateRoomName, BorderLayout.CENTER); JPanel subpanelMaxPlayers = new JPanel(new BorderLayout()); containerpanelCreateRoomMain.add(subpanelMaxPlayers); JLabel labelMaxPlayers = new JLabel(getUIText("CreateRoom_MaxPlayers")); subpanelMaxPlayers.add(labelMaxPlayers, BorderLayout.WEST); int defaultMaxPlayers = propConfig.getProperty("createroom.defaultMaxPlayers", 6); spinnerCreateRoomMaxPlayers = new JSpinner(new SpinnerNumberModel(defaultMaxPlayers, 1, 6, 1)); spinnerCreateRoomMaxPlayers.setPreferredSize(new Dimension(200, 20)); spinnerCreateRoomMaxPlayers.setToolTipText(getUIText("CreateRoom_MaxPlayers_Tip")); subpanelMaxPlayers.add(spinnerCreateRoomMaxPlayers, BorderLayout.EAST); // ** Hurryup JPanel subpanelHurryupSeconds = new JPanel(new BorderLayout()); containerpanelCreateRoomMain.add(subpanelHurryupSeconds); JLabel labelHurryupSeconds = new JLabel(getUIText("CreateRoom_HurryupSeconds")); subpanelHurryupSeconds.add(labelHurryupSeconds, BorderLayout.WEST); int defaultHurryupSeconds = propConfig.getProperty("createroom.defaultHurryupSeconds", 90); spinnerCreateRoomHurryupSeconds = new JSpinner(new SpinnerNumberModel(defaultHurryupSeconds, -1, 999, 1)); spinnerCreateRoomHurryupSeconds.setPreferredSize(new Dimension(200, 20)); spinnerCreateRoomHurryupSeconds.setToolTipText(getUIText("CreateRoom_HurryupSeconds_Tip")); subpanelHurryupSeconds.add(spinnerCreateRoomHurryupSeconds, BorderLayout.EAST); // ** Hurryup JPanel subpanelHurryupInterval = new JPanel(new BorderLayout()); containerpanelCreateRoomMain.add(subpanelHurryupInterval); JLabel labelHurryupInterval = new JLabel(getUIText("CreateRoom_HurryupInterval")); subpanelHurryupInterval.add(labelHurryupInterval, BorderLayout.WEST); int defaultHurryupInterval = propConfig.getProperty("createroom.defaultHurryupInterval", 5); spinnerCreateRoomHurryupInterval = new JSpinner(new SpinnerNumberModel(defaultHurryupInterval, 1, 99, 1)); spinnerCreateRoomHurryupInterval.setPreferredSize(new Dimension(200, 20)); spinnerCreateRoomHurryupInterval.setToolTipText(getUIText("CreateRoom_HurryupInterval_Tip")); subpanelHurryupInterval.add(spinnerCreateRoomHurryupInterval, BorderLayout.EAST); JPanel subpanelMapSetID = new JPanel(new BorderLayout()); containerpanelCreateRoomMain.add(subpanelMapSetID); JLabel labelMapSetID = new JLabel(getUIText("CreateRoom_MapSetID")); subpanelMapSetID.add(labelMapSetID, BorderLayout.WEST); int defaultMapSetID = propConfig.getProperty("createroom.defaultMapSetID", 0); spinnerCreateRoomMapSetID = new JSpinner(new SpinnerNumberModel(defaultMapSetID, 0, 99, 1)); spinnerCreateRoomMapSetID.setPreferredSize(new Dimension(200, 20)); spinnerCreateRoomMapSetID.setToolTipText(getUIText("CreateRoom_MapSetID_Tip")); subpanelMapSetID.add(spinnerCreateRoomMapSetID, BorderLayout.EAST); chkboxCreateRoomUseMap = new JCheckBox(getUIText("CreateRoom_UseMap")); chkboxCreateRoomUseMap.setMnemonic('P'); chkboxCreateRoomUseMap.setSelected(propConfig.getProperty("createroom.defaultUseMap", false)); chkboxCreateRoomUseMap.setToolTipText(getUIText("CreateRoom_UseMap_Tip")); containerpanelCreateRoomMain.add(chkboxCreateRoomUseMap); chkboxCreateRoomRuleLock = new JCheckBox(getUIText("CreateRoom_RuleLock")); chkboxCreateRoomRuleLock.setMnemonic('L'); chkboxCreateRoomRuleLock.setSelected(propConfig.getProperty("createroom.defaultRuleLock", false)); chkboxCreateRoomRuleLock.setToolTipText(getUIText("CreateRoom_RuleLock_Tip")); containerpanelCreateRoomMain.add(chkboxCreateRoomRuleLock); // speed tab JPanel containerpanelCreateRoomSpeed = new JPanel(); containerpanelCreateRoomSpeed.setLayout(new BoxLayout(containerpanelCreateRoomSpeed, BoxLayout.Y_AXIS)); containerpanelCreateRoomSpeedOwner.add(containerpanelCreateRoomSpeed, BorderLayout.NORTH); JPanel subpanelGravity = new JPanel(new BorderLayout()); containerpanelCreateRoomSpeed.add(subpanelGravity); JLabel labelGravity = new JLabel(getUIText("CreateRoom_Gravity")); subpanelGravity.add(labelGravity, BorderLayout.WEST); int defaultGravity = propConfig.getProperty("createroom.defaultGravity", 1); spinnerCreateRoomGravity = new JSpinner(new SpinnerNumberModel(defaultGravity, -1, 99999, 1)); spinnerCreateRoomGravity.setPreferredSize(new Dimension(200, 20)); subpanelGravity.add(spinnerCreateRoomGravity, BorderLayout.EAST); JPanel subpanelDenominator = new JPanel(new BorderLayout()); containerpanelCreateRoomSpeed.add(subpanelDenominator); JLabel labelDenominator = new JLabel(getUIText("CreateRoom_Denominator")); subpanelDenominator.add(labelDenominator, BorderLayout.WEST); int defaultDenominator = propConfig.getProperty("createroom.defaultDenominator", 60); spinnerCreateRoomDenominator = new JSpinner(new SpinnerNumberModel(defaultDenominator, 0, 99999, 1)); spinnerCreateRoomDenominator.setPreferredSize(new Dimension(200, 20)); subpanelDenominator.add(spinnerCreateRoomDenominator, BorderLayout.EAST); // ** ARE JPanel subpanelARE = new JPanel(new BorderLayout()); containerpanelCreateRoomSpeed.add(subpanelARE); JLabel labelARE = new JLabel(getUIText("CreateRoom_ARE")); subpanelARE.add(labelARE, BorderLayout.WEST); int defaultARE = propConfig.getProperty("createroom.defaultARE", 30); spinnerCreateRoomARE = new JSpinner(new SpinnerNumberModel(defaultARE, 0, 99, 1)); spinnerCreateRoomARE.setPreferredSize(new Dimension(200, 20)); subpanelARE.add(spinnerCreateRoomARE, BorderLayout.EAST); // ** ARE JPanel subpanelARELine = new JPanel(new BorderLayout()); containerpanelCreateRoomSpeed.add(subpanelARELine); JLabel labelARELine = new JLabel(getUIText("CreateRoom_ARELine")); subpanelARELine.add(labelARELine, BorderLayout.WEST); int defaultARELine = propConfig.getProperty("createroom.defaultARELine", 30); spinnerCreateRoomARELine = new JSpinner(new SpinnerNumberModel(defaultARELine, 0, 99, 1)); spinnerCreateRoomARELine.setPreferredSize(new Dimension(200, 20)); subpanelARELine.add(spinnerCreateRoomARELine, BorderLayout.EAST); JPanel subpanelLineDelay = new JPanel(new BorderLayout()); containerpanelCreateRoomSpeed.add(subpanelLineDelay); JLabel labelLineDelay = new JLabel(getUIText("CreateRoom_LineDelay")); subpanelLineDelay.add(labelLineDelay, BorderLayout.WEST); int defaultLineDelay = propConfig.getProperty("createroom.defaultLineDelay", 20); spinnerCreateRoomLineDelay = new JSpinner(new SpinnerNumberModel(defaultLineDelay, 0, 99, 1)); spinnerCreateRoomLineDelay.setPreferredSize(new Dimension(200, 20)); subpanelLineDelay.add(spinnerCreateRoomLineDelay, BorderLayout.EAST); JPanel subpanelLockDelay = new JPanel(new BorderLayout()); containerpanelCreateRoomSpeed.add(subpanelLockDelay); JLabel labelLockDelay = new JLabel(getUIText("CreateRoom_LockDelay")); subpanelLockDelay.add(labelLockDelay, BorderLayout.WEST); int defaultLockDelay = propConfig.getProperty("createroom.defaultLockDelay", 30); spinnerCreateRoomLockDelay = new JSpinner(new SpinnerNumberModel(defaultLockDelay, 0, 98, 1)); spinnerCreateRoomLockDelay.setPreferredSize(new Dimension(200, 20)); subpanelLockDelay.add(spinnerCreateRoomLockDelay, BorderLayout.EAST); JPanel subpanelDAS = new JPanel(new BorderLayout()); containerpanelCreateRoomSpeed.add(subpanelDAS); JLabel labelDAS = new JLabel(getUIText("CreateRoom_DAS")); subpanelDAS.add(labelDAS, BorderLayout.WEST); int defaultDAS = propConfig.getProperty("createroom.defaultDAS", 14); spinnerCreateRoomDAS = new JSpinner(new SpinnerNumberModel(defaultDAS, 0, 99, 1)); spinnerCreateRoomDAS.setPreferredSize(new Dimension(200, 20)); subpanelDAS.add(spinnerCreateRoomDAS, BorderLayout.EAST); // bonus tab // bonus panel JPanel containerpanelCreateRoomBonus = new JPanel(); containerpanelCreateRoomBonus.setLayout(new BoxLayout(containerpanelCreateRoomBonus, BoxLayout.Y_AXIS)); containerpanelCreateRoomBonusOwner.add(containerpanelCreateRoomBonus, BorderLayout.NORTH); JPanel subpanelTSpinEnableType = new JPanel(new BorderLayout()); containerpanelCreateRoomBonus.add(subpanelTSpinEnableType); JLabel labelTSpinEnableType = new JLabel(getUIText("CreateRoom_TSpinEnableType")); subpanelTSpinEnableType.add(labelTSpinEnableType, BorderLayout.WEST); String[] strSpinBonusNames = new String[COMBOBOX_SPINBONUS_NAMES.length]; for(int i = 0; i < strSpinBonusNames.length; i++) { strSpinBonusNames[i] = getUIText(COMBOBOX_SPINBONUS_NAMES[i]); } comboboxCreateRoomTSpinEnableType = new JComboBox(strSpinBonusNames); comboboxCreateRoomTSpinEnableType.setSelectedIndex(propConfig.getProperty("createroom.defaultTSpinEnableType", 1)); comboboxCreateRoomTSpinEnableType.setPreferredSize(new Dimension(200, 20)); comboboxCreateRoomTSpinEnableType.setToolTipText(getUIText("CreateRoom_TSpinEnableType_Tip")); subpanelTSpinEnableType.add(comboboxCreateRoomTSpinEnableType, BorderLayout.EAST); // ** Spin check type panel JPanel subpanelSpinCheckType = new JPanel(new BorderLayout()); containerpanelCreateRoomBonus.add(subpanelSpinCheckType); JLabel labelSpinCheckType = new JLabel(getUIText("CreateRoom_SpinCheckType")); subpanelSpinCheckType.add(labelSpinCheckType, BorderLayout.WEST); String[] strSpinCheckTypeNames = new String[COMBOBOX_SPINCHECKTYPE_NAMES.length]; for(int i = 0; i < strSpinCheckTypeNames.length; i++) { strSpinCheckTypeNames[i] = getUIText(COMBOBOX_SPINCHECKTYPE_NAMES[i]); } comboboxCreateRoomSpinCheckType = new JComboBox(strSpinCheckTypeNames); comboboxCreateRoomSpinCheckType.setSelectedIndex(propConfig.getProperty("createroom.defaultSpinCheckType", 0)); comboboxCreateRoomSpinCheckType.setPreferredSize(new Dimension(200, 20)); comboboxCreateRoomSpinCheckType.setToolTipText(getUIText("CreateRoom_SpinCheckType_Tip")); subpanelSpinCheckType.add(comboboxCreateRoomSpinCheckType, BorderLayout.EAST); // ** EZ Spin checkbox chkboxCreateRoomTSpinEnableEZ = new JCheckBox(getUIText("CreateRoom_TSpinEnableEZ")); chkboxCreateRoomTSpinEnableEZ.setMnemonic('E'); chkboxCreateRoomTSpinEnableEZ.setSelected(propConfig.getProperty("createroom.defaultTSpinEnableEZ", false)); chkboxCreateRoomTSpinEnableEZ.setToolTipText(getUIText("CreateRoom_TSpinEnableEZ_Tip")); containerpanelCreateRoomBonus.add(chkboxCreateRoomTSpinEnableEZ); // ** B2B chkboxCreateRoomB2B = new JCheckBox(getUIText("CreateRoom_B2B")); chkboxCreateRoomB2B.setMnemonic('B'); chkboxCreateRoomB2B.setSelected(propConfig.getProperty("createroom.defaultB2B", true)); chkboxCreateRoomB2B.setToolTipText(getUIText("CreateRoom_B2B_Tip")); containerpanelCreateRoomBonus.add(chkboxCreateRoomB2B); chkboxCreateRoomCombo = new JCheckBox(getUIText("CreateRoom_Combo")); chkboxCreateRoomCombo.setMnemonic('M'); chkboxCreateRoomCombo.setSelected(propConfig.getProperty("createroom.defaultCombo", true)); chkboxCreateRoomCombo.setToolTipText(getUIText("CreateRoom_Combo_Tip")); containerpanelCreateRoomBonus.add(chkboxCreateRoomCombo); // ** Bravo bonus chkboxCreateRoomBravo = new JCheckBox(getUIText("CreateRoom_Bravo")); chkboxCreateRoomBravo.setMnemonic('A'); chkboxCreateRoomBravo.setSelected(propConfig.getProperty("createroom.defaultBravo", true)); chkboxCreateRoomBravo.setToolTipText(getUIText("CreateRoom_Bravo_Tip")); containerpanelCreateRoomBonus.add(chkboxCreateRoomBravo); // garbage tab // garbage panel JPanel containerpanelCreateRoomGarbage = new JPanel(); containerpanelCreateRoomGarbage.setLayout(new BoxLayout(containerpanelCreateRoomGarbage, BoxLayout.Y_AXIS)); containerpanelCreateRoomGarbageOwner.add(containerpanelCreateRoomGarbage, BorderLayout.NORTH); // ** Garbage change rate panel JPanel subpanelGarbagePercent = new JPanel(new BorderLayout()); containerpanelCreateRoomGarbage.add(subpanelGarbagePercent); // ** Label for garbage change rate JLabel labelGarbagePercent = new JLabel(getUIText("CreateRoom_GarbagePercent")); subpanelGarbagePercent.add(labelGarbagePercent, BorderLayout.WEST); // ** Spinner for garbage change rate int defaultGarbagePercent = propConfig.getProperty("createroom.defaultGarbagePercent", 100); spinnerCreateRoomGarbagePercent = new JSpinner(new SpinnerNumberModel(defaultGarbagePercent, 0, 100, 10)); spinnerCreateRoomGarbagePercent.setPreferredSize(new Dimension(200, 20)); spinnerCreateRoomGarbagePercent.setToolTipText(getUIText("CreateRoom_GarbagePercent_Tip")); subpanelGarbagePercent.add(spinnerCreateRoomGarbagePercent, BorderLayout.EAST); // ** Set garbage type chkboxCreateRoomGarbageChangePerAttack = new JCheckBox(getUIText("CreateRoom_GarbageChangePerAttack")); chkboxCreateRoomGarbageChangePerAttack.setMnemonic('G'); chkboxCreateRoomGarbageChangePerAttack.setSelected(propConfig.getProperty("createroom.defaultGarbageChangePerAttack", true)); chkboxCreateRoomGarbageChangePerAttack.setToolTipText(getUIText("CreateRoom_GarbageChangePerAttack_Tip")); containerpanelCreateRoomGarbage.add(chkboxCreateRoomGarbageChangePerAttack); // ** B2B chunk chkboxCreateRoomB2BChunk = new JCheckBox(getUIText("CreateRoom_B2BChunk")); chkboxCreateRoomB2BChunk.setMnemonic('B'); chkboxCreateRoomB2BChunk.setSelected(propConfig.getProperty("createroom.defaultB2BChunk", false)); chkboxCreateRoomB2BChunk.setToolTipText(getUIText("CreateRoom_B2BChunk_Tip")); containerpanelCreateRoomGarbage.add(chkboxCreateRoomB2BChunk); // ** Rensa/Combo Block chkboxCreateRoomRensaBlock = new JCheckBox(getUIText("CreateRoom_RensaBlock")); chkboxCreateRoomRensaBlock.setMnemonic('E'); chkboxCreateRoomRensaBlock.setSelected(propConfig.getProperty("createroom.defaultRensaBlock", true)); chkboxCreateRoomRensaBlock.setToolTipText(getUIText("CreateRoom_RensaBlock_Tip")); containerpanelCreateRoomGarbage.add(chkboxCreateRoomRensaBlock); // ** Garbage countering chkboxCreateRoomCounter = new JCheckBox(getUIText("CreateRoom_Counter")); chkboxCreateRoomCounter.setMnemonic('C'); chkboxCreateRoomCounter.setSelected(propConfig.getProperty("createroom.defaultCounter", true)); chkboxCreateRoomCounter.setToolTipText(getUIText("CreateRoom_Counter_Tip")); containerpanelCreateRoomGarbage.add(chkboxCreateRoomCounter); chkboxCreateRoomReduceLineSend = new JCheckBox(getUIText("CreateRoom_ReduceLineSend")); chkboxCreateRoomReduceLineSend.setMnemonic('R'); chkboxCreateRoomReduceLineSend.setSelected(propConfig.getProperty("createroom.defaultReduceLineSend", false)); chkboxCreateRoomReduceLineSend.setToolTipText(getUIText("CreateRoom_ReduceLineSend_Tip")); containerpanelCreateRoomGarbage.add(chkboxCreateRoomReduceLineSend); chkboxCreateRoomUseFractionalGarbage = new JCheckBox(getUIText("CreateRoom_UseFractionalGarbage")); chkboxCreateRoomUseFractionalGarbage.setMnemonic('F'); chkboxCreateRoomUseFractionalGarbage.setSelected(propConfig.getProperty("createroom.defaultUseFractionalGarbage", false)); chkboxCreateRoomUseFractionalGarbage.setToolTipText(getUIText("CreateRoom_UseFractionalGarbage_Tip")); containerpanelCreateRoomGarbage.add(chkboxCreateRoomUseFractionalGarbage); // misc tab // misc panel JPanel containerpanelCreateRoomMisc = new JPanel(); containerpanelCreateRoomMisc.setLayout(new BoxLayout(containerpanelCreateRoomMisc, BoxLayout.Y_AXIS)); containerpanelCreateRoomMiscOwner.add(containerpanelCreateRoomMisc, BorderLayout.NORTH); JPanel subpanelAutoStartSeconds = new JPanel(new BorderLayout()); containerpanelCreateRoomMisc.add(subpanelAutoStartSeconds); JLabel labelAutoStartSeconds = new JLabel(getUIText("CreateRoom_AutoStartSeconds")); subpanelAutoStartSeconds.add(labelAutoStartSeconds, BorderLayout.WEST); int defaultAutoStartSeconds = propConfig.getProperty("createroom.defaultAutoStartSeconds", 15); spinnerCreateRoomAutoStartSeconds = new JSpinner(new SpinnerNumberModel(defaultAutoStartSeconds, 0, 999, 1)); spinnerCreateRoomAutoStartSeconds.setPreferredSize(new Dimension(200, 20)); spinnerCreateRoomAutoStartSeconds.setToolTipText(getUIText("CreateRoom_AutoStartSeconds_Tip")); subpanelAutoStartSeconds.add(spinnerCreateRoomAutoStartSeconds, BorderLayout.EAST); // ** TNET2 chkboxCreateRoomAutoStartTNET2 = new JCheckBox(getUIText("CreateRoom_AutoStartTNET2")); chkboxCreateRoomAutoStartTNET2.setMnemonic('A'); chkboxCreateRoomAutoStartTNET2.setSelected(propConfig.getProperty("createroom.defaultAutoStartTNET2", false)); chkboxCreateRoomAutoStartTNET2.setToolTipText(getUIText("CreateRoom_AutoStartTNET2_Tip")); containerpanelCreateRoomMisc.add(chkboxCreateRoomAutoStartTNET2); chkboxCreateRoomDisableTimerAfterSomeoneCancelled = new JCheckBox(getUIText("CreateRoom_DisableTimerAfterSomeoneCancelled")); chkboxCreateRoomDisableTimerAfterSomeoneCancelled.setMnemonic('D'); chkboxCreateRoomDisableTimerAfterSomeoneCancelled.setSelected(propConfig.getProperty("createroom.defaultDisableTimerAfterSomeoneCancelled", false)); chkboxCreateRoomDisableTimerAfterSomeoneCancelled.setToolTipText(getUIText("CreateRoom_DisableTimerAfterSomeoneCancelled_Tip")); containerpanelCreateRoomMisc.add(chkboxCreateRoomDisableTimerAfterSomeoneCancelled); // buttons JPanel subpanelButtons = new JPanel(); subpanelButtons.setLayout(new BoxLayout(subpanelButtons, BoxLayout.X_AXIS)); //containerpanelCreateRoom.add(subpanelButtons); mainpanelCreateRoom.add(subpanelButtons, BorderLayout.SOUTH); btnCreateRoomOK = new JButton(getUIText("CreateRoom_OK")); btnCreateRoomOK.addActionListener(this); btnCreateRoomOK.setActionCommand("CreateRoom_OK"); btnCreateRoomOK.setMnemonic('O'); btnCreateRoomOK.setMaximumSize(new Dimension(Short.MAX_VALUE, btnCreateRoomOK.getMaximumSize().height)); subpanelButtons.add(btnCreateRoomOK); btnCreateRoomJoin = new JButton(getUIText("CreateRoom_Join")); btnCreateRoomJoin.addActionListener(this); btnCreateRoomJoin.setActionCommand("CreateRoom_Join"); btnCreateRoomJoin.setMnemonic('J'); btnCreateRoomJoin.setMaximumSize(new Dimension(Short.MAX_VALUE, btnCreateRoomJoin.getMaximumSize().height)); subpanelButtons.add(btnCreateRoomJoin); btnCreateRoomWatch = new JButton(getUIText("CreateRoom_Watch")); btnCreateRoomWatch.addActionListener(this); btnCreateRoomWatch.setActionCommand("CreateRoom_Watch"); btnCreateRoomWatch.setMnemonic('W'); btnCreateRoomWatch.setMaximumSize(new Dimension(Short.MAX_VALUE, btnCreateRoomWatch.getMaximumSize().height)); subpanelButtons.add(btnCreateRoomWatch); btnCreateRoomCancel = new JButton(getUIText("CreateRoom_Cancel")); btnCreateRoomCancel.addActionListener(this); btnCreateRoomCancel.setActionCommand("CreateRoom_Cancel"); btnCreateRoomCancel.setMnemonic('C'); btnCreateRoomCancel.setMaximumSize(new Dimension(Short.MAX_VALUE, btnCreateRoomCancel.getMaximumSize().height)); subpanelButtons.add(btnCreateRoomCancel); } /** * UI * @param str * @return UIstr */ public String getUIText(String str) { String result = propLang.getProperty(str); if(result == null) { result = propLangDefault.getProperty(str, str); } return result; } /** * * @param cardNumber */ public void changeCurrentScreenCard(int cardNumber) { contentPaneCardLayout.show(this.getContentPane(), SCREENCARD_NAMES[cardNumber]); currentScreenCardNumber = cardNumber; JButton defaultButton = null; switch(currentScreenCardNumber) { case SCREENCARD_SERVERSELECT: defaultButton = btnServerConnect; break; case SCREENCARD_LOBBY: defaultButton = btnLobbyChatSend; break; case SCREENCARD_ROOM: defaultButton = btnRoomChatSend; break; case SCREENCARD_SERVERADD: defaultButton = btnServerAddOK; break; case SCREENCARD_CREATEROOM: if (btnCreateRoomOK.isVisible()) defaultButton = btnCreateRoomOK; else defaultButton = btnCreateRoomCancel; break; } this.getRootPane().setDefaultButton(defaultButton); } /** * @return */ public JTextPane getCurrentChatLogTextPane() { if(currentScreenCardNumber == SCREENCARD_ROOM) { return txtpaneRoomChatLog; } return txtpaneLobbyChatLog; } /** * String * @return */ public String getCurrentTimeAsString() { GregorianCalendar currentTime = new GregorianCalendar(); String strTime = String.format("%02d:%02d:%02d", currentTime.get(Calendar.HOUR_OF_DAY), currentTime.get(Calendar.MINUTE), currentTime.get(Calendar.SECOND)); return strTime; } /** * * @param pInfo * @return () */ public String getPlayerNameWithTripCode(NetPlayerInfo pInfo) { return convTripCode(pInfo.strName); } /** * * @param s () * @return */ public String convTripCode(String s) { if(propLang.getProperty("TripSeparator_EnableConvert", false) == false) return s; String strName = s; strName = strName.replace(getUIText("TripSeparator_True"), getUIText("TripSeparator_False")); strName = strName.replace("!", getUIText("TripSeparator_True")); strName = strName.replace("?", getUIText("TripSeparator_False")); return strName; } /** * () * @param txtpane * @param str */ public void addSystemChatLog(JTextPane txtpane, String str) { addSystemChatLog(txtpane, str, null); } /** * () * @param txtpane * @param str * @param fgcolor (null) */ public void addSystemChatLog(JTextPane txtpane, String str, Color fgcolor) { String strTime = getCurrentTimeAsString(); SimpleAttributeSet sas = null; if(fgcolor != null) { sas = new SimpleAttributeSet(); StyleConstants.setForeground(sas, fgcolor); } try { Document doc = txtpane.getDocument(); doc.insertString(doc.getLength(), str + "\n", sas); txtpane.setCaretPosition(doc.getLength()); if(writerChatLog != null) { writerChatLog.println("[" + strTime + "] " + str); writerChatLog.flush(); } } catch (Exception e) {} } /** * () * @param txtpane * @param str */ public void addSystemChatLogLater(final JTextPane txtpane, final String str) { SwingUtilities.invokeLater(new Runnable() { public void run() { addSystemChatLog(txtpane, str); } }); } /** * () * @param txtpane * @param str * @param fgcolor (null) */ public void addSystemChatLogLater(final JTextPane txtpane, final String str, final Color fgcolor) { SwingUtilities.invokeLater(new Runnable() { public void run() { addSystemChatLog(txtpane, str, fgcolor); } }); } /** * () * @param txtpane * @param username * @param str */ public void addUserChatLog(JTextPane txtpane, String username, String str) { SimpleAttributeSet sasTime = new SimpleAttributeSet(); StyleConstants.setForeground(sasTime, Color.gray); String strTime = getCurrentTimeAsString(); SimpleAttributeSet sas = new SimpleAttributeSet(); StyleConstants.setBold(sas, true); StyleConstants.setUnderline(sas, true); try { Document doc = txtpane.getDocument(); doc.insertString(doc.getLength(), "[" + strTime + "]", sasTime); doc.insertString(doc.getLength(), "<" + username + ">", sas); doc.insertString(doc.getLength(), " " + str + "\n", null); txtpane.setCaretPosition(doc.getLength()); if(writerChatLog != null) { writerChatLog.println("[" + strTime + "]" + "<" + username + "> " + str); writerChatLog.flush(); } } catch (Exception e) {} } /** * () * @param txtpane * @param username * @param str */ public void addUserChatLogLater(final JTextPane txtpane, final String username, final String str) { SwingUtilities.invokeLater(new Runnable() { public void run() { addUserChatLog(txtpane, username, str); } }); } /** * DefaultListModel * @param listModel DefaultListModel * @param filename * @return true */ public boolean loadListToDefaultListModel(DefaultListModel listModel, String filename) { try { BufferedReader in = new BufferedReader(new FileReader(filename)); listModel.clear(); String str = null; while((str = in.readLine()) != null) { if(str.length() > 0) listModel.addElement(str); } } catch (IOException e) { log.debug("Failed to load server list", e); return false; } return true; } /** * DefaultListModel * @param listModel DefaultListModel * @param filename * @return true */ public boolean saveListFromDefaultListModel(DefaultListModel listModel, String filename) { try { PrintWriter out = new PrintWriter(filename); for(int i = 0; i < listModel.size(); i++) { out.println(listModel.get(i)); } out.flush(); out.close(); } catch (IOException e) { log.debug("Failed to save server list", e); return false; } return true; } /** * * @param b truefalse */ public void setLobbyButtonsEnabled(boolean b) { btnRoomListQuickStart.setEnabled(b); btnRoomListRoomCreate.setEnabled(b); btnRoomListTeamChange.setEnabled(b); btnLobbyChatSend.setEnabled(b); txtfldLobbyChatInput.setEnabled(b); } /** * * @param b truefalse */ public void setRoomButtonsEnabled(boolean b) { btnRoomButtonsTeamChange.setEnabled(b); btnRoomButtonsJoin.setEnabled(b); btnRoomButtonsSitOut.setEnabled(b); btnRoomChatSend.setEnabled(b); txtfldRoomChatInput.setEnabled(b); } /** * * @param b truefalse */ public void setRoomJoinButtonVisible(boolean b) { btnRoomButtonsJoin.setVisible(b); btnRoomButtonsJoin.setEnabled(true); btnRoomButtonsSitOut.setVisible(!b); btnRoomButtonsSitOut.setEnabled(true); } /** * * @param r * @return */ public String[] createRoomListRowData(NetRoomInfo r) { String[] rowData = new String[6]; rowData[0] = Integer.toString(r.roomID); rowData[1] = r.strName; rowData[2] = r.ruleLock ? r.ruleName.toUpperCase() : getUIText("RoomTable_RuleName_Any"); rowData[3] = r.playing ? getUIText("RoomTable_Status_Playing") : getUIText("RoomTable_Status_Waiting"); rowData[4] = r.playerSeatedCount + "/" + r.maxPlayers; rowData[5] = Integer.toString(r.spectatorCount); return rowData; } /** * * @param roomID ID * @param watch true */ public void joinRoom(int roomID, boolean watch) { changeCurrentScreenCard(SCREENCARD_ROOM); netPlayerClient.send("roomjoin\t" + roomID + "\t" + watch + "\n"); txtpaneRoomChatLog.setText(""); setRoomButtonsEnabled(false); } /** * * @param isDetailMode falsetrue * @param roomInfo (isDetailMode == true) */ public void setCreateRoomUIType(boolean isDetailMode, NetRoomInfo roomInfo) { NetRoomInfo r = null; if(isDetailMode) { btnCreateRoomOK.setVisible(false); btnCreateRoomJoin.setVisible(true); btnCreateRoomWatch.setVisible(true); r = roomInfo; if(netPlayerClient.getYourPlayerInfo().roomID != -1) { btnCreateRoomJoin.setVisible(false); btnCreateRoomWatch.setVisible(false); } } else { btnCreateRoomOK.setVisible(true); btnCreateRoomJoin.setVisible(false); btnCreateRoomWatch.setVisible(false); if(backupRoomInfo != null) { r = backupRoomInfo; } else { r = new NetRoomInfo(); r.maxPlayers = propConfig.getProperty("createroom.defaultMaxPlayers", 6); r.autoStartSeconds = propConfig.getProperty("createroom.defaultAutoStartSeconds", 15); r.gravity = propConfig.getProperty("createroom.defaultGravity", 1); r.denominator = propConfig.getProperty("createroom.defaultDenominator", 60); r.are = propConfig.getProperty("createroom.defaultARE", 30); r.areLine = propConfig.getProperty("createroom.defaultARELine", 30); r.lineDelay = propConfig.getProperty("createroom.defaultLineDelay", 20); r.lockDelay = propConfig.getProperty("createroom.defaultLockDelay", 30); r.das = propConfig.getProperty("createroom.defaultDAS", 14); r.hurryupSeconds = propConfig.getProperty("createroom.defaultHurryupSeconds", 90); r.hurryupInterval = propConfig.getProperty("createroom.defaultHurryupInterval", 5); r.garbagePercent = propConfig.getProperty("createroom.defaultGarbagePercent", 100); r.ruleLock = propConfig.getProperty("createroom.defaultRuleLock", false); r.tspinEnableType = propConfig.getProperty("createroom.defaultTSpinEnableType", 1); r.spinCheckType = propConfig.getProperty("createroom.defaultSpinCheckType", 0); r.b2b = propConfig.getProperty("createroom.defaultB2B", true); r.combo = propConfig.getProperty("createroom.defaultCombo", true); r.rensaBlock = propConfig.getProperty("createroom.defaultRensaBlock", true); r.counter = propConfig.getProperty("createroom.defaultCounter", true); r.bravo = propConfig.getProperty("createroom.defaultBravo", true); r.reduceLineSend = propConfig.getProperty("createroom.defaultReduceLineSend", false); r.garbageChangePerAttack = propConfig.getProperty("createroom.defaultGarbageChangePerAttack", true); r.b2bChunk = propConfig.getProperty("createroom.defaultB2BChunk", false); r.useFractionalGarbage = propConfig.getProperty("createroom.defaultUseFractionalGarbage", false); r.autoStartTNET2 = propConfig.getProperty("createroom.defaultAutoStartTNET2", false); r.disableTimerAfterSomeoneCancelled = propConfig.getProperty("createroom.defaultDisableTimerAfterSomeoneCancelled", false); r.useMap = propConfig.getProperty("createroom.defaultUseMap", false); //propConfig.getProperty("createroom.defaultMapSetID", 0); } } if(r != null) { txtfldCreateRoomName.setText(r.strName); spinnerCreateRoomMaxPlayers.setValue(r.maxPlayers); spinnerCreateRoomAutoStartSeconds.setValue(r.autoStartSeconds); spinnerCreateRoomGravity.setValue(r.gravity); spinnerCreateRoomDenominator.setValue(r.denominator); spinnerCreateRoomARE.setValue(r.are); spinnerCreateRoomARELine.setValue(r.areLine); spinnerCreateRoomLineDelay.setValue(r.lineDelay); spinnerCreateRoomLockDelay.setValue(r.lockDelay); spinnerCreateRoomDAS.setValue(r.das); spinnerCreateRoomHurryupSeconds.setValue(r.hurryupSeconds); spinnerCreateRoomHurryupInterval.setValue(r.hurryupInterval); spinnerCreateRoomGarbagePercent.setValue(r.garbagePercent); chkboxCreateRoomUseMap.setSelected(r.useMap); chkboxCreateRoomRuleLock.setSelected(r.ruleLock); comboboxCreateRoomTSpinEnableType.setSelectedIndex(r.tspinEnableType); comboboxCreateRoomSpinCheckType.setSelectedIndex(r.spinCheckType); chkboxCreateRoomTSpinEnableEZ.setSelected(r.tspinEnableEZ); chkboxCreateRoomB2B.setSelected(r.b2b); chkboxCreateRoomCombo.setSelected(r.combo); chkboxCreateRoomRensaBlock.setSelected(r.rensaBlock); chkboxCreateRoomCounter.setSelected(r.counter); chkboxCreateRoomBravo.setSelected(r.bravo); chkboxCreateRoomReduceLineSend.setSelected(r.reduceLineSend); chkboxCreateRoomGarbageChangePerAttack.setSelected(r.garbageChangePerAttack); chkboxCreateRoomB2BChunk.setSelected(r.b2bChunk); chkboxCreateRoomUseFractionalGarbage.setSelected(r.useFractionalGarbage); chkboxCreateRoomAutoStartTNET2.setSelected(r.autoStartTNET2); chkboxCreateRoomDisableTimerAfterSomeoneCancelled.setSelected(r.disableTimerAfterSomeoneCancelled); } } /** * * @param roomID ID */ public void viewRoomDetail(int roomID) { NetRoomInfo roomInfo = netPlayerClient.getRoomInfo(roomID); if(roomInfo != null) { currentViewDetailRoomID = roomID; setCreateRoomUIType(true, roomInfo); changeCurrentScreenCard(SCREENCARD_CREATEROOM); } } public void updateLobbyUserList() { LinkedList<NetPlayerInfo> pList = new LinkedList<NetPlayerInfo>(netPlayerClient.getPlayerInfoList()); if(!pList.isEmpty()) { listmodelLobbyChatPlayerList.clear(); for(int i = 0; i < pList.size(); i++) { NetPlayerInfo pInfo = pList.get(i); String name = getPlayerNameWithTripCode(pInfo); if(pInfo.uid == netPlayerClient.getPlayerUID()) name = "*" + getPlayerNameWithTripCode(pInfo); if(pInfo.strTeam.length() > 0) { name = getPlayerNameWithTripCode(pInfo) + " - " + pInfo.strTeam; if(pInfo.uid == netPlayerClient.getPlayerUID()) name = "*" + getPlayerNameWithTripCode(pInfo) + " - " + pInfo.strTeam; } if(pInfo.strCountry.length() > 0) { name += " (" + pInfo.strCountry + ")"; } if(pInfo.strHost.length() > 0) { name += " {" + pInfo.strHost + "}"; } if(pInfo.roomID == -1) { listmodelLobbyChatPlayerList.addElement(name); } } for(int i = 0; i < pList.size(); i++) { NetPlayerInfo pInfo = pList.get(i); String name = getPlayerNameWithTripCode(pInfo); if(pInfo.uid == netPlayerClient.getPlayerUID()) name = "*" + getPlayerNameWithTripCode(pInfo); if(pInfo.strTeam.length() > 0) { name = getPlayerNameWithTripCode(pInfo) + " - " + pInfo.strTeam; if(pInfo.uid == netPlayerClient.getPlayerUID()) name = "*" + getPlayerNameWithTripCode(pInfo) + " - " + pInfo.strTeam; } if(pInfo.strCountry.length() > 0) { name += " (" + pInfo.strCountry + ")"; } if(pInfo.strHost.length() > 0) { name += " {" + pInfo.strHost + "}"; } if(pInfo.roomID != -1) { listmodelLobbyChatPlayerList.addElement("{" + pInfo.roomID + "} " + name); } } } } public void updateRoomUserList() { NetRoomInfo roomInfo = netPlayerClient.getRoomInfo(netPlayerClient.getYourPlayerInfo().roomID); if(roomInfo == null) return; LinkedList<NetPlayerInfo> pList = new LinkedList<NetPlayerInfo>(netPlayerClient.getPlayerInfoList()); if(!pList.isEmpty()) { listmodelRoomChatPlayerList.clear(); for(int i = 0; i < roomInfo.maxPlayers; i++) { listmodelRoomChatPlayerList.addElement("[" + (i + 1) + "]"); } for(int i = 0; i < pList.size(); i++) { NetPlayerInfo pInfo = pList.get(i); String name = getPlayerNameWithTripCode(pInfo); if(pInfo.uid == netPlayerClient.getPlayerUID()) name = "*" + getPlayerNameWithTripCode(pInfo); if(pInfo.strTeam.length() > 0) { name = getPlayerNameWithTripCode(pInfo) + " - " + pInfo.strTeam; if(pInfo.uid == netPlayerClient.getPlayerUID()) name = "*" + getPlayerNameWithTripCode(pInfo) + " - " + pInfo.strTeam; } if(pInfo.strCountry.length() > 0) { name += " (" + pInfo.strCountry + ")"; } if(pInfo.strHost.length() > 0) { name += " {" + pInfo.strHost + "}"; } if(pInfo.playing) name += getUIText("RoomUserList_Playing"); else if(pInfo.ready) name += getUIText("RoomUserList_Ready"); if(pInfo.roomID == roomInfo.roomID) { if((pInfo.seatID >= 0) && (pInfo.seatID < roomInfo.maxPlayers)) { listmodelRoomChatPlayerList.set(pInfo.seatID, "[" + (pInfo.seatID + 1) + "] " + name); } else if(pInfo.queueID != -1) { listmodelRoomChatPlayerList.addElement((pInfo.queueID + 1) + ". " + name); } else { listmodelRoomChatPlayerList.addElement(name); } } } } } /** * * @return */ public LinkedList<NetPlayerInfo> updateSameRoomPlayerInfoList() { LinkedList<NetPlayerInfo> pList = new LinkedList<NetPlayerInfo>(netPlayerClient.getPlayerInfoList()); int roomID = netPlayerClient.getYourPlayerInfo().roomID; sameRoomPlayerInfoList.clear(); for(NetPlayerInfo pInfo: pList) { if(pInfo.roomID == roomID) { sameRoomPlayerInfoList.add(pInfo); } } return sameRoomPlayerInfoList; } /** * () * @return */ public LinkedList<NetPlayerInfo> getSameRoomPlayerInfoList() { return sameRoomPlayerInfoList; } public void sendMyRuleDataToServer() { if(ruleOpt == null) ruleOpt = new RuleOptions(); CustomProperties prop = new CustomProperties(); ruleOpt.writeProperty(prop, 0); String strRuleTemp = prop.encode("RuleData"); String strRuleData = NetUtil.compressString(strRuleTemp); log.debug("RuleData uncompressed:" + strRuleTemp.length() + " compressed:" + strRuleData.length()); Adler32 checksumObj = new Adler32(); checksumObj.update(NetUtil.stringToBytes(strRuleData)); long sChecksum = checksumObj.getValue(); netPlayerClient.send("ruledata\t" + sChecksum + "\t" + strRuleData + "\n"); } public void saveConfig() { propConfig.setProperty("mainwindow.width", this.getSize().width); propConfig.setProperty("mainwindow.height", this.getSize().height); propConfig.setProperty("mainwindow.x", this.getLocation().x); propConfig.setProperty("mainwindow.y", this.getLocation().y); propConfig.setProperty("lobby.splitLobby.location", splitLobby.getDividerLocation()); propConfig.setProperty("lobby.splitLobbyChat.location", splitLobbyChat.getDividerLocation()); propConfig.setProperty("room.splitRoom.location", splitRoom.getDividerLocation()); propConfig.setProperty("room.splitRoomChat.location", splitRoomChat.getDividerLocation()); propConfig.setProperty("serverselect.txtfldPlayerName.text", txtfldPlayerName.getText()); propConfig.setProperty("serverselect.txtfldPlayerTeam.text", txtfldPlayerTeam.getText()); Object listboxServerListSelectedValue = listboxServerList.getSelectedValue(); if((listboxServerListSelectedValue != null) && (listboxServerListSelectedValue instanceof String)) { propConfig.setProperty("serverselect.listboxServerList.value", (String)listboxServerListSelectedValue); } else { propConfig.setProperty("serverselect.listboxServerList.value", ""); } TableColumnModel tm = tableRoomList.getColumnModel(); propConfig.setProperty("tableRoomList.width.id", tm.getColumn(0).getWidth()); propConfig.setProperty("tableRoomList.width.name", tm.getColumn(1).getWidth()); propConfig.setProperty("tableRoomList.width.rulename", tm.getColumn(2).getWidth()); propConfig.setProperty("tableRoomList.width.status", tm.getColumn(3).getWidth()); propConfig.setProperty("tableRoomList.width.players", tm.getColumn(4).getWidth()); propConfig.setProperty("tableRoomList.width.spectators", tm.getColumn(5).getWidth()); tm = tableGameStat.getColumnModel(); propConfig.setProperty("tableGameStat.width.rank", tm.getColumn(0).getWidth()); propConfig.setProperty("tableGameStat.width.name", tm.getColumn(1).getWidth()); propConfig.setProperty("tableGameStat.width.attack", tm.getColumn(2).getWidth()); propConfig.setProperty("tableGameStat.width.apm", tm.getColumn(3).getWidth()); propConfig.setProperty("tableGameStat.width.lines", tm.getColumn(4).getWidth()); propConfig.setProperty("tableGameStat.width.lpm", tm.getColumn(5).getWidth()); propConfig.setProperty("tableGameStat.width.piece", tm.getColumn(6).getWidth()); propConfig.setProperty("tableGameStat.width.pps", tm.getColumn(7).getWidth()); propConfig.setProperty("tableGameStat.width.time", tm.getColumn(8).getWidth()); propConfig.setProperty("tableGameStat.width.ko", tm.getColumn(9).getWidth()); propConfig.setProperty("tableGameStat.width.wins", tm.getColumn(10).getWidth()); propConfig.setProperty("tableGameStat.width.games", tm.getColumn(11).getWidth()); if(backupRoomInfo != null) { propConfig.setProperty("createroom.defaultMaxPlayers", backupRoomInfo.maxPlayers); propConfig.setProperty("createroom.defaultAutoStartSeconds", backupRoomInfo.autoStartSeconds); propConfig.setProperty("createroom.defaultGravity", backupRoomInfo.gravity); propConfig.setProperty("createroom.defaultDenominator", backupRoomInfo.denominator); propConfig.setProperty("createroom.defaultARE", backupRoomInfo.are); propConfig.setProperty("createroom.defaultARELine", backupRoomInfo.areLine); propConfig.setProperty("createroom.defaultLineDelay", backupRoomInfo.lineDelay); propConfig.setProperty("createroom.defaultLockDelay", backupRoomInfo.lockDelay); propConfig.setProperty("createroom.defaultDAS", backupRoomInfo.das); propConfig.setProperty("createroom.defaultGarbagePercent", backupRoomInfo.garbagePercent); propConfig.setProperty("createroom.defaultHurryupSeconds", backupRoomInfo.hurryupSeconds); propConfig.setProperty("createroom.defaultHurryupInterval", backupRoomInfo.hurryupInterval); propConfig.setProperty("createroom.defaultRuleLock", backupRoomInfo.ruleLock); propConfig.setProperty("createroom.defaultTSpinEnableType", backupRoomInfo.tspinEnableType); propConfig.setProperty("createroom.defaultSpinCheckType", backupRoomInfo.spinCheckType); propConfig.setProperty("createroom.defaultTSpinEnableEZ", backupRoomInfo.tspinEnableEZ); propConfig.setProperty("createroom.defaultB2B", backupRoomInfo.b2b); propConfig.setProperty("createroom.defaultCombo", backupRoomInfo.combo); propConfig.setProperty("createroom.defaultRensaBlock", backupRoomInfo.rensaBlock); propConfig.setProperty("createroom.defaultCounter", backupRoomInfo.counter); propConfig.setProperty("createroom.defaultBravo", backupRoomInfo.bravo); propConfig.setProperty("createroom.defaultReduceLineSend", backupRoomInfo.reduceLineSend); propConfig.setProperty("createroom.defaultGarbageChangePerAttack", backupRoomInfo.garbageChangePerAttack); propConfig.setProperty("createroom.defaultB2BChunk", backupRoomInfo.b2bChunk); propConfig.setProperty("createroom.defaultUseFractionalGarbage", backupRoomInfo.useFractionalGarbage); propConfig.setProperty("createroom.defaultAutoStartTNET2", backupRoomInfo.autoStartTNET2); propConfig.setProperty("createroom.defaultDisableTimerAfterSomeoneCancelled", backupRoomInfo.disableTimerAfterSomeoneCancelled); propConfig.setProperty("createroom.defaultUseMap", backupRoomInfo.useMap); propConfig.setProperty("createroom.defaultMapSetID", (Integer)spinnerCreateRoomMapSetID.getValue()); } try { FileOutputStream out = new FileOutputStream("config/setting/netlobby.cfg"); propConfig.store(out, "NullpoMino NetLobby Config"); out.close(); } catch (IOException e) { log.warn("Failed to save netlobby config file", e); } } public void shutdown() { saveConfig(); if(writerChatLog != null) { writerChatLog.flush(); writerChatLog.close(); writerChatLog = null; } if(netPlayerClient != null) { if(netPlayerClient.isConnected()) { netPlayerClient.send("disconnect\n"); } netPlayerClient.threadRunning = false; netPlayerClient.interrupt(); netPlayerClient = null; } // Listener if(listeners != null) { for(NetLobbyListener l: listeners) { l.netlobbyOnExit(this); } listeners = null; } this.dispose(); } public void serverSelectDeleteButtonClicked() { int index = listboxServerList.getSelectedIndex(); if(index != -1) { String server = (String)listboxServerList.getSelectedValue(); int answer = JOptionPane.showConfirmDialog(this, getUIText("MessageBody_ServerDelete") + "\n" + server, getUIText("MessageTitle_ServerDelete"), JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.YES_OPTION) { listmodelServerList.remove(index); saveListFromDefaultListModel(listmodelServerList, "config/setting/netlobby_serverlist.cfg"); } } } public void serverSelectConnectButtonClicked() { int index = listboxServerList.getSelectedIndex(); if(index != -1) { String strServer = (String)listboxServerList.getSelectedValue(); int portSpliter = strServer.indexOf(":"); if(portSpliter == -1) portSpliter = strServer.length(); String strHost = strServer.substring(0, portSpliter); log.debug("Host:" + strHost); int port = NetPlayerClient.DEFAULT_PORT; try { String strPort = strServer.substring(portSpliter + 1, strServer.length()); port = Integer.parseInt(strPort); } catch (Exception e2) { log.debug("Failed to get port number; Try to use default port"); } log.debug("Port:" + port); netPlayerClient = new NetPlayerClient(strHost, port, txtfldPlayerName.getText(), txtfldPlayerTeam.getText().trim()); netPlayerClient.setDaemon(true); netPlayerClient.addListener(this); netPlayerClient.start(); txtpaneLobbyChatLog.setText(""); setLobbyButtonsEnabled(false); tablemodelRoomList.setRowCount(0); changeCurrentScreenCard(SCREENCARD_LOBBY); } } public void serverSelectSetObserverButtonClicked() { int index = listboxServerList.getSelectedIndex(); if(index != -1) { String strServer = (String)listboxServerList.getSelectedValue(); int portSpliter = strServer.indexOf(":"); if(portSpliter == -1) portSpliter = strServer.length(); String strHost = strServer.substring(0, portSpliter); log.debug("Host:" + strHost); int port = NetPlayerClient.DEFAULT_PORT; try { String strPort = strServer.substring(portSpliter + 1, strServer.length()); port = Integer.parseInt(strPort); } catch (Exception e2) { log.debug("Failed to get port number; Try to use default port"); } log.debug("Port:" + port); int answer = JOptionPane.showConfirmDialog(this, getUIText("MessageBody_SetObserver") + "\n" + strServer, getUIText("MessageTitle_SetObserver"), JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.YES_OPTION) { propObserver.setProperty("observer.enable", true); propObserver.setProperty("observer.host", strHost); propObserver.setProperty("observer.port", port); try { FileOutputStream out = new FileOutputStream("config/setting/netobserver.cfg"); propObserver.store(out, "NullpoMino NetObserver Config"); out.close(); } catch (IOException e) { log.warn("Failed to save NetObserver config file", e); } } } } /** * ID * @return ID */ public int getCurrentSelectedMapSetID() { if(spinnerCreateRoomMapSetID != null) { return (Integer)spinnerCreateRoomMapSetID.getValue(); } return 0; } /** * * @param strMsg */ public void sendChat(String strMsg) { String msg = strMsg; if(msg.startsWith("/team")) { msg = msg.replaceFirst("/team", ""); msg = msg.trim(); netPlayerClient.send("changeteam\t" + NetUtil.urlEncode(msg) + "\n"); } else { netPlayerClient.send("chat\t" + NetUtil.urlEncode(msg) + "\n"); } } public void actionPerformed(ActionEvent e) { //addSystemChatLog(getCurrentChatLogTextPane(), e.getActionCommand(), Color.magenta); if(e.getActionCommand() == "ServerSelect_ServerAdd") { changeCurrentScreenCard(SCREENCARD_SERVERADD); } if(e.getActionCommand() == "ServerSelect_ServerDelete") { serverSelectDeleteButtonClicked(); } if(e.getActionCommand() == "ServerSelect_Connect") { serverSelectConnectButtonClicked(); } if(e.getActionCommand() == "ServerSelect_SetObserver") { serverSelectSetObserverButtonClicked(); } if(e.getActionCommand() == "ServerSelect_UnsetObserver") { if(propObserver.getProperty("observer.enable", false) == true) { String strCurrentHost = propObserver.getProperty("observer.host", ""); int currentPort = propObserver.getProperty("observer.port", 0); String strMessageBox = String.format(getUIText("MessageBody_UnsetObserver"), strCurrentHost, currentPort); int answer = JOptionPane.showConfirmDialog(this, strMessageBox, getUIText("MessageTitle_UnsetObserver"), JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.YES_OPTION) { propObserver.setProperty("observer.enable", false); try { FileOutputStream out = new FileOutputStream("config/setting/netobserver.cfg"); propObserver.store(out, "NullpoMino NetObserver Config"); out.close(); } catch (IOException e2) { log.warn("Failed to save NetObserver config file", e2); } } } } if(e.getActionCommand() == "ServerSelect_Exit") { shutdown(); } if(e.getActionCommand() == "Lobby_QuickStart") { // TODO: } if(e.getActionCommand() == "Lobby_RoomCreate") { currentViewDetailRoomID = -1; setCreateRoomUIType(false, null); changeCurrentScreenCard(SCREENCARD_CREATEROOM); } if(e.getActionCommand() == "Lobby_TeamChange") { if((netPlayerClient != null) && (netPlayerClient.isConnected())) { txtfldRoomListTeam.setText(netPlayerClient.getYourPlayerInfo().strTeam); roomListTopBarCardLayout.next(subpanelRoomListTopBar); } } if(e.getActionCommand() == "Lobby_Disconnect") { if((netPlayerClient != null) && (netPlayerClient.isConnected())) { netPlayerClient.send("disconnect\n"); netPlayerClient.threadRunning = false; netPlayerClient.interrupt(); netPlayerClient = null; } changeCurrentScreenCard(SCREENCARD_SERVERSELECT); } if(e.getActionCommand() == "Lobby_ChatSend") { if((txtfldLobbyChatInput.getText().length() > 0) && (netPlayerClient != null) && netPlayerClient.isConnected()) { sendChat(txtfldLobbyChatInput.getText()); txtfldLobbyChatInput.setText(""); } } if(e.getActionCommand() == "Lobby_TeamChange_OK") { if((netPlayerClient != null) && (netPlayerClient.isConnected())) { netPlayerClient.send("changeteam\t" + NetUtil.urlEncode(txtfldRoomListTeam.getText()) + "\n"); roomListTopBarCardLayout.first(subpanelRoomListTopBar); } } if(e.getActionCommand() == "Lobby_TeamChange_Cancel") { roomListTopBarCardLayout.first(subpanelRoomListTopBar); } if(e.getActionCommand() == "Room_Leave") { netPlayerClient.send("roomjoin\t-1\tfalse\n"); txtpaneLobbyChatLog.setText(""); tablemodelGameStat.setRowCount(0); changeCurrentScreenCard(SCREENCARD_LOBBY); } if(e.getActionCommand() == "Room_Join") { netPlayerClient.send("changestatus\tfalse\n"); btnRoomButtonsJoin.setEnabled(false); } if(e.getActionCommand() == "Room_SitOut") { netPlayerClient.send("changestatus\ttrue\n"); btnRoomButtonsSitOut.setEnabled(false); } if(e.getActionCommand() == "Room_TeamChange") { if((netPlayerClient != null) && (netPlayerClient.isConnected())) { txtfldRoomTeam.setText(netPlayerClient.getYourPlayerInfo().strTeam); roomTopBarCardLayout.next(subpanelRoomTopBar); } } if(e.getActionCommand() == "Room_TeamChange_OK") { if((netPlayerClient != null) && (netPlayerClient.isConnected())) { netPlayerClient.send("changeteam\t" + NetUtil.urlEncode(txtfldRoomTeam.getText()) + "\n"); roomTopBarCardLayout.first(subpanelRoomTopBar); } } if(e.getActionCommand() == "Room_TeamChange_Cancel") { roomTopBarCardLayout.first(subpanelRoomTopBar); } if(e.getActionCommand() == "Room_ViewSetting") { viewRoomDetail(netPlayerClient.getYourPlayerInfo().roomID); } if(e.getActionCommand() == "Room_ChatSend") { if((txtfldRoomChatInput.getText().length() > 0) && (netPlayerClient != null) && netPlayerClient.isConnected()) { sendChat(txtfldRoomChatInput.getText()); txtfldRoomChatInput.setText(""); } } if(e.getActionCommand() == "ServerAdd_OK") { if(txtfldServerAddHost.getText().length() > 0) { listmodelServerList.addElement(txtfldServerAddHost.getText()); saveListFromDefaultListModel(listmodelServerList, "config/setting/netlobby_serverlist.cfg"); txtfldServerAddHost.setText(""); } changeCurrentScreenCard(SCREENCARD_SERVERSELECT); } if(e.getActionCommand() == "ServerAdd_Cancel") { txtfldServerAddHost.setText(""); changeCurrentScreenCard(SCREENCARD_SERVERSELECT); } if(e.getActionCommand() == "CreateRoom_OK") { try { String roomName = txtfldCreateRoomName.getText(); Integer integerMaxPlayers = (Integer)spinnerCreateRoomMaxPlayers.getValue(); Integer integerAutoStartSeconds = (Integer)spinnerCreateRoomAutoStartSeconds.getValue(); Integer integerGravity = (Integer)spinnerCreateRoomGravity.getValue(); Integer integerDenominator = (Integer)spinnerCreateRoomDenominator.getValue(); Integer integerARE = (Integer)spinnerCreateRoomARE.getValue(); Integer integerARELine = (Integer)spinnerCreateRoomARELine.getValue(); Integer integerLineDelay = (Integer)spinnerCreateRoomLineDelay.getValue(); Integer integerLockDelay = (Integer)spinnerCreateRoomLockDelay.getValue(); Integer integerDAS = (Integer)spinnerCreateRoomDAS.getValue(); Integer integerHurryupSeconds = (Integer)spinnerCreateRoomHurryupSeconds.getValue(); Integer integerHurryupInterval = (Integer)spinnerCreateRoomHurryupInterval.getValue(); boolean rulelock = chkboxCreateRoomRuleLock.isSelected(); int tspinEnableType = comboboxCreateRoomTSpinEnableType.getSelectedIndex(); int spinCheckType = comboboxCreateRoomSpinCheckType.getSelectedIndex(); boolean tspinEnableEZ = chkboxCreateRoomTSpinEnableEZ.isSelected(); boolean b2b = chkboxCreateRoomB2B.isSelected(); boolean combo = chkboxCreateRoomCombo.isSelected(); boolean rensaBlock = chkboxCreateRoomRensaBlock.isSelected(); boolean counter = chkboxCreateRoomCounter.isSelected(); boolean bravo = chkboxCreateRoomBravo.isSelected(); boolean reduceLineSend = chkboxCreateRoomReduceLineSend.isSelected(); boolean autoStartTNET2 = chkboxCreateRoomAutoStartTNET2.isSelected(); boolean disableTimerAfterSomeoneCancelled = chkboxCreateRoomDisableTimerAfterSomeoneCancelled.isSelected(); boolean useMap = chkboxCreateRoomUseMap.isSelected(); boolean useFractionalGarbage = chkboxCreateRoomUseFractionalGarbage.isSelected(); boolean garbageChangePerAttack = chkboxCreateRoomGarbageChangePerAttack.isSelected(); Integer integerGarbagePercent = (Integer)spinnerCreateRoomGarbagePercent.getValue(); boolean b2bChunk = chkboxCreateRoomB2BChunk.isSelected(); if(backupRoomInfo == null) backupRoomInfo = new NetRoomInfo(); backupRoomInfo.strName = roomName; backupRoomInfo.maxPlayers = integerMaxPlayers; backupRoomInfo.autoStartSeconds = integerAutoStartSeconds; backupRoomInfo.gravity = integerGravity; backupRoomInfo.denominator = integerDenominator; backupRoomInfo.are = integerARE; backupRoomInfo.areLine = integerARELine; backupRoomInfo.lineDelay = integerLineDelay; backupRoomInfo.lockDelay = integerLockDelay; backupRoomInfo.das = integerDAS; backupRoomInfo.hurryupSeconds = integerHurryupSeconds; backupRoomInfo.hurryupInterval = integerHurryupInterval; backupRoomInfo.ruleLock = rulelock; backupRoomInfo.tspinEnableType = tspinEnableType; backupRoomInfo.spinCheckType = spinCheckType; backupRoomInfo.tspinEnableEZ = tspinEnableEZ; backupRoomInfo.b2b = b2b; backupRoomInfo.combo = combo; backupRoomInfo.rensaBlock = rensaBlock; backupRoomInfo.counter = counter; backupRoomInfo.bravo = bravo; backupRoomInfo.reduceLineSend = reduceLineSend; backupRoomInfo.autoStartTNET2 = autoStartTNET2; backupRoomInfo.disableTimerAfterSomeoneCancelled = disableTimerAfterSomeoneCancelled; backupRoomInfo.useMap = useMap; backupRoomInfo.useFractionalGarbage = useFractionalGarbage; backupRoomInfo.garbageChangePerAttack = garbageChangePerAttack; backupRoomInfo.garbagePercent = integerGarbagePercent; backupRoomInfo.b2bChunk = b2bChunk; String msg; msg = "roomcreate\t" + roomName + "\t" + integerMaxPlayers + "\t" + integerAutoStartSeconds + "\t"; msg += integerGravity + "\t" + integerDenominator + "\t" + integerARE + "\t" + integerARELine + "\t"; msg += integerLineDelay + "\t" + integerLockDelay + "\t" + integerDAS + "\t" + rulelock + "\t"; msg += tspinEnableType + "\t" + b2b + "\t" + combo + "\t" + rensaBlock + "\t"; msg += counter + "\t" + bravo + "\t" + reduceLineSend + "\t" + integerHurryupSeconds + "\t"; msg += integerHurryupInterval + "\t" + autoStartTNET2 + "\t" + disableTimerAfterSomeoneCancelled + "\t"; msg += useMap + "\t" + useFractionalGarbage + "\t" + garbageChangePerAttack + "\t" + integerGarbagePercent + "\t"; msg += spinCheckType + "\t" + tspinEnableEZ + "\t" + b2bChunk + "\n"; txtpaneRoomChatLog.setText(""); setRoomButtonsEnabled(false); changeCurrentScreenCard(SCREENCARD_ROOM); netPlayerClient.send(msg); } catch (Exception e2) { log.error("Error on CreateRoom_OK", e2); } } if(e.getActionCommand() == "CreateRoom_Join") { joinRoom(currentViewDetailRoomID, false); } if(e.getActionCommand() == "CreateRoom_Watch") { joinRoom(currentViewDetailRoomID, true); } if(e.getActionCommand() == "CreateRoom_Cancel") { if(netPlayerClient.getYourPlayerInfo().roomID != -1) { changeCurrentScreenCard(SCREENCARD_ROOM); } else { changeCurrentScreenCard(SCREENCARD_LOBBY); } } } public void netOnMessage(NetBaseClient client, String[] message) throws IOException { //addSystemChatLog(getCurrentChatLogTextPane(), message[0], Color.green); if(message[0].equals("welcome")) { //welcome\t[VERSION]\t[PLAYERS] if(writerChatLog == null) { try { GregorianCalendar currentTime = new GregorianCalendar(); int month = currentTime.get(Calendar.MONTH) + 1; String filename = String.format( "log/chat_%04d_%02d_%02d_%02d_%02d_%02d.txt", currentTime.get(Calendar.YEAR), month, currentTime.get(Calendar.DATE), currentTime.get(Calendar.HOUR_OF_DAY), currentTime.get(Calendar.MINUTE), currentTime.get(Calendar.SECOND) ); writerChatLog = new PrintWriter(filename); } catch (Exception e) { log.warn("Failed to create chat log file", e); } } String strTemp = String.format(getUIText("SysMsg_ServerConnected"), netPlayerClient.getHost(), netPlayerClient.getPort()); addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_ServerVersion") + message[1], Color.blue); addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_NumberOfPlayers") + message[2], Color.blue); } if(message[0].equals("loginsuccess")) { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_LoginOK"), Color.blue); addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_YourNickname") + convTripCode(NetUtil.urlDecode(message[1])), Color.blue); addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_YourUID") + netPlayerClient.getPlayerUID(), Color.blue); addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_SendRuleDataStart"), Color.blue); sendMyRuleDataToServer(); } if(message[0].equals("loginfail")) { setLobbyButtonsEnabled(false); String reason = ""; for(int i = 1; i < message.length; i++) { reason += message[i] + " "; } addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_LoginFail") + reason, Color.red); } if(message[0].equals("ruledatasuccess")) { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_SendRuleDataOK"), Color.blue); // Listener for(NetLobbyListener l: listeners) { l.netlobbyOnLoginOK(this, netPlayerClient); } setLobbyButtonsEnabled(true); } if(message[0].equals("ruledatafail")) { sendMyRuleDataToServer(); } if(message[0].equals("playerlist") || message[0].equals("playerupdate") || message[0].equals("playernew") || message[0].equals("playerlogout")) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateLobbyUserList(); } }); if(currentScreenCardNumber == SCREENCARD_ROOM) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateRoomUserList(); } }); if(message[0].equals("playerlogout")) { NetPlayerInfo p = new NetPlayerInfo(message[1]); NetPlayerInfo p2 = netPlayerClient.getYourPlayerInfo(); if((p != null) && (p2 != null) && (p.roomID == p2.roomID)) { String strTemp = ""; if(p.strHost.length() > 0) { strTemp = String.format(getUIText("SysMsg_LeaveRoomWithHost"), getPlayerNameWithTripCode(p), p.strHost); } else { strTemp = String.format(getUIText("SysMsg_LeaveRoom"), getPlayerNameWithTripCode(p)); } addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); } } } } if(message[0].equals("playerenter")) { int uid = Integer.parseInt(message[1]); NetPlayerInfo pInfo = netPlayerClient.getPlayerInfoByUID(uid); if(pInfo != null) { String strTemp = ""; if(pInfo.strHost.length() > 0) { strTemp = String.format(getUIText("SysMsg_EnterRoomWithHost"), getPlayerNameWithTripCode(pInfo), pInfo.strHost); } else { strTemp = String.format(getUIText("SysMsg_EnterRoom"), getPlayerNameWithTripCode(pInfo)); } addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); } } if(message[0].equals("playerleave")) { int uid = Integer.parseInt(message[1]); NetPlayerInfo pInfo = netPlayerClient.getPlayerInfoByUID(uid); if(pInfo != null) { String strTemp = ""; if(pInfo.strHost.length() > 0) { strTemp = String.format(getUIText("SysMsg_LeaveRoomWithHost"), getPlayerNameWithTripCode(pInfo), pInfo.strHost); } else { strTemp = String.format(getUIText("SysMsg_LeaveRoom"), getPlayerNameWithTripCode(pInfo)); } addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); } } if(message[0].equals("changeteam")) { int uid = Integer.parseInt(message[1]); NetPlayerInfo pInfo = netPlayerClient.getPlayerInfoByUID(uid); if(pInfo != null) { String strTeam = ""; String strTemp = ""; if(message.length > 3) { strTeam = NetUtil.urlDecode(message[3]); strTemp = String.format(getUIText("SysMsg_ChangeTeam"), getPlayerNameWithTripCode(pInfo), strTeam); } else { strTemp = String.format(getUIText("SysMsg_ChangeTeam_None"), getPlayerNameWithTripCode(pInfo)); } addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); } } if(message[0].equals("roomlist")) { int size = Integer.parseInt(message[1]); tablemodelRoomList.setRowCount(0); for(int i = 0; i < size; i++) { NetRoomInfo r = new NetRoomInfo(message[2 + i]); tablemodelRoomList.addRow(createRoomListRowData(r)); } } if(message[0].equals("roomcreate")) { NetRoomInfo r = new NetRoomInfo(message[1]); tablemodelRoomList.addRow(createRoomListRowData(r)); } if(message[0].equals("roomupdate")) { NetRoomInfo r = new NetRoomInfo(message[1]); int columnID = tablemodelRoomList.findColumn(getUIText(ROOMTABLE_COLUMNNAMES[0])); for(int i = 0; i < tablemodelRoomList.getRowCount(); i++) { String strID = (String)tablemodelRoomList.getValueAt(i, columnID); int roomID = Integer.parseInt(strID); if(roomID == r.roomID) { String[] rowData = createRoomListRowData(r); for(int j = 0; j < rowData.length; j++) { tablemodelRoomList.setValueAt(rowData[j], i, j); } break; } } } if(message[0].equals("roomdelete")) { NetRoomInfo r = new NetRoomInfo(message[1]); int columnID = tablemodelRoomList.findColumn(getUIText(ROOMTABLE_COLUMNNAMES[0])); for(int i = 0; i < tablemodelRoomList.getRowCount(); i++) { String strID = (String)tablemodelRoomList.getValueAt(i, columnID); int roomID = Integer.parseInt(strID); if(roomID == r.roomID) { tablemodelRoomList.removeRow(i); break; } } if((r.roomID == currentViewDetailRoomID) && (currentScreenCardNumber == SCREENCARD_CREATEROOM)) { changeCurrentScreenCard(SCREENCARD_LOBBY); } } if(message[0].equals("roomcreatemapready")) { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_RoomCreateMapReady"), Color.blue); } if(message[0].equals("roomcreatesuccess") || message[0].equals("roomjoinsuccess")) { int roomID = Integer.parseInt(message[1]); int seatID = Integer.parseInt(message[2]); int queueID = Integer.parseInt(message[3]); netPlayerClient.getYourPlayerInfo().roomID = roomID; netPlayerClient.getYourPlayerInfo().seatID = seatID; netPlayerClient.getYourPlayerInfo().queueID = queueID; if(roomID != -1) { NetRoomInfo roomInfo = netPlayerClient.getRoomInfo(roomID); NetPlayerInfo pInfo = netPlayerClient.getYourPlayerInfo(); if((seatID == -1) && (queueID == -1)) { String strTemp = String.format(getUIText("SysMsg_StatusChange_Spectator"), getPlayerNameWithTripCode(pInfo)); addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); setRoomJoinButtonVisible(true); } else if(seatID == -1) { String strTemp = String.format(getUIText("SysMsg_StatusChange_Queue"), getPlayerNameWithTripCode(pInfo)); addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); setRoomJoinButtonVisible(false); } else { String strTemp = String.format(getUIText("SysMsg_StatusChange_Joined"), getPlayerNameWithTripCode(pInfo)); addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); setRoomJoinButtonVisible(false); } SwingUtilities.invokeLater(new Runnable() { public void run() { setRoomButtonsEnabled(true); updateRoomUserList(); } }); String strTitle = roomInfo.strName; this.setTitle(getUIText("Title_NetLobby") + " - " + strTitle); addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_RoomJoin_Title") + strTitle, Color.blue); addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_RoomJoin_ID") + roomInfo.roomID, Color.blue); if(roomInfo.ruleLock) { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_RoomJoin_Rule") + roomInfo.ruleName, Color.blue); } // Listener for(NetLobbyListener l: listeners) { l.netlobbyOnRoomJoin(this, netPlayerClient, roomInfo); } } else { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_RoomJoin_Lobby"), Color.blue); this.setTitle(getUIText("Title_NetLobby")); // Listener for(NetLobbyListener l: listeners) { l.netlobbyOnRoomLeave(this, netPlayerClient); } } } if(message[0].equals("roomjoinfail")) { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_RoomJoinFail"), Color.red); } if(message[0].equals("chat")) { int uid = Integer.parseInt(message[1]); NetPlayerInfo pInfo = netPlayerClient.getPlayerInfoByUID(uid); if(pInfo != null) { String strMsgBody = NetUtil.urlDecode(message[3]); addUserChatLogLater(getCurrentChatLogTextPane(), getPlayerNameWithTripCode(pInfo), strMsgBody); } } if(message[0].equals("changestatus")) { int uid = Integer.parseInt(message[2]); NetPlayerInfo pInfo = netPlayerClient.getPlayerInfoByUID(uid); if(pInfo != null) { if(message[1].equals("watchonly")) { String strTemp = String.format(getUIText("SysMsg_StatusChange_Spectator"), getPlayerNameWithTripCode(pInfo)); addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); if(uid == netPlayerClient.getPlayerUID()) setRoomJoinButtonVisible(true); } else if(message[1].equals("joinqueue")) { String strTemp = String.format(getUIText("SysMsg_StatusChange_Queue"), getPlayerNameWithTripCode(pInfo)); addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); if(uid == netPlayerClient.getPlayerUID()) setRoomJoinButtonVisible(false); } else if(message[1].equals("joinseat")) { String strTemp = String.format(getUIText("SysMsg_StatusChange_Joined"), getPlayerNameWithTripCode(pInfo)); addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, Color.blue); if(uid == netPlayerClient.getPlayerUID()) setRoomJoinButtonVisible(false); } } SwingUtilities.invokeLater(new Runnable() { public void run() { updateRoomUserList(); } }); } if(message[0].equals("autostartbegin")) { String strTemp = String.format(getUIText("SysMsg_AutoStartBegin"), message[1]); addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, new Color(64, 128, 0)); } if(message[0].equals("start")) { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_GameStart"), new Color(0, 128, 0)); tablemodelGameStat.setRowCount(0); if(netPlayerClient.getYourPlayerInfo().seatID != -1) { btnRoomButtonsSitOut.setEnabled(false); btnRoomButtonsTeamChange.setEnabled(false); roomTopBarCardLayout.first(subpanelRoomTopBar); } } if(message[0].equals("dead")) { int uid = Integer.parseInt(message[1]); String name = convTripCode(NetUtil.urlDecode(message[2])); if(message.length > 6) { String strTemp = String.format(getUIText("SysMsg_KO"), convTripCode(NetUtil.urlDecode(message[6])), name); addSystemChatLogLater(getCurrentChatLogTextPane(), strTemp, new Color(0, 128, 0)); } if(uid == netPlayerClient.getPlayerUID()) { btnRoomButtonsSitOut.setEnabled(true); btnRoomButtonsTeamChange.setEnabled(true); } } if(message[0].equals("gstat")) { String[] rowdata = new String[12]; int myRank = Integer.parseInt(message[4]); rowdata[0] = Integer.toString(myRank); rowdata[1] = convTripCode(NetUtil.urlDecode(message[3])); rowdata[2] = message[5]; rowdata[3] = message[6]; // APM rowdata[4] = message[7]; rowdata[5] = message[8]; // LPM rowdata[6] = message[9]; rowdata[7] = message[10]; // PPS rowdata[8] = GeneralUtil.getTime(Integer.parseInt(message[11])); rowdata[9] = message[12]; rowdata[10] = message[13]; rowdata[11] = message[14]; int insertPos = 0; for(int i = 0; i < tablemodelGameStat.getRowCount(); i++) { String strRank = (String)tablemodelGameStat.getValueAt(i, 0); int rank = Integer.parseInt(strRank); if(myRank > rank) { insertPos = i + 1; } } tablemodelGameStat.insertRow(insertPos, rowdata); if(writerChatLog != null) { writerChatLog.print("[" + getCurrentTimeAsString() + "] "); for(int i = 0; i < rowdata.length; i++) { writerChatLog.print(rowdata[i]); if(i < rowdata.length - 1) writerChatLog.print(","); else writerChatLog.print("\n"); } writerChatLog.flush(); } } if(message[0].equals("finish")) { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_GameEnd"), new Color(0, 128, 0)); if((message.length > 3) && (message[3].length() > 0)) { boolean flagTeamWin = false; if(message.length > 4) flagTeamWin = Boolean.parseBoolean(message[4]); String strWinner = ""; if(flagTeamWin) strWinner = String.format(getUIText("SysMsg_WinnerTeam"), NetUtil.urlDecode(message[3])); else strWinner = String.format(getUIText("SysMsg_Winner"), convTripCode(NetUtil.urlDecode(message[3]))); addSystemChatLogLater(getCurrentChatLogTextPane(), strWinner, new Color(0, 128, 0)); } btnRoomButtonsSitOut.setEnabled(true); btnRoomButtonsTeamChange.setEnabled(true); } // Listener if(listeners != null) { for(NetLobbyListener l: listeners) { l.netlobbyOnMessage(this, netPlayerClient, message); } } } public void netOnDisconnect(NetBaseClient client, Throwable ex) { SwingUtilities.invokeLater(new Runnable() { public void run() { setLobbyButtonsEnabled(false); setRoomButtonsEnabled(false); tablemodelRoomList.setRowCount(0); } }); if(ex != null) { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_DisconnectedError") + "\n" + ex.getLocalizedMessage(), Color.red); log.info("Server Disconnected", ex); } else { addSystemChatLogLater(getCurrentChatLogTextPane(), getUIText("SysMsg_DisconnectedOK"), new Color(128, 0, 0)); log.info("Server Disconnected (null)"); } // Listener if(listeners != null) { for(NetLobbyListener l: listeners) { if(l != null) { l.netlobbyOnDisconnect(this, netPlayerClient, ex); } } } } /** * NetLobbyListener * @param l NetLobbyListener */ public void addListener(NetLobbyListener l) { listeners.add(l); } /** * NetLobbyListener * @param l NetLobbyListener * @return truefalse */ public boolean removeListener(NetLobbyListener l) { return listeners.remove(l); } /** * * @param args */ public static void main(String[] args) { PropertyConfigurator.configure("config/etc/log.cfg"); NetLobbyFrame frame = new NetLobbyFrame(); frame.init(); frame.setVisible(true); } protected class TextComponentPopupMenu extends JPopupMenu { private static final long serialVersionUID = 1L; private Action cutAction; private Action copyAction; @SuppressWarnings("unused") private Action pasteAction; private Action deleteAction; private Action selectAllAction; public TextComponentPopupMenu(final JTextComponent field) { super(); add(cutAction = new AbstractAction(getUIText("Popup_Cut")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { field.cut(); } }); add(copyAction = new AbstractAction(getUIText("Popup_Copy")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { field.copy(); } }); add(pasteAction = new AbstractAction(getUIText("Popup_Paste")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { field.paste(); } }); add(deleteAction = new AbstractAction(getUIText("Popup_Delete")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { field.replaceSelection(null); } }); add(selectAllAction = new AbstractAction(getUIText("Popup_SelectAll")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { field.selectAll(); } }); } @Override public void show(Component c, int x, int y) { JTextComponent field = (JTextComponent) c; boolean flg = field.getSelectedText() != null; cutAction.setEnabled(flg); copyAction.setEnabled(flg); deleteAction.setEnabled(flg); selectAllAction.setEnabled(field.isFocusOwner()); super.show(c, x, y); } } protected class ListBoxPopupMenu extends JPopupMenu { private static final long serialVersionUID = 1L; private JList listbox; private Action copyAction; public ListBoxPopupMenu(JList l) { super(); this.listbox = l; add(copyAction = new AbstractAction(getUIText("Popup_Copy")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { if(listbox == null) return; Object selectedObj = listbox.getSelectedValue(); if((selectedObj != null) && (selectedObj instanceof String)) { String selectedString = (String)selectedObj; StringSelection ss = new StringSelection(selectedString); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(ss, ss); } } }); } @Override public void show(Component c, int x, int y) { if(listbox.getSelectedIndex() != -1) { copyAction.setEnabled(true); super.show(c, x, y); } } } protected class ServerSelectListBoxPopupMenu extends JPopupMenu { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") private Action connectAction; @SuppressWarnings("unused") private Action deleteAction; @SuppressWarnings("unused") private Action setObserverAction; public ServerSelectListBoxPopupMenu() { super(); add(connectAction = new AbstractAction(getUIText("Popup_ServerSelect_Connect")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { serverSelectConnectButtonClicked(); } }); add(deleteAction = new AbstractAction(getUIText("Popup_ServerSelect_Delete")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { serverSelectDeleteButtonClicked(); } }); add(setObserverAction = new AbstractAction(getUIText("Popup_ServerSelect_SetObserver")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { serverSelectSetObserverButtonClicked(); } }); } @Override public void show(Component c, int x, int y) { if(listboxServerList.getSelectedIndex() != -1) { super.show(c, x, y); } } } /** * MouseAdapter */ protected class ServerSelectListBoxMouseAdapter extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { if((e.getClickCount() == 2) && (e.getButton() == MouseEvent.BUTTON1)) { serverSelectConnectButtonClicked(); } } } protected class RoomTablePopupMenu extends JPopupMenu { private static final long serialVersionUID = 1L; private Action joinAction; private Action watchAction; private Action detailAction; public RoomTablePopupMenu() { super(); add(joinAction = new AbstractAction(getUIText("Popup_RoomTable_Join")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { int row = tableRoomList.getSelectedRow(); if(row != -1) { int columnID = tablemodelRoomList.findColumn(getUIText(ROOMTABLE_COLUMNNAMES[0])); String strRoomID = (String)tablemodelRoomList.getValueAt(row, columnID); int roomID = Integer.parseInt(strRoomID); joinRoom(roomID, false); } } }); add(watchAction = new AbstractAction(getUIText("Popup_RoomTable_Watch")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { int row = tableRoomList.getSelectedRow(); if(row != -1) { int columnID = tablemodelRoomList.findColumn(getUIText(ROOMTABLE_COLUMNNAMES[0])); String strRoomID = (String)tablemodelRoomList.getValueAt(row, columnID); int roomID = Integer.parseInt(strRoomID); joinRoom(roomID, true); } } }); add(detailAction = new AbstractAction(getUIText("Popup_RoomTable_Detail")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { int row = tableRoomList.getSelectedRow(); if(row != -1) { int columnID = tablemodelRoomList.findColumn(getUIText(ROOMTABLE_COLUMNNAMES[0])); String strRoomID = (String)tablemodelRoomList.getValueAt(row, columnID); int roomID = Integer.parseInt(strRoomID); viewRoomDetail(roomID); } } }); } @Override public void show(Component c, int x, int y) { if(tableRoomList.getSelectedRow() != -1) { joinAction.setEnabled(true); watchAction.setEnabled(true); detailAction.setEnabled(true); super.show(c, x, y); } } } /** * MouseAdapter */ protected class RoomTableMouseAdapter extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { if((e.getClickCount() == 2) && (e.getButton() == MouseEvent.BUTTON1)) { Point pt = e.getPoint(); int row = tableRoomList.rowAtPoint(pt); if(row != -1) { int columnID = tablemodelRoomList.findColumn(getUIText(ROOMTABLE_COLUMNNAMES[0])); String strRoomID = (String)tablemodelRoomList.getValueAt(row, columnID); int roomID = Integer.parseInt(strRoomID); joinRoom(roomID, false); } } } } /** * KeyAdapter */ protected class RoomTableKeyAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { e.consume(); } } @Override public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { int row = tableRoomList.getSelectedRow(); if(row != -1) { int columnID = tablemodelRoomList.findColumn(getUIText(ROOMTABLE_COLUMNNAMES[0])); String strRoomID = (String)tablemodelRoomList.getValueAt(row, columnID); int roomID = Integer.parseInt(strRoomID); joinRoom(roomID, false); } e.consume(); } } } protected class LogPopupMenu extends JPopupMenu { private static final long serialVersionUID = 1L; private Action copyAction; private Action selectAllAction; @SuppressWarnings("unused") private Action clearAction; public LogPopupMenu(final JTextComponent field) { super(); add(copyAction = new AbstractAction(getUIText("Popup_Copy")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { field.copy(); } }); add(selectAllAction = new AbstractAction(getUIText("Popup_SelectAll")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { field.selectAll(); } }); add(clearAction = new AbstractAction(getUIText("Popup_Clear")) { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { field.setText(null); } }); } @Override public void show(Component c, int x, int y) { JTextComponent field = (JTextComponent) c; boolean flg = field.getSelectedText() != null; copyAction.setEnabled(flg); selectAllAction.setEnabled(field.isFocusOwner()); super.show(c, x, y); } } /** * KeyAdapter */ protected class LogKeyAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { if( (e.getKeyCode() != KeyEvent.VK_UP) && (e.getKeyCode() != KeyEvent.VK_DOWN) && (e.getKeyCode() != KeyEvent.VK_LEFT) && (e.getKeyCode() != KeyEvent.VK_RIGHT) && (e.getKeyCode() != KeyEvent.VK_HOME) && (e.getKeyCode() != KeyEvent.VK_END) && (e.getKeyCode() != KeyEvent.VK_PAGE_UP) && (e.getKeyCode() != KeyEvent.VK_PAGE_DOWN) && ((e.getKeyCode() != KeyEvent.VK_A) || (e.isControlDown() == false)) && ((e.getKeyCode() != KeyEvent.VK_C) || (e.isControlDown() == false)) && (!e.isAltDown()) ) { e.consume(); } } @Override public void keyTyped(KeyEvent e) { e.consume(); } } }
package org.jetbrains.plugins.scala.compiler; import com.intellij.compiler.CompilerConfigurationImpl; import com.intellij.compiler.OutputParser; import com.intellij.compiler.impl.javaCompiler.ExternalCompiler; import com.intellij.compiler.impl.javaCompiler.ModuleChunk; import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.MockJdkWrapper; import com.intellij.openapi.roots.*; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NonNls; import org.jetbrains.plugins.scala.ScalaBundle; import org.jetbrains.plugins.scala.ScalaFileType; import org.jetbrains.plugins.scala.compiler.rt.ScalacRunner; import org.jetbrains.plugins.scala.config.ScalaConfigUtils; import java.io.*; import java.util.*; /** * @author ilyas */ public class ScalacCompiler extends ExternalCompiler { private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.scala.compiler.ScalacCompiler"); private final Project myProject; private final List<File> myTempFiles = new ArrayList<File>(); // VM properties @NonNls private static final String XMX_COMPILER_PROPERTY = "-Xmx300m"; @NonNls private final String XSS_COMPILER_PROPERTY = "-Xss128m"; // Scalac parameters @NonNls private static final String DEBUG_INFO_LEVEL_PROPEERTY = "-g:vars"; @NonNls private static final String VERBOSE_PROPERTY = "-verbose"; @NonNls private static final String DESTINATION_COMPILER_PROPERTY = "-d"; @NonNls private static final String DEBUG_PROPERTY = "-Ydebug"; @NonNls private static final String WARNINGS_PROPERTY = "-unchecked"; public ScalacCompiler(Project project) { myProject = project; } public boolean checkCompiler(CompileScope scope) { VirtualFile[] files = scope.getFiles(ScalaFileType.SCALA_FILE_TYPE, true); if (files.length == 0) return true; final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); Set<Module> modules = new HashSet<Module>(); for (VirtualFile file : files) { Module module = index.getModuleForFile(file); if (module != null) { modules.add(module); } } for (Module module : modules) { final String installPath = ScalaConfigUtils.getScalaInstallPath(module); if (installPath.length() == 0) { Messages.showErrorDialog(myProject, ScalaBundle.message("cannot.compile.scala.files.no.facet", module.getName()), ScalaBundle.message("cannot.compile")); return false; } } Set<Module> nojdkModules = new HashSet<Module>(); for (Module module : scope.getAffectedModules()) { Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); if (sdk == null || !(sdk.getSdkType() instanceof JavaSdkType)) { nojdkModules.add(module); } } if (!nojdkModules.isEmpty()) { final Module[] noJdkArray = nojdkModules.toArray(new Module[nojdkModules.size()]); if (noJdkArray.length == 1) { Messages.showErrorDialog(myProject, ScalaBundle.message("cannot.compile.scala.files.no.sdk", noJdkArray[0].getName()), ScalaBundle.message("cannot.compile")); } else { StringBuffer modulesList = new StringBuffer(); for (int i = 0; i < noJdkArray.length; i++) { if (i > 0) modulesList.append(", "); modulesList.append(noJdkArray[i].getName()); } Messages.showErrorDialog(myProject, ScalaBundle.message("cannot.compile.scala.files.no.sdk.mult", modulesList.toString()), ScalaBundle.message("cannot.compile")); } return false; } return true; } @NotNull public String getId() { return "Scalac"; } @NotNull public String getPresentableName() { return ScalaBundle.message("scalac.compiler.name"); } @NotNull public Configurable createConfigurable() { // todo implement me as for javac! return null; } public OutputParser createErrorParser(String outputDir) { return new ScalacOutputParser(); } public OutputParser createOutputParser(String outputDir) { return new OutputParser() { @Override public boolean processMessageLine(Callback callback) { if (super.processMessageLine(callback)) { return true; } return callback.getCurrentLine() != null; } }; } @NotNull public String[] createStartupCommand(final ModuleChunk chunk, CompileContext context, final String outputPath) throws IOException, IllegalArgumentException { final ArrayList<String> commandLine = new ArrayList<String>(); final Exception[] ex = new Exception[]{null}; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { try { createStartupCommandImpl(chunk, commandLine, outputPath); } catch (IllegalArgumentException e) { ex[0] = e; } catch (IOException e) { ex[0] = e; } } }); if (ex[0] != null) { if (ex[0] instanceof IOException) { throw (IOException) ex[0]; } else if (ex[0] instanceof IllegalArgumentException) { throw (IllegalArgumentException) ex[0]; } else { LOG.error(ex[0]); } } return commandLine.toArray(new String[commandLine.size()]); } @NotNull @Override public Collection<? extends FileType> getCompilableFileTypes() { return Arrays.asList(ScalaFileType.SCALA_FILE_TYPE, StdFileTypes.JAVA); } private void createStartupCommandImpl(ModuleChunk chunk, ArrayList<String> commandLine, String outputPath) throws IOException { final Sdk jdk = getJdkForStartupCommand(chunk); final String versionString = jdk.getVersionString(); if (versionString == null || "".equals(versionString)) { throw new IllegalArgumentException(ScalaBundle.message("javac.error.unknown.jdk.version", jdk.getName())); } final JavaSdkType sdkType = (JavaSdkType) jdk.getSdkType(); final String toolsJarPath = sdkType.getToolsPath(jdk); if (toolsJarPath == null) { throw new IllegalArgumentException(ScalaBundle.message("javac.error.tools.jar.missing", jdk.getName())); } if (!allModulesHaveSameScalaSdk(chunk)) { throw new IllegalArgumentException(ScalaBundle.message("different.scala.sdk.in.modules")); } String javaExecutablePath = sdkType.getVMExecutablePath(jdk); commandLine.add(javaExecutablePath); //todo setup via ScalacSettings commandLine.add("-cp"); String rtJarPath = PathUtil.getJarPathForClass(ScalacRunner.class); final StringBuilder classPathBuilder = new StringBuilder(); classPathBuilder.append(rtJarPath).append(File.pathSeparator); classPathBuilder.append(sdkType.getToolsPath(jdk)).append(File.pathSeparator); String scalaPath = ScalaConfigUtils.getScalaInstallPath(chunk.getModules()[0]); String libPath = (scalaPath + "/lib").replace(File.separatorChar, '/'); VirtualFile lib = LocalFileSystem.getInstance().findFileByPath(libPath); if (lib != null) { for (VirtualFile file : lib.getChildren()) { if (required(file.getName())) { classPathBuilder.append(file.getPath()); classPathBuilder.append(File.pathSeparator); } } } commandLine.add(classPathBuilder.toString()); commandLine.add(ScalacRunner.class.getName()); try { File fileWithParams = File.createTempFile("scalac", ".tmp"); fillFileWithScalacParams(chunk, fileWithParams, outputPath); commandLine.add(fileWithParams.getPath()); } catch (IOException e) { LOG.error(e); } } private static void fillFileWithScalacParams(ModuleChunk chunk, File fileWithParameters, String outputPath) throws FileNotFoundException { PrintStream printer = new PrintStream(new FileOutputStream(fileWithParameters)); printer.println(VERBOSE_PROPERTY); printer.println(DEBUG_PROPERTY); printer.println(WARNINGS_PROPERTY); printer.println(DEBUG_INFO_LEVEL_PROPEERTY); printer.println(DESTINATION_COMPILER_PROPERTY); printer.println(outputPath.replace('/', File.separatorChar)); //write classpath printer.println("-cp"); for (Module module : chunk.getModules()) { ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); OrderEntry[] entries = moduleRootManager.getOrderEntries(); Set<VirtualFile> cpVFiles = new HashSet<VirtualFile>(); for (OrderEntry orderEntry : entries) { cpVFiles.addAll(Arrays.asList(orderEntry.getFiles(OrderRootType.COMPILATION_CLASSES))); } for (VirtualFile file : cpVFiles) { String path = file.getPath(); int jarSeparatorIndex = path.indexOf(JarFileSystem.JAR_SEPARATOR); if (jarSeparatorIndex > 0) { path = path.substring(0, jarSeparatorIndex); } printer.print(path); printer.print(File.pathSeparator); } } printer.println(); for (VirtualFile file : chunk.getFilesToCompile()) { printer.println(file.getPath()); } printer.close(); } private boolean allModulesHaveSameScalaSdk(ModuleChunk chunk) { if (chunk.getModuleCount() == 0) return false; final Module[] modules = chunk.getModules(); final Module first = modules[0]; final String firstVersion = ScalaConfigUtils.getScalaVersion(ScalaConfigUtils.getScalaInstallPath(first)); for (Module module : modules) { final String path = ScalaConfigUtils.getScalaInstallPath(module); final String version = ScalaConfigUtils.getScalaVersion(path); if (!version.equals(firstVersion)) return false; } return true; } public void compileFinished() { FileUtil.asyncDelete(myTempFiles); } private Sdk getJdkForStartupCommand(final ModuleChunk chunk) { final Sdk jdk = chunk.getJdk(); if (ApplicationManager.getApplication().isUnitTestMode() && JavacSettings.getInstance(myProject).isTestsUseExternalCompiler()) { final String jdkHomePath = CompilerConfigurationImpl.getTestsExternalCompilerHome(); if (jdkHomePath == null) { throw new IllegalArgumentException("[TEST-MODE] Cannot determine home directory for JDK to use javac from"); } // when running under Mock JDK use VM executable from the JDK on which the tests run return new MockJdkWrapper(jdkHomePath, jdk); } return jdk; } static HashSet<String> required = new HashSet<String>(); static { required.add("scala"); required.add("sbaz"); } private static boolean required(String name) { name = name.toLowerCase(); if (!name.endsWith(".jar")) return false; name = name.substring(0, name.lastIndexOf('.')); int ind = name.lastIndexOf('-'); if (ind != -1 && name.length() > ind + 1 && Character.isDigit(name.charAt(ind + 1))) { name = name.substring(0, ind); } for (String requiredStr : required) { if (name.contains(requiredStr)) return true; } return false; } }
package org.jmist.framework.services; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.jmist.framework.Job; import org.jmist.framework.ProgressMonitor; import org.jmist.framework.TaskWorker; /** * A job that processes tasks for a parallelizable job from a remote * <code>JobServiceMaster<code>. This class may potentially use multiple * threads to process tasks. * @author bkimmel */ public final class ThreadServiceWorkerJob implements Job { /** * Initializes the address of the master and the amount of time to idle * when no task is available. * @param masterHost The URL of the master. * @param idleTime The time (in milliseconds) to idle when no task is * available. * @param maxConcurrentWorkers The maximum number of concurrent worker * threads to allow. * @param executor The <code>Executor</code> to use to process tasks. */ public ThreadServiceWorkerJob(String masterHost, long idleTime, int maxConcurrentWorkers, Executor executor) { assert(maxConcurrentWorkers > 0); this.masterHost = masterHost; this.idleTime = idleTime; this.executor = executor; this.workerSlot = new Semaphore(maxConcurrentWorkers, true); } /* (non-Javadoc) * @see org.jmist.framework.Job#go(org.jmist.framework.ProgressMonitor) */ @Override public void go(ProgressMonitor monitor) { try { monitor.notifyIndeterminantProgress(); monitor.notifyStatusChanged("Looking up master..."); Registry registry = LocateRegistry.getRegistry(this.masterHost); this.service = (JobMasterService) registry.lookup("JobMasterService"); while (monitor.notifyIndeterminantProgress()) { this.workerSlot.acquire(); monitor.notifyStatusChanged("Queueing worker process..."); this.executor.execute(new Worker(monitor.createChildProgressMonitor())); } monitor.notifyStatusChanged("Cancelled."); } catch (Exception e) { monitor.notifyStatusChanged("Exception: " + e.toString()); System.err.println("Client exception: " + e.toString()); e.printStackTrace(); } finally { monitor.notifyCancelled(); } } /** * An entry in the <code>TaskWorker</code> cache. * @author bkimmel */ private static class WorkerCacheEntry { /** * Initializes the cache entry. * @param jobId The <code>UUID</code> of the job that the * <code>TaskWorker</code> processes tasks for. */ public WorkerCacheEntry(UUID jobId) { this.jobId = jobId; this.writeLock = this.lock.writeLock(); } /** * Returns a value indicating if this <code>WorkerCacheEntry</code> * is to be used for the job with the specified <code>UUID</code>. * @param jobId The job's <code>UUID</code> to test. * @return A value indicating if this <code>WorkerCacheEntry</code> * applies to the specified job. */ public boolean matches(UUID jobId) { return this.jobId.equals(jobId); } /** * Sets the <code>TaskWorker</code> to use. * @param worker The <code>TaskWorker</code> to use for matching * jobs. */ public synchronized void setWorker(TaskWorker worker) { /* If this method has already been called, then the write lock will * have been unlocked and removed, so obtain a new write lock. */ if (this.writeLock == null) { this.writeLock = this.lock.writeLock(); } /* Set the worker. */ this.worker = worker; /* Release and discard the lock. */ this.writeLock.unlock(); this.writeLock = null; } /** * Gets the <code>TaskWorker</code> to use to process tasks for the * matching job. This method will wait for <code>setWorker</code> * to be called if it has not yet been called. * @return The <code>TaskWorker</code> to use to process tasks for * the matching job. * @see {@link #setWorker(TaskWorker)}. */ public TaskWorker getWorker() { Lock lock = this.lock.readLock(); TaskWorker worker = this.worker; lock.unlock(); return worker; } /** * The <code>UUID</code> of the job that the <code>TaskWorker</code> * processes tasks for. */ private final UUID jobId; /** * The cached <code>TaskWorker</code>. */ private TaskWorker worker; /** * The <code>ReadWriteLock</code> to use before reading from or writing * to the <code>worker</code> field. */ private final ReadWriteLock lock = new ReentrantReadWriteLock(); /** * The <code>Lock</code> held for writing to the <code>worker</code> * field. */ private Lock writeLock = null; } /** * Searches for the <code>WorkerCacheEntry</code> matching the job with the * specified <code>UUID</code>. * @param jobId The <code>UUID</code> of the job whose * <code>WorkerCacheEntry</code> to search for. * @return The <code>WorkerCacheEntry</code> corresponding to the job with * the specified <code>UUID</code>, or <code>null</code> if the * no such entry exists. */ private WorkerCacheEntry getCacheEntry(UUID jobId) { assert(jobId != null); synchronized (this.workerCache) { Iterator<WorkerCacheEntry> i = this.workerCache.iterator(); /* Search for the worker for the specified job. */ while (i.hasNext()) { WorkerCacheEntry entry = i.next(); if (entry.matches(jobId)) { /* Remove the entry and re-insert it at the end of the list. * This will ensure that when an item is removed from the list, * the item that is removed will always be the least recently * used. */ i.remove(); this.workerCache.add(entry); return entry; } } /* cache miss */ return null; } } /** * Removes the specified entry from the task worker cache. * @param entry The <code>WorkerCacheEntry</code> to remove. */ private void removeCacheEntry(WorkerCacheEntry entry) { assert(entry != null); synchronized (this.workerCache) { this.workerCache.remove(entry); } } /** * Removes least recently used entries from the task worker cache until * there are at most <code>this.maxCachedWorkers</code> entries. */ private void removeOldCacheEntries() { synchronized (this.workerCache) { /* If the cache has exceeded capacity, then remove the least * recently used entry. */ assert(this.maxCachedWorkers > 0); while (this.workerCache.size() > this.maxCachedWorkers) { this.workerCache.remove(0); } } } /** * Obtains the task worker to process tasks for the job with the specified * <code>UUID</code>. * @param jobId The <code>UUID</code> of the job to obtain the task worker * for. * @return The <code>TaskWorker</code> to process tasks for the job with * the specified <code>UUID</code>, or <code>null</code> if the job * is invalid or has already been completed. * @throws RemoteException */ private TaskWorker getTaskWorker(UUID jobId) throws RemoteException { WorkerCacheEntry entry = null; boolean hit; synchronized (this.workerCache) { /* First try to get the worker from the cache. */ entry = this.getCacheEntry(jobId); hit = (entry != null); /* If there was no matching cache entry, then add a new entry to * the cache. */ if (!hit) { entry = new WorkerCacheEntry(jobId); this.workerCache.add(entry); } } if (hit) { /* We found a cache entry, so get the worker from that entry. */ return entry.getWorker(); } else { /* cache miss */ /* The task worker was not in the cache, so use the service to * obtain the task worker. */ TaskWorker worker = this.service.getTaskWorker(jobId); entry.setWorker(worker); /* If we couldn't get a worker from the service, then don't keep * the cache entry. */ if (worker == null) { this.removeCacheEntry(entry); } /* Clean up the cache. */ this.removeOldCacheEntries(); return worker; } } /** * Used to process tasks in threads. * @author bkimmel */ private class Worker implements Runnable { /** * Initializes the progress monitor to report to. * @param monitor The <code>ProgressMonitor</code> to report * the progress of the task to. */ public Worker(ProgressMonitor monitor) { this.monitor = monitor; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { try { this.monitor.notifyIndeterminantProgress(); this.monitor.notifyStatusChanged("Requesting task..."); TaskDescription taskDesc = service.requestTask(); if (taskDesc != null) { this.monitor.notifyStatusChanged("Obtaining task worker..."); TaskWorker worker = getTaskWorker(taskDesc.getJobId()); if (worker == null) { this.monitor.notifyStatusChanged("Could not obtain worker..."); this.monitor.notifyCancelled(); return; } this.monitor.notifyStatusChanged("Performing task..."); Object results = worker.performTask(taskDesc.getTask(), monitor); this.monitor.notifyStatusChanged("Submitting task results..."); service.submitTaskResults(taskDesc.getJobId(), taskDesc.getTaskId(), results); } else { /* taskDesc == null */ this.monitor.notifyStatusChanged("Idling..."); try { Thread.sleep(idleTime); } catch (InterruptedException e) { // continue. } } this.monitor.notifyComplete(); } catch (RemoteException e) { this.monitor.notifyStatusChanged("Failed to communicate with master."); this.monitor.notifyCancelled(); System.err.println("Remote exception: " + e.toString()); e.printStackTrace(); } finally { workerSlot.release(); } } /** * The <code>ProgressMonitor</code> to report to. */ private final ProgressMonitor monitor; } /** The URL of the master. */ private final String masterHost; /** * The amount of time (in milliseconds) to idle when no task is available. */ private final long idleTime; /** The <code>Executor</code> to use to process tasks. */ private final Executor executor; /** * The <code>Semaphore</code> to use to throttle <code>Worker</code> * threads. */ private final Semaphore workerSlot; /** * The <code>JobMasterService</code> to obtain tasks from and submit * results to. */ private JobMasterService service = null; /** * A list of recently used <code>TaskWorker</code>s and their associated * job's <code>UUID</code>s, in order from least recently used to most * recently used. */ private final List<WorkerCacheEntry> workerCache = new LinkedList<WorkerCacheEntry>(); /** * The maximum number of <code>TaskWorker</code>s to retain in the cache. */ private final int maxCachedWorkers = 5; }
package org.pi.litepost.databaseAccess; import java.sql.ResultSet; import java.util.HashMap; public class DatabaseQueryManager { DatabaseConnector databaseConnector; HashMap<String, DatabaseQuery> databaseQueries; public DatabaseQueryManager(DatabaseConnector databaseConnector) { this.databaseConnector = databaseConnector; databaseQueries = new HashMap<String, DatabaseQuery>(); // Comments: databaseQueries.put("deleteComment", new DatabaseQuery(false, "DELETE FROM Comments WHERE comment_id = ?" )); databaseQueries.put("deleteCommentByUser", new DatabaseQuery(false, "DELETE FROM Comments WHERE comment_id = ?" )); databaseQueries.put("getComment", new DatabaseQuery(true, "SELECT * FROM Comments WHERE comment_id = ?" )); databaseQueries.put("getCommentsByPost", new DatabaseQuery(true, "SELECT * FROM Comments WHERE post_id = ?" )); databaseQueries.put("insertComment", new DatabaseQuery(false, "INSERT INTO Comments(comment_id, user_id, content, date, parent_id, post_id) VALUES(?, ?, ?, ?, ?, ?)", "Comments" )); databaseQueries.put("updateComment", new DatabaseQuery(false, "UPDATE Comments SET text = ? WHERE comment_id = ?" )); databaseQueries.put("reportComment", new DatabaseQuery(false, "UPDATE comments SET reported = 1" )); databaseQueries.put("getCommentByParentId", new DatabaseQuery(true, "SELECT * FROM Comments WHERE parentId = ?" )); databaseQueries.put("getReportedComments", new DatabaseQuery(true, "SELECT * FROM Comments WHERE reported = 1" )); // Messages: databaseQueries.put("deleteMessage", new DatabaseQuery(false, "DELETE FROM Messages WHERE message_id = ?" )); databaseQueries.put("deleteMessageByUser", new DatabaseQuery(false, "DELETE FROM Messages WHERE receiver = ? OR sender = ?" )); databaseQueries.put("getMessagesByUser", new DatabaseQuery(true, "SELECT * FROM Messages WHERE userId = ?" )); databaseQueries.put("insertMessage",new DatabaseQuery(false, "INSERT INTO Messages(message_id, date, sender, receiver, subject, content) VALUES(?, ?, ?, ?, ?, ?)", "Messages" )); databaseQueries.put("getMessagesById", new DatabaseQuery(true, "SELECT * FROM Messages WHERE message_id = ?" )); // Posts: databaseQueries.put("deletePost", new DatabaseQuery(false, "DELETE FROM Posts WHERE post_id = ?" )); databaseQueries.put("deletePostByUser", new DatabaseQuery(false, "DELETE FROM Posts WHERE user_id = ?" )); databaseQueries.put("getReportPost", new DatabaseQuery(true, "SELECT * FROM Posts WHERE reported = 1" )); databaseQueries.put("insertPost", new DatabaseQuery(false, "INSERT INTO Posts(post_id, title, content, date, contact, user_id) VALUES(?, ?, ?, ?, ?, ?)", "Posts" )); // TODO funktioniert das so? databaseQueries.put("deleteOldPosts", new DatabaseQuery(false, "DELETE FROM Posts WHERE date < ?" )); databaseQueries.put("updatePost", new DatabaseQuery(false, "UPDATE Comments SET title = ?," + " content = ?, contact = ? WHERE comment_id = ?" )); databaseQueries.put("getAllPosts", new DatabaseQuery(true, "SELECT * FROM Posts" )); databaseQueries.put("getPostById", new DatabaseQuery(true, "SELECT * FROM Posts WHERE post_id = ?" )); databaseQueries.put("getPostByUser", new DatabaseQuery(true, "SELECT * FROM Posts WHERE user_id = ?" )); databaseQueries.put("reportPost", new DatabaseQuery(false, "UPDATE posts SET reported = 1" )); databaseQueries.put("getReportedPosts", new DatabaseQuery(true, "SELECT * FROM posts WHERE reported = 1" )); // Events: databaseQueries.put("getEvents", new DatabaseQuery(true, "SELECT * FROM Posts NATURAL JOIN Events" )); // Images: databaseQueries.put("getImagesByPost", new DatabaseQuery(true, "SELECT * FROM Images" + " WHERE image_id = " + "(SELECT image_id FROM Post_has_Images WHERE post_id = ?)" )); // User: databaseQueries.put("deleteUser", new DatabaseQuery(false, "DELETE FROM Users WHERE user_id = ?" )); databaseQueries.put("checkUsername", new DatabaseQuery(true, "SELECT * FROM Users WHERE username = ?" )); databaseQueries.put("insertUser", new DatabaseQuery(false, "INSERT INTO Users(user_id, username, password, firstname, lastname, email, admin) VALUES(?, ?, ?, ?, ?, ?)", "Users" )); databaseQueries.put("checkUser", new DatabaseQuery(true, "SELECT * FROM Users WHERE username = ?, password = ?" )); databaseQueries.put("updateUser", new DatabaseQuery(false, "UPDATE Users SET username = ?, password = ?," + " firstname = ?, lastname = ?, email = ? WHERE id = ?" )); databaseQueries.put("getUserByUsername", new DatabaseQuery(true, "SELECT * FROM Users WHERE username = ?" )); databaseQueries.put("getUserById", new DatabaseQuery(true, "SELECT * FROM Users WHERE user_id = ?" )); databaseQueries.put("setAdmin", new DatabaseQuery(false, "UPDATE Users SET admin = 1" )); // Session databaseQueries.put("startSession", new DatabaseQuery(false, "INSERT INTO Sessions(session_id, key, value) VALUES(?, ?, ?)" )); databaseQueries.put("endSession", new DatabaseQuery(false, "DELETE FROM Sessions WHERE token = ?" )); databaseQueries.put("setSessionVar", new DatabaseQuery(false, "INSERT INTO Sessions(session_id, key, value) VALUES(?, ?, ?)" )); databaseQueries.put("getSessionVar", new DatabaseQuery(true, "SELECT value FROM Sessions WHERE session_id = ? and key = ?" )); databaseQueries.put("updateSessionVar", new DatabaseQuery(true, "UPDATE Sessions SET value = ? where session_id = ? and key = ?" )); databaseQueries.put("sessionKeyExists", new DatabaseQuery(true, "SELECT Count(*) FROM Sessions WHERE session_id = ? and key = ?" )); databaseQueries.put("getAllSessions", new DatabaseQuery(true, "SELECT * FROM Sessions WHERE key = \"expiration\"" )); databaseQueries.put("removeSession", new DatabaseQuery(false, "DELETE FROM Sessions WHERE session_id = ?" )); // Ids: databaseQueries.put("getIdByTableName", new DatabaseQuery(true, "SELECT next_id FROM Ids WHERE table_name = ?" )); databaseQueries.put("incrementId", new DatabaseQuery(false, "UPDATE Ids SET next_Id = next_Id + 1 WHERE table_name = ?" )); databaseQueries.put("initialiseByTableName", new DatabaseQuery(false, "INSERT INTO Ids VALUES(?, 2)" )); } public ResultSet executeQuery(String queryName, Object... values) throws DatabaseCriticalErrorException{ DatabaseQuery databaseQuery = databaseQueries.get(queryName); return databaseQuery.execute(this, databaseConnector, values); } }
package org.smof.bson.codecs.string; import org.bson.codecs.Codec; import org.bson.codecs.configuration.CodecRegistry; import org.smof.bson.codecs.SmofCodecProvider; import com.google.common.base.Objects; @SuppressWarnings("javadoc") public class SmofStringCodecProvider implements SmofCodecProvider { private final Codec<String> stringCodec; public SmofStringCodecProvider() { stringCodec = new StringCodec(); } @SuppressWarnings("unchecked") @Override public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) { if(String.class.equals(clazz)) { return (Codec<T>) stringCodec; } return null; } @Override public boolean contains(Class<?> clazz) { return Objects.equal(clazz, String.class); } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc1073.robot17.commands; import edu.wpi.first.wpilibj.command.CommandGroup; import org.usfirst.frc1073.robot17.subsystems.*; public class AutonomousGear extends CommandGroup { int gearNumber; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS public AutonomousGear(int GearNumber) { gearNumber = GearNumber; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS // Add Commands here: // e.g. addSequential(new Command1()); // addSequential(new Command2()); // these will run in order. // To run multiple commands at the same time, // use addParallel() // e.g. addParallel(new Command1()); // addSequential(new Command2()); // Command1 and Command2 will run in parallel. // A command group will require all of the subsystems that each member // would require. // e.g. if Command1 requires chassis, and Command2 requires arm, // a CommandGroup containing them would require both the chassis and the // arm. // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS if (gearNumber == 1){ addSequential(new AutoDrive(0, 0)); addSequential(new AutoTurn(0, 0, "right")); }else if(gearNumber == 2){ addSequential(new AutoDrive(.5, 114.3)); }else if(gearNumber == 3){ addSequential(new AutoDrive(0, 0)); addSequential(new AutoTurn(0, 0, "right")); }else{ } } }
package org.slf4j.agent; import static org.slf4j.helpers.MessageFormatter.format; import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.instrument.Instrumentation; import java.util.Date; import java.util.Properties; import org.slf4j.instrumentation.LogTransformer; public class AgentPremain { private static final String START_MSG = "Start at {}"; private static final String STOP_MSG = "Stop at {}, execution time = {} ms"; public static void premain(String agentArgument, Instrumentation instrumentation) { System.err.println("THIS JAVAAGENT IS NOT RELEASED YET. DO NOT USE IN PRODUCTION ENVIRONMENTS."); LogTransformer.Builder builder = new LogTransformer.Builder(); builder = builder.addEntryExit(true); if (agentArgument != null) { Properties args = parseArguments(agentArgument); if (args.containsKey("verbose")) { builder = builder.verbose(true); } if (args.containsKey("time")) { printStartStopTimes(); } if (args.containsKey("ignore")) { builder = builder.ignore(args.getProperty("ignore").split(",")); } if (args.containsKey("level")) { builder = builder.level(args.getProperty("level")); } // ... more agent option handling here } instrumentation.addTransformer(builder.build()); } private static Properties parseArguments(String agentArgument) { Properties p = new Properties(); try { byte[] bytes = agentArgument.replaceAll(";", "\n").getBytes(); p.load(new ByteArrayInputStream(bytes)); } catch (IOException e) { throw new RuntimeException( "Could not load arguments as properties", e); } return p; } /** * Print the start message with the time NOW, and register a shutdown hook * which will print the stop message with the time then and the number of * milliseconds passed since. * */ private static void printStartStopTimes() { final long start = System.currentTimeMillis(); System.err.println(format(START_MSG, new Date())); Thread hook = new Thread() { public void run() { long timePassed = System.currentTimeMillis() - start; String message = format(STOP_MSG, new Date(), timePassed); System.err.println(message); } }; Runtime.getRuntime().addShutdownHook(hook); } }
package com.growthbeat.link; import java.util.HashMap; import java.util.Map; import android.content.Context; import android.net.Uri; import android.os.Handler; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info; import com.growthbeat.CatchableThread; import com.growthbeat.GrowthbeatCore; import com.growthbeat.GrowthbeatException; import com.growthbeat.Logger; import com.growthbeat.Preference; import com.growthbeat.analytics.GrowthAnalytics; import com.growthbeat.http.GrowthbeatHttpClient; import com.growthbeat.link.model.Click; import com.growthbeat.link.model.Synchronization; import com.growthbeat.utils.AppUtils; public class GrowthLink { public static final String LOGGER_DEFAULT_TAG = "GrowthLink"; public static final String HTTP_CLIENT_DEFAULT_BASE_URL = "https://api.link.growthbeat.com/"; private static final int HTTP_CLIENT_DEFAULT_CONNECTION_TIMEOUT = 60 * 1000; private static final int HTTP_CLIENT_DEFAULT_SOCKET_TIMEOUT = 60 * 1000; public static final String PREFERENCE_DEFAULT_FILE_NAME = "growthlink-preferences"; private static final GrowthLink instance = new GrowthLink(); private final Logger logger = new Logger(LOGGER_DEFAULT_TAG); private final GrowthbeatHttpClient httpClient = new GrowthbeatHttpClient(HTTP_CLIENT_DEFAULT_BASE_URL, HTTP_CLIENT_DEFAULT_CONNECTION_TIMEOUT, HTTP_CLIENT_DEFAULT_SOCKET_TIMEOUT); private final Preference preference = new Preference(PREFERENCE_DEFAULT_FILE_NAME); private Context context = null; private String applicationId = null; private String credentialId = null; private boolean initialized = false; private boolean isFirstSession = false; private GrowthLink() { super(); } public static GrowthLink getInstance() { return instance; } public void initialize(final Context context, final String applicationId, final String credentialId) { if (initialized) return; initialized = true; if (context == null) { logger.warning("The context parameter cannot be null."); return; } this.context = context.getApplicationContext(); this.applicationId = applicationId; this.credentialId = credentialId; GrowthbeatCore.getInstance().initialize(context, applicationId, credentialId); this.preference.setContext(GrowthbeatCore.getInstance().getContext()); if (GrowthbeatCore.getInstance().getClient() == null || (GrowthbeatCore.getInstance().getClient().getApplication() != null && !GrowthbeatCore.getInstance().getClient() .getApplication().getId().equals(applicationId))) { preference.removeAll(); } GrowthAnalytics.getInstance().initialize(context, applicationId, credentialId); synchronize(); } public void handleOpenUrl(Uri uri) { if (uri == null) return; final String clickId = uri.getQueryParameter("clickId"); if (clickId == null) { logger.error("Unabled to get clickId from url."); return; } final String uuId = uri.getQueryParameter("uuid"); if (uuId != null){ GrowthAnalytics.getInstance().tag("UUID",uuId); } final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { logger.info("Deeplinking..."); try { final Click click = Click.deeplink(GrowthbeatCore.getInstance().waitClient().getId(), clickId, isFirstSession, credentialId); if (click == null || click.getPattern() == null || click.getPattern().getLink() == null) { logger.error("Failed to deeplink."); return; } logger.info(String.format("Deeplink success. (clickId: %s)", click.getId())); handler.post(new Runnable() { @Override public void run() { Map<String, String> properties = new HashMap<String, String>(); properties.put("linkId", click.getPattern().getLink().getId()); properties.put("patternId", click.getPattern().getId()); if (click.getPattern().getIntent() != null) properties.put("intentId", click.getPattern().getIntent().getId()); if (isFirstSession) GrowthAnalytics.getInstance().track("GrowthLink", "Install", properties, null); GrowthAnalytics.getInstance().track("GrowthLink", "Open", properties, null); isFirstSession = false; if (click.getPattern().getIntent() != null) { GrowthbeatCore.getInstance().handleIntent(click.getPattern().getIntent()); } } }); } catch (GrowthbeatException e) { logger.info(String.format("Synchronization is not found.", e.getMessage())); } } }).start(); } private void synchronize() { logger.info("Check initialization..."); if (Synchronization.load() != null) { logger.info("Already initialized."); return; } isFirstSession = true; final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { logger.info("Synchronizing..."); try { String version = AppUtils.getaAppVersion(context); Synchronization synchronization = Synchronization.synchronize(applicationId, version, credentialId); if (synchronization == null) { logger.error("Failed to Synchronize."); return; } Synchronization.save(synchronization); logger.info(String.format("Synchronize success. (browser: %s)", synchronization.getBrowser())); if (synchronization.getBrowser()) { handler.post(new Runnable() { @Override public void run() { String urlString = "http://gbt.io/l/synchronize?applicationId=" + applicationId; try { Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(GrowthbeatCore.getInstance().getContext()); String advertisingId = adInfo.getId(); if (advertisingId != null){ urlString += "&advertisingId=" + advertisingId; } } catch (Exception e) { logger.warning("Failed to get advertising info: " + e.getMessage()); } Uri uri = Uri.parse(urlString); android.content.Intent androidIntent = new android.content.Intent(android.content.Intent.ACTION_VIEW, uri); androidIntent.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(androidIntent); } }); } } catch (GrowthbeatException e) { logger.info(String.format("Synchronization is not found. %s", e.getMessage())); } } }).start(); } public Context getContext() { return context; } public String getApplicationId() { return applicationId; } public String getCredentialId() { return credentialId; } public Logger getLogger() { return logger; } public GrowthbeatHttpClient getHttpClient() { return httpClient; } public Preference getPreference() { return preference; } private static class Thread extends CatchableThread { public Thread(Runnable runnable) { super(runnable); } @Override public void uncaughtException(java.lang.Thread thread, Throwable e) { String link = "Uncaught Exception: " + e.getClass().getName(); if (e.getMessage() != null) link += "; " + e.getMessage(); GrowthLink.getInstance().getLogger().warning(link); e.printStackTrace(); } } }
package com.simplifiedlogic.nitro.jlink.impl; import java.util.ArrayList; import java.util.List; import java.util.Vector; import com.ptc.cipjava.jxthrowable; import com.ptc.pfc.pfcExceptions.XToolkitBadContext; import com.ptc.pfc.pfcExceptions.XToolkitFound; import com.ptc.pfc.pfcExceptions.XToolkitNotFound; import com.simplifiedlogic.nitro.jlink.calls.seq.CallStringSeq; import com.simplifiedlogic.nitro.jlink.calls.server.CallServer; import com.simplifiedlogic.nitro.jlink.calls.server.CallWorkspaceDefinition; import com.simplifiedlogic.nitro.jlink.calls.server.CallWorkspaceDefinitions; import com.simplifiedlogic.nitro.jlink.calls.session.CallSession; import com.simplifiedlogic.nitro.jlink.data.AbstractJLISession; import com.simplifiedlogic.nitro.jlink.intf.DebugLogging; import com.simplifiedlogic.nitro.jlink.intf.IJLFile; import com.simplifiedlogic.nitro.jlink.intf.IJLWindchill; import com.simplifiedlogic.nitro.jlink.intf.JShellProvider; import com.simplifiedlogic.nitro.rpc.JLIException; import com.simplifiedlogic.nitro.rpc.JLISession; import com.simplifiedlogic.nitro.util.JLConnectionUtil; import com.simplifiedlogic.nitro.util.WorkspaceFileLooper; /** * @author Adam Andrews * */ public class JLWindchill implements IJLWindchill { /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#authorize(java.lang.String, java.lang.String, java.lang.String) */ @Override public void authorize(String user, String password, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); authorize(user, password, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#authorize(java.lang.String, java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public void authorize(String user, String password, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.authorize: " + user, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (user==null || user.trim().length()==0) throw new JLIException("No user parameter given"); if (password==null || password.trim().length()==0) throw new JLIException("No password parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return; session.authenticateBrowser(user, password); } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.authorize: " + user, start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#setServer(java.lang.String, java.lang.String) */ @Override public void setServer(String serverUrl, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); setServer(serverUrl, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#setServer(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public void setServer(String serverUrl, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.set_server: " + serverUrl, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (serverUrl==null || serverUrl.trim().length()==0) throw new JLIException("No server URL parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return; /* Debugging code for getting a list of servers Servers servers = session.getSession().ListServers(); System.out.println("Servers:"); if (servers!=null) { int len = servers.getarraysize(); for (int i=0; i<len; i++) { Server svr = servers.get(i); System.out.println(" " + svr.GetAlias() + " : " + svr.GetLocation() + ", active=" + svr.GetIsActive()); } } else { System.out.println(" No servers found."); } */ CallServer activeServer = session.getActiveServer(); CallServer server = null; if (serverUrl!=null) { if (NitroUtils.isValidURL(serverUrl)) { server = session.getServerByUrl(serverUrl, null); if (server==null) throw new JLIException("Could not find server for URL " + serverUrl); } else { server = session.getServerByAlias(serverUrl); if (server==null) throw new JLIException("Could not find server for Alias " + serverUrl); } if (activeServer==null || !server.getAlias().equals(activeServer.getAlias())) { server.activate(); } } } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.set_server: " + serverUrl, start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#serverExists(java.lang.String, java.lang.String) */ @Override public boolean serverExists(String serverUrl, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); return serverExists(serverUrl, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#serverExists(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public boolean serverExists(String serverUrl, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.server_exists: " + serverUrl, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (serverUrl==null || serverUrl.trim().length()==0) throw new JLIException("No server parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return false; CallServer server = null; if (NitroUtils.isValidURL(serverUrl)) { server = session.getServerByUrl(serverUrl, null); } else { server = session.getServerByAlias(serverUrl); } return server!=null; } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.server_exists: " + serverUrl, start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#listWorkspaces(java.lang.String) */ @Override public List<String> listWorkspaces(String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); return listWorkspaces(sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#listWorkspaces(com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public List<String> listWorkspaces(AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.list_workspaces", NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return null; CallServer server = session.getActiveServer(); if (server==null) throw new JLIException("No server is selected."); CallWorkspaceDefinitions workspaces = server.collectWorkspaces(); if (workspaces==null) { return null; } List<String> out = new ArrayList<String>(); int len = workspaces.getarraysize(); for (int i=0; i<len; i++) { CallWorkspaceDefinition wdef = workspaces.get(i); String wname = wdef.getWorkspaceName(); out.add(wname); } if (out.size()==0) return null; return out; } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.list_workspaces", start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#setWorkspace(java.lang.String, java.lang.String) */ @Override public void setWorkspace(String workspace, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); setWorkspace(workspace, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#setWorkspace(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public void setWorkspace(String workspace, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.set_workspace: " + workspace, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (workspace==null || workspace.trim().length()==0) throw new JLIException("No workspace parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return; CallServer server = session.getActiveServer(); if (server==null) throw new JLIException("No server is selected."); String activeWorkspace = server.getActiveWorkspace(); if (activeWorkspace==null || !activeWorkspace.equals(workspace)) { if (!workspaceExists(server, workspace)) throw new JLIException("Workspace '" + workspace + "' does not exist on the active server"); IJLFile fileHandler = JShellProvider.getInstance().getJLFile(); if (fileHandler!=null) fileHandler.erase(null, null, true, sess); server.setActiveWorkspace(workspace); } } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.set_workspace: " + workspace, start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#getWorkspace(java.lang.String) */ @Override public String getWorkspace(String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); return getWorkspace(sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#getWorkspace(com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public String getWorkspace(AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.get_workspace", NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return null; CallServer server = session.getActiveServer(); if (server==null) throw new JLIException("No server is selected."); String activeWorkspace = server.getActiveWorkspace(); return activeWorkspace; } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.get_workspace", start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#workspaceExists(java.lang.String, java.lang.String) */ @Override public boolean workspaceExists(String workspace, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); return workspaceExists(workspace, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#workspaceExists(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public boolean workspaceExists(String workspace, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.workspace_exists: " + workspace, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (workspace==null || workspace.trim().length()==0) throw new JLIException("No workspace parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return false; CallServer server = session.getActiveServer(); if (server==null) throw new JLIException("No server is selected."); boolean exists = workspaceExists(server, workspace); return exists; } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.workspace_exists: " + workspace, start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#createWorkspace(java.lang.String, java.lang.String, java.lang.String) */ @Override public void createWorkspace(String workspace, String context, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); createWorkspace(workspace, context, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#createWorkspace(java.lang.String, java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public void createWorkspace(String workspace, String context, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.create_workspace: " + workspace, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (workspace==null || workspace.trim().length()==0) throw new JLIException("No workspace parameter given"); if (context==null || context.trim().length()==0) throw new JLIException("No context parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return; CallServer server = session.getActiveServer(); if (server==null) throw new JLIException("No server is selected."); if (workspaceExists(server, workspace)) throw new JLIException("Workspace '" + workspace + "' already exists"); CallWorkspaceDefinition wdef = CallWorkspaceDefinition.create(workspace, context); server.createWorkspace(wdef); } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.create_workspace: " + workspace, start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#clearWorkspace(java.lang.String, java.util.List, java.lang.String) */ @Override public void clearWorkspace(String workspace, List<String> filenames, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); clearWorkspace(workspace, filenames, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#clearWorkspace(java.lang.String, java.util.List, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public void clearWorkspace(String workspace, List<String> filenames, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.clear_workspace: " + workspace, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (workspace==null || workspace.trim().length()==0) throw new JLIException("No workspace parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return; CallServer server = session.getActiveServer(); if (server==null) throw new JLIException("No server is selected."); if (!workspaceExists(server, workspace)) throw new JLIException("Workspace '" + workspace + "' does not exist"); CallStringSeq seq = null; if (filenames!=null && filenames.size()>0) { seq = CallStringSeq.create(); for (String name : filenames) { seq.append(name); } } String activeWorkspace = server.getActiveWorkspace(); if (activeWorkspace==null || !activeWorkspace.equals(workspace)) server.setActiveWorkspace(workspace); try { server.removeObjects(seq); } catch (XToolkitNotFound e) { // ignore "not found" error } catch (XToolkitFound e) { // ignore "found" error } finally { if (activeWorkspace!=null && !activeWorkspace.equals(workspace)) server.setActiveWorkspace(activeWorkspace); } } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.clear_workspace: " + workspace, start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#deleteWorkspace(java.lang.String, java.lang.String) */ @Override public void deleteWorkspace(String workspace, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); deleteWorkspace(workspace, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#deleteWorkspace(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public void deleteWorkspace(String workspace, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.delete_workspace: " + workspace, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (workspace==null || workspace.trim().length()==0) throw new JLIException("No workspace parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return; CallServer server = session.getActiveServer(); if (server==null) throw new JLIException("No server is selected."); String activeWorkspace = server.getActiveWorkspace(); if (activeWorkspace!=null && activeWorkspace.equals(workspace)) throw new JLIException("Cannot delete the active workspace"); if (!workspaceExists(server, workspace)) throw new JLIException("Workspace '" + workspace + "' does not exist on the active server"); server.deleteWorkspace(workspace); } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.delete_workspace: " + workspace, start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#fileCheckedOut(java.lang.String, java.lang.String, java.lang.String) */ @Override public boolean fileCheckedOut(String workspace, String fileName, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); return fileCheckedOut(workspace, fileName, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#fileCheckedOut(java.lang.String, java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public boolean fileCheckedOut(String workspace, String fileName, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.file_checked_out: " + fileName, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (workspace==null || workspace.trim().length()==0) throw new JLIException("No workspace parameter given"); if (fileName==null || fileName.trim().length()==0) throw new JLIException("No file name parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return false; CallServer server = session.getActiveServer(); if (server==null) throw new JLIException("No server is selected."); try { boolean checkedOut = server.isObjectCheckedOut(workspace, fileName); return checkedOut; } catch (XToolkitNotFound e) { return false; } catch (XToolkitBadContext e) { return false; } } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.file_checked_out: " + fileName, start, NitroConstants.DEBUG_KEY); } } } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#listWorkspaceFiles(java.lang.String, java.lang.String, java.lang.String) */ @Override public List<String> listWorkspaceFiles(String filename, String workspace, String sessionId) throws JLIException { JLISession sess = JLISession.getSession(sessionId); return listWorkspaceFiles(filename, workspace, sess); } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jlink.intf.IJLWindchill#listWorkspaceFiles(java.lang.String, java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession) */ @Override public List<String> listWorkspaceFiles(String filename, String workspace, AbstractJLISession sess) throws JLIException { DebugLogging.sendDebugMessage("windchill.list_workspace_files: " + workspace, NitroConstants.DEBUG_KEY); if (sess==null) throw new JLIException("No session found"); if (workspace==null || workspace.trim().length()==0) throw new JLIException("No workspace parameter given"); long start = 0; if (NitroConstants.TIME_TASKS) start = System.currentTimeMillis(); try { JLGlobal.loadLibrary(); CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId()); if (session == null) return null; CallServer server = session.getActiveServer(); if (server==null) throw new JLIException("No server is selected."); if (!workspaceExists(server, workspace)) throw new JLIException("Workspace '" + workspace + "' does not exist"); ListLooper looper = new ListLooper(); looper.setNamePattern(filename); looper.setSession(session); looper.setServerAlias(server.getAlias()); looper.setWorkspace(workspace); looper.loop(); if (looper.output==null) return new Vector<String>(); else return looper.output; } catch (jxthrowable e) { throw JlinkUtils.createException(e); } finally { if (NitroConstants.TIME_TASKS) { DebugLogging.sendTimerMessage("windchill.list_workspace_files: " + workspace, start, NitroConstants.DEBUG_KEY); } } } /** * Check whether a given workspace exists on a server * @param server The server containing the workspace * @param workspace Workspace name * @return Whether the workspace exists on the server * @throws jxthrowable */ private boolean workspaceExists(CallServer server, String workspace) throws jxthrowable { CallWorkspaceDefinitions workspaces = server.collectWorkspaces(); if (workspaces==null) return false; int len = workspaces.getarraysize(); boolean found=false; for (int i=0; i<len; i++) { CallWorkspaceDefinition wdef = workspaces.get(i); String wname = wdef.getWorkspaceName(); if (workspace!=null && workspace.equals(wname)) { found=true; } } return found; } /** * An implementation of WorkspaceFileLooper which gets a list of * workspace file names * @author Adam Andrews */ private static class ListLooper extends WorkspaceFileLooper { /** * An output list of model names */ public List<String> output = null; /* (non-Javadoc) * @see com.simplifiedlogic.nitro.util.WorkspaceFileLooper#loopAction(java.lang.String) */ @Override public boolean loopAction(String fileName) throws JLIException, jxthrowable { if (output==null) output = new Vector<String>(); output.add(fileName); return false; } } }
package etf.si.projekat.data_vision; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import java.awt.Choice; import javax.swing.JButton; import net.sourceforge.jdatepicker.impl.JDatePickerImpl; import org.hibernate.Session; import org.hibernate.Transaction; import ba.unsa.etf.si.beans.DeviceType; import etf.si.projekat.util.HibernateUtil; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; public class Add2Sensors extends JFrame { Choice choice = new Choice(); Choice choice_1 = new Choice(); JButton btnProcess = new JButton("Process"); ArrayList<DeviceType> list_device = new ArrayList<DeviceType>(); private JPanel contentPane; public String graphType; final List<String> senzori; final JDatePickerImpl datePickerFrom; final JDatePickerImpl datePickerTo; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { //Add2Sensors frame = new Add2Sensors(graphType); //frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Add2Sensors(String _graphType, JDatePickerImpl dp1, JDatePickerImpl dp2) { senzori=new ArrayList<String>(); datePickerFrom=dp1; datePickerTo=dp2; graphType=_graphType; setBounds(100, 100, 305, 170); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblSensorType = new JLabel("Sensor type 1"); lblSensorType.setBounds(10, 27, 85, 14); contentPane.add(lblSensorType); JLabel lblSensorType_1 = new JLabel("Sensor type 2"); lblSensorType_1.setBounds(10, 52, 85, 14); contentPane.add(lblSensorType_1); choice.setBounds(100, 23, 150, 20); contentPane.add(choice); choice_1.setBounds(100, 48, 150, 20); contentPane.add(choice_1); choice.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e){ fillChoices(1); } }); choice_1.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e){ fillChoices(2); } }); btnProcess.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(graphType=="Bar") { senzori.add(choice.getSelectedItem()); senzori.add(choice_1.getSelectedItem()); BarPlotShow bp=new BarPlotShow(senzori); dispose(); } else{ senzori.add(choice.getSelectedItem()); senzori.add(choice_1.getSelectedItem()); OneGraphShow og=new OneGraphShow(senzori, datePickerFrom, datePickerTo); } //dispose(); } }); btnProcess.setBounds(190, 98, 89, 23); contentPane.add(btnProcess); btnProcess.setVisible(false); JButton btnExit = new JButton("Cancel"); btnExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); btnExit.setBounds(91, 98, 89, 23); contentPane.add(btnExit); Session session = HibernateUtil.getSessionFactory().openSession(); Transaction t=null; try{ t = session.beginTransaction(); List list = session.createQuery("from DeviceType").list(); for (Iterator iterator = list.iterator(); iterator.hasNext();){ DeviceType dt =(DeviceType) iterator.next(); list_device.add(dt); choice.addItem(dt.getType()); } t.commit(); } catch(Exception e) { System.out.println("Error:"+e); } finally{ session.close(); } } public void fillChoices(int k){ if(k==1) { for(int i=0; i<list_device.size();i++){ if(choice.getSelectedItem() == list_device.get(i).getType()) continue; choice_1.add(list_device.get(i).getType()); } choice.disable(); } if(k==2){ choice_1.disable(); btnProcess.setVisible(true); } } }
package net.fortuna.ical4j.model; import java.net.URISyntaxException; import net.fortuna.ical4j.model.parameter.Abbrev; import net.fortuna.ical4j.model.parameter.AltRep; import net.fortuna.ical4j.model.parameter.Cn; import net.fortuna.ical4j.model.parameter.CuType; import net.fortuna.ical4j.model.parameter.DelegatedFrom; import net.fortuna.ical4j.model.parameter.DelegatedTo; import net.fortuna.ical4j.model.parameter.Dir; import net.fortuna.ical4j.model.parameter.Encoding; import net.fortuna.ical4j.model.parameter.FbType; import net.fortuna.ical4j.model.parameter.FmtType; import net.fortuna.ical4j.model.parameter.Language; import net.fortuna.ical4j.model.parameter.Member; import net.fortuna.ical4j.model.parameter.PartStat; import net.fortuna.ical4j.model.parameter.Range; import net.fortuna.ical4j.model.parameter.RelType; import net.fortuna.ical4j.model.parameter.Related; import net.fortuna.ical4j.model.parameter.Role; import net.fortuna.ical4j.model.parameter.Rsvp; import net.fortuna.ical4j.model.parameter.SentBy; import net.fortuna.ical4j.model.parameter.Type; import net.fortuna.ical4j.model.parameter.TzId; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.model.parameter.Vvenue; import net.fortuna.ical4j.model.parameter.XParameter; import net.fortuna.ical4j.util.Strings; /** * A factory for creating iCalendar parameters. * * $Id $ * * [05-Apr-2004] * * @author Ben Fortuna */ public class ParameterFactoryImpl extends AbstractContentFactory implements ParameterFactory { private static ParameterFactoryImpl instance = new ParameterFactoryImpl(); /** * Constructor made private to prevent instantiation. */ protected ParameterFactoryImpl() { registerDefaultFactory(Parameter.ABBREV, new AbbrevFactory()); registerDefaultFactory(Parameter.ALTREP, new AltRepFactory()); registerDefaultFactory(Parameter.CN, new CnFactory()); registerDefaultFactory(Parameter.CUTYPE, new CuTypeFactory()); registerDefaultFactory(Parameter.DELEGATED_FROM, new DelegatedFromFactory()); registerDefaultFactory(Parameter.DELEGATED_TO, new DelegatedToFactory()); registerDefaultFactory(Parameter.DIR, new DirFactory()); registerDefaultFactory(Parameter.ENCODING, new EncodingFactory()); registerDefaultFactory(Parameter.FMTTYPE, new FmtTypeFactory()); registerDefaultFactory(Parameter.FBTYPE, new FbTypeFactory()); registerDefaultFactory(Parameter.LANGUAGE, new LanguageFactory()); registerDefaultFactory(Parameter.MEMBER, new MemberFactory()); registerDefaultFactory(Parameter.PARTSTAT, new PartStatFactory()); registerDefaultFactory(Parameter.RANGE, new RangeFactory()); registerDefaultFactory(Parameter.RELATED, new RelatedFactory()); registerDefaultFactory(Parameter.RELTYPE, new RelTypeFactory()); registerDefaultFactory(Parameter.ROLE, new RoleFactory()); registerDefaultFactory(Parameter.RSVP, new RsvpFactory()); registerDefaultFactory(Parameter.SENT_BY, new SentByFactory()); registerDefaultFactory(Parameter.TYPE, new TypeFactory()); registerDefaultFactory(Parameter.TZID, new TzIdFactory()); registerDefaultFactory(Parameter.VALUE, new ValueFactory()); registerDefaultFactory(Parameter.VVENUE, new VvenueFactory()); } /** * @return Returns the instance. */ public static ParameterFactoryImpl getInstance() { return instance; } /** * Creates a parameter. * @param name name of the parameter * @param value a parameter value * @return a component * @throws URISyntaxException thrown when the specified string is not a valid representation of a URI for selected * parameters */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { final ParameterFactory factory = (ParameterFactory) getFactory(name); Parameter parameter = null; if (factory != null) { parameter = factory.createParameter(name, value); } else if (isExperimentalName(name)) { parameter = new XParameter(name, value); } else if (allowIllegalNames()) { parameter = new XParameter(name, value); } else { throw new IllegalArgumentException("Invalid parameter name: " + name); } return parameter; } /** * @param name * @return */ private boolean isExperimentalName(final String name) { return name.startsWith(Parameter.EXPERIMENTAL_PREFIX) && name.length() > Parameter.EXPERIMENTAL_PREFIX.length(); } private static class AbbrevFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Abbrev(value); } } private static class AltRepFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new AltRep(value); } } private static class CnFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Cn(value); } } private static class CuTypeFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { CuType parameter = new CuType(value); if (CuType.INDIVIDUAL.equals(parameter)) { parameter = CuType.INDIVIDUAL; } else if (CuType.GROUP.equals(parameter)) { parameter = CuType.GROUP; } else if (CuType.RESOURCE.equals(parameter)) { parameter = CuType.RESOURCE; } else if (CuType.ROOM.equals(parameter)) { parameter = CuType.ROOM; } else if (CuType.UNKNOWN.equals(parameter)) { parameter = CuType.UNKNOWN; } return parameter; } } private static class DelegatedFromFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new DelegatedFrom(value); } } private static class DelegatedToFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new DelegatedTo(value); } } private static class DirFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Dir(value); } } private static class EncodingFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { Encoding parameter = new Encoding(value); if (Encoding.EIGHT_BIT.equals(parameter)) { parameter = Encoding.EIGHT_BIT; } else if (Encoding.BASE64.equals(parameter)) { parameter = Encoding.BASE64; } return parameter; } } private static class FmtTypeFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new FmtType(value); } } private static class FbTypeFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { FbType parameter = new FbType(value); if (FbType.FREE.equals(parameter)) { parameter = FbType.FREE; } else if (FbType.BUSY.equals(parameter)) { parameter = FbType.BUSY; } else if (FbType.BUSY_TENTATIVE.equals(parameter)) { parameter = FbType.BUSY_TENTATIVE; } else if (FbType.BUSY_UNAVAILABLE.equals(parameter)) { parameter = FbType.BUSY_UNAVAILABLE; } return parameter; } } private static class LanguageFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Language(value); } } private static class MemberFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Member(value); } } private static class PartStatFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { PartStat parameter = new PartStat(value); if (PartStat.NEEDS_ACTION.equals(parameter)) { parameter = PartStat.NEEDS_ACTION; } else if (PartStat.ACCEPTED.equals(parameter)) { parameter = PartStat.ACCEPTED; } else if (PartStat.DECLINED.equals(parameter)) { parameter = PartStat.DECLINED; } else if (PartStat.TENTATIVE.equals(parameter)) { parameter = PartStat.TENTATIVE; } else if (PartStat.DELEGATED.equals(parameter)) { parameter = PartStat.DELEGATED; } else if (PartStat.COMPLETED.equals(parameter)) { parameter = PartStat.COMPLETED; } else if (PartStat.IN_PROCESS.equals(parameter)) { parameter = PartStat.IN_PROCESS; } return parameter; } } private static class RangeFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { Range parameter = new Range(value); if (Range.THISANDFUTURE.equals(parameter)) { parameter = Range.THISANDFUTURE; } else if (Range.THISANDPRIOR.equals(parameter)) { parameter = Range.THISANDPRIOR; } return parameter; } } private static class RelatedFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { Related parameter = new Related(value); if (Related.START.equals(parameter)) { parameter = Related.START; } else if (Related.END.equals(parameter)) { parameter = Related.END; } return parameter; } } private static class RelTypeFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { RelType parameter = new RelType(value); if (RelType.PARENT.equals(parameter)) { parameter = RelType.PARENT; } else if (RelType.CHILD.equals(parameter)) { parameter = RelType.CHILD; } if (RelType.SIBLING.equals(parameter)) { parameter = RelType.SIBLING; } return parameter; } } private static class RoleFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { Role parameter = new Role(value); if (Role.CHAIR.equals(parameter)) { parameter = Role.CHAIR; } else if (Role.REQ_PARTICIPANT.equals(parameter)) { parameter = Role.REQ_PARTICIPANT; } else if (Role.OPT_PARTICIPANT.equals(parameter)) { parameter = Role.OPT_PARTICIPANT; } else if (Role.NON_PARTICIPANT.equals(parameter)) { parameter = Role.NON_PARTICIPANT; } return parameter; } } private static class RsvpFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { Rsvp parameter = new Rsvp(value); if (Rsvp.TRUE.equals(parameter)) { parameter = Rsvp.TRUE; } else if (Rsvp.FALSE.equals(parameter)) { parameter = Rsvp.FALSE; } return parameter; } } private static class SentByFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new SentBy(value); } } private static class VvenueFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Vvenue(value); } } private static class TypeFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Type(value); } } private static class TzIdFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new TzId(Strings.unescape(value)); } } private static class ValueFactory implements ParameterFactory { public Parameter createParameter(final String name, final String value) throws URISyntaxException { Value parameter = new Value(value); if (Value.BINARY.equals(parameter)) { parameter = Value.BINARY; } else if (Value.BOOLEAN.equals(parameter)) { parameter = Value.BOOLEAN; } else if (Value.CAL_ADDRESS.equals(parameter)) { parameter = Value.CAL_ADDRESS; } else if (Value.DATE.equals(parameter)) { parameter = Value.DATE; } else if (Value.DATE_TIME.equals(parameter)) { parameter = Value.DATE_TIME; } else if (Value.DURATION.equals(parameter)) { parameter = Value.DURATION; } else if (Value.FLOAT.equals(parameter)) { parameter = Value.FLOAT; } else if (Value.INTEGER.equals(parameter)) { parameter = Value.INTEGER; } else if (Value.PERIOD.equals(parameter)) { parameter = Value.PERIOD; } else if (Value.RECUR.equals(parameter)) { parameter = Value.RECUR; } else if (Value.TEXT.equals(parameter)) { parameter = Value.TEXT; } else if (Value.TIME.equals(parameter)) { parameter = Value.TIME; } else if (Value.URI.equals(parameter)) { parameter = Value.URI; } else if (Value.UTC_OFFSET.equals(parameter)) { parameter = Value.UTC_OFFSET; } return parameter; } } }
package net.fortuna.ical4j.model.component; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateList; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.RDate; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.model.property.TzOffsetFrom; import net.fortuna.ical4j.model.property.TzOffsetTo; import net.fortuna.ical4j.util.Dates; import net.fortuna.ical4j.util.PropertyValidator; import net.fortuna.ical4j.util.TimeZones; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * $Id$ [05-Apr-2004] * * Defines an iCalendar sub-component representing a timezone observance. Class made abstract such that only Standard * and Daylight instances are valid. * @author Ben Fortuna */ public abstract class Observance extends Component implements Comparable { private static final long serialVersionUID = 2523330383042085994L; /** * one of 'standardc' or 'daylightc' MUST occur and each MAY occur more than once. */ public static final String STANDARD = "STANDARD"; /** * Token for daylight observance. */ public static final String DAYLIGHT = "DAYLIGHT"; private transient Log log = LogFactory.getLog(Observance.class); // TODO: clear cache when observance definition changes (??) private long[] onsetsMillisec; private DateTime[] onsetsDates; private Map onsets = new TreeMap(); private Date initialOnset = null; /** * Used for parsing times in a UTC date-time representation. */ private static final String UTC_PATTERN = "yyyyMMdd'T'HHmmss"; private static final DateFormat UTC_FORMAT = new SimpleDateFormat( UTC_PATTERN); static { UTC_FORMAT.setTimeZone(TimeZone.getTimeZone(TimeZones.UTC_ID)); UTC_FORMAT.setLenient(false); } /* If this is set we have rrules. If we get a date after this rebuild onsets */ private Date onsetLimit; /** * Constructs a timezone observance with the specified name and no properties. * @param name the name of this observance component */ protected Observance(final String name) { super(name); } /** * Constructor protected to enforce use of sub-classes from this library. * @param name the name of the time type * @param properties a list of properties */ protected Observance(final String name, final PropertyList properties) { super(name, properties); } /** * {@inheritDoc} */ public final void validate(final boolean recurse) throws ValidationException { // From "4.8.3.3 Time Zone Offset From": // Conformance: This property MUST be specified in a "VTIMEZONE" // calendar component. PropertyValidator.getInstance().assertOne(Property.TZOFFSETFROM, getProperties()); // From "4.8.3.4 Time Zone Offset To": // Conformance: This property MUST be specified in a "VTIMEZONE" // calendar component. PropertyValidator.getInstance().assertOne(Property.TZOFFSETTO, getProperties()); /* * ; the following are each REQUIRED, ; but MUST NOT occur more than once dtstart / tzoffsetto / tzoffsetfrom / */ PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties()); /* * ; the following are optional, ; and MAY occur more than once comment / rdate / rrule / tzname / x-prop */ if (recurse) { validateProperties(); } } /** * Returns the latest applicable onset of this observance for the specified date. * @param date the latest date that an observance onset may occur * @return the latest applicable observance date or null if there is no applicable observance onset for the * specified date */ public final Date getLatestOnset(final Date date) { if (initialOnset == null) { try { initialOnset = applyOffsetFrom(calculateOnset(((DtStart) getProperty(Property.DTSTART)).getDate())); } catch (ParseException e) { log.error("Unexpected error calculating initial onset", e); // XXX: is this correct? return null; } } // observance not applicable if date is before the effective date of this observance.. if (date.before(initialOnset)) { return null; } if ((onsetsMillisec != null) && (onsetLimit == null || date.before(onsetLimit))) { return getCachedOnset(date); } Date onset = initialOnset; Date initialOnsetUTC; // get first onset without adding TZFROM as this may lead to a day boundary // change which would be incompatible with BYDAY RRULES // we will have to add the offset to all cacheable onsets try { initialOnsetUTC = calculateOnset(((DtStart) getProperty(Property.DTSTART)).getDate()); } catch (ParseException e) { log.error("Unexpected error calculating initial onset", e); // XXX: is this correct? return null; } // collect all onsets for the purposes of caching.. final DateList cacheableOnsets = new DateList(); cacheableOnsets.setUtc(true); cacheableOnsets.add(initialOnset); // check rdates for latest applicable onset.. final PropertyList rdates = getProperties(Property.RDATE); for (final Iterator i = rdates.iterator(); i.hasNext();) { final RDate rdate = (RDate) i.next(); for (final Iterator j = rdate.getDates().iterator(); j.hasNext();) { try { final DateTime rdateOnset = applyOffsetFrom(calculateOnset((Date) j.next())); if (!rdateOnset.after(date) && rdateOnset.after(onset)) { onset = rdateOnset; } /* * else if (rdateOnset.after(date) && rdateOnset.after(onset) && (nextOnset == null || * rdateOnset.before(nextOnset))) { nextOnset = rdateOnset; } */ cacheableOnsets.add(rdateOnset); } catch (ParseException e) { log.error("Unexpected error calculating onset", e); } } } // check recurrence rules for latest applicable onset.. final PropertyList rrules = getProperties(Property.RRULE); for (final Iterator i = rrules.iterator(); i.hasNext();) { final RRule rrule = (RRule) i.next(); // include future onsets to determine onset period.. final Calendar cal = Dates.getCalendarInstance(date); cal.setTime(date); cal.add(Calendar.YEAR, 10); onsetLimit = Dates.getInstance(cal.getTime(), Value.DATE_TIME); final DateList recurrenceDates = rrule.getRecur().getDates(initialOnsetUTC, onsetLimit, Value.DATE_TIME); for (final Iterator j = recurrenceDates.iterator(); j.hasNext();) { final DateTime rruleOnset = applyOffsetFrom((DateTime) j.next()); if (!rruleOnset.after(date) && rruleOnset.after(onset)) { onset = rruleOnset; } /* * else if (rruleOnset.after(date) && rruleOnset.after(onset) && (nextOnset == null || * rruleOnset.before(nextOnset))) { nextOnset = rruleOnset; } */ cacheableOnsets.add(rruleOnset); } } // cache onsets.. Collections.sort(cacheableOnsets); DateTime cacheableOnset = null; this.onsetsMillisec = new long[cacheableOnsets.size()]; this.onsetsDates = new DateTime[onsetsMillisec.length]; for (int i = 0; i < onsetsMillisec.length; i++) { cacheableOnset = (DateTime)cacheableOnsets.get(i); onsetsMillisec[i] = cacheableOnset.getTime(); onsetsDates[i] = cacheableOnset; } return onset; } /** * Returns a cached onset for the specified date. * @param date * @return a cached onset date or null if no cached onset is applicable for the specified date */ private DateTime getCachedOnset(final Date date) { int index = Arrays.binarySearch(onsetsMillisec, date.getTime()); if (index >= 0) { return onsetsDates[index]; } else { int insertionIndex = -index -1; return onsetsDates[insertionIndex -1]; } } /** * Returns the mandatory dtstart property. * @return the DTSTART property or null if not specified */ public final DtStart getStartDate() { return (DtStart) getProperty(Property.DTSTART); } /** * Returns the mandatory tzoffsetfrom property. * @return the TZOFFSETFROM property or null if not specified */ public final TzOffsetFrom getOffsetFrom() { return (TzOffsetFrom) getProperty(Property.TZOFFSETFROM); } /** * Returns the mandatory tzoffsetto property. * @return the TZOFFSETTO property or null if not specified */ public final TzOffsetTo getOffsetTo() { return (TzOffsetTo) getProperty(Property.TZOFFSETTO); } /** * {@inheritDoc} */ public final int compareTo(final Object arg0) { return compareTo((Observance) arg0); } /** * @param arg0 another observance instance * @return a positve value if this observance starts earlier than the other, * a negative value if it occurs later than the other, or zero if they start * at the same time */ public final int compareTo(final Observance arg0) { // TODO: sort by RDATE?? final DtStart dtStart = (DtStart) getProperty(Property.DTSTART); final DtStart dtStart0 = (DtStart) arg0.getProperty(Property.DTSTART); return dtStart.getDate().compareTo(dtStart0.getDate()); } /** * @param stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); log = LogFactory.getLog(Observance.class); } // private Date calculateOnset(DateProperty dateProperty) { // return calculateOnset(dateProperty.getValue()); private DateTime calculateOnset(Date date) throws ParseException { return calculateOnset(date.toString()); } private DateTime calculateOnset(String dateStr) throws ParseException { // Translate local onset into UTC time by parsing local time // as GMT and adjusting by TZOFFSETFROM if required long utcOnset; synchronized (UTC_FORMAT) { utcOnset = UTC_FORMAT.parse(dateStr).getTime(); } // return a UTC DateTime onset = new DateTime(true); onset.setTime(utcOnset); return onset; } private DateTime applyOffsetFrom(DateTime orig) { DateTime withOffset = new DateTime(true); withOffset.setTime(orig.getTime() - getOffsetFrom().getOffset().getOffset()); return withOffset; } }
package com.almende.dialog.agent; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.jivesoftware.smack.XMPPException; import com.almende.dialog.accounts.AdapterConfig; import com.almende.dialog.accounts.Dialog; import com.almende.dialog.adapter.MailServlet; import com.almende.dialog.adapter.TwitterServlet; import com.almende.dialog.adapter.TwitterServlet.TwitterEndpoint; import com.almende.dialog.adapter.XMPPServlet; import com.almende.dialog.adapter.tools.Broadsoft; import com.almende.dialog.exception.ConflictException; import com.almende.dialog.model.ddr.DDRRecord; import com.almende.dialog.util.DDRUtils; import com.almende.dialog.util.ServerUtils; import com.almende.dialog.util.TimeUtils; import com.almende.eve.agent.Agent; import com.almende.eve.rpc.annotation.Access; import com.almende.eve.rpc.annotation.AccessType; import com.almende.eve.rpc.annotation.Name; import com.almende.eve.rpc.annotation.Optional; import com.almende.eve.rpc.jsonrpc.JSONRPCException; import com.almende.eve.rpc.jsonrpc.JSONRPCException.CODE; import com.almende.eve.rpc.jsonrpc.JSONRequest; import com.almende.eve.rpc.jsonrpc.jackson.JOM; import com.almende.util.twigmongo.TwigCompatibleMongoDatastore; import com.almende.util.uuid.UUID; import com.askfast.commons.agent.intf.AdapterAgentInterface; import com.askfast.commons.entity.AccountType; import com.askfast.commons.entity.Adapter; import com.askfast.commons.entity.AdapterProviders; import com.askfast.commons.entity.AdapterType; import com.fasterxml.jackson.databind.node.ArrayNode; @Access(AccessType.PUBLIC) public class AdapterAgent extends Agent implements AdapterAgentInterface { public static final int EMAIL_SCHEDULER_INTERVAL = 30 * 1000; //30seconds public static final int TWITTER_SCHEDULER_INTERVAL = 61 * 1000; //61seconds private static final Logger log = Logger.getLogger(AdapterAgent.class.getSimpleName()); public static final String ADAPTER_TYPE_CALL = AdapterType.CALL.toString(); public static final String ADAPTER_TYPE_SMS = AdapterType.SMS.toString(); public static final String ADAPTER_TYPE_FACEBOOK = AdapterType.FACEBOOK.toString(); public static final String ADAPTER_TYPE_EMAIL = AdapterType.EMAIL.toString(); public static final String ADAPTER_TYPE_XMPP = AdapterType.XMPP.toString(); public static final String ADAPTER_TYPE_TWITTER = AdapterType.TWITTER.toString(); public static final String ADAPTER_TYPE_USSD = AdapterType.USSD.toString(); public static final String ADAPTER_TYPE_PUSH = AdapterType.PUSH.toString(); @Override protected void onCreate() { //start inbound schedulers for email and xmpp startAllInboundSceduler(); } /** * starts scedulers for all inbound services such as Email, Twitter, XMPP etc */ public void startAllInboundSceduler() { startEmailInboundSceduler(); startTwitterInboundSceduler(); } /** * stops scedulers for all inbound services such as Email, Twitter, XMPP etc */ public void stopAllInboundSceduler() { stopEmailInboundSceduler(); stopTwitterInboundSceduler(); } /** * start scheduler for email only. * @return schedulerId */ public String startEmailInboundSceduler() { String id = getState().get( "emailScedulerTaskId", String.class ); if ( id == null ) { try { JSONRequest req = new JSONRequest( "checkInBoundEmails", null ); id = getScheduler().createTask( req, EMAIL_SCHEDULER_INTERVAL, true, true ); getState().put( "emailScedulerTaskId", id ); } catch ( Exception e ) { e.printStackTrace(); log.warning( "Exception in scheduler creation: "+ e.getLocalizedMessage() ); } } else { log.warning( "Task already running" ); } return id; } /** * stops the scheduler which checks for inbound emails * @return scheduler id */ public String stopEmailInboundSceduler() { String schedulerId = getState().get("emailScedulerTaskId", String.class); getScheduler().cancelTask(schedulerId); getState().remove( "emailScedulerTaskId" ); return schedulerId; } /** * start scheduler for twitter only */ public String startTwitterInboundSceduler() { String id = getState().get( "twitterScedulerTaskId", String.class ); if ( id == null ) { try { JSONRequest req = new JSONRequest( "checkInBoundTwitterPosts", null ); id = getScheduler().createTask( req, TWITTER_SCHEDULER_INTERVAL, true, true ); getState().put( "twitterScedulerTaskId", id ); } catch ( Exception e ) { e.printStackTrace(); log.warning( "Exception in scheduler creation: "+ e.getLocalizedMessage() ); } } else { log.warning( "Task already running" ); } return id; } /** * stops the scheduler which checks for inbound twitter updates */ public String stopTwitterInboundSceduler() { String schedulerId = getState().get("twitterScedulerTaskId", String.class); if (schedulerId != null) { getScheduler().cancelTask(schedulerId); } getState().remove( "twitterScedulerTaskId" ); return schedulerId; } /** * check inbound email */ public void checkInBoundEmails() { log.info( "starting email scheduler check for inbound emails..." ); ArrayList<AdapterConfig> adapters = AdapterConfig.findAdapters( AdapterType.EMAIL.toString(), null, null ); for ( AdapterConfig adapterConfig : adapters ) { Runnable mailServlet = new MailServlet( adapterConfig ); Thread mailServletThread = new Thread( mailServlet ); mailServletThread.run(); try { mailServletThread.join(); } catch ( InterruptedException e ) { e.printStackTrace(); log.warning( "Failed to join the thread. Message" + e.getLocalizedMessage() ); } } } /** * check inbound twitter updates */ public void checkInBoundTwitterPosts() { log.info( "starting twitter scheduler check for mentions and direct messages..." ); ArrayList<AdapterConfig> adapters = AdapterConfig.findAdapters( AdapterType.TWITTER.toString(), null, null ); for ( AdapterConfig adapterConfig : adapters ) { Runnable twitterDirectMessageServlet = new TwitterServlet( adapterConfig, TwitterEndpoint.DIRECT_MESSAGE ); Thread twitterDirectMessageThread = new Thread( twitterDirectMessageServlet ); Runnable twitterTweetMentionServlet = new TwitterServlet( adapterConfig, TwitterEndpoint.MENTIONS ); Thread twitterTweetMentionThread = new Thread( twitterTweetMentionServlet ); twitterDirectMessageThread.run(); twitterTweetMentionThread.run(); try { twitterDirectMessageThread.join(); twitterTweetMentionThread.join(); } catch ( InterruptedException e ) { e.printStackTrace(); log.warning( "Failed to join the thread. Message" + e.getLocalizedMessage() ); } } } /** * Adds a new broadsoft adapter * * @param address * @param username * @param password * @param preferredLanguage * @param accountId * @param anonymous * @return AdapterId * @throws Exception */ public String createBroadSoftAdapter(@Name("address") String address, @Name("username") @Optional String username, @Name("password") @Optional String password, @Name("preferredLanguage") @Optional String preferredLanguage, @Name("accountId") @Optional String accountId, @Name("anonymous") boolean anonymous, @Name("accountType") @Optional String accountType) throws Exception { preferredLanguage = (preferredLanguage == null ? "nl" : preferredLanguage); String normAddress = address.replaceFirst("^0", "").replace("+31", "").replace("@ask.ask.voipit.nl", ""); String externalAddress = "+31" + normAddress; String myAddress = "0" + (normAddress.contains("@ask.ask.voipit.nl") ? normAddress : (normAddress + "@ask.ask.voipit.nl")); username = username != null ? username : myAddress; AdapterConfig config = new AdapterConfig(); config.setAdapterType(AdapterType.CALL.toString()); config.setMyAddress(myAddress); config.setAddress(externalAddress); config.setPreferred_language(preferredLanguage); config.setPublicKey(accountId); config.setXsiUser(username); config.setXsiPasswd(password); config.setOwner(accountId); config.addAccount(accountId); config.setAnonymous(anonymous); config.setAccountType(AccountType.fromJson(accountType)); config.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.BROADSOFT); AdapterConfig newConfig = createAdapter(config); return newConfig.getConfigId(); } /** * Adds a new broadsoft adapter * * @param address * @param username * @param password * @param preferredLanguage * @param accountId * @param anonymous * @return AdapterId * @throws Exception */ public String createTwilioAdapter(@Name("address") String address, @Name("accountSid") @Optional String accountSid, @Name("authToken") @Optional String authToken, @Name("preferredLanguage") @Optional String preferredLanguage, @Name("accountId") @Optional String accountId, @Name("anonymous") @Optional Boolean anonymous) throws Exception { preferredLanguage = (preferredLanguage == null ? "nl" : preferredLanguage); anonymous = (anonymous == null ? false : anonymous); String normAddress = address.replaceFirst("^0", "").replace("+31", ""); String externalAddress = "+31" + normAddress; AdapterConfig config = new AdapterConfig(); config.setAdapterType(AdapterType.CALL.toString()); config.setMyAddress(externalAddress); config.setAddress(externalAddress); config.setPreferred_language(preferredLanguage); config.setPublicKey(accountId); config.setOwner(accountId); config.setAccessToken(accountSid); config.setAccessTokenSecret(authToken); config.addAccount(accountId); config.setAnonymous(anonymous); config.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.TWILIO); AdapterConfig newConfig = createAdapter(config); return newConfig.getConfigId(); } public String createEmailAdapter( @Name( "emailAddress" ) String emailAddress, @Name( "password" ) String password, @Name( "name" ) @Optional String name, @Name( "preferredLanguage" ) @Optional String preferredLanguage, @Name( "sendingProtocol" ) @Optional String sendingProtocol, @Name( "sendingHost" ) @Optional String sendingHost, @Name( "sendingPort" ) @Optional String sendingPort, @Name( "receivingProtocol" ) @Optional String receivingProtocol, @Name( "receivingHost" ) @Optional String receivingHost, @Name( "accountId" ) @Optional String accountId, @Name( "initialAgentURL" ) @Optional String initialAgentURL, @Name( "accountType" ) @Optional String accountType) throws Exception { preferredLanguage = ( preferredLanguage == null ? "nl" : preferredLanguage ); AdapterConfig config = new AdapterConfig(); config.setAdapterType( AdapterType.EMAIL.toString() ); //by default create gmail account adapter config.getProperties().put( MailServlet.SENDING_PROTOCOL_KEY, sendingProtocol != null ? sendingProtocol : MailServlet.GMAIL_SENDING_PROTOCOL ); config.getProperties().put( MailServlet.SENDING_HOST_KEY, sendingHost != null ? sendingHost : MailServlet.GMAIL_SENDING_HOST ); config.getProperties().put( MailServlet.SENDING_PORT_KEY, sendingPort != null ? sendingPort : MailServlet.GMAIL_SENDING_PORT ); config.getProperties().put( MailServlet.RECEIVING_PROTOCOL_KEY, receivingProtocol != null ? receivingProtocol : MailServlet.GMAIL_RECEIVING_PROTOCOL ); config.getProperties().put( MailServlet.RECEIVING_HOST_KEY, receivingHost != null ? receivingHost : MailServlet.GMAIL_RECEIVING_HOST ); emailAddress = getEnvironmentSpecificEmailAddress(emailAddress); config.setMyAddress( emailAddress ); config.setAddress( name ); config.setXsiUser( emailAddress ); config.setXsiPasswd( password ); config.setPreferred_language( preferredLanguage ); config.setPublicKey( accountId ); config.setOwner( accountId ); config.addAccount( accountId ); config.setAnonymous( false ); config.setAccountType(AccountType.fromJson(accountType)); config.setInitialAgentURL(initialAgentURL ); AdapterConfig newConfig = createAdapter( config ); return newConfig.getConfigId(); } public String createXMPPAdapter(@Name("xmppAddress") String xmppAddress, @Name("password") String password, @Name("name") @Optional String name, @Name("preferredLanguage") @Optional String preferredLanguage, @Name("host") @Optional String host, @Name("port") @Optional String port, @Name("service") @Optional String service, @Name("accountId") @Optional String accountId, @Name("initialAgentURL") @Optional String initialAgentURL, @Name("accountType") @Optional String accountType) throws Exception { AdapterConfig newConfig = createSimpleXMPPAdapter(xmppAddress, password, name, preferredLanguage, host, port, service, accountId, initialAgentURL, accountType); //set for incoming requests XMPPServlet xmppServlet = new XMPPServlet(); xmppServlet.listenForIncomingChats(newConfig); return newConfig.getConfigId(); } public String createUSSDAdapter(@Name("address") String address, @Name("keyword") @Optional String keyword, @Name("username") String username, @Name("password") String password, @Name("preferredLanguage") @Optional String preferredLanguage, @Name("accountId") @Optional String accountId, @Name("accountType") @Optional String accountType) throws Exception { preferredLanguage = (preferredLanguage == null ? "nl" : preferredLanguage); AdapterConfig config = new AdapterConfig(); config.setAdapterType(AdapterType.USSD.toString()); config.setMyAddress(address); config.setKeyword(keyword); config.setPreferred_language(preferredLanguage); config.setPublicKey(accountId); config.setOwner(accountId); config.addAccount(accountId); config.setAnonymous(false); config.setAccessToken(username); config.setAccessTokenSecret(password); config.setAccountType(AccountType.fromJson(accountType)); config.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.CLX); AdapterConfig newConfig = createAdapter(config); return newConfig.getConfigId(); } public String createPushAdapter(@Name("address") String address, @Name("keyword") @Optional String keyword, @Name("username") String username, @Name("password") String password, @Name("preferredLanguage") @Optional String preferredLanguage, @Name("accountId") @Optional String accountId, @Name("accountType") @Optional String accountType) throws Exception { preferredLanguage = (preferredLanguage == null ? "nl" : preferredLanguage); AdapterConfig config = new AdapterConfig(); config.setAdapterType(AdapterType.PUSH.toString()); config.setMyAddress(address); config.setKeyword(keyword); config.setPreferred_language(preferredLanguage); config.setPublicKey(accountId); config.setOwner(accountId); config.addAccount(accountId); config.setAnonymous(false); config.setAccessToken(username); config.setAccessTokenSecret(password); config.setAccountType(AccountType.fromJson(accountType)); config.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.NOTIFICARE); AdapterConfig newConfig = createAdapter(config); return newConfig.getConfigId(); } public String registerASKFastXMPPAdapter(@Name("xmppAddress") String xmppAddress, @Name("password") String password, @Name("name") @Optional String name, @Name("email") @Optional String email, @Name("preferredLanguage") @Optional String preferredLanguage, @Name("accountId") @Optional String accountId, @Name("initialAgentURL") @Optional String initialAgentURL, @Name("accountType") @Optional String accountType) throws Exception { xmppAddress = xmppAddress.endsWith("@xmpp.ask-fast.com") ? xmppAddress : (xmppAddress + "@xmpp.ask-fast.com"); ArrayList<AdapterConfig> adapters = AdapterConfig.findAdapters(AdapterType.XMPP.toString(), xmppAddress, null); AdapterConfig newConfig = adapters != null && !adapters.isEmpty() ? adapters.iterator().next() : null; //check if adapter exists if (newConfig == null) { newConfig = createSimpleXMPPAdapter(xmppAddress, password, name, preferredLanguage, XMPPServlet.DEFAULT_XMPP_HOST, String.valueOf(XMPPServlet.DEFAULT_XMPP_PORT), null, accountId, initialAgentURL, accountType); } else if (accountId != null && !accountId.isEmpty() && !accountId.equals(newConfig.getOwner())) //check if the accountId owns this adapter { throw new Exception(String.format("Adapter exists but AccountId: %s does not own it", accountId)); } try { XMPPServlet.registerASKFastXMPPAccount(xmppAddress, password, name, email); XMPPServlet xmppServlet = new XMPPServlet(); xmppServlet.listenForIncomingChats(newConfig); } catch (XMPPException e) { if (e.getXMPPError().getCode() == 409) //just listen to incoming chats if account already exists. { XMPPServlet xmppServlet = new XMPPServlet(); xmppServlet.listenForIncomingChats(newConfig); } log.severe("Error registering an ASK-Fast account. Error: " + e.getLocalizedMessage()); throw e; } return newConfig != null ? newConfig.getConfigId() : null; } public String deregisterASKFastXMPPAdapter( @Name( "xmppAddress" ) @Optional String xmppAddress, @Name( "accountId" ) String accountId, @Name( "adapterId" ) @Optional String adapterId) throws Exception { xmppAddress = xmppAddress.endsWith( "@xmpp.ask-fast.com" ) ? xmppAddress : ( xmppAddress + "@xmpp.ask-fast.com" ); ArrayList<AdapterConfig> adapters = AdapterConfig.findAdapters( AdapterType.XMPP.toString(), xmppAddress, null ); AdapterConfig adapterConfig = adapters != null && !adapters.isEmpty() ? adapters.iterator().next() : null; //check if adapter is owned by the accountId if ( adapterConfig != null && accountId.equals( adapterConfig.getOwner() )) { XMPPServlet.deregisterASKFastXMPPAccount( adapterConfig ); adapterConfig.delete(); } else { throw new Exception( String.format( "Adapter either doesnt exist or now owned by AccountId: %s", accountId ) ); } return adapterConfig != null ? adapterConfig.getConfigId() : null; } public String createMBAdapter(@Name("address") String address, @Name("keyword") @Optional String keyword, @Name("username") String username, @Name("password") String password, @Name("preferredLanguage") @Optional String preferredLanguage, @Name("accountId") @Optional String accountId, @Name("accountType") @Optional String accountType) throws Exception { return createGenericSMSAdapter(address, AdapterProviders.MB, keyword, username, password, preferredLanguage, accountId, accountType); } /** * Creates a generic SMS adapter. Based on the adapterType, username and password, this can * be assigned to a unique provider. * @param address The address of the sender * @param adapterType The type of the SMS provider used * @param keyword * @param username Username of the provider account * @param password * @param preferredLanguage * @param accountId * @param accountType * @return * @throws Exception */ public String createGenericSMSAdapter(@Name("address") String address, @Name("provider") @Optional AdapterProviders provider, @Name("keyword") @Optional String keyword, @Name("username") String username, @Name("password") String password, @Name("preferredLanguage") @Optional String preferredLanguage, @Name("accountId") @Optional String accountId, @Name("accountType") @Optional String accountType) throws Exception { preferredLanguage = (preferredLanguage == null ? "nl" : preferredLanguage); AdapterConfig config = new AdapterConfig(); config.setAdapterType(AdapterType.SMS.toString()); config.setMyAddress(address); config.setKeyword(keyword); config.setPreferred_language(preferredLanguage); config.setPublicKey(accountId); config.setOwner(accountId); config.addAccount(accountId); config.setAnonymous(false); config.setAccessToken(username); config.setAccessTokenSecret(password); config.setAccountType(AccountType.fromJson(accountType)); if (provider != null) { config.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, provider); } AdapterConfig newConfig = createAdapter(config); return newConfig.getConfigId(); } public String createNexmoAdapter(@Name("address") String address, @Name("keyword") @Optional String keyword, @Name("username") String username, @Name("password") String password, @Name("preferredLanguage") @Optional String preferredLanguage, @Name("accountId") @Optional String accountId) throws Exception { return createGenericSMSAdapter(address, AdapterProviders.NEXMO, keyword, username, password, preferredLanguage, accountId, null); } public String attachTwitterAdapterToUser( @Name( "adapterID" ) @Optional String adapterID, @Name( "twitterUserName" ) @Optional String twitterUserName, @Name( "accountId" ) String accountId ) throws Exception { AdapterConfig adapterConfig = null; if ( adapterID != null && !adapterID.trim().isEmpty() ) { adapterConfig = AdapterConfig.getAdapterConfig( adapterID.trim() ); } if ( adapterConfig == null && twitterUserName != null && !twitterUserName.trim().isEmpty() ) { twitterUserName = twitterUserName.startsWith( "@" ) ? twitterUserName : "@" + twitterUserName; ArrayList<AdapterConfig> adapterConfigs = AdapterConfig.findAdapters(AdapterType.TWITTER.toString(), twitterUserName, null); adapterConfig = !adapterConfigs.isEmpty() ? adapterConfigs.iterator().next() : null; } if ( adapterConfig != null ) { if( adapterConfig.getOwner()!= null && !accountId.equals( adapterConfig.getOwner())) { throw new JSONRPCException( CODE.INVALID_PARAMS, "Adapter not owned by the accountId: "+ accountId ); } adapterConfig.addAccount( accountId ); adapterConfig.update(); return ServerUtils.serialize( adapterConfig ); } else { throw new JSONRPCException( CODE.INVALID_PARAMS, "Adapter not found" ); } } public String createFacebookAdapter() { // TODO: implement return null; } public void setOwner(@Name("adapterId") String adapterId, @Name("accountId") String accountId) throws Exception { AdapterConfig config = AdapterConfig.getAdapterConfig(adapterId); if (config == null) throw new Exception("No adapter with this id"); if (config.getOwner() != null) { throw new Exception("Adapter is already owned by someone else"); } config.setOwner(accountId); config.addAccount(accountId); //add cost/ddr DDRUtils.createDDRRecordOnAdapterPurchase(config, true); config.update(); } public void addAccount(@Name("adapterId") String adapterId, @Name("accountId") String accountId) throws Exception { AdapterConfig config = AdapterConfig.getAdapterConfig(adapterId); if(config==null) throw new Exception("No adapter with this id"); config.addAccount(accountId); config.update(); } public Object getAdapter(@Name("accoutId") String accountId, @Name("adapterId") String adapterId) throws Exception { AdapterConfig config = AdapterConfig.getAdapterConfig(adapterId); if (config == null) throw new Exception("No adapter linked to this account or with this id"); if (AdapterConfig.checkIfAdapterMatchesForAccountId(Arrays.asList(accountId), config, false) == null) { throw new Exception("No adapter linked to this account or with this id"); } return config; } public Object updateAdapter(@Name("accoutId") String accountId, @Name("adapterId") String adapterId, @Name("adapter") Adapter adapter) throws Exception { AdapterConfig config = (AdapterConfig) getAdapter(accountId, adapterId); if (config != null) { if (adapter.getInitialAgentURL() != null) { config.setInitialAgentURL(adapter.getInitialAgentURL()); } if (adapter.isAnonymous() != null) { config.setAnonymous(adapter.isAnonymous()); } if (adapter.getDialogId() != null) { //check if the accoundId is the owner of this adapter. Incoming scenarios only work if //one owns the adapter if(accountId.equals(config.getOwner())) { config.setDialogId(adapter.getDialogId()); } else { throw new Exception(String.format("Account: %s does not own adapter: %s with address: %s", accountId, config.getConfigId(), config.getAddress())); } } if (adapter.getAccountType() != null) { config.setAccountType(adapter.getAccountType()); } //allow keywords to be changed only for sms adapters if (adapter.getAdapterType() != null) { AdapterType adapterType = AdapterType.fromJson(adapter.getAdapterType()); switch (adapterType) { case EMAIL: case PUSH: case USSD: if (adapter.getMyAddress() != null) { config.setMyAddress(adapter.getMyAddress()); } break; case SMS: if (adapter.getKeyword() != null) { config.setKeyword(adapter.getKeyword()); } break; default: //no updates needed for other adapter types } } config.update(); return config; } else { throw new Exception(String.format("Adapter: %s with address:%s probably does not belong to account: %s", adapter, adapter.getMyAddress(), accountId)); } } public void setAllAdapterAccountType(@Name("accountId") String accountId, @Name("accountType") AccountType type) { ArrayList<AdapterConfig> ownedAdapters = AdapterConfig.findAdapterByOwner(accountId, null, null); for(AdapterConfig adapter : ownedAdapters) { adapter.setAccountType( type ); adapter.update(); } } /** * detach an adapter from this account. if adapter is: <br> * 1. XMPP: then this also deregisters him (if its an ask-fast account) <br> * 2. CALL: unlinks it from the account only. makes it free <br> * 3. CALL: unlinks it from the account only. makes it free <br> * 4. rest: deletes the adapter. <br> * @param adapterId * @param accountId If this is same as the adapter owner, it frees the adapter. If it is * same as the accoundId, it just unlinks the accountId from the adapter * @throws Exception */ public void removeAdapter(@Name("adapterId") String adapterId, @Name("accountId") String accountId) throws Exception { AdapterConfig config = AdapterConfig.getAdapterConfig(adapterId); if (config == null) { throw new Exception("No adapter with this id owned by you"); } else { AdapterType adapterType = AdapterType.fromJson(config.getAdapterType()); if (AdapterConfig.checkIfAdapterMatchesForAccountId(Arrays.asList(accountId), config, false) != null) { config.removeAccount(accountId); switch (adapterType) { case XMPP: //deregister if its an askfast xmpp account if (config.getMyAddress().contains("xmpp.ask-fast.com")) { deregisterASKFastXMPPAdapter(config.getMyAddress(), accountId, adapterId); } default: config.update(); break; } } } } public ArrayNode getAdapters(@Name("accoutId") String accountId, @Name("adapterType") @Optional String adapterType, @Name("address") @Optional String address) { List<AdapterConfig> adapters = AdapterConfig.findAdapterByAccount(accountId, adapterType, address); return JOM.getInstance().convertValue(adapters, ArrayNode.class); } public ArrayNode findAdapters(@Name("adapterType") @Optional String type, @Name("address") @Optional String address, @Name("keyword") @Optional String keyword) { ArrayList<AdapterConfig> adapters = AdapterConfig.findAdapters(type, address, keyword); return JOM.getInstance().convertValue(adapters, ArrayNode.class); } /** * Gets all the adapters owned by the given accountId * * @param type * @param address * @param keyword * @return */ public ArrayNode findOwnedAdapters(@Name("ownerId") String ownerId, @Name("adapterType") @Optional String type, @Name("address") @Optional String address) { ArrayList<AdapterConfig> ownedAdapters = AdapterConfig.findAdapterByOwner(ownerId, type, address); return JOM.getInstance().convertValue(ownedAdapters, ArrayNode.class); } /** * Set provider for a particular adapter * * @param type * @param address * @param keyword * @return */ public Object setProviderForAdapters(@Name("adapterId") String adapterId, @Name("provider") AdapterProviders provider) { AdapterConfig adapterConfig = AdapterConfig.getAdapterConfig(adapterId); if (adapterConfig != null) { adapterConfig.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, provider); adapterConfig.update(); } return adapterConfig; } /** * Set provider for a particular adapter * * @param type * @param address * @param keyword * @return */ public Object removeProviderForAdapters(@Name("adapterId") String adapterId) { AdapterConfig adapterConfig = AdapterConfig.getAdapterConfig(adapterId); if (adapterConfig != null) { Map<String, Object> properties = adapterConfig.getProperties(); properties.remove(AdapterConfig.ADAPTER_PROVIDER_KEY); adapterConfig.update(); } return adapterConfig; } public ArrayNode findFreeAdapters(@Name("adapterType") @Optional String adapterType, @Name("address") @Optional String address) { ArrayList<AdapterConfig> adapters = AdapterConfig.findAdapterByAccount(null, adapterType, address); return JOM.getInstance().convertValue(adapters, ArrayNode.class); } /** * Updates all adapters with the generic format * * @return * @throws Exception */ public HashMap<String, String> updateAllAdaptersWithProviders() throws Exception { HashMap<String, String> warnings = new HashMap<String, String>(); ArrayList<AdapterConfig> allAdapters = AdapterConfig.findAdapters(null, null, null); if (allAdapters != null) { for (AdapterConfig adapterConfig : allAdapters) { switch (adapterConfig.getAdapterType().toLowerCase()) { case "broadsoft": adapterConfig.setAdapterType(ADAPTER_TYPE_CALL); adapterConfig.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.BROADSOFT); break; case "voxeo": adapterConfig.setAdapterType(ADAPTER_TYPE_CALL); adapterConfig.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.TWILIO); break; case "cm": case "sms": adapterConfig.setAdapterType(ADAPTER_TYPE_SMS); adapterConfig.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.CM); break; case "route-sms": adapterConfig.setAdapterType(ADAPTER_TYPE_SMS); adapterConfig.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.ROUTE_SMS); break; case "mb": adapterConfig.setAdapterType(ADAPTER_TYPE_SMS); adapterConfig.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.ROUTE_SMS); break; case "ussd": adapterConfig.setAdapterType(ADAPTER_TYPE_USSD); adapterConfig.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.CLX); break; case "notificare": adapterConfig.setAdapterType(ADAPTER_TYPE_PUSH); adapterConfig.addMediaProperties(AdapterConfig.ADAPTER_PROVIDER_KEY, AdapterProviders.NOTIFICARE); break; default: warnings.put(adapterConfig.getConfigId(), String.format("Not updated. type: %s address: %s", adapterConfig.getAdapterType(), adapterConfig.getMyAddress())); break; } adapterConfig.update(); } } return warnings; } /** * saves the AdapterConfig in the datastore * * @param config * @return * @throws Exception */ private AdapterConfig createAdapter(AdapterConfig config) throws Exception { if (AdapterConfig.adapterExists(config.getAdapterType(), config.getMyAddress(), config.getKeyword())) { throw new ConflictException("Adapter already exists"); } if (config.getConfigId() == null) { config.configId = new UUID().toString(); } //add creation timestamp to the adapter config.getProperties().put(AdapterConfig.ADAPTER_CREATION_TIME_KEY, TimeUtils.getServerCurrentTimeInMillis()); //change the casing to lower in case adatertype if email or xmpp if (config.getMyAddress() != null && (AdapterType.EMAIL.equals(AdapterType.getByValue(config.getAdapterType()))) || AdapterType.XMPP.equals(AdapterType.getByValue(config.getAdapterType()))) { config.setMyAddress(config.getMyAddress().toLowerCase()); } //check if there is an initialAgent url given. Create a dialog if it is if (config.getURLForInboundScenario(null) != null && !config.getURLForInboundScenario(null).isEmpty()) { Dialog dialog = Dialog.createDialog("Dialog created on adapter creation", config.getURLForInboundScenario(null), config.getOwner()); config.getProperties().put(AdapterConfig.DIALOG_ID_KEY, dialog.getId()); } config.setAdapterType(config.getAdapterType().toLowerCase()); TwigCompatibleMongoDatastore datastore = new TwigCompatibleMongoDatastore(); datastore.store(config); if (AdapterProviders.BROADSOFT.equals(DialogAgent.getProvider(config.getAdapterType(), config))) { Broadsoft bs = new Broadsoft(config); bs.hideCallerId(config.isAnonymous()); } //add costs for creating this adapter DDRRecord ddrRecord = DDRUtils.createDDRRecordOnAdapterPurchase(config, true); //push the cost to hte queue Double totalCost = DDRUtils.calculateCommunicationDDRCost(ddrRecord, true); DDRUtils.publishDDREntryToQueue(config.getOwner(), totalCost); //attach cost to ddr is prepaid type if (ddrRecord != null && AccountType.PRE_PAID.equals(ddrRecord.getAccountType())) { ddrRecord.setTotalCost(totalCost); ddrRecord.createOrUpdate(); } return config; } /** creates a simple adapter of type XMPP. doesnt register and listen for messages * @param xmppAddress * @param password * @param name * @param preferredLanguage * @param host * @param port * @param service * @param accountId * @param initialAgentURL * @return * @throws Exception */ private AdapterConfig createSimpleXMPPAdapter(String xmppAddress, String password, String name, String preferredLanguage, String host, String port, String service, String accountId, String initialAgentURL, String accountType) throws Exception { preferredLanguage = (preferredLanguage == null ? "nl" : preferredLanguage); AdapterConfig config = new AdapterConfig(); config.setAdapterType(ADAPTER_TYPE_XMPP); //by default create gmail xmpp adapter config.getProperties().put(XMPPServlet.XMPP_HOST_KEY, host != null ? host : XMPPServlet.DEFAULT_XMPP_HOST); config.getProperties().put(XMPPServlet.XMPP_PORT_KEY, port != null ? port : XMPPServlet.DEFAULT_XMPP_PORT); if (service != null) { config.getProperties().put(XMPPServlet.XMPP_SERVICE_KEY, service); } config.setMyAddress(xmppAddress.toLowerCase()); config.setAddress(name); config.setXsiUser(xmppAddress.toLowerCase().split("@")[0]); config.setXsiPasswd(password); config.setPreferred_language(preferredLanguage); config.setPublicKey(accountId); config.setOwner(accountId); config.addAccount(accountId); config.setAnonymous(false); config.setInitialAgentURL(initialAgentURL); config.setAccountType(AccountType.fromJson(accountType)); AdapterConfig newConfig = createAdapter(config); return newConfig; } /** * appends "appspotmail.com" for the given address based on the current * jetty environment. * * @param address * @return */ private static String getEnvironmentSpecificEmailAddress(String address) { if (ServerUtils.isInDevelopmentEnvironment()) { address = (address.contains("appspotmail.com") || address.contains("@")) ? address : (address + "@char-a-lot.appspotmail.com"); } else if (ServerUtils.isInProductionEnvironment()) { address = (address.contains("appspotmail.com") || address.contains("@")) ? address : (address + "@ask-charlotte.appspotmail.com"); } return address; } }
package org.opencms.gwt.client.ui; import org.opencms.gwt.client.I_CmsDescendantResizeHandler; import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle; import org.opencms.gwt.client.util.CmsDomUtil; import org.opencms.gwt.client.util.CmsDomUtil.Style; import org.opencms.gwt.client.util.CmsFadeAnimation; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.Style.Overflow; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.MouseOutEvent; import com.google.gwt.event.dom.client.MouseOutHandler; import com.google.gwt.event.dom.client.MouseOverEvent; import com.google.gwt.event.dom.client.MouseOverHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.AbstractNativeScrollbar; import com.google.gwt.user.client.ui.VerticalScrollbar; import com.google.gwt.user.client.ui.Widget; /** * Scroll panel implementation with custom scroll bars. Works in all browsers but IE7.<p> */ public class CmsScrollPanelImpl extends CmsScrollPanel { /** * Handler to show and hide the scroll bar on hover.<p> */ private class HoverHandler implements MouseOutHandler, MouseOverHandler { /** The owner element. */ Element m_owner; /** The element to fade in and out. */ private Element m_fadeElement; /** The currently running hide animation. */ private CmsFadeAnimation m_hideAnimation; /** The timer to hide the scroll bar with a delay. */ private Timer m_removeTimer; /** * Constructor.<p> * * @param owner the owner element * @param fadeElement the element to fade in and out on hover */ HoverHandler(Element owner, Element fadeElement) { m_owner = owner; m_fadeElement = fadeElement; } /** * @see com.google.gwt.event.dom.client.MouseOutHandler#onMouseOut(com.google.gwt.event.dom.client.MouseOutEvent) */ public void onMouseOut(MouseOutEvent event) { m_removeTimer = new Timer() { /** * @see com.google.gwt.user.client.Timer#run() */ @Override public void run() { clearShowing(); } }; m_removeTimer.schedule(1000); } /** * @see com.google.gwt.event.dom.client.MouseOverHandler#onMouseOver(com.google.gwt.event.dom.client.MouseOverEvent) */ public void onMouseOver(MouseOverEvent event) { if ((m_hideAnimation != null) || !CmsDomUtil.hasClass(I_CmsLayoutBundle.INSTANCE.scrollBarCss().showBars(), m_owner)) { if (m_hideAnimation != null) { m_hideAnimation.cancel(); m_hideAnimation = null; } else { CmsFadeAnimation.fadeIn(m_fadeElement, null, 100); } m_owner.addClassName(I_CmsLayoutBundle.INSTANCE.scrollBarCss().showBars()); } if (m_removeTimer != null) { m_removeTimer.cancel(); m_removeTimer = null; } } /** * Hides the scroll bar.<p> */ void clearShowing() { m_hideAnimation = CmsFadeAnimation.fadeOut(m_fadeElement, new Command() { public void execute() { m_owner.removeClassName(I_CmsLayoutBundle.INSTANCE.scrollBarCss().showBars()); } }, 200); m_removeTimer = null; } } /** Hidden element to measure the appropriate size of the container element. */ private Element m_hiddenSize; /** The measured width of the native scroll bars. */ private int m_nativeScrollbarWidth; /** The vertical scroll bar. */ private VerticalScrollbar m_scrollbar; /** The scroll layer. */ private Element m_scrollLayer; /** The scroll bar change handler registration. */ private HandlerRegistration m_verticalScrollbarHandlerRegistration; /** The scroll bar width. */ private int m_verticalScrollbarWidth; /** * Constructor.<p> */ public CmsScrollPanelImpl() { super(DOM.createDiv(), DOM.createDiv(), DOM.createDiv()); setStyleName(I_CmsLayoutBundle.INSTANCE.scrollBarCss().scrollPanel()); Element scrollable = getScrollableElement(); scrollable.getStyle().clearPosition(); scrollable.getStyle().setOverflowX(Overflow.HIDDEN); scrollable.setClassName(I_CmsLayoutBundle.INSTANCE.scrollBarCss().scrollable()); getElement().appendChild(scrollable); Element container = getContainerElement(); container.setClassName(I_CmsLayoutBundle.INSTANCE.scrollBarCss().scrollContainer()); scrollable.appendChild(container); m_scrollLayer = DOM.createDiv(); getElement().appendChild(m_scrollLayer); m_scrollLayer.setClassName(I_CmsLayoutBundle.INSTANCE.scrollBarCss().scrollbarLayer()); CmsScrollBar scrollbar = new CmsScrollBar(scrollable, container); setVerticalScrollbar(scrollbar, 8); m_hiddenSize = DOM.createDiv(); m_hiddenSize.setClassName(I_CmsLayoutBundle.INSTANCE.scrollBarCss().hiddenSize()); /* * Listen for scroll events from the root element and the scrollable element * so we can align the scrollbars with the content. Scroll events usually * come from the scrollable element, but they can also come from the root * element if the user clicks and drags the content, which reveals the * hidden scrollbars. */ Event.sinkEvents(getElement(), Event.ONSCROLL); Event.sinkEvents(scrollable, Event.ONSCROLL); initHoverHandler(); } /** * @see com.google.gwt.user.client.ui.SimplePanel#iterator() */ @Override public Iterator<Widget> iterator() { // Return a simple iterator that enumerates the 0 or 1 elements in this // panel. List<Widget> widgets = new ArrayList<Widget>(); if (getWidget() != null) { widgets.add(getWidget()); } if (getVerticalScrollBar() != null) { widgets.add(getVerticalScrollBar().asWidget()); } final Iterator<Widget> internalIterator = widgets.iterator(); return new Iterator<Widget>() { public boolean hasNext() { return internalIterator.hasNext(); } public Widget next() { return internalIterator.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * @see com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt.user.client.Event) */ @Override public void onBrowserEvent(Event event) { // Align the scrollbars with the content. if (Event.ONSCROLL == event.getTypeInt()) { maybeUpdateScrollbarPositions(); } super.onBrowserEvent(event); } /** * @see org.opencms.gwt.client.ui.CmsScrollPanel#onResizeDescendant() */ @Override public void onResizeDescendant() { int maxHeight = CmsDomUtil.getCurrentStyleInt(getElement(), Style.maxHeight); if (maxHeight > 0) { getScrollableElement().getStyle().setPropertyPx("maxHeight", maxHeight); } // appending div to measure panel width, doing it every time anew to avoid rendering bugs in Chrome getElement().appendChild(m_hiddenSize); int width = m_hiddenSize.getClientWidth(); m_hiddenSize.removeFromParent(); if (width > 0) { getContainerElement().getStyle().setWidth(width, Unit.PX); maybeUpdateScrollbars(); } } /** * @see org.opencms.gwt.client.ui.CmsScrollPanel#setResizable(boolean) */ @Override public void setResizable(boolean resize) { super.setResizable(resize); if (resize) { m_scrollbar.asWidget().getElement().getStyle().setMarginBottom(7, Unit.PX); } else { m_scrollbar.asWidget().getElement().getStyle().setMarginBottom(0, Unit.PX); } } /** * Returns the vertical scroll bar.<p> * * @return the vertical scroll bar */ protected VerticalScrollbar getVerticalScrollBar() { return m_scrollbar; } /** * @see com.google.gwt.user.client.ui.ScrollPanel#onAttach() */ @Override protected void onAttach() { super.onAttach(); hideNativeScrollbars(); onResizeDescendant(); } /** * @see com.google.gwt.user.client.ui.Widget#onLoad() */ @Override protected void onLoad() { super.onLoad(); hideNativeScrollbars(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { onResizeDescendant(); } }); } /** * Hide the native scrollbars. We call this after attaching to ensure that we * inherit the direction (rtl or ltr). */ private void hideNativeScrollbars() { m_nativeScrollbarWidth = AbstractNativeScrollbar.getNativeScrollbarWidth(); getScrollableElement().getStyle().setMarginRight(-(m_nativeScrollbarWidth + 10), Unit.PX); } /** * Initializes the hover handler to hide and show the scroll bar on hover.<p> */ private void initHoverHandler() { HoverHandler handler = new HoverHandler(getElement(), m_scrollbar.asWidget().getElement()); addDomHandler(handler, MouseOverEvent.getType()); addDomHandler(handler, MouseOutEvent.getType()); } /** * Synchronize the scroll positions of the scrollbars with the actual scroll * position of the content. */ private void maybeUpdateScrollbarPositions() { if (!isAttached()) { return; } if (m_scrollbar != null) { int vPos = getVerticalScrollPosition(); if (m_scrollbar.getVerticalScrollPosition() != vPos) { m_scrollbar.setVerticalScrollPosition(vPos); } } } /** * Update the position of the scrollbars.<p> * If only the vertical scrollbar is present, it takes up the entire height of * the right side. If only the horizontal scrollbar is present, it takes up * the entire width of the bottom. If both scrollbars are present, the * vertical scrollbar extends from the top to just above the horizontal * scrollbar, and the horizontal scrollbar extends from the left to just right * of the vertical scrollbar, leaving a small square in the bottom right * corner.<p> */ private void maybeUpdateScrollbars() { if (!isAttached()) { return; } /* * Measure the height and width of the content directly. Note that measuring * the height and width of the container element (which should be the same) * doesn't work correctly in IE. */ Widget w = getWidget(); int contentHeight = (w == null) ? 0 : w.getOffsetHeight(); // Determine which scrollbars to show. int realScrollbarHeight = 0; int realScrollbarWidth = 0; if ((m_scrollbar != null) && (getElement().getClientHeight() < contentHeight)) { // Vertical scrollbar is defined and required. realScrollbarWidth = m_verticalScrollbarWidth; } if (realScrollbarWidth > 0) { m_scrollLayer.getStyle().clearDisplay(); m_scrollbar.setScrollHeight(Math.max(0, contentHeight - realScrollbarHeight)); } else if (m_scrollLayer != null) { m_scrollLayer.getStyle().setDisplay(Display.NONE); } if (m_scrollbar instanceof I_CmsDescendantResizeHandler) { ((I_CmsDescendantResizeHandler)m_scrollbar).onResizeDescendant(); } maybeUpdateScrollbarPositions(); } /** * Set the scrollbar used for vertical scrolling. * * @param scrollbar the scrollbar, or null to clear it * @param width the width of the scrollbar in pixels */ private void setVerticalScrollbar(final CmsScrollBar scrollbar, int width) { // Validate. if ((scrollbar == m_scrollbar) || (scrollbar == null)) { return; } // Detach new child. scrollbar.asWidget().removeFromParent(); // Remove old child. if (m_scrollbar != null) { if (m_verticalScrollbarHandlerRegistration != null) { m_verticalScrollbarHandlerRegistration.removeHandler(); m_verticalScrollbarHandlerRegistration = null; } remove(m_scrollbar); } m_scrollLayer.appendChild(scrollbar.asWidget().getElement()); adopt(scrollbar.asWidget()); // Logical attach. m_scrollbar = scrollbar; m_verticalScrollbarWidth = width; // Initialize the new scrollbar. m_verticalScrollbarHandlerRegistration = scrollbar.addValueChangeHandler(new ValueChangeHandler<Integer>() { public void onValueChange(ValueChangeEvent<Integer> event) { int vPos = scrollbar.getVerticalScrollPosition(); int v = getVerticalScrollPosition(); if (v != vPos) { setVerticalScrollPosition(vPos); } } }); maybeUpdateScrollbars(); } }
package org.minimalj.frontend.impl.vaadin; import java.util.HashMap; import java.util.List; import java.util.Map; import org.minimalj.application.Application; import org.minimalj.backend.Backend; import org.minimalj.frontend.Frontend; import org.minimalj.frontend.Frontend.IContent; import org.minimalj.frontend.Frontend.Search; import org.minimalj.frontend.Frontend.TableActionListener; import org.minimalj.frontend.action.Action; import org.minimalj.frontend.action.Action.ActionChangeListener; import org.minimalj.frontend.action.ActionGroup; import org.minimalj.frontend.action.Separator; import org.minimalj.frontend.impl.swing.component.SwingDecoration; import org.minimalj.frontend.impl.util.PageStore; import org.minimalj.frontend.impl.vaadin.toolkit.VaadinDialog; import org.minimalj.frontend.impl.vaadin.toolkit.VaadinEditorLayout; import org.minimalj.frontend.page.IDialog; import org.minimalj.frontend.page.Page; import org.minimalj.frontend.page.PageManager; import org.minimalj.security.Authentication.LoginListener; import org.minimalj.security.AuthenticationFailedPage; import org.minimalj.security.Subject; import org.minimalj.util.StringUtils; import com.github.wolfie.history.HistoryExtension; import com.github.wolfie.history.HistoryExtension.PopStateEvent; import com.github.wolfie.history.HistoryExtension.PopStateListener; import com.vaadin.addon.contextmenu.ContextMenu; import com.vaadin.addon.contextmenu.MenuItem; import com.vaadin.annotations.Theme; import com.vaadin.event.ItemClickEvent; import com.vaadin.event.ItemClickEvent.ItemClickListener; import com.vaadin.event.ShortcutAction; import com.vaadin.event.ShortcutListener; import com.vaadin.server.FontAwesome; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinService; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.AbstractComponent; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Component; import com.vaadin.ui.ComponentContainer; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.HorizontalSplitPanel; import com.vaadin.ui.Label; import com.vaadin.ui.Panel; import com.vaadin.ui.TextField; import com.vaadin.ui.Tree; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; @Theme("mjtheme") public class Vaadin extends UI implements PageManager, LoginListener { private static final long serialVersionUID = 1L; private Subject subject; private final HistoryExtension history; private final PageStore pageStore = new PageStore(); private Map<String, String> state; // position -> page id private HorizontalSplitPanel splitPanel; private VerticalLayout verticalScrollPane; private Tree tree; private float lastSplitPosition = -1; public Vaadin() { PopStateListener myPopStateListener = new PopStateListener() { @Override public void popState(PopStateEvent event) { if (event.getStateAsJson() != null) { state = event.getStateAsMap(); updateContent(); } } }; history = HistoryExtension.extend(this, myPopStateListener); history.addPopStateListener(myPopStateListener); } @Override protected void init(VaadinRequest request) { VerticalLayout outerPanel = new VerticalLayout(); setContent(outerPanel); setSizeFull(); outerPanel.setSizeFull(); HorizontalLayout topbar = new HorizontalLayout(); outerPanel.addComponent(topbar); outerPanel.setExpandRatio(topbar, 0f); topbar.setHeight("5ex"); topbar.setWidth("100%"); topbar.setStyleName("topbar"); topbar.setSpacing(true); topbar.setMargin(new MarginInfo(false, true, false, false)); Button buttonNavigation = new Button(FontAwesome.NAVICON); buttonNavigation.addClickListener(e -> { if (lastSplitPosition > -1) { if (lastSplitPosition < 100) { lastSplitPosition = 200; } splitPanel.setSplitPosition(lastSplitPosition); lastSplitPosition = -1; } else { lastSplitPosition = splitPanel.getSplitPosition(); splitPanel.setSplitPosition(0); } }); topbar.addComponent(buttonNavigation); topbar.setComponentAlignment(buttonNavigation, Alignment.MIDDLE_LEFT); Button buttonLogin = new Button(FontAwesome.SIGN_IN); buttonLogin.addClickListener(e -> Backend.getInstance().getAuthentication().login(this)); topbar.addComponent(buttonLogin); topbar.setComponentAlignment(buttonLogin, Alignment.MIDDLE_LEFT); Panel panel = new Panel(); topbar.addComponent(panel); topbar.setExpandRatio(panel, 1.0f); TextField textFieldSearch = createSearchField(); textFieldSearch.setEnabled(Application.getInstance().hasSearchPages()); topbar.addComponent(textFieldSearch); topbar.setComponentAlignment(textFieldSearch, Alignment.MIDDLE_RIGHT); splitPanel = new HorizontalSplitPanel(); outerPanel.addComponent(splitPanel); outerPanel.setExpandRatio(splitPanel, 1.0f); tree = new Tree(); tree.setSelectable(false); tree.addItemClickListener(new ItemClickListener() { private static final long serialVersionUID = 1L; @Override public void itemClick(ItemClickEvent event) { Object itemId = event.getItemId(); if (itemId instanceof Action) { ((Action) itemId).action(); } } }); updateNavigation(); splitPanel.setFirstComponent(tree); splitPanel.setSplitPosition(200, Unit.PIXELS); verticalScrollPane = new VerticalLayout(); splitPanel.setSecondComponent(verticalScrollPane); if (subject == null && Frontend.loginAtStart()) { Backend.getInstance().getAuthentication().login(this); } else { show(Application.getInstance().createDefaultPage()); } } private TextField createSearchField() { TextField textFieldSearch = new TextField(); textFieldSearch.setWidth("30ex"); textFieldSearch.addShortcutListener(new ShortcutListener("Search", ShortcutAction.KeyCode.ENTER, null) { private static final long serialVersionUID = 1L; @Override public void handleAction(Object sender, Object target) { if (target == textFieldSearch) { String query = textFieldSearch.getValue(); Page page = Application.getInstance().createSearchPage(query); show(page); } } }); return textFieldSearch; } private void updateNavigation() { tree.clear(); List<Action> actions = Application.getInstance().getNavigation(); addNavigationActions(actions, null); } private void addNavigationActions(List<Action> actions, Object parentId) { for (Action action : actions) { addNavigationAction(action, parentId); if (action instanceof ActionGroup) { ActionGroup actionGroup = (ActionGroup) action; addNavigationActions(actionGroup.getItems(), actionGroup); tree.expandItem(actionGroup); } else { tree.setChildrenAllowed(action, false); } } } private void addNavigationAction(Action action, Object parentId) { // String itemId = Rendering.render(action, Rendering.RenderType.PLAIN_TEXT); tree.addItem(action); tree.setItemCaption(action, action.getName()); tree.setParent(action, parentId); } @Override public void loginSucceded(Subject subject) { this.subject = subject; Subject.setCurrent(subject); VaadinService.getCurrentRequest().getWrappedSession().setAttribute("subject", subject); updateNavigation(); show(Application.getInstance().createDefaultPage()); } @Override public void loginCancelled() { if (subject == null && Application.getInstance().isLoginRequired()) { show(new AuthenticationFailedPage()); } }; public Subject getSubject() { return subject; } @Override public void showMessage(String text) { com.vaadin.ui.Notification.show(text, com.vaadin.ui.Notification.Type.HUMANIZED_MESSAGE); } @Override public void showError(String text) { com.vaadin.ui.Notification.show(text, com.vaadin.ui.Notification.Type.ERROR_MESSAGE); } protected void updateWindowTitle() { Page visiblePage = getPageAtLevel(0); String title = Application.getInstance().getName(); if (visiblePage != null) { String pageTitle = visiblePage.getTitle(); if (!StringUtils.isBlank(pageTitle)) { title = title + " - " + pageTitle; } } UI.getCurrent().getPage().setTitle(title); } @Override public void show(Page page) { String pageId = pageStore.put(page); state = new HashMap<>(); state.put("0", pageId); history.pushState(state, ""); updateContent(); } @Override public void showDetail(Page mainPage, Page detail) { int pos = indexOfDetail(mainPage); for (int j = state.size()-1; j>pos; j state.remove(String.valueOf(j)); } String detailId = pageStore.put(detail); state.put(String.valueOf(state.size()), detailId); updateContent(); } @Override public void hideDetail(Page detail) { int pos = indexOfDetail(detail); for (int j = state.size()-1; j>=pos; j state.remove(String.valueOf(j)); } updateContent(); } @Override public boolean isDetailShown(Page detail) { return indexOfDetail(detail) >= 0; } private int indexOfDetail(Page detail) { for (int pos = 0; pos < state.size(); pos++) { String id = state.get(String.valueOf(pos)); Page d = pageStore.get(id); if (d == detail) { return pos; } } return -1; } private void updateContent() { verticalScrollPane.removeAllComponents(); for (int pos = 0; state.containsKey(String.valueOf(pos)); pos++) { Component content; String pageId = state.get(String.valueOf(pos)); Page page = pageStore.get(pageId); content = (Component) page.getContent(); createMenu((AbstractComponent) content, page.getActions()); if (content != null) { ClickListener closeListener = new ClickListener() { @Override public void buttonClick(ClickEvent event) { hideDetail(page); } }; Component decoratedContent = new VaadinDecoration(page.getTitle(), content, SwingDecoration.SHOW_MINIMIZE, closeListener); verticalScrollPane.addComponent(decoratedContent); } } } private static class VaadinDecoration extends VerticalLayout { private static final long serialVersionUID = 1L; public VaadinDecoration(String title, Component content, boolean showMinimize, ClickListener closeListener) { HorizontalLayout titleBar = new HorizontalLayout(); titleBar.setWidth("100%"); Label label = new Label(title); titleBar.addComponent(label); titleBar.setComponentAlignment(label, Alignment.MIDDLE_LEFT); titleBar.setExpandRatio(label, 1.0f); Button closeButton = new Button(FontAwesome.CLOSE); closeButton.addClickListener(closeListener); titleBar.addComponent(closeButton); titleBar.setComponentAlignment(closeButton, Alignment.MIDDLE_RIGHT); addComponent(titleBar); addComponent(content); } } private ContextMenu createMenu(AbstractComponent parentComponent, List<Action> actions) { if (actions != null && actions.size() > 0) { ContextMenu menu = new ContextMenu(parentComponent, true); addActions(menu, actions); return menu; } return null; } private static void addActions(ContextMenu menu, List<Action> actions) { for (Action action : actions) { if (action instanceof ActionGroup) { ActionGroup actionGroup = (org.minimalj.frontend.action.ActionGroup) action; MenuItem subMenu = menu.addItem(actionGroup.getName(), e -> {}); addActions(subMenu, actionGroup.getItems()); } else if (action instanceof Separator) { menu.addSeparator(); } else { adaptAction(menu, action); } } } // no common interface between MenuItem and ContextMenu private static void addActions(MenuItem menu, List<Action> actions) { for (Action action : actions) { if (action instanceof ActionGroup) { ActionGroup actionGroup = (org.minimalj.frontend.action.ActionGroup) action; MenuItem subMenu = menu.addItem(actionGroup.getName(), e -> {}); addActions(subMenu, actionGroup.getItems()); } else if (action instanceof Separator) { menu.addSeparator(); } else { adaptAction(menu, action); } } } private static MenuItem adaptAction(MenuItem menu, Action action) { MenuItem item = menu.addItem(action.getName(), e -> { action.action(); }); action.setChangeListener(new ActionChangeListener() { { update(); } @Override public void change() { update(); } protected void update() { item.setEnabled(action.isEnabled()); item.setDescription(action.getDescription()); } }); return item; } private static MenuItem adaptAction(ContextMenu menu, Action action) { MenuItem item = menu.addItem(action.getName(), e -> { action.action(); }); action.setChangeListener(new ActionChangeListener() { { update(); } @Override public void change() { update(); } protected void update() { item.setEnabled(action.isEnabled()); item.setDescription(action.getDescription()); } }); return item; } private Page getPageAtLevel(int level) { String pageId = state.get(String.valueOf(level)); return pageId != null ? pageStore.get(pageId) : null; } @Override public IDialog showDialog(String title, IContent content, Action saveAction, Action closeAction, Action... actions) { Component component = new VaadinEditorLayout(content, actions); return new VaadinDialog((ComponentContainer) component, title, saveAction, closeAction); } @Override public <T> IDialog showSearchDialog(Search<T> index, Object[] keys, TableActionListener<T> listener) { // TODO Auto-generated method stub return null; } }
package org.exist.xquery.modules.image; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.imageio.ImageIO; import org.exist.util.Base64Decoder; import org.exist.xquery.AbstractInternalModule; import org.exist.xquery.FunctionDef; import org.exist.xquery.XPathException; import org.exist.xquery.value.Base64Binary; /** * eXist Image Module Extension * * An extension module for the eXist Native XML Database that allows operations * on images stored in the eXist database. * * @author Adam Retter <adam.retter@devon.gov.uk> * @author ljo * @serial 2006-03-10 * @version 1.0 * * @see org.exist.xquery.AbstractInternalModule#AbstractInternalModule(org.exist.xquery.FunctionDef[]) */ public class ImageModule extends AbstractInternalModule { /* * TODO: metadata extraction from images, especially JPEG's */ public final static String NAMESPACE_URI = "http://exist-db.org/xquery/image"; public final static String PREFIX = "image"; public final static String INCLUSION_DATE = "2006-03-13"; public final static String RELEASED_IN_VERSION = "eXist-1.2"; private final static FunctionDef[] functions = { new FunctionDef(GetWidthFunction.signature, GetWidthFunction.class), new FunctionDef(GetHeightFunction.signature, GetHeightFunction.class), new FunctionDef(GetMetadataFunction.signatures[0], GetMetadataFunction.class), new FunctionDef(GetMetadataFunction.signatures[1], GetMetadataFunction.class), new FunctionDef(ScaleFunction.signature, ScaleFunction.class), new FunctionDef(GetThumbnailsFunction.signature, GetThumbnailsFunction.class) }; public ImageModule() { super(functions); } public String getNamespaceURI() { return NAMESPACE_URI; } public String getDefaultPrefix() { return PREFIX; } public String getDescription() { return "A module for performing operations on Images stored in the eXist db"; } public String getReleaseVersion() { return RELEASED_IN_VERSION; } /** * Get's an the raw binary data from base64 binary encoded image data * * @param imgBase64Data The base64 encoded image data * * @return The raw binary data */ protected static byte[] getImageData(Base64Binary imgBase64Data) throws XPathException { //decode the base64 image data Base64Decoder dec = new Base64Decoder(); dec.translate(imgBase64Data.getStringValue()); //return the raw binary data return dec.getByteArray(); } /** * Get's an Image object from base64 binary encoded image data * * @param imgBase64Data The base64 encoded image data * * @return An Image object */ protected static Image getImage(Base64Binary imgBase64Data) throws IOException, XPathException { //Create an Image object from the byte array return ImageIO.read(new ByteArrayInputStream(getImageData(imgBase64Data))); } /** * @author Rafael Troilo (rtroilo@gmail.com) */ protected static BufferedImage createThumb(Image image, int height, int width) { int thumbWidth = 0; int thumbHeight = 0; double scaleFactor = 0.0; BufferedImage thumbImage = null; Graphics2D graphics2D = null; int imageHeight = image.getHeight(null); int imageWidth = image.getWidth(null); if (imageHeight >= imageWidth) { scaleFactor = (double) height / (double) imageHeight; thumbWidth = (int) (imageWidth * scaleFactor); thumbHeight = height; if (thumbWidth > width) { // thumbwidth is greater than // maxThumbWidth, so we have to scale // again scaleFactor = (double) width / (double) thumbWidth; thumbHeight = (int) (thumbHeight * scaleFactor); thumbWidth = width; } } else { scaleFactor = (double) width / (double) imageWidth; thumbHeight = (int) (imageHeight * scaleFactor); thumbWidth = width; if (thumbHeight > height) { // thumbHeight is greater than // maxThumbHeight, so we have to scale // again scaleFactor = (double) height / (double) thumbHeight; thumbWidth = (int) (thumbWidth * scaleFactor); thumbHeight = height; } } thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); graphics2D.dispose(); return thumbImage; } }
package com.datatorrent.flume.storage; import java.io.IOException; import java.io.RandomAccessFile; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.flume.Context; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import com.datatorrent.flume.sink.Server; import com.google.common.primitives.Longs; import org.junit.After; import org.junit.Before; /** * * @author Gaurav Gupta <gaurav@datatorrent.com> */ public class HDFSStorageTest { public static final String STORAGE_DIRECTORY = "target"; private HDFSStorage getStorage(String id, boolean restore) { Context ctx = new Context(); ctx.put(HDFSStorage.BASE_DIR_KEY, STORAGE_DIRECTORY); ctx.put(HDFSStorage.RESTORE_KEY, Boolean.toString(restore)); ctx.put(HDFSStorage.ID, id); ctx.put(HDFSStorage.BLOCKSIZE, "256"); HDFSStorage lstorage = new HDFSStorage(); lstorage.configure(ctx); lstorage.setup(null); return lstorage; } private HDFSStorage storage; @Before public void setup() { storage = getStorage("1", false); } @After public void teardown() { storage.cleanHelperFiles(); storage.teardown(); } @Test public void testPartialFlush() throws Exception{ Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = "ab".getBytes(); byte[] address = storage.store(b); Assert.assertNotNull(address); storage.flush(); b = "cb".getBytes(); byte[] addr = storage.store(b); Assert.assertNull(storage.retrieve(addr)); Assert.assertNull(storage.store(b)); storage.flush(); match(storage.retrieve(address),"cb"); Assert.assertNotNull(storage.store(b)); } @Test public void testPartialFlushRollOver() throws Exception{ Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = new byte[] { 48, 48, 48, 48, 98, 48, 52, 54, 49, 57, 55, 51, 52, 97, 53, 101, 56, 56, 97, 55, 98, 53, 52, 51, 98, 50, 102, 51, 49, 97, 97, 54, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 51, 49, 58, 52, 56, 1, 49, 48, 53, 53, 57, 52, 50, 1, 50, 1, 49, 53, 49, 49, 54, 49, 56, 52, 1, 49, 53, 49, 49, 57, 50, 49, 49, 1, 49, 53, 49, 50, 57, 54, 54, 53, 1, 49, 53, 49, 50, 49, 53, 52, 56, 1, 49, 48, 48, 56, 48, 51, 52, 50, 1, 55, 56, 56, 50, 54, 53, 52, 56, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }; byte[] b_org = new byte[] { 48, 48, 48, 48, 98, 48, 52, 54, 49, 57, 55, 51, 52, 97, 53, 101, 56, 56, 97, 55, 98, 53, 52, 51, 98, 50, 102, 51, 49, 97, 97, 54, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 51, 49, 58, 52, 56, 1, 49, 48, 53, 53, 57, 52, 50, 1, 50, 1, 49, 53, 49, 49, 54, 49, 56, 52, 1, 49, 53, 49, 49, 57, 50, 49, 49, 1, 49, 53, 49, 50, 57, 54, 54, 53, 1, 49, 53, 49, 50, 49, 53, 52, 56, 1, 49, 48, 48, 56, 48, 51, 52, 50, 1, 55, 56, 56, 50, 54, 53, 52, 56, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }; int length = b.length; byte[] address = storage.store(b); Assert.assertNotNull(address); storage.flush(); byte[] addr = null; for(int i = 0; i < 5; i++){ b[0] = (byte) (b[0]+1); addr = storage.store(b); } Assert.assertNull(storage.retrieve(addr)); for(int i = 0; i < 5; i++){ b[0] = (byte) (b[0]+1); Assert.assertNull(storage.store(b)); } storage.flush(); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieve(address),new String(b_org)); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieveNext(),new String(b_org)); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieveNext(),new String(b_org)); } @Test public void testPartialFlushRollOverWithFailure() throws Exception{ Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = new byte[] { 48, 48, 48, 48, 98, 48, 52, 54, 49, 57, 55, 51, 52, 97, 53, 101, 56, 56, 97, 55, 98, 53, 52, 51, 98, 50, 102, 51, 49, 97, 97, 54, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 51, 49, 58, 52, 56, 1, 49, 48, 53, 53, 57, 52, 50, 1, 50, 1, 49, 53, 49, 49, 54, 49, 56, 52, 1, 49, 53, 49, 49, 57, 50, 49, 49, 1, 49, 53, 49, 50, 57, 54, 54, 53, 1, 49, 53, 49, 50, 49, 53, 52, 56, 1, 49, 48, 48, 56, 48, 51, 52, 50, 1, 55, 56, 56, 50, 54, 53, 52, 56, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }; byte[] b_org = new byte[] { 48, 48, 48, 48, 98, 48, 52, 54, 49, 57, 55, 51, 52, 97, 53, 101, 56, 56, 97, 55, 98, 53, 52, 51, 98, 50, 102, 51, 49, 97, 97, 54, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 51, 49, 58, 52, 56, 1, 49, 48, 53, 53, 57, 52, 50, 1, 50, 1, 49, 53, 49, 49, 54, 49, 56, 52, 1, 49, 53, 49, 49, 57, 50, 49, 49, 1, 49, 53, 49, 50, 57, 54, 54, 53, 1, 49, 53, 49, 50, 49, 53, 52, 56, 1, 49, 48, 48, 56, 48, 51, 52, 50, 1, 55, 56, 56, 50, 54, 53, 52, 56, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }; int length = b.length; byte[] address = storage.store(b); Assert.assertNotNull(address); storage.flush(); byte[] addr = null; for(int i = 0; i < 5; i++){ b[0] = (byte) (b[0]+1); addr = storage.store(b); } storage = getStorage("1", true); Assert.assertNull(storage.retrieve(addr)); for(int i = 0; i < 5; i++){ b[0] = (byte) (b[0]+1); Assert.assertNull(storage.store(b)); } storage.flush(); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieve(address),new String(b_org)); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieveNext(),new String(b_org)); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieveNext(),new String(b_org)); } @Test public void testPartialFlushWithClean() throws Exception{ Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = new byte[] { 48, 48, 48, 48, 98, 48, 52, 54, 49, 57, 55, 51, 52, 97, 53, 101, 56, 56, 97, 55, 98, 53, 52, 51, 98, 50, 102, 51, 49, 97, 97, 54, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 51, 49, 58, 52, 56, 1, 49, 48, 53, 53, 57, 52, 50, 1, 50, 1, 49, 53, 49, 49, 54, 49, 56, 52, 1, 49, 53, 49, 49, 57, 50, 49, 49, 1, 49, 53, 49, 50, 57, 54, 54, 53, 1, 49, 53, 49, 50, 49, 53, 52, 56, 1, 49, 48, 48, 56, 48, 51, 52, 50, 1, 55, 56, 56, 50, 54, 53, 52, 56, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }; byte[] b_org = new byte[] { 48, 48, 48, 48, 98, 48, 52, 54, 49, 57, 55, 51, 52, 97, 53, 101, 56, 56, 97, 55, 98, 53, 52, 51, 98, 50, 102, 51, 49, 97, 97, 54, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 51, 49, 58, 52, 56, 1, 49, 48, 53, 53, 57, 52, 50, 1, 50, 1, 49, 53, 49, 49, 54, 49, 56, 52, 1, 49, 53, 49, 49, 57, 50, 49, 49, 1, 49, 53, 49, 50, 57, 54, 54, 53, 1, 49, 53, 49, 50, 49, 53, 52, 56, 1, 49, 48, 48, 56, 48, 51, 52, 50, 1, 55, 56, 56, 50, 54, 53, 52, 56, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }; int length = b.length; byte[] address = storage.store(b); Assert.assertNotNull(address); storage.flush(); storage.clean(address); byte[] addr = null; for(int i = 0; i < 5; i++){ b[0] = (byte) (b[0]+1); addr = storage.store(b); } Assert.assertNull(storage.retrieve(addr)); for(int i = 0; i < 5; i++){ b[0] = (byte) (b[0]+1); Assert.assertNull(storage.store(b)); } storage.flush(); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieve(address),new String(b_org)); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieveNext(),new String(b_org)); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieveNext(),new String(b_org)); } @Test public void testPartialFlushWithCleanFailure() throws Exception{ Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = new byte[] { 48, 48, 48, 48, 98, 48, 52, 54, 49, 57, 55, 51, 52, 97, 53, 101, 56, 56, 97, 55, 98, 53, 52, 51, 98, 50, 102, 51, 49, 97, 97, 54, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 51, 49, 58, 52, 56, 1, 49, 48, 53, 53, 57, 52, 50, 1, 50, 1, 49, 53, 49, 49, 54, 49, 56, 52, 1, 49, 53, 49, 49, 57, 50, 49, 49, 1, 49, 53, 49, 50, 57, 54, 54, 53, 1, 49, 53, 49, 50, 49, 53, 52, 56, 1, 49, 48, 48, 56, 48, 51, 52, 50, 1, 55, 56, 56, 50, 54, 53, 52, 56, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }; byte[] b_org = new byte[] { 48, 48, 48, 48, 98, 48, 52, 54, 49, 57, 55, 51, 52, 97, 53, 101, 56, 56, 97, 55, 98, 53, 52, 51, 98, 50, 102, 51, 49, 97, 97, 54, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 51, 49, 58, 52, 56, 1, 49, 48, 53, 53, 57, 52, 50, 1, 50, 1, 49, 53, 49, 49, 54, 49, 56, 52, 1, 49, 53, 49, 49, 57, 50, 49, 49, 1, 49, 53, 49, 50, 57, 54, 54, 53, 1, 49, 53, 49, 50, 49, 53, 52, 56, 1, 49, 48, 48, 56, 48, 51, 52, 50, 1, 55, 56, 56, 50, 54, 53, 52, 56, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }; int length = b.length; byte[] address = storage.store(b); Assert.assertNotNull(address); storage.flush(); storage.clean(address); byte[] addr = null; for(int i = 0; i < 5; i++){ b[0] = (byte) (b[0]+1); addr = storage.store(b); } storage = getStorage("1", true); Assert.assertNull(storage.retrieve(addr)); for(int i = 0; i < 5; i++){ b[0] = (byte) (b[0]+1); Assert.assertNull(storage.store(b)); } storage.flush(); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieve(address),new String(b_org)); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieveNext(),new String(b_org)); b_org[0]=(byte)(b_org[0]+1); match(storage.retrieveNext(),new String(b_org)); } /** * This test covers following use case * The file is flushed and then more data is written to the same file, but the new data is not flushed and file is not roll over and storage fails * The new storage comes up and client asks for data at the last returned address from earlier storage instance. The new storage returns null. * Client stores the data again but the address returned this time is null and the retrieval of the earlier address now returns data * @throws Exception */ @Test public void testPartialFlushWithFailure() throws Exception{ Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = "ab".getBytes(); byte[] address = storage.store(b); Assert.assertNotNull(address); storage.flush(); b = "cb".getBytes(); byte[] addr = storage.store(b); storage = getStorage("1", true); Assert.assertNull(storage.retrieve(addr)); Assert.assertNull(storage.store(b)); storage.flush(); match(storage.retrieve(address),"cb"); } private void match(byte[] data, String match){ byte[] tempData = new byte[data.length - 8]; System.arraycopy(data, 8, tempData, 0, tempData.length); Assert.assertEquals("matched the stored value with retrieved value", match, new String(tempData)); } @Test public void testStorage() throws IOException { Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = new byte[200]; byte[] identifier = new byte[8]; Assert.assertNotNull(storage.store(b)); Assert.assertNotNull(storage.store(b)); Assert.assertNull(storage.retrieve(new byte[8])); Assert.assertNotNull(storage.store(b)); Assert.assertNotNull(storage.store(b)); storage.flush(); byte[] data = storage.retrieve(new byte[8]); Assert.assertNotNull(storage.store(b)); identifier = storage.store(b); byte[] tempData = new byte[data.length - 8]; System.arraycopy(data, 8, tempData, 0, tempData.length); Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData)); Assert.assertNull(storage.retrieve(identifier)); } @Test public void testStorageWithRestore() throws IOException { Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = new byte[200]; Assert.assertNotNull(storage.store(b)); storage.flush(); storage.teardown(); storage = getStorage("1", true); storage.store(b); storage.flush(); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); boolean exists = fs.exists(new Path(STORAGE_DIRECTORY + "/1/" + "1")); Assert.assertEquals("file shoule exist", true, exists); } @Test public void testCleanup() throws IOException { RandomAccessFile r = new RandomAccessFile("src/test/resources/TestInput.txt", "r"); r.seek(0); byte[] b = r.readLine().getBytes(); storage.store(b); byte[] val = storage.store(b); storage.flush(); storage.clean(val); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); boolean exists = fs.exists(new Path(STORAGE_DIRECTORY + "/" + "0")); Assert.assertEquals("file shoule not exist", false, exists); r.close(); } @Test public void testNext() throws IOException { RandomAccessFile r = new RandomAccessFile("src/test/resources/TestInput.txt", "r"); r.seek(0); Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = r.readLine().getBytes(); storage.store(b); byte[] b1 = r.readLine().getBytes(); storage.store(b1); storage.store(b); storage.flush(); storage.store(b1); storage.store(b); storage.flush(); byte[] data = storage.retrieve(new byte[8]); byte[] tempData = new byte[data.length - 8]; System.arraycopy(data, 8, tempData, 0, tempData.length); Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData)); data = storage.retrieveNext(); tempData = new byte[data.length - 8]; System.arraycopy(data, 8, tempData, 0, tempData.length); Assert.assertEquals("matched the stored value with retrieved value", new String(b1), new String(tempData)); data = storage.retrieveNext(); tempData = new byte[data.length - 8]; System.arraycopy(data, 8, tempData, 0, tempData.length); Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData)); r.close(); } @Test public void testFailure() throws IOException { byte[] address; byte[] b = new byte[200]; storage.retrieve(new byte[8]); for (int i = 0; i < 5; i++) { storage.store(b); address = storage.store(b); storage.flush(); storage.clean(address); } storage.teardown(); byte[] identifier = new byte[8]; storage = getStorage("1", true); storage.retrieve(identifier); storage.store(b); storage.store(b); storage.store(b); storage.flush(); byte[] data = storage.retrieve(identifier); byte[] tempData = new byte[data.length - 8]; System.arraycopy(data, 8, tempData, 0, tempData.length); Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData)); } @Test public void testCleanForUnflushedData() throws IOException { byte[] address = null; byte[] b = new byte[200]; storage.retrieve(new byte[8]); for (int i = 0; i < 5; i++) { storage.store(b); address = storage.store(b); storage.flush(); // storage.clean(address); } byte[] lastWrittenAddress = null; for (int i = 0; i < 5; i++) { storage.store(b); lastWrittenAddress = storage.store(b); } storage.clean(lastWrittenAddress); byte[] cleanedOffset = storage.readData(new Path(STORAGE_DIRECTORY + "/1/cleanoffsetFile")); Assert.assertArrayEquals(address, cleanedOffset); } @Test public void testCleanForFlushedData() throws IOException { byte[] b = new byte[200]; storage.retrieve(new byte[8]); for (int i = 0; i < 5; i++) { storage.store(b); storage.store(b); storage.flush(); // storage.clean(address); } byte[] lastWrittenAddress = null; for (int i = 0; i < 5; i++) { storage.store(b); lastWrittenAddress = storage.store(b); } storage.flush(); storage.clean(lastWrittenAddress); byte[] cleanedOffset = storage.readData(new Path(STORAGE_DIRECTORY + "/1/cleanoffsetFile")); Assert.assertArrayEquals(lastWrittenAddress, cleanedOffset); } @Test public void testCleanForPartialFlushedData() throws IOException { byte[] b = new byte[8]; storage.retrieve(new byte[8]); storage.store(b); byte[] address = storage.store("1a".getBytes()); storage.flush(); storage.clean(address); byte[] lastWrittenAddress = null; for (int i = 0; i < 5; i++) { storage.store((i+"").getBytes()); lastWrittenAddress = storage.store(b); } Assert.assertNull(storage.retrieve(new byte[8])); Assert.assertNull(storage.retrieve(lastWrittenAddress)); address = storage.store(b); storage.flush(); Assert.assertNull(storage.retrieve(lastWrittenAddress)); } @Test public void testRandomSequence() throws IOException { storage.retrieve(new byte[] {0, 0, 0, 0, 0, 0, 0, 0 }); storage.store(new byte[] { 48, 48, 48, 51, 101, 100, 55, 56, 55, 49, 53, 99, 52, 101, 55, 50, 97, 52, 48, 49, 51, 99, 97, 54, 102, 57, 55, 53, 57, 100, 49, 99, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 48, 48, 58, 52, 54, 1, 52, 50, 49, 50, 51, 1, 50, 1, 49, 53, 49, 49, 52, 50, 54, 53, 1, 49, 53, 49, 49, 57, 51, 53, 49, 1, 49, 53, 49, 50, 57, 56, 50, 52, 1, 49, 53, 49, 50, 49, 55, 48, 55, 1, 49, 48, 48, 55, 55, 51, 57, 51, 1, 49, 57, 49, 52, 55, 50, 53, 52, 54, 49, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }); storage.flush(); storage.clean(new byte[] { -109, 0, 0, 0, 0, 0, 0, 0 }); storage.retrieve(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }); for (int i = 0; i < 2555; i++) { storage.store(new byte[] { 48, 48, 48, 55, 56, 51, 98, 101, 50, 54, 50, 98, 52, 102, 50, 54, 56, 97, 55, 56, 102, 48, 54, 54, 50, 49, 49, 54, 99, 98, 101, 99, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 48, 48, 58, 53, 49, 1, 49, 49, 49, 49, 54, 51, 57, 1, 50, 1, 49, 53, 49, 48, 57, 57, 56, 51, 1, 49, 53, 49, 49, 49, 55, 48, 52, 1, 49, 53, 49, 50, 49, 51, 55, 49, 1, 49, 53, 49, 49, 52, 56, 51, 49, 1, 49, 48, 48, 55, 49, 57, 56, 49, 1, 49, 50, 48, 50, 55, 54, 49, 54, 56, 53, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }); storage.flush(); } storage.retrieve(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }); for (int i = 0; i < 1297; i++) { storage.retrieveNext(); } storage.retrieve(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }); for (int i = 0; i < 1302; i++) { storage.retrieveNext(); } storage.retrieve(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }); for (int i = 0; i < 1317; i++) { storage.retrieveNext(); } storage.retrieve(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }); for (int i = 0; i < 2007; i++) { storage.retrieveNext(); } storage.retrieve(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }); for (int i = 0; i < 2556; i++) { ; storage.retrieveNext(); } storage.store(new byte[] { 48, 48, 48, 48, 98, 48, 52, 54, 49, 57, 55, 51, 52, 97, 53, 101, 56, 56, 97, 55, 98, 53, 52, 51, 98, 50, 102, 51, 49, 97, 97, 54, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 1, 50, 48, 49, 51, 45, 49, 49, 45, 48, 55, 32, 48, 48, 58, 51, 49, 58, 52, 56, 1, 49, 48, 53, 53, 57, 52, 50, 1, 50, 1, 49, 53, 49, 49, 54, 49, 56, 52, 1, 49, 53, 49, 49, 57, 50, 49, 49, 1, 49, 53, 49, 50, 57, 54, 54, 53, 1, 49, 53, 49, 50, 49, 53, 52, 56, 1, 49, 48, 48, 56, 48, 51, 52, 50, 1, 55, 56, 56, 50, 54, 53, 52, 56, 1, 49, 1, 48, 1, 48, 46, 48, 1, 48, 46, 48, 1, 48, 46, 48 }); storage.flush(); storage.retrieve(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }); for (int i = 0; i < 2062; i++) { storage.retrieveNext(); } } private long calculateOffset(long fileOffset, long fileCounter) { return ((fileCounter << 32) | (fileOffset & 0xffffffffl)); } @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(HDFSStorageTest.class); }
package ubic.gemma.apps; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.lang.time.StopWatch; import ubic.gemma.analysis.linkAnalysis.EffectSizeService; import ubic.gemma.analysis.linkAnalysis.GenePair; import ubic.gemma.model.expression.experiment.ExpressionExperiment; import ubic.gemma.model.expression.experiment.ExpressionExperimentService; import ubic.gemma.model.genome.Gene; import ubic.gemma.model.genome.Taxon; import ubic.gemma.model.genome.TaxonService; import ubic.gemma.model.genome.gene.GeneService; import ubic.gemma.util.AbstractSpringAwareCLI; public class NoCorrelationAnalysisCLI extends AbstractSpringAwareCLI { private String geneListFile; private String partnerGeneListFile; private String outFilePrefix; private Taxon taxon; private EffectSizeService effectSizeService; private ExpressionExperimentService eeService; private GeneService geneService; public NoCorrelationAnalysisCLI() { super(); } @Override protected void buildOptions() { Option geneFileOption = OptionBuilder.hasArg().isRequired() .withArgName("geneFile").withDescription( "File containing list of gene offical symbols") .withLongOpt("geneFile").create('g'); addOption(geneFileOption); Option partnerFileOption = OptionBuilder.hasArg().isRequired() .withArgName("partnerGeneFile").withDescription( "File containing list of partner gene offical symbols") .withLongOpt("partnerGeneFile").create('a'); addOption(partnerFileOption); Option taxonOption = OptionBuilder.hasArg().isRequired().withArgName( "Taxon").withDescription("the taxon of the genes").withLongOpt( "Taxon").create('t'); addOption(taxonOption); Option outputFileOption = OptionBuilder.hasArg().isRequired() .withArgName("outFilePrefix").withDescription( "File prefix for saving the output").withLongOpt( "outFilePrefix").create('o'); addOption(outputFileOption); } @Override protected void processOptions() { super.processOptions(); if (hasOption('g')) { this.geneListFile = getOptionValue('g'); } if (hasOption('a')) { this.partnerGeneListFile = getOptionValue('a'); } if (hasOption('t')) { String taxonName = getOptionValue('t'); taxon = Taxon.Factory.newInstance(); taxon.setCommonName(taxonName); TaxonService taxonService = (TaxonService) this .getBean("taxonService"); taxon = taxonService.find(taxon); if (taxon == null) { log.info("No Taxon found!"); } } if (hasOption('o')) { this.outFilePrefix = getOptionValue('o'); } initBeans(); } protected void initBeans() { effectSizeService = (EffectSizeService) this .getBean("effectSizeService"); eeService = (ExpressionExperimentService) this .getBean("expressionExperimentService"); geneService = (GeneService) this.getBean("geneService"); } @Override protected Exception doWork(String[] args) { Exception exc = processCommandLine("NoCorrelationAnalysis", args); if (exc != null) { return exc; } Collection<GenePair> genePairs; Collection<ExpressionExperiment> allEEs = eeService.findByTaxon(taxon); Collection<ExpressionExperiment> EEs = new ArrayList<ExpressionExperiment>(); for (ExpressionExperiment ee : allEEs) { if (ee.getShortName().equals("GSE7529")) { log.info("Removing expression experiment GSE7529"); } else { EEs.add(ee); } } Collection<Gene> partnerGenes = new ArrayList<Gene>(); log.info("Reading partner genes from " + partnerGeneListFile); try { BufferedReader in = new BufferedReader(new FileReader(partnerGeneListFile)); String line; while ((line = in.readLine()) != null) { if (line.startsWith(" continue; } String symbol = line.trim(); for (Gene gene : (Collection<Gene>) geneService.findByOfficialSymbol(symbol)) { if (gene.getTaxon().equals(taxon)) { partnerGenes.add(gene); break; } } } in.close(); } catch (IOException e) { return e; } try { genePairs = effectSizeService.pairGenesByOfficialSymbol(geneListFile, partnerGenes, taxon); } catch (IOException e) { return e; } effectSizeService.calculateEffectSize(EEs, genePairs); try { effectSizeService.saveCorrelationsToFile(outFilePrefix + ".corr.txt", genePairs, EEs, false, false); effectSizeService.saveMaxCorrelationsToFile(outFilePrefix + ".max_corr.txt", genePairs, EEs, false, false); effectSizeService.saveExprLevelToFile(outFilePrefix + ".expr_lvl.txt", genePairs, EEs, false, false); effectSizeService.saveExprProfilesToFile(outFilePrefix + ".eps.txt", genePairs, EEs); } catch (IOException e) { return e; } return null; } public static void main(String[] args) { NoCorrelationAnalysisCLI analysis = new NoCorrelationAnalysisCLI(); StopWatch watch = new StopWatch(); watch.start(); log.info("Starting No Correlation Analysis"); Exception exc = analysis.doWork(args); if (exc != null) { log.error(exc.getMessage()); } log.info("Finished analysis in " + watch.getTime() / 1000 + " seconds"); } }
package de.starwit.generator.services; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Date; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import de.starwit.dto.GeneratorDto; import de.starwit.generator.config.Constants; import de.starwit.persistence.entity.App; import de.starwit.persistence.entity.AppTemplate; import de.starwit.persistence.exception.NotificationException; import de.starwit.service.impl.AppService; import de.starwit.service.impl.AppTemplateService; @Service public class AppCheckout { final static Logger LOG = LoggerFactory.getLogger(AppCheckout.class); @Autowired private AppTemplateService appTemplateService; @Autowired private AppService appService; public String createTempAppDirectory(final App app) throws NotificationException { try { Path destDir = null; destDir = Files.createTempDirectory(Constants.LJ_PREFIX + app.getTitle()); return destDir.getFileName().toString(); } catch (final IOException e) { LOG.error("Error creating temporary folder for app", e); throw new NotificationException("error.appcheckout.createtempappfolder", "Error creating temporary folder for app"); } } public void deleteTempURLApp(final String oldDestDirUrl) { final File oldDestDir = new File(oldDestDirUrl); deleteTempApp(oldDestDir); } private void deleteTempApp(final File oldDestDir) { if (!oldDestDir.exists()) { return; } final Path oldDestDirPath = oldDestDir.toPath(); try { Files.walkFileTree(oldDestDirPath, new DeleteFileVisitor()); } catch (final IOException e) { LOG.error("Error deleting temporary folder for app", e); } } /** * Deletes all temp files created during git clone / checkout. */ public void findFilesAndDelete() { File oldDestDir = new File(Constants.TMP_DIR); final File[] files = oldDestDir.listFiles((File pathname) -> pathname .getName().startsWith(Constants.LJ_PREFIX)); for (File file : files) { long diff = new Date().getTime() - file.lastModified(); if (diff > Constants.MILLISECONDS_UNTIL_DELETION) { deleteTempApp(file); } } } private class DeleteFileVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) throws IOException { final File file1 = new File(file.toUri()); file1.setWritable(true); Files.deleteIfExists(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException { Files.deleteIfExists(dir); return FileVisitResult.CONTINUE; } } /** * Copies the app template and tomee to an new app location. * * @param entity * @return * @throws NotificationException */ public void checkoutAppTemplate(final GeneratorDto dto) throws NotificationException { final App app = appService.findById(dto.getAppId()); String destDirString = Constants.TMP_DIR + Constants.FILE_SEP + app.getTargetPath(); final File destDir = new File(destDirString); String srcDir = app.getTemplate().getLocation(); String branch = Constants.DEFAULT_BRANCH; if (app.getTemplate().getBranch() != null) { branch = app.getTemplate().getBranch(); } if (app.getTemplate().isCredentialsRequired()) { dto.setPassword(dto.getPass().replaceAll("@", "%40")); srcDir = srcDir.replaceAll("://", "://" + dto.getUser() + ":" + dto.getPass() + "@"); LOG.info("Source directory is: " + srcDir); } try { Git.gitClone(destDir.toPath(), srcDir, branch); saveTemplateProperties(app.getTemplate(), destDir.getAbsolutePath()); } catch (IOException | InterruptedException e) { this.deleteTempURLApp(Constants.TMP_DIR + Constants.FILE_SEP + destDirString); LOG.error("Error copying files for app template.", e); throw new NotificationException("error.appcheckout.checkoutapptemplate.transport", "Error copying files for app template."); } catch (RuntimeException e) { this.deleteTempURLApp(Constants.TMP_DIR + Constants.FILE_SEP + destDirString); LOG.error("Error copying files for app template.", e); throw new NotificationException("error.appcheckout.checkoutapptemplate.git", "Error copying files for app template."); } } protected void saveTemplateProperties(AppTemplate template, String newAppFolder) throws NotificationException { Properties props = readTemplateProperties(newAppFolder); if (template == null) { LOG.error("Error: template should not be null."); throw new NotificationException("error.appcheckout.templatenull.git", "Error: template should not be null."); } if (template.getId() != null) { template = appTemplateService.findById(template.getId()); } template.setTemplateName(props.getProperty("templateName", "lirejarp")); template.setPackagePlaceholder(props.getProperty("packagePlaceholder", "starwit")); appTemplateService.saveOrUpdate(template); } private Properties readTemplateProperties(String newAppFolder) throws NotificationException { Properties props = new Properties(); try { InputStream inputStream = new FileInputStream(newAppFolder + Constants.FILE_SEP + Constants.APPTEMPLATE_PROPERTIES); props.load(inputStream); } catch (FileNotFoundException e) { LOG.error("Template properties file" + Constants.APPTEMPLATE_PROPERTIES + "not found in apptemplate.", e); String path = newAppFolder + Constants.FILE_SEP + Constants.APPTEMPLATE_PROPERTIES; throw new NotificationException("error.appcheckout.templatepropertiesnotfound.git", "Template properties file " + path + " not found."); } catch (IOException e) { LOG.error("Template properties file" + Constants.APPTEMPLATE_PROPERTIES + "could not be read.", e); throw new NotificationException("error.appcheckout.templatepropertiesnotread.git", "Template properties file " + Constants.APPTEMPLATE_PROPERTIES + " could not be read."); } return props; } }
package gov.nih.nci.calab.dto.inventory; import java.util.List; /** * This class captures the database pre-loaded information about containers and * is used to prepopulate the Create Sample and Create Aliquot pages. * * @author pansu * */ /* CVS $Id: ContainerInfoBean.java,v 1.3 2007-01-09 22:53:45 pansu Exp $ */ public class ContainerInfoBean { private List<String> quantityUnits; private List<String> concentrationUnits; private List<String> volumeUnits; private List<String> storageLabs; private List<String> storageRooms; private List<String> storageFreezers; private List<String> storageShelves; private List<String> storageBoxes; public List<String> getStorageBoxes() { return storageBoxes; } public void setStorageBoxes(List<String> storageBoxes) { this.storageBoxes = storageBoxes; } public List<String> getStorageShelves() { return storageShelves; } public void setStorageShelves(List<String> storageShelves) { this.storageShelves = storageShelves; } public ContainerInfoBean(List<String> quantityUnits, List<String> concentrationUnits, List<String> volumeUnits, List<String> storageLabs, List<String> storeageRooms, List<String> storageFreezers, List<String> storageShelves, List<String> storageBoxes) { super(); // TODO Auto-generated constructor stub this.quantityUnits = quantityUnits; this.concentrationUnits = concentrationUnits; this.volumeUnits = volumeUnits; this.storageLabs = storageLabs; this.storageRooms = storeageRooms; this.storageFreezers = storageFreezers; this.storageShelves = storageShelves; this.storageBoxes = storageBoxes; } public List<String> getConcentrationUnits() { return concentrationUnits; } public void setConcentrationUnits(List<String> concentrationUnits) { this.concentrationUnits = concentrationUnits; } public List<String> getStorageFreezers() { return storageFreezers; } public void setStorageFreezers(List<String> freezers) { this.storageFreezers = freezers; } public List<String> getQuantityUnits() { return quantityUnits; } public void setQuantityUnits(List<String> quantityUnits) { this.quantityUnits = quantityUnits; } public List<String> getStorageRooms() { return storageRooms; } public void setStorageRooms(List<String> rooms) { this.storageRooms = rooms; } public List<String> getVolumeUnits() { return volumeUnits; } public void setVolumeUnits(List<String> volumeUnits) { this.volumeUnits = volumeUnits; } public List<String> getStorageLabs() { return storageLabs; } public void setStorageLabs(List<String> storageLabs) { this.storageLabs = storageLabs; } public List<String> getStoreageRooms() { return storageRooms; } public void setStoreageRooms(List<String> storeageRooms) { this.storageRooms = storeageRooms; } }
package gov.nih.nci.calab.service.util; import java.util.HashMap; import java.util.Map; public class CaNanoLabConstants { public static final String CSM_APP_NAME = "caNanoLab"; public static final String DATE_FORMAT = "MM/dd/yyyy"; public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy"; // Storage element public static final String STORAGE_BOX = "Box"; public static final String STORAGE_SHELF = "Shelf"; public static final String STORAGE_RACK = "Rack"; public static final String STORAGE_FREEZER = "Freezer"; public static final String STORAGE_ROOM = "Room"; public static final String STORAGE_LAB = "Lab"; // DataStatus public static final String MASK_STATUS = "Masked"; public static final String ACTIVE_STATUS = "Active"; // for Container type public static final String OTHER = "Other"; public static final String[] DEFAULT_CONTAINER_TYPES = new String[] { "Tube", "Vial", "Other" }; // Sample Container type public static final String ALIQUOT = "Aliquot"; public static final String SAMPLE_CONTAINER = "Sample_container"; // Run Name public static final String RUN = "Run"; // File upload public static final String FILEUPLOAD_PROPERTY = "fileupload.properties"; public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles"; public static final String EMPTY = "N/A"; // File input/output type public static final String INPUT = "Input"; public static final String OUTPUT = "Output"; // zip file name public static final String ALL_FILES = "ALL_FILES"; public static final String URI_SEPERATOR = "/"; // caNanoLab property file public static final String CANANOLAB_PROPERTY = "caNanoLab.properties"; public static final String CSM_READ_ROLE = "R"; public static final String CSM_READ_PRIVILEGE = "READ"; // caLAB Submission property file public static final String SUBMISSION_PROPERTY = "exception.properties"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES, BOOLEAN_NO }; public static final String DEFAULT_SAMPLE_PREFIX = "NANO-"; public static final String DEFAULT_APP_OWNER = "NCICB"; public static final String APP_OWNER; static { String appOwner = PropertyReader.getProperty(CANANOLAB_PROPERTY, "applicationOwner"); if (appOwner == null || appOwner.length() == 0) appOwner = DEFAULT_APP_OWNER; APP_OWNER = appOwner; } public static final String SAMPLE_PREFIX; static { String samplePrefix = PropertyReader.getProperty(CANANOLAB_PROPERTY, "samplePrefix"); if (samplePrefix == null || samplePrefix.length() == 0) samplePrefix = DEFAULT_SAMPLE_PREFIX; SAMPLE_PREFIX = samplePrefix; } /* * The following Strings are nano specific * */ public static final String PHYSICAL_CHARACTERIZATION = "Physical"; public static final String COMPOSITION_CHARACTERIZATION = "Composition"; public static final String INVITRO_CHARACTERIZATION = "In Vitro"; public static final String INVIVO_CHARACTERIZATION = "In Vivo"; public static final String TOXICITY_CHARACTERIZATION = "Toxicity"; public static final String CYTOXICITY_CHARACTERIZATION = "Cytoxicity"; public static final String APOPTOSIS_CELL_DEATH_METHOD_CYTOXICITY_CHARACTERIZATION = "apoptosis"; public static final String NECROSIS_CELL_DEATH_METHOD_CYTOXICITY_CHARACTERIZATION = "necrosis"; public static final String BLOOD_CONTACT_IMMUNOTOXICITY_CHARACTERIZATION = "Blood Contact"; public static final String IMMUNE_CELL_FUNCTION_IMMUNOTOXICITY_CHARACTERIZATION = "Immune Cell Function"; public static final String METABOLIC_STABILITY_TOXICITY_CHARACTERIZATION = "Metabolic Stability"; public static final String PHYSICAL_SIZE = "Size"; public static final String PHYSICAL_SHAPE = "Shape"; public static final String PHYSICAL_MOLECULAR_WEIGHT = "Molecular Weight"; public static final String PHYSICAL_SOLUBILITY = "Solubility"; public static final String PHYSICAL_SURFACE = "Surface"; public static final String PHYSICAL_STABILITY = "Stability"; public static final String PHYSICAL_PURITY = "Purity"; public static final String PHYSICAL_FUNCTIONAL = "Functional"; public static final String PHYSICAL_MORPHOLOGY = "Morphology"; public static final String PHYSICAL_COMPOSITION = "Composition"; public static final String TOXICITY_OXIDATIVE_STRESS = "Oxidative Stress"; public static final String TOXICITY_OXIDATIVE_STRESS_DATA_TYPE = "Percent Oxidative Stress"; public static final String TOXICITY_ENZYME_FUNCTION = "Enzyme Function"; public static final String TOXICITY_ENZYME_FUNCTION_DATA_TYPE = "Percent Enzyme Induction"; public static final String CYTOTOXICITY_CELL_VIABILITY = "Cell Viability"; public static final String CYTOTOXICITY_CELL_VIABILITY_DATA_TYPE = "Percent Cell Viability"; public static final String CYTOTOXICITY_CASPASE3_ACTIVIATION = "Caspase 3 Activation"; public static final String CYTOTOXICITY_CASPASE3_ACTIVIATION_DATA_TYPE = "Percent Caspase 3 Activation"; public static final String BLOODCONTACTTOX_PLATE_AGGREGATION = "Platelet Aggregation"; public static final String BLOODCONTACTTOX_PLATE_AGGREGATION_DATA_TYPE = "Percent Platelet Aggregation"; public static final String BLOODCONTACTTOX_HEMOLYSIS = "Hemolysis"; public static final String BLOODCONTACTTOX_HEMOLYSIS_DATA_TYPE = "Percent Hemolysis"; public static final String BLOODCONTACTTOX_COAGULATION = "Coagulation"; public static final String BLOODCONTACTTOX_COAGULATION_DATA_TYPE = "Coagulation Time"; public static final String BLOODCONTACTTOX_PLASMA_PROTEIN_BINDING = "Plasma Protein Binding"; public static final String BLOODCONTACTTOX_PLASMA_PROTEIN_BINDING_DATA_TYPE = "Percent Plasma Protein Binding"; public static final String IMMUNOCELLFUNCTOX_PHAGOCYTOSIS = "Phagocytosis"; public static final String IMMUNOCELLFUNCTOX_PHAGOCYTOSIS_DATA_TYPE = "Fold Induction"; public static final String IMMUNOCELLFUNCTOX_OXIDATIVE_BURST = "Oxidative Burst"; public static final String IMMUNOCELLFUNCTOX_OXIDATIVE_BURST_DATA_TYPE = "Percent Oxidative Burst"; public static final String IMMUNOCELLFUNCTOX_CHEMOTAXIS = "Chemotaxis"; public static final String IMMUNOCELLFUNCTOX_CHEMOTAXIS_DATA_TYPE = "Relative Fluorescent Values"; public static final String IMMUNOCELLFUNCTOX_CYTOKINE_INDUCTION = "Cytokine Induction"; public static final String IMMUNOCELLFUNCTOX_CYTOKINE_INDUCTION_DATA_TYPE = "Cytokine Concentration"; public static final String IMMUNOCELLFUNCTOX_COMPLEMENT_ACTIVATION = "Complement Activation"; public static final String IMMUNOCELLFUNCTOX_COMPLEMENT_ACTIVATION_DATA_TYPE = "Percent Complement Activation"; public static final String IMMUNOCELLFUNCTOX_LEUKOCYTE_PROLIFERATION = "Leukocyte Proliferation"; public static final String IMMUNOCELLFUNCTOX_LEUKOCYTE_PROLIFERATION_DATA_TYPE = "Percent Leukocyte Proliferation"; public static final String IMMUNOCELLFUNCTOX_NKCELL_CYTOTOXIC_ACTIVITY = "Cytotoxic Activity of NK Cells"; public static final String IMMUNOCELLFUNCTOX_NKCELL_CYTOTOXIC_ACTIVITY_DATA_TYPE = "Percent Cytotoxic Activity"; public static final String METABOLIC_STABILITY_CYP450 = "CYP450"; public static final String METABOLIC_STABILITY_ROS = "ROS"; public static final String METABOLIC_STABILITY_GLUCURONIDATION_SULPHATION = "Glucuronidation Sulphation"; public static final String IMMUNOCELLFUNCTOX_CFU_GM = "CFU_GM"; public static final String IMMUNOCELLFUNCTOX_CFU_GM_DATA_TYPE = "CFU_GM"; public static final String DENDRIMER_TYPE = "Dendrimer"; public static final String POLYMER_TYPE = "Polymer"; public static final String LIPOSOME_TYPE = "Liposome"; public static final String CARBON_NANOTUBE_TYPE = "Carbon Nanotube"; public static final String FULLERENE_TYPE = "Fullerene"; public static final String QUANTUM_DOT_TYPE = "Quantum Dot"; public static final String METAL_PARTICLE_TYPE = "Metal Particle"; public static final String EMULSION_TYPE = "Emulsion"; public static final String COMPLEX_PARTICLE_TYPE = "Complex Particle"; public static final String CORE = "core"; public static final String SHELL = "shell"; public static final String COATING = "coating"; public static final String[] CHARACTERIZATION_SOURCES = new String[] { "NCL", "Vendor" }; public static final String[] CARBON_NANOTUBE_WALLTYPES = new String[] { "Single (SWNT)", "Double (DWMT)", "Multiple (MWNT)" }; public static final String REPORT = APP_OWNER + " Report"; public static final String ASSOCIATED_FILE = "Other Associated File"; public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] { "Free Radicals", "Peroxide" }; public static final String[] DEFAULT_DENDRIMER_BRANCHES = new String[] { "1-2", "1-3" }; public static final String[] DEFAULT_DENDRIMER_GENERATIONS = new String[] { "0", "0.5", "1.0", "1.5", "2.0", "2.5", "3.0", "3.5", "4.0", "4.5", "5.0", "5.5", "6.0", "6.5", "7.0", "7.5", "8.0", "8.5", "9.0", "9.5", "10.0" }; public static final String CHARACTERIZATION_FILE = "characterizationFile"; public static final String DNA = "DNA"; public static final String PEPTIDE = "Peptide"; public static final String SMALL_MOLECULE = "Small Molecule"; public static final String PROBE = "Probe"; public static final String ANTIBODY = "Antibody"; public static final String IMAGE_CONTRAST_AGENT = "Image Contrast Agent"; public static final String ATTACHMENT = "Attachment"; public static final String ENCAPSULATION = "Encapsulation"; public static final String[] FUNCTION_AGENT_TYPES = new String[] { DNA, PEPTIDE, SMALL_MOLECULE, PROBE, ANTIBODY, IMAGE_CONTRAST_AGENT }; public static final String[] FUNCTION_LINKAGE_TYPES = new String[] { ATTACHMENT, ENCAPSULATION }; public static final String RECEPTOR = "Receptor"; public static final String ANTIGEN = "Antigen"; public static final int MAX_VIEW_TITLE_LENGTH = 23; public static final String[] DEFAULT_CELLLINES = new String[] { "LLC-PK1", "Hep-G2" }; public static final String[] DEFAULT_SHAPE_TYPES = new String[] { "Cubic", "Hexagonal", "Irregular", "Needle", "Oblate", "Rod", "Spherical", "Tetrahedron", "Tetrapod", "Triangle", "Eliptical", "Composite", "Cylindrical", "Vesicular", "Elliposid" }; public static final String[] DEFAULT_MORPHOLOGY_TYPES = new String[] { "Powder", "Liquid", "Solid", "Crystalline", "Copolymer", "Fibril", "Colloid", "Oil" }; public static final String[] DEFAULT_SURFACE_GROUP_NAMES = new String[] { "Amine", "Carboxyl", "Hydroxyl" }; public static final String ABBR_COMPOSITION = "CP"; public static final String ABBR_SIZE = "SZ"; public static final String ABBR_MOLECULAR_WEIGHT = "MW"; public static final String ABBR_MORPHOLOGY = "MP"; public static final String ABBR_SHAPE = "SH"; public static final String ABBR_SURFACE = "SF"; public static final String ABBR_SOLUBILITY = "SL"; public static final String ABBR_PURITY = "PT"; public static final String ABBR_OXIDATIVE_STRESS = "OS"; public static final String ABBR_ENZYME_FUNCTION = "EF"; public static final String ABBR_CELL_VIABILITY = "CV"; public static final String ABBR_CASPASE3_ACTIVATION = "C3"; public static final String ABBR_PLATELET_AGGREGATION = "PA"; public static final String ABBR_HEMOLYSIS = "HM"; public static final String ABBR_PLASMA_PROTEIN_BINDING = "PB"; public static final String ABBR_COAGULATION = "CG"; public static final String ABBR_OXIDATIVE_BURST = "OB"; public static final String ABBR_CHEMOTAXIS = "CT"; public static final String ABBR_LEUKOCYTE_PROLIFERATION = "LP"; public static final String ABBR_PHAGOCYTOSIS = "PC"; public static final String ABBR_CYTOKINE_INDUCTION = "CI"; public static final String ABBR_CFU_GM = "CU"; public static final String ABBR_COMPLEMENT_ACTIVATION = "CA"; public static final String ABBR_NKCELL_CYTOTOXIC_ACTIVITY = "NK"; public static final String[] SPECIES_SCIENTIFIC = { "Mus musculus", "Homo sapiens", "Rattus rattus", "Sus scrofa", "Meriones unguiculatus", "Mesocricetus auratus", "Cavia porcellus", "Bos taurus", "Canis familiaris", "Capra hircus", "Equus Caballus", "Ovis aries", "Felis catus", "Saccharomyces cerevisiae", "Danio rerio" }; public static final String[] SPECIES_COMMON = { "Mouse", "Human", "Rat", "Pig", "Mongolian Gerbil", "Hamster", "Guinea pig", "Cattle", "Dog", "Goat", "Horse", "Sheep", "Cat", "Yeast", "Zebrafish" }; public static final String UNIT_PERCENT = "%"; public static final String UNIT_CFU = "CFU"; public static final String UNIT_RFU = "RFU"; public static final String UNIT_SECOND = "SECOND"; public static final String UNIT_MG_ML = "mg/ml"; public static final String UNIT_FOLD = "Fold"; public static final String ORGANIC_HYDROCARBON = "organic:hydrocarbon"; public static final String ORGANIC_CARBON = "organic:carbon"; public static final String ORGANIC = "organic"; public static final String INORGANIC = "inorganic"; public static final String COMPLEX = "complex"; public static final Map<String, String> PARTICLE_CLASSIFICATION_MAP; static { PARTICLE_CLASSIFICATION_MAP = new HashMap<String, String>(); PARTICLE_CLASSIFICATION_MAP.put(DENDRIMER_TYPE, ORGANIC_HYDROCARBON); PARTICLE_CLASSIFICATION_MAP.put(POLYMER_TYPE, ORGANIC_HYDROCARBON); PARTICLE_CLASSIFICATION_MAP.put(FULLERENE_TYPE, ORGANIC_CARBON); PARTICLE_CLASSIFICATION_MAP.put(CARBON_NANOTUBE_TYPE, ORGANIC_CARBON); PARTICLE_CLASSIFICATION_MAP.put(LIPOSOME_TYPE, ORGANIC); PARTICLE_CLASSIFICATION_MAP.put(EMULSION_TYPE, ORGANIC); PARTICLE_CLASSIFICATION_MAP.put(METAL_PARTICLE_TYPE, INORGANIC); PARTICLE_CLASSIFICATION_MAP.put(QUANTUM_DOT_TYPE, INORGANIC); PARTICLE_CLASSIFICATION_MAP.put(COMPLEX_PARTICLE_TYPE, COMPLEX); } public static final String CSM_PI = APP_OWNER+"_PI"; public static final String CSM_RESEARCHER = APP_OWNER+"_Researcher"; public static final String CSM_ADMIN=APP_OWNER+"_Administrator"; public static final String[] VISIBLE_GROUPS = new String[] { CSM_PI, CSM_RESEARCHER }; }
package org.rstudio.core.client; import com.google.gwt.safehtml.shared.SafeUri; public class SafeUriStringImpl implements SafeUri { public SafeUriStringImpl(String value) { value_ = value; } @Override public String asString() { return value_; } @Override public int hashCode() { return value_.hashCode(); } @Override public boolean equals(Object o) { if (o == null ^ value_ == null) return false; if (value_ == null) return false; return value_.equals(o.toString()); } @Override public String toString() { return value_; } private final String value_; }
package org.basex.query.expr.path; import static org.basex.query.QueryText.*; import static org.basex.query.expr.path.Axis.*; import java.util.*; import org.basex.core.locks.*; import org.basex.data.*; import org.basex.index.path.*; import org.basex.query.*; import org.basex.query.expr.*; import org.basex.query.expr.List; import org.basex.query.expr.constr.*; import org.basex.query.expr.index.*; import org.basex.query.expr.path.Test.*; import org.basex.query.util.*; import org.basex.query.util.list.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.value.seq.*; import org.basex.query.value.type.*; import org.basex.query.var.*; import org.basex.util.*; public abstract class Path extends ParseExpr { /** XPath axes that are expected to be expensive when at the start of a path. */ private static final EnumSet<Axis> EXPENSIVE = EnumSet.of(DESC, DESCORSELF, PREC, PRECSIBL, FOLL, FOLLSIBL); /** Root expression (can be {@code null}). */ public Expr root; /** Path steps. */ public final Expr[] steps; /** * Constructor. * @param info input info * @param root root expression (can be {@code null}) * @param steps steps */ protected Path(final InputInfo info, final Expr root, final Expr[] steps) { super(info, SeqType.ITEM_ZM); this.root = root; this.steps = steps; } /** * Returns a new path instance. * A path implementation is chosen that works fastest for the given steps. * @param info input info * @param root root expression (can be {@code null}) * @param steps steps * @return path instance */ public static ParseExpr get(final InputInfo info, final Expr root, final Expr... steps) { // new list with steps int sl = steps.length; final ExprList list = new ExprList(sl); // merge nested paths Expr rt = root; if(rt instanceof Path) { final Path path = (Path) rt; list.add(path.steps); rt = path.root; } // remove redundant context reference if(rt instanceof ContextValue) rt = null; // add steps of input array for(final Expr expr : steps) { Expr step = expr; if(step instanceof ContextValue) { // remove redundant context references if(sl > 1) continue; // single step: rewrite to axis step (required to sort results of path) step = Step.get(((ContextValue) step).info, SELF, KindTest.NOD); } else if(step instanceof Filter) { // rewrite filter to axis step final Filter f = (Filter) step; if(f.root instanceof ContextValue) { step = Step.get(f.info, SELF, KindTest.NOD, f.exprs); } } else if(step instanceof Path) { // rewrite path to axis steps final Path p = (Path) step; if(p.root != null && !(p.root instanceof ContextValue)) list.add(p.root); final int pl = p.steps.length - 1; for(int i = 0; i < pl; i++) list.add(p.steps[i]); step = p.steps[pl]; } list.add(step); } // check if all steps are axis steps int axes = 0; final Expr[] st = list.toArray(); for(final Expr step : st) { if(step instanceof Step) axes++; } sl = st.length; if(axes == sl) return iterative(rt, st) ? new IterPath(info, rt, st) : new CachedPath(info, rt, st); // if last expression yields no nodes, rewrite mixed path to simple map // example: $a/b/string -> $a/b ! string() final Expr last = st[sl - 1]; if(sl > 1 && last.seqType().type.instanceOf(AtomType.AAT)) { list.remove(sl - 1); return (SimpleMap) SimpleMap.get(info, Path.get(info, rt, list.finish()), last); } return new MixedPath(info, rt, st); } @Override public final void checkUp() throws QueryException { checkNoUp(root); final int ss = steps.length; for(int s = 0; s < ss - 1; s++) checkNoUp(steps[s]); steps[ss - 1].checkUp(); } @Override public final Expr compile(final CompileContext cc) throws QueryException { if(root != null) { root = root.compile(cc); if(root.seqType().zero() || steps.length == 0) return root; cc.pushFocus(root); } else { if(steps.length == 0) return new ContextValue(info).optimize(cc); cc.pushFocus(cc.qc.focus.value); } final int sl = steps.length; for(int s = 0; s < sl; s++) { Expr step = steps[s]; try { step = step.compile(cc); } catch(final QueryException ex) { // replace original expression with error step = cc.error(ex, this); } cc.updateFocus(step); steps[s] = step; } cc.removeFocus(); // optimize path return optimize(cc); } @Override public final Expr optimize(final CompileContext cc) throws QueryException { // root returns no results... if(root != null && root.seqType().zero()) return cc.replaceWith(this, root); // simplify path with empty root expression or empty step final Value rt = rootValue(cc); if(emptyPath(rt)) return cc.emptySeq(this); seqType(cc, rt); // merge descendant steps Expr expr = mergeSteps(cc); // check index access if(expr == this) expr = index(cc, rt); /* rewrite descendant to child steps. this optimization is called after the index rewritings, * as it is cheaper to invert a descendant step. examples: * - //C[. = '...'] -> IA('...', C) * - /A/B/C[. = '...'] -> IA('...', C)/parent::B/parent::A */ if(expr == this) expr = children(cc, rt); if(expr != this) return expr.optimize(cc); // choose best path implementation and set type information return copyType(get(info, root, steps)); } @Override public Expr optimizeEbv(final CompileContext cc) throws QueryException { final Expr last = steps[steps.length - 1]; if(last instanceof Step) { final Step step = (Step) last; if(step.exprs.length == 1 && step.seqType().type instanceof NodeType && !step.exprs[0].seqType().mayBeNumber()) { // merge nested predicates. example: if(a[b]) -> if(a/b) final Expr s = step.optimizeEbv(this, cc); if(s != step) { step.exprs = new Expr[0]; return cc.replaceEbv(this, s); } } } return super.optimizeEbv(cc); } @Override public Data data() { if(root != null) { // data reference final Data data = root.data(); if(data != null) { final int sl = steps.length; for(int s = 0; s < sl; s++) { if(axisStep(s) == null) return null; } return data; } } return null; } @Override public final boolean has(final Flag... flags) { /* Context dependency: check if no root exists, or if it depends on context. * Examples: text(); ./abc */ if(Flag.CTX.in(flags) && (root == null || root.has(Flag.CTX))) return true; /* Positional access: only check root node (steps will refer to result of root node). * Example: position()/a */ if(Flag.POS.in(flags) && (root != null && root.has(Flag.POS))) return true; // check remaining flags final Flag[] flgs = Flag.POS.remove(Flag.CTX.remove(flags)); if(flgs.length != 0) { for(final Expr step : steps) if(step.has(flgs)) return true; return root != null && root.has(flgs); } return false; } /** * Tries to cast the specified step into an axis step. * @param index index * @return axis step, or {@code null}) */ private Step axisStep(final int index) { return steps[index] instanceof Step ? (Step) steps[index] : null; } /** * Returns the path nodes that will result from this path. * @param cc compilation context * @return path nodes or {@code null} if nodes cannot be evaluated */ public final ArrayList<PathNode> pathNodes(final CompileContext cc) { // skip computation if path does not start with document nodes final Value rt = rootValue(cc); if(cc.nestedFocus() || rt == null || rt.type != NodeType.DOC) return null; final Data data = rt.data(); if(data == null || !data.meta.uptodate) return null; ArrayList<PathNode> nodes = data.paths.root(); final int sl = steps.length; for(int s = 0; s < sl; s++) { final Step curr = axisStep(s); if(curr == null) return null; nodes = curr.nodes(nodes, data); if(nodes == null) return null; } return nodes; } /** * Returns a root value for this path. * @param cc compilation context * @return context value, dummy item or {@code null} */ private Value rootValue(final CompileContext cc) { // no root expression: return context value (possibly empty) if(root == null) return cc.qc.focus.value; // root is value: return root if(root instanceof Value) return (Value) root; // otherwise, create dummy item return cc.dummyItem(root); } /** * Estimates the cost to evaluate this path. This is used to determine if the path * can be inlined into a loop to enable index rewritings. * @return guess */ public final boolean cheap() { if(!(root instanceof ANode) || ((Value) root).type != NodeType.DOC) return false; final int sl = steps.length; for(int i = 0; i < sl; i++) { final Step s = axisStep(i); if(s == null || i < 2 && EXPENSIVE.contains(s.axis)) return false; final Expr[] ps = s.exprs; if(!(ps.length == 0 || ps.length == 1 && ps[0] instanceof ItrPos)) return false; } return true; } /** * Checks if the path can be rewritten for iterative evaluation. * @param root root expression; can be a {@code null} reference * @param steps path steps * @return result of check */ private static boolean iterative(final Expr root, final Expr... steps) { if(root == null || !root.iterable()) return false; final long size = root.size(); final SeqType st = root.seqType(); boolean atMostOne = size == 0 || size == 1 || st.zeroOrOne(); boolean sameDepth = atMostOne || st.type == NodeType.DOC || st.type == NodeType.DEL; for(final Expr expr : steps) { final Step step = (Step) expr; switch(step.axis) { case ANC: case ANCORSELF: case PREC: case PRECSIBL: // backwards axes must be reordered return false; case FOLL: // can overlap if(!atMostOne) return false; atMostOne = false; sameDepth = false; break; case FOLLSIBL: // can overlap, preserves level if(!atMostOne) return false; atMostOne = false; break; case ATTR: // only unique for exact QName matching atMostOne &= step.test.kind == Kind.URI_NAME; break; case CHILD: // order is only ensured if all nodes are on the same level if(!sameDepth) return false; atMostOne = false; break; case DESC: case DESCORSELF: // non-overlapping if all nodes are on the same level if(!sameDepth) return false; atMostOne = false; sameDepth = false; break; case PARENT: // overlaps if(!atMostOne) return false; break; case SELF: // nothing changes break; default: throw Util.notExpected(); } } return true; } /** * Assigns a sequence type and (if statically known) result size. * @param rt root value (can be {@code null}) * @param cc compilation context */ private void seqType(final CompileContext cc, final Value rt) { // assign data reference final int sl = steps.length; final long size = size(cc, rt); final Expr last = steps[sl - 1]; final SeqType st = last.seqType(); final Type type = st.type; Occ occ = Occ.ZERO_MORE; // unknown result size: single attribute with exact name test will return at most one result if(size < 0 && root == null && sl == 1 && last instanceof Step && cc.nestedFocus()) { final Step step = (Step) last; if(step.axis == ATTR && step.test.one) { occ = Occ.ZERO_ONE; step.exprType.assign(occ); } } exprType.assign(type, occ, size); } /** * Computes the number of results. * @param rt root value (can be {@code null}) * @param cc compilation context * @return number of results */ private long size(final CompileContext cc, final Value rt) { if(root != null && root.size() == 0) return 0; for(final Expr step : steps) { if(step.size() == 0) return 0; } // skip computation if path does not start with document nodes if(cc.nestedFocus() || rt == null || rt.type != NodeType.DOC) return -1; // skip computation if no database instance is available, is outdated, or // if context does not contain all database nodes final Data data = rt.data(); if(data == null || !data.meta.uptodate || data.meta.ndocs != rt.size()) return -1; ArrayList<PathNode> nodes = data.paths.root(); long lastSize = 1; final int sl = steps.length; for(int s = 0; s < sl; s++) { final Step curr = axisStep(s); if(curr != null) { nodes = curr.nodes(nodes, data); if(nodes == null) return -1; } else if(s + 1 == sl) { lastSize = steps[s].size(); } else { // stop if a non-axis step is not placed last return -1; } } long size = 0; for(final PathNode pn : nodes) size += pn.stats.count; return size * lastSize; } /** * Returns all summary path nodes for the specified location step. * @param data data reference (can be {@code null}) * @param last last step to be checked * @return path nodes, or {@code null} if nodes cannot be retrieved */ private ArrayList<PathNode> pathNodes(final Data data, final int last) { // skip request if no path index exists or might be out-of-date if(data == null || !data.meta.uptodate) return null; ArrayList<PathNode> nodes = data.paths.root(); for(int s = 0; s <= last; s++) { // only follow axis steps final Step curr = axisStep(s); if(curr == null) return null; final boolean desc = curr.axis == DESC; if(!desc && curr.axis != CHILD || curr.test.kind != Kind.NAME) return null; final int name = data.elemNames.id(curr.test.name.local()); final ArrayList<PathNode> tmp = new ArrayList<>(); for(final PathNode node : PathIndex.desc(nodes, desc)) { if(node.kind == Data.ELEM && name == node.name) { // skip test if an element name occurs on different levels if(!tmp.isEmpty() && tmp.get(0).level() != node.level()) return null; tmp.add(node); } } if(tmp.isEmpty()) return null; nodes = tmp; } return nodes; } /** * Checks if the path will never yield results. * @param rt root value (can be {@code null}) * @return {@code true} if steps will never yield results */ private boolean emptyPath(final Value rt) { final int sl = steps.length; for(int s = 0; s < sl; s++) { if(emptyStep(rt, s)) return true; } return false; } /** * Checks if the specified step will never yield results. * @param rt root value (can be {@code null}) * @param s index of step * @return {@code true} if steps will never yield results */ private boolean emptyStep(final Value rt, final int s) { if(steps[s] == Empty.SEQ) return true; final Step step = axisStep(s); if(step == null) return false; final Axis axis = step.axis; if(s == 0) { // first location step: if(root instanceof CAttr) { // @.../child:: / @.../descendant:: if(axis == CHILD || axis == DESC) return true; } else if(root instanceof Root || root instanceof CDoc || rt != null && rt.type == NodeType.DOC) { switch(axis) { case SELF: case ANCORSELF: if(step.test != KindTest.NOD && step.test != KindTest.DOC) return true; break; case CHILD: case DESC: if(step.test == KindTest.DOC || step.test == KindTest.ATT) return true; break; case DESCORSELF: if(step.test == KindTest.ATT) return true; break; default: return true; } } } else { // remaining steps: final Step last = axisStep(s - 1); if(last == null) return false; // .../self:: / .../descendant-or-self:: if(axis == SELF || axis == DESCORSELF) { if(step.test == KindTest.NOD) return false; // @.../..., text()/... if(last.axis == ATTR && step.test.type != NodeType.ATT || last.test == KindTest.TXT && step.test != KindTest.TXT) return true; if(axis == DESCORSELF) return false; // .../self:: final QNm name = step.test.name, lastName = last.test.name; if(lastName == null || name == null || lastName.local().length == 0 || name.local().length == 0) return false; return !name.eq(lastName); } // .../following-sibling:: / .../preceding-sibling:: if(axis == FOLLSIBL || axis == PRECSIBL) return last.axis == ATTR; // .../descendant:: / .../child:: / .../attribute:: if(axis == DESC || axis == CHILD || axis == ATTR) return last.axis == ATTR || last.test == KindTest.TXT || last.test == KindTest.COM || last.test == KindTest.PI || axis == ATTR && step.test == KindTest.NSP; // .../parent:: / .../ancestor:: if(axis == PARENT || axis == ANC) return last.test == KindTest.DOC; } return false; } /** * Converts descendant to child steps. * @param cc compilation context * @param rt root value * @return original or new expression */ private Expr children(final CompileContext cc, final Value rt) { // only rewrite on document level if(cc.nestedFocus() || rt == null || rt.type != NodeType.DOC) return this; // skip if index does not exist or is out-dated, or if several namespaces occur in the input final Data data = rt.data(); if(data == null || !data.meta.uptodate || data.nspaces.globalUri() == null) return this; Expr path = this; final int sl = steps.length; for(int s = 0; s < sl; s++) { // don't allow predicates in preceding location steps final Step prev = s > 0 ? axisStep(s - 1) : null; if(prev != null && prev.exprs.length != 0) break; // ignore axes other than descendant, or numeric predicates final Step curr = axisStep(s); if(curr == null || curr.axis != DESC || curr.positional()) continue; // check if child steps can be retrieved for current step ArrayList<PathNode> nodes = pathNodes(data, s); if(nodes == null) continue; // cache child steps final ArrayList<QNm> qnm = new ArrayList<>(); while(nodes.get(0).parent != null) { QNm nm = new QNm(data.elemNames.key(nodes.get(0).name)); // skip children with prefixes if(nm.hasPrefix()) return this; for(final PathNode p : nodes) { if(nodes.get(0).name != p.name) nm = null; } qnm.add(nm); nodes = PathIndex.parent(nodes); } cc.info(OPTCHILD_X, steps[s]); // build new steps int ts = qnm.size(); final Expr[] stps = new Expr[ts + sl - s - 1]; for(int t = 0; t < ts; t++) { final Expr[] preds = t == ts - 1 ? ((Preds) steps[s]).exprs : new Expr[0]; final QNm nm = qnm.get(ts - t - 1); final NameTest nt = nm == null ? new NameTest(false) : new NameTest(nm, Kind.NAME, false, null); stps[t] = Step.get(info, CHILD, nt, preds); } while(++s < sl) stps[ts++] = steps[s]; path = get(info, root, stps); break; } // check if all steps yield results; if not, return empty sequence final ArrayList<PathNode> nodes = pathNodes(cc); if(nodes != null && nodes.isEmpty()) { cc.info(OPTPATH_X, path); return Empty.SEQ; } return path; } /** * Returns an equivalent expression which accesses an index. * If the expression cannot be rewritten, the original expression is returned. * * The following types of queries can be rewritten (in the examples, the equality comparison * is used, which will be rewritten to {@link ValueAccess} instances): * * <pre> * 1. A[text() = '...'] : IA('...', A) * 2. A[. = '...'] : IA('...', A) * 3. text()[. = '...'] : IA('...') * 4. A[B = '...'] : IA('...', B)/parent::A * 1. A[B/text() = '...'] : IA('...')/parent::B/parent::A * 2. A[B/C = '...'] : IA('...', C)/parent::B/parent::A * 7. A[@a = '...'] : IA('...', @a)/parent::A * 8. @a[. = '...'] : IA('...', @a)</pre> * * Queries of type 1, 3, 5 will not yield any results if the string to be compared is empty. * * @param cc compilation context * @param rt root value (can be {@code null}) * @return original or new expression * @throws QueryException query exception */ private Expr index(final CompileContext cc, final Value rt) throws QueryException { // skip optimization if path does not start with document nodes if(cc.nestedFocus() || rt != null && rt.type != NodeType.DOC) return this; // cache index access costs IndexInfo index = null; // cheapest predicate and step int indexPred = 0, indexStep = 0; // check if path can be converted to an index access final Data data = rt != null ? rt.data() : null; final int sl = steps.length; for(int s = 0; s < sl; s++) { // only accept descendant steps without positional predicates // Example for position predicate: child:x[1] != parent::x[1] final Step step = axisStep(s); if(step == null || !step.axis.down || step.positional()) break; final int el = step.exprs.length; if(el > 0) { // check if path is iterable (i.e., will be duplicate-free) final boolean iter = pathNodes(data, s) != null; final IndexDb db = data != null ? new IndexStaticDb(data, iter, info) : new IndexDynDb(info, iter, root == null ? new ContextValue(info) : root); // choose cheapest index access for(int e = 0; e < el; e++) { final IndexInfo ii = new IndexInfo(db, cc.qc, step); if(!step.exprs[e].indexAccessible(ii)) continue; if(ii.costs.results() == 0) { // no results... cc.info(OPTNORESULTS_X, ii.step); return Empty.SEQ; } if(index == null || index.costs.compareTo(ii.costs) > 0) { index = ii; indexPred = e; indexStep = s; } } } } // skip rewriting if no index access is possible, or if it is too expensive if(index == null || data != null && index.costs.tooExpensive(data)) return this; // skip optimization if it is not enforced if(rt instanceof Dummy && !index.enforce()) return this; // rewrite for index access cc.info(index.optInfo); // invert steps that occur before index step and add them as predicate final ExprList newPreds = new ExprList(); final Test rootTest = InvDocTest.get(rt); final ExprList invSteps = new ExprList(); if(rootTest != KindTest.DOC || data == null || !data.meta.uptodate || predSteps(data, indexStep)) { for(int s = indexStep; s >= 0; s final Axis invAxis = axisStep(s).axis.invert(); if(s == 0) { // add document test for collections and axes other than ancestors if(rootTest != KindTest.DOC || invAxis != ANC && invAxis != ANCORSELF) invSteps.add(Step.get(info, invAxis, rootTest)); } else { final Step prevStep = axisStep(s - 1); final Axis newAxis = prevStep.axis == ATTR ? ATTR : invAxis; invSteps.add(Step.get(info, newAxis, prevStep.test, prevStep.exprs)); } } } if(!invSteps.isEmpty()) newPreds.add(get(info, null, invSteps.finish())); // add remaining predicates final Expr[] preds = index.step.exprs; final int pl = preds.length; for(int p = 0; p < pl; p++) { if(p != indexPred) newPreds.add(preds[p]); } // create resulting expression final ExprList resultSteps = new ExprList(); final Expr resultRoot; if(index.expr instanceof Path) { final Path path = (Path) index.expr; resultRoot = path.root; resultSteps.add(path.steps); } else { resultRoot = index.expr; } // only one hit: update sequence type if(index.costs.results() == 1) { final Occ occ = resultRoot instanceof IndexAccess ? Occ.ONE : Occ.ZERO_ONE; ((ParseExpr) resultRoot).exprType.assign(occ); } if(!newPreds.isEmpty()) { int ls = resultSteps.size() - 1; final Step step; if(ls < 0 || !(resultSteps.get(ls) instanceof Step)) { // add at least one self axis step step = Step.get(info, SELF, KindTest.NOD); ls++; } else { step = (Step) resultSteps.get(ls); } // add remaining predicates to last step resultSteps.set(ls, step.addPreds(newPreds.finish())); } // add remaining steps for(int s = indexStep + 1; s < sl; s++) resultSteps.add(steps[s]); return resultSteps.isEmpty() ? resultRoot : get(info, resultRoot, resultSteps.finish()); } /** * Checks if steps before index step need to be inverted and traversed. * @param data data reference * @param i index step * @return result of check */ private boolean predSteps(final Data data, final int i) { for(int s = i; s >= 0; s final Step step = axisStep(s); // ensure that the index step does not use wildcard if(step.test.kind == Kind.WILDCARD && s != i) continue; // consider child steps with name test and without predicates if(step.test.kind != Kind.NAME || step.axis != CHILD || s != i && step.exprs.length > 0) return true; // support only unique paths with nodes on the correct level final ArrayList<PathNode> pn = data.paths.desc(step.test.name.local()); if(pn.size() != 1 || pn.get(0).level() != s + 1) return true; } return false; } /** * Merges expensive descendant-or-self::node() steps. * @param cc compilation context * @return original or new expression */ private Expr mergeSteps(final CompileContext cc) { boolean opt = false; final int sl = steps.length; final ExprList stps = new ExprList(sl); for(int s = 0; s < sl; s++) { final Expr step = steps[s]; // check for simple descendants-or-self step with succeeding step if(s < sl - 1 && step instanceof Step) { final Step curr = (Step) step; if(curr.simple(DESCORSELF, false)) { // check succeeding step final Expr next = steps[s + 1]; // descendant-or-self::node()/child::X -> descendant::X if(simpleChild(next)) { ((Step) next).axis = DESC; opt = true; continue; } // descendant-or-self::node()/(X, Y) -> (descendant::X | descendant::Y) Expr expr = mergeList(next); if(expr != null) { steps[s + 1] = expr; opt = true; continue; } // //(X, Y)[text()] -> (/descendant::X | /descendant::Y)[text()] if(next instanceof Filter && !((Filter) next).positional()) { final Filter f = (Filter) next; expr = mergeList(f.root); if(expr != null) { f.root = expr; opt = true; continue; } } } } stps.add(step); } if(opt) { cc.info(OPTDESC); return stps.isEmpty() ? root : get(info, root, stps.finish()); } return this; } /** * Tries to rewrite union or list expressions. * @param expr input expression * @return rewriting flag or {@code null} */ private Expr mergeList(final Expr expr) { if(expr instanceof Union || expr instanceof List) { final Arr array = (Arr) expr; if(childSteps(array)) { for(final Expr ex : array.exprs) ((Step) ((Path) ex).steps[0]).axis = DESC; return new Union(array.info, array.exprs); } } return null; } /** * Checks if the expressions in the specified array start with child steps. * @param array array expression to be checked * @return result of check */ private static boolean childSteps(final Arr array) { for(final Expr expr : array.exprs) { if(!(expr instanceof Path)) return false; final Path path = (Path) expr; if(path.root != null || !simpleChild(path.steps[0])) return false; } return true; } /** * Checks if the expressions is a simple child step. * @param expr expression to be checked * @return result of check */ private static boolean simpleChild(final Expr expr) { if(expr instanceof Step) { final Step step = (Step) expr; if(step.axis == CHILD && !step.positional()) return true; } return false; } @Override public final boolean removable(final Var var) { for(final Expr step : steps) if(step.uses(var)) return false; return root == null || root.removable(var); } @Override public VarUsage count(final Var var) { final VarUsage inRoot = root == null ? VarUsage.NEVER : root.count(var); return VarUsage.sum(var, steps) == VarUsage.NEVER ? inRoot : VarUsage.MORE_THAN_ONCE; } @Override public final Expr inline(final Var var, final Expr ex, final CompileContext cc) throws QueryException { // #1202: during inlining, expressions will be optimized, which are based on the context value boolean changed = false; if(root != null) { final Expr rt = root.inline(var, ex, cc); if(rt != null) { root = rt; changed = true; } } cc.pushFocus(root != null ? root : cc.qc.focus.value); try { final int sl = steps.length; for(int s = 0; s < sl; s++) { final Expr exp = steps[s].inline(var, ex, cc); if(exp != null) { steps[s] = exp; changed = true; } cc.updateFocus(steps[s]); } } finally { cc.removeFocus(); } return changed ? optimize(cc) : null; } @Override public boolean accept(final ASTVisitor visitor) { if(root == null) { visitor.lock(Locking.CONTEXT); } else if(!root.accept(visitor)) { return false; } visitor.enterFocus(); if(!visitAll(visitor, steps)) return false; visitor.exitFocus(); return true; } @Override public final int exprSize() { int size = 1; for(final Expr step : steps) size += step.exprSize(); return root == null ? size : size + root.exprSize(); } @Override public final boolean equals(final Object obj) { if(!(obj instanceof Path)) return false; final Path path = (Path) obj; return Objects.equals(root, path.root) && Array.equals(steps, path.steps); } @Override public final void plan(final FElem plan) { addPlan(plan, planElem(), root, steps); } @Override public final String toString() { final StringBuilder sb = new StringBuilder(); if(root != null) sb.append(root); for(final Expr step : steps) { if(sb.length() != 0) sb.append('/'); final String s = step.toString(); final boolean par = !s.contains("[") && s.contains(" "); if(par) sb.append('('); sb.append(step); if(par) sb.append(')'); } return sb.toString(); } }
package com.tinkerpop.gremlin.structure; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.tinkerpop.gremlin.AbstractGremlinTest; import com.tinkerpop.gremlin.FeatureRequirement; import com.tinkerpop.gremlin.LoadGraphWith; import com.tinkerpop.gremlin.process.T; import com.tinkerpop.gremlin.structure.Graph.Features.EdgePropertyFeatures; import com.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures; import com.tinkerpop.gremlin.structure.io.GraphMigrator; import com.tinkerpop.gremlin.structure.io.GraphReader; import com.tinkerpop.gremlin.structure.io.GraphWriter; import com.tinkerpop.gremlin.structure.io.graphml.GraphMLReader; import com.tinkerpop.gremlin.structure.io.graphml.GraphMLWriter; import com.tinkerpop.gremlin.structure.io.graphson.GraphSONReader; import com.tinkerpop.gremlin.structure.io.graphson.GraphSONTokens; import com.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter; import com.tinkerpop.gremlin.structure.io.graphson.LegacyGraphSONReader; import com.tinkerpop.gremlin.structure.io.kryo.GremlinKryo; import com.tinkerpop.gremlin.structure.io.kryo.KryoReader; import com.tinkerpop.gremlin.structure.io.kryo.KryoWriter; import com.tinkerpop.gremlin.structure.io.kryo.VertexByteArrayInputStream; import com.tinkerpop.gremlin.util.StreamFactory; import org.apache.commons.configuration.Configuration; import org.junit.Test; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static com.tinkerpop.gremlin.structure.Graph.Features.ElementFeatures.FEATURE_ANY_IDS; import static com.tinkerpop.gremlin.structure.Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS; import static com.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures.*; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; public class IoTest extends AbstractGremlinTest { private static final String GRAPHML_RESOURCE_PATH_PREFIX = "/com/tinkerpop/gremlin/structure/util/io/graphml/"; private static final String GRAPHSON_RESOURCE_PATH_PREFIX = "/com/tinkerpop/gremlin/structure/util/io/graphson/"; @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) public void shouldReadGraphML() throws IOException { readGraphMLIntoGraph(g); assertToyGraph(g, false, true, false); } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_BOOLEAN_VALUES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_LONG_VALUES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_DOUBLE_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) public void shouldReadGraphMLAnAllSupportedDataTypes() throws IOException { final GraphReader reader = GraphMLReader.build().create(); try (final InputStream stream = IoTest.class.getResourceAsStream(GRAPHML_RESOURCE_PATH_PREFIX + "graph-types.xml")) { reader.readGraph(stream, g); } final Vertex v = g.V().next(); assertEquals(123.45d, v.value("d"), 0.000001d); assertEquals("some-string", v.<String>value("s")); assertEquals(29, v.<Integer>value("i").intValue()); assertEquals(true, v.<Boolean>value("b")); assertEquals(123.54f, v.value("f"), 0.000001f); assertEquals(10000000l, v.<Long>value("l").longValue()); assertEquals("junk", v.<String>value("n")); } /** * Only need to execute this test with TinkerGraph or other graphs that support user supplied identifiers. */ @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_NUMERIC_IDS) @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) public void shouldWriteNormalizedGraphML() throws Exception { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final GraphMLWriter w = GraphMLWriter.build().normalize(true).create(); w.writeGraph(bos, g); final String expected = streamToString(IoTest.class.getResourceAsStream(GRAPHML_RESOURCE_PATH_PREFIX + "tinkerpop-classic-normalized.xml")); assertEquals(expected.replace("\n", "").replace("\r", ""), bos.toString().replace("\n", "").replace("\r", "")); } } /** * Only need to execute this test with TinkerGraph or other graphs that support user supplied identifiers. */ @Test @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_NUMERIC_IDS) @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) public void shouldWriteNormalizedGraphSON() throws Exception { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final GraphSONWriter w = GraphSONWriter.build().normalize(true).create(); w.writeGraph(bos, g); final String expected = streamToString(IoTest.class.getResourceAsStream(GRAPHSON_RESOURCE_PATH_PREFIX + "tinkerpop-classic-normalized.json")); assertEquals(expected.replace("\n", "").replace("\r", ""), bos.toString().replace("\n", "").replace("\r", "")); } } /** * Note: this is only a very lightweight test of writer/reader encoding. It is known that there are characters * which, when written by GraphMLWriter, cause parse errors for GraphMLReader. However, this happens uncommonly * enough that is not yet known which characters those are. Only need to execute this test with TinkerGraph * or other graphs that support user supplied identifiers. */ @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_STRING_IDS) public void shouldProperlyEncodeWithGraphML() throws Exception { final Vertex v = g.addVertex(T.id, "1"); v.property("text", "\u00E9"); final GraphMLWriter w = GraphMLWriter.build().create(); final File f = File.createTempFile("test", "txt"); try (final OutputStream out = new FileOutputStream(f)) { w.writeGraph(out, g); } validateXmlAgainstGraphMLXsd(f); // reusing the same config used for creation of "g". final Configuration configuration = graphProvider.newGraphConfiguration( "g2", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g2 = graphProvider.openTestGraph(configuration); final GraphMLReader r = GraphMLReader.build().create(); try (final InputStream in = new FileInputStream(f)) { r.readGraph(in, g2); } final Vertex v2 = g2.v("1"); assertEquals("\u00E9", v2.property("text").value()); // need to manually close the "g2" instance graphProvider.clear(g2, configuration); } /** * This is just a serialization check. */ @Test @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_ANY_IDS) public void shouldProperlySerializeDeserializeCustomIdWithGraphSON() throws Exception { final UUID id = UUID.fromString("AF4B5965-B176-4552-B3C1-FBBE2F52C305"); g.addVertex(T.id, new CustomId("vertex", id)); final SimpleModule module = new SimpleModule(); module.addSerializer(CustomId.class, new CustomId.CustomIdJacksonSerializer()); module.addDeserializer(CustomId.class, new CustomId.CustomIdJacksonDeserializer()); final GraphWriter writer = GraphSONWriter.build() .embedTypes(true) .customModule(module).create(); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { writer.writeGraph(baos, g); final JsonNode jsonGraph = new ObjectMapper().readTree(baos.toByteArray()); final JsonNode onlyVertex = jsonGraph.findValues(GraphSONTokens.VERTICES).get(0).get(0); final JsonNode idValue = onlyVertex.get(GraphSONTokens.ID); assertTrue(idValue.has("cluster")); assertEquals("vertex", idValue.get("cluster").asText()); assertTrue(idValue.has("elementId")); assertEquals("AF4B5965-B176-4552-B3C1-FBBE2F52C305".toLowerCase(), idValue.get("elementId").asText()); // reusing the same config used for creation of "g". final Configuration configuration = graphProvider.newGraphConfiguration( "g2", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g2 = graphProvider.openTestGraph(configuration); try (final InputStream is = new ByteArrayInputStream(baos.toByteArray())) { final GraphReader reader = GraphSONReader.build() .embedTypes(true) .customModule(module).create(); reader.readGraph(is, g2); } final Vertex v2 = g2.V().next(); final CustomId customId = (CustomId) v2.id(); assertEquals(id, customId.getElementId()); assertEquals("vertex", customId.getCluster()); // need to manually close the "g2" instance graphProvider.clear(g2, configuration); } } @Test @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_ANY_IDS) public void shouldProperlySerializeCustomIdWithKryo() throws Exception { g.addVertex(T.id, new CustomId("vertex", UUID.fromString("AF4B5965-B176-4552-B3C1-FBBE2F52C305"))); final GremlinKryo kryo = GremlinKryo.build().addCustom(CustomId.class).create(); final KryoWriter writer = KryoWriter.build().custom(kryo).create(); final KryoReader reader = KryoReader.build().custom(kryo).create(); final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g1 = graphProvider.openTestGraph(configuration); GraphMigrator.migrateGraph(g, g1, reader, writer); final Vertex onlyVertex = g1.V().next(); final CustomId id = (CustomId) onlyVertex.id(); assertEquals("vertex", id.getCluster()); assertEquals(UUID.fromString("AF4B5965-B176-4552-B3C1-FBBE2F52C305"), id.getElementId()); // need to manually close the "g1" instance graphProvider.clear(g1, configuration); } @Test @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) public void shouldMigrateGraphWithFloat() throws Exception { final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g1 = graphProvider.openTestGraph(configuration); GraphMigrator.migrateGraph(g, g1); assertToyGraph(g1, false, false, false); // need to manually close the "g1" instance graphProvider.clear(g1, configuration); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) public void shouldMigrateGraph() throws Exception { final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g1 = graphProvider.openTestGraph(configuration); GraphMigrator.migrateGraph(g, g1); // by making this lossy for float it will assert floats for doubles assertToyGraph(g1, true, false, true); // need to manually close the "g1" instance graphProvider.clear(g1, configuration); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_NUMERIC_IDS) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) public void shouldReadWriteModernToKryo() throws Exception { try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeGraph(os, g); final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g1 = graphProvider.openTestGraph(configuration); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readGraph(bais, g1); } // by making this lossy for float it will assert floats for doubles assertToyGraph(g1, true, false, true); // need to manually close the "g1" instance graphProvider.clear(g1, configuration); } } @Test @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_NUMERIC_IDS) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) public void shouldReadWriteClassicToKryo() throws Exception { try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeGraph(os, g); final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g1 = graphProvider.openTestGraph(configuration); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readGraph(bais, g1); } assertToyGraph(g1, false, false, false); // need to manually close the "g1" instance graphProvider.clear(g1, configuration); } } @Test @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) public void shouldReadWriteClassicToGraphSON() throws Exception { try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeGraph(os, g); final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g1 = graphProvider.openTestGraph(configuration); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readGraph(bais, g1); } assertToyGraph(g1, true, false, false); // need to manually close the "g1" instance graphProvider.clear(g1, configuration); } } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) public void shouldReadWriteModernToGraphSON() throws Exception { try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeGraph(os, g); final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName()); graphProvider.clear(configuration); final Graph g1 = graphProvider.openTestGraph(configuration); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readGraph(bais, g1); } assertToyGraph(g1, true, false, true); // need to manually close the "g1" instance graphProvider.clear(g1, configuration); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) public void shouldReadWriteEdgeToKryoUsingFloatProperty() throws Exception { final Vertex v1 = g.addVertex(T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e = v1.addEdge("friend", v2, "weight", 0.5f, Graph.Key.hide("acl"), "rw"); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeEdge(os, e); final AtomicBoolean called = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readEdge(bais, detachedEdge -> { assertEquals(e.id(), detachedEdge.id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(e.hiddenKeys().size(), StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(e.keys().size(), StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5f, detachedEdge.iterators().properties("weight").next().value()); assertEquals("rw", detachedEdge.iterators().hiddens("acl").next().value()); called.set(true); return null; }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteEdgeToKryo() throws Exception { final Vertex v1 = g.addVertex(T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e = v1.addEdge("friend", v2, "weight", 0.5d, Graph.Key.hide("acl"), "rw"); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeEdge(os, e); final AtomicBoolean called = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readEdge(bais, detachedEdge -> { assertEquals(e.id(), detachedEdge.id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(e.hiddenKeys().size(), StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(e.keys().size(), StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, e.iterators().properties("weight").next().value()); assertEquals("rw", e.iterators().hiddens("acl").next().value()); called.set(true); return null; }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteEdgeToGraphSON() throws Exception { final Vertex v1 = g.addVertex(T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e = v1.addEdge("friend", v2, "weight", 0.5f, Graph.Key.hide("acl"), "rw"); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeEdge(os, e); final AtomicBoolean called = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readEdge(bais, detachedEdge -> { assertEquals(e.id().toString(), detachedEdge.id().toString()); // lossy assertEquals(v1.id().toString(), detachedEdge.iterators().vertices(Direction.OUT).next().id().toString()); // lossy assertEquals(v2.id().toString(), detachedEdge.iterators().vertices(Direction.IN).next().id().toString()); // lossy assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(e.hiddenKeys().size(), StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(e.keys().size(), StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, detachedEdge.iterators().properties("weight").next().value()); assertEquals("rw", detachedEdge.iterators().hiddens("acl").next().value()); called.set(true); return null; }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_NUMERIC_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_USER_SUPPLIED_IDS) public void shouldReadWriteEdgeToGraphSONNonLossy() throws Exception { final Vertex v1 = g.addVertex(T.id, 1l, T.label, "person"); final Vertex v2 = g.addVertex(T.id, 2l, T.label, "person"); final Edge e = v1.addEdge("friend", v2, "weight", 0.5f, Graph.Key.hide("acl"), "rw"); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build() .embedTypes(true) .create(); writer.writeEdge(os, e); final AtomicBoolean called = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build() .embedTypes(true) .create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readEdge(bais, detachedEdge -> { assertEquals(e.id(), detachedEdge.id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(e.hiddenKeys().size(), StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(e.keys().size(), StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5f, detachedEdge.iterators().properties("weight").next().value()); assertEquals("rw", detachedEdge.iterators().hiddens("acl").next().value()); called.set(true); return null; }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_SERIALIZABLE_VALUES) public void shouldSupportUUIDInGraphSON() throws Exception { final UUID id = UUID.randomUUID(); final Vertex v1 = g.addVertex(T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e = v1.addEdge("friend", v2, "uuid", id); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build() .embedTypes(true) .create(); writer.writeEdge(os, e); final AtomicBoolean called = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build() .embedTypes(true) .create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readEdge(bais, detachedEdge -> { assertEquals(e.id(), detachedEdge.id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(e.keys().size(), StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(id, detachedEdge.value("uuid")); called.set(true); return null; }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_SERIALIZABLE_VALUES) public void shouldSupportUUIDInKryo() throws Exception { final UUID id = UUID.randomUUID(); final Vertex v1 = g.addVertex(T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e = v1.addEdge("friend", v2, "uuid", id); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeEdge(os, e); final AtomicBoolean called = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readEdge(bais, detachedEdge -> { assertEquals(e.id(), detachedEdge.id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(e.hiddenKeys().size(), StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(e.keys().size(), StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(id, detachedEdge.value("uuid")); called.set(true); return null; }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) public void shouldReadWriteVertexNoEdgesToKryoUsingFloatProperty() throws Exception { final Vertex v1 = g.addVertex("name", "marko", Graph.Key.hide("acl"), "rw"); final Vertex v2 = g.addVertex(); v1.addEdge("friends", v2, "weight", 0.5f); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1); final AtomicBoolean called = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, detachedVertex -> { assertEquals(v1.id(), detachedVertex.id()); assertEquals(v1.label(), detachedVertex.label()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals(v1.value("name"), detachedVertex.value("name").toString()); assertEquals(v1.hiddens("acl").value().next().toString(), detachedVertex.value(Graph.Key.hide("acl")).toString()); called.set(true); return mock(Vertex.class); }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexNoEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko", Graph.Key.hide("acl"), "rw"); final Vertex v2 = g.addVertex(); v1.addEdge("friends", v2, "weight", 0.5d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1); final AtomicBoolean called = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, detachedVertex -> { assertEquals(v1.id(), detachedVertex.id()); assertEquals(v1.label(), detachedVertex.label()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals(v1.value("name"), detachedVertex.value("name").toString()); assertEquals(v1.hiddens("acl").value().next().toString(), detachedVertex.value(Graph.Key.hide("acl")).toString()); called.set(true); return mock(Vertex.class); }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexMultiPropsNoEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko", "name", "mark", Graph.Key.hide("acl"), "rw"); v1.property("propsSquared", 123, "x", "a", "y", "b"); final Vertex v2 = g.addVertex(); v1.addEdge("friends", v2, "weight", 0.5d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1); final AtomicBoolean called = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, detachedVertex -> { assertEquals(v1.id(), detachedVertex.id()); assertEquals(v1.label(), detachedVertex.label()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(3, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals("a", detachedVertex.property("propsSquared").value("x")); assertEquals("b", detachedVertex.property("propsSquared").value("y")); assertEquals(2, StreamFactory.stream(detachedVertex.iterators().properties("name")).count()); assertTrue(StreamFactory.stream(detachedVertex.iterators().properties("name")).allMatch(p -> p.key().equals("name") && (p.value().equals("marko") || p.value().equals("mark")))); assertEquals(v1.hiddens("acl").value().next().toString(), detachedVertex.value(Graph.Key.hide("acl")).toString()); called.set(true); return mock(Vertex.class); }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexNoEdgesToGraphSON() throws Exception { final Vertex v1 = g.addVertex("name", "marko"); final Vertex v2 = g.addVertex(); v1.addEdge("friends", v2, "weight", 0.5f); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeVertex(os, v1); final AtomicBoolean called = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, detachedVertex -> { assertEquals(v1.id().toString(), detachedVertex.id().toString()); // lossy assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals("marko", detachedVertex.value("name")); called.set(true); return detachedVertex; }); } assertTrue(called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexMultiPropsNoEdgesToGraphSON() throws Exception { final Vertex v1 = g.addVertex("name", "marko", "name", "mark", Graph.Key.hide("acl"), "rw"); v1.property("propsSquared", 123, "x", "a", "y", "b"); final Vertex v2 = g.addVertex(); v1.addEdge("friends", v2, "weight", 0.5d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeVertex(os, v1); final AtomicBoolean called = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, detachedVertex -> { assertEquals(v1.id().toString(), detachedVertex.id().toString()); // lossy assertEquals(v1.label(), detachedVertex.label()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(3, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals("a", detachedVertex.property("propsSquared").value("x")); assertEquals("b", detachedVertex.property("propsSquared").value("y")); assertEquals(2, StreamFactory.stream(detachedVertex.iterators().properties("name")).count()); assertTrue(StreamFactory.stream(detachedVertex.iterators().properties("name")).allMatch(p -> p.key().equals("name") && (p.value().equals("marko") || p.value().equals("mark")))); assertEquals(v1.hiddens("acl").value().next().toString(), detachedVertex.value(Graph.Key.hide("acl")).toString()); called.set(true); return mock(Vertex.class); }); } assertTrue(called.get()); } } @Test @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) public void shouldReadWriteVerticesNoEdgesToKryoManual() throws Exception { try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertices(os, g.V().has("age", T.gt, 30)); final AtomicInteger called = new AtomicInteger(0); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final VertexByteArrayInputStream vbais = new VertexByteArrayInputStream(new ByteArrayInputStream(os.toByteArray()))) { reader.readVertex(new ByteArrayInputStream(vbais.readVertexBytes().toByteArray()), detachedVertex -> { called.incrementAndGet(); return detachedVertex; }); reader.readVertex(new ByteArrayInputStream(vbais.readVertexBytes().toByteArray()), detachedVertex -> { called.incrementAndGet(); return detachedVertex; }); } assertEquals(2, called.get()); } } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldReadWriteVerticesNoEdgesToKryo() throws Exception { try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertices(os, g.V().has("age", T.gt, 30)); final AtomicInteger called = new AtomicInteger(0); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { final Iterator<Vertex> itty = reader.readVertices(bais, null, detachedVertex -> { called.incrementAndGet(); return detachedVertex; }, null); assertNotNull(itty.next()); assertNotNull(itty.next()); assertFalse(itty.hasNext()); } assertEquals(2, called.get()); } } @Test @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) public void shouldReadWriteVerticesNoEdgesToGraphSONManual() throws Exception { try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeVertices(os, g.V().has("age", T.gt, 30)); final AtomicInteger called = new AtomicInteger(0); final GraphSONReader reader = GraphSONReader.build().create(); final BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(os.toByteArray()))); String line = br.readLine(); reader.readVertex(new ByteArrayInputStream(line.getBytes()), detachedVertex -> { called.incrementAndGet(); return mock(Vertex.class); }); line = br.readLine(); reader.readVertex(new ByteArrayInputStream(line.getBytes()), detachedVertex -> { called.incrementAndGet(); return mock(Vertex.class); }); assertEquals(2, called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithOUTOUTEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e = v1.addEdge("friends", v2, "weight", 0.5d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1, Direction.OUT); final AtomicBoolean calledVertex = new AtomicBoolean(false); final AtomicBoolean calledEdge = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); // todo: add standard helper to always return Detached class try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.OUT, detachedVertex -> { assertEquals(v1.id(), detachedVertex.id()); assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals(v1.value("name"), detachedVertex.value("name").toString()); calledVertex.set(true); return detachedVertex; }, detachedEdge -> { assertEquals(e.id(), detachedEdge.id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, detachedEdge.value("weight"), 0.00001d); calledEdge.set(true); return detachedEdge; }); } assertTrue(calledVertex.get()); assertTrue(calledEdge.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithOUTOUTEdgesToGraphSON() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e = v1.addEdge("friends", v2, "weight", 0.5f); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeVertex(os, v1, Direction.OUT); final AtomicBoolean calledVertex = new AtomicBoolean(false); final AtomicBoolean calledEdge = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.OUT, detachedVertex -> { assertEquals(v1.id().toString(), detachedVertex.id().toString()); // lossy assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals("marko", detachedVertex.value("name")); calledVertex.set(true); return null; }, detachedEdge -> { assertEquals(e.id().toString(), detachedEdge.id().toString()); // lossy assertEquals(v1.id().toString(), detachedEdge.iterators().vertices(Direction.OUT).next().id().toString()); // lossy assertEquals(v2.id().toString(), detachedEdge.iterators().vertices(Direction.IN).next().id().toString()); // lossy assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, detachedEdge.value("weight"), 0.000001d); // lossy calledEdge.set(true); return null; }); } assertTrue(calledVertex.get()); assertTrue(calledEdge.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithININEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e = v2.addEdge("friends", v1, "weight", 0.5d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1, Direction.IN); final AtomicBoolean calledVertex = new AtomicBoolean(false); final AtomicBoolean calledEdge = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.IN, detachedVertex -> { assertEquals(v1.id(), detachedVertex.id()); assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals(v1.value("name"), detachedVertex.value("name").toString()); calledVertex.set(true); return detachedVertex; }, detachedEdge -> { assertEquals(e.id(), detachedEdge.id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, detachedEdge.value("weight"), 0.00001d); calledEdge.set(true); return detachedEdge; }); } assertTrue(calledVertex.get()); assertTrue(calledEdge.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithININEdgesToGraphSON() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e = v2.addEdge("friends", v1, "weight", 0.5f); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeVertex(os, v1, Direction.IN); os.close(); final AtomicBoolean calledVertex = new AtomicBoolean(false); final AtomicBoolean calledEdge = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.IN, detachedVertex -> { assertEquals(v1.id().toString(), detachedVertex.id().toString()); // lossy assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals("marko", detachedVertex.value("name")); calledVertex.set(true); return null; }, detachedEdge -> { assertEquals(e.id().toString(), detachedEdge.id().toString()); // lossy assertEquals(v1.id().toString(), detachedEdge.iterators().vertices(Direction.IN).next().id().toString()); // lossy assertEquals(v2.id().toString(), detachedEdge.iterators().vertices(Direction.OUT).next().id().toString()); // lossy assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, detachedEdge.value("weight"), 0.000001d); // lossy calledEdge.set(true); return null; }); } assertTrue(calledVertex.get()); assertTrue(calledEdge.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithBOTHBOTHEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e1 = v2.addEdge("friends", v1, "weight", 0.5d); final Edge e2 = v1.addEdge("friends", v2, "weight", 1.0d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1, Direction.BOTH); final AtomicBoolean calledVertex = new AtomicBoolean(false); final AtomicBoolean calledEdge1 = new AtomicBoolean(false); final AtomicBoolean calledEdge2 = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.BOTH, detachedVertex -> { assertEquals(v1.id(), detachedVertex.id()); assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals(v1.value("name"), detachedVertex.value("name").toString()); calledVertex.set(true); return detachedVertex; }, detachedEdge -> { if (detachedEdge.id().equals(e1.id())) { assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e1.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, detachedEdge.value("weight"), 0.00001d); calledEdge1.set(true); } else if (detachedEdge.id().equals(e2.id())) { assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e1.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(1.0d, detachedEdge.value("weight"), 0.00001d); calledEdge2.set(true); } else { fail("An edge id generated that does not exist"); } return null; }); } assertTrue(calledVertex.get()); assertTrue(calledEdge1.get()); assertTrue(calledEdge2.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithBOTHBOTHEdgesToGraphSON() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e1 = v2.addEdge("friends", v1, "weight", 0.5f); final Edge e2 = v1.addEdge("friends", v2, "weight", 1.0f); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeVertex(os, v1, Direction.BOTH); final AtomicBoolean vertexCalled = new AtomicBoolean(false); final AtomicBoolean edge1Called = new AtomicBoolean(false); final AtomicBoolean edge2Called = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.BOTH,detachedVertex -> { assertEquals(v1.id().toString(), detachedVertex.id().toString()); // lossy assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals("marko", detachedVertex.value("name")); vertexCalled.set(true); return null; }, detachedEdge -> { if (detachedEdge.id().toString().equals(e1.id().toString())) { // lossy assertEquals(e1.id().toString(), detachedEdge.id().toString()); // lossy assertEquals(v1.id().toString(), detachedEdge.iterators().vertices(Direction.IN).next().id().toString()); // lossy assertEquals(v2.id().toString(), detachedEdge.iterators().vertices(Direction.OUT).next().id().toString()); // lossy assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e1.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, detachedEdge.value("weight"), 0.000001d); // lossy edge1Called.set(true); } else if (detachedEdge.id().toString().equals(e2.id().toString())) { // lossy assertEquals(e2.id().toString(), detachedEdge.id().toString()); // lossy assertEquals(v2.id().toString(), detachedEdge.iterators().vertices(Direction.IN).next().id().toString()); // lossy assertEquals(v1.id().toString(), detachedEdge.iterators().vertices(Direction.OUT).next().id().toString()); // lossy assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e2.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(1.0d, detachedEdge.value("weight"), 0.000001d); // lossy edge2Called.set(true); } else { fail("An edge id generated that does not exist"); } return null; }); } assertTrue(vertexCalled.get()); assertTrue(edge1Called.get()); assertTrue(edge2Called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithBOTHBOTHEdgesToGraphSONWithTypes() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e1 = v2.addEdge("friends", v1, "weight", 0.5f); final Edge e2 = v1.addEdge("friends", v2, "weight", 1.0f); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().embedTypes(true).create(); writer.writeVertex(os, v1, Direction.BOTH); final AtomicBoolean vertexCalled = new AtomicBoolean(false); final AtomicBoolean edge1Called = new AtomicBoolean(false); final AtomicBoolean edge2Called = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build().embedTypes(true).create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.BOTH, detachedVertex -> { assertEquals(v1.id(), detachedVertex.id()); assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals(v1.value("name"), detachedVertex.value("name").toString()); vertexCalled.set(true); return null; }, detachedEdge -> { if (detachedEdge.id().equals(e1.id())) { assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e1.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5f, detachedEdge.value("weight"), 0.00001f); edge1Called.set(true); } else if (detachedEdge.id().equals(e2.id())) { assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e1.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(1.0f, detachedEdge.value("weight"), 0.00001f); edge2Called.set(true); } else { fail("An edge id generated that does not exist"); } return null; }); } assertTrue(vertexCalled.get()); assertTrue(edge1Called.get()); assertTrue(edge2Called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithBOTHINEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e1 = v2.addEdge("friends", v1, "weight", 0.5d); v1.addEdge("friends", v2, "weight", 1.0d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1, Direction.BOTH); final AtomicBoolean vertexCalled = new AtomicBoolean(false); final AtomicBoolean edge1Called = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.IN, detachedVertex -> { assertEquals(v1.id(), detachedVertex.id()); assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals(v1.value("name"), detachedVertex.value("name").toString()); vertexCalled.set(true); return detachedVertex; }, detachedEdge -> { if (detachedEdge.id().equals(e1.id())) { assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e1.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, detachedEdge.value("weight"), 0.00001d); edge1Called.set(true); } else { fail("An edge id generated that does not exist"); } return null; }); } assertTrue(vertexCalled.get()); assertTrue(edge1Called.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithBOTHINEdgesToGraphSON() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); final Edge e1 = v2.addEdge("friends", v1, "weight", 0.5f); v1.addEdge("friends", v2, "weight", 1.0f); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeVertex(os, v1, Direction.BOTH); final AtomicBoolean vertexCalled = new AtomicBoolean(false); final AtomicBoolean edgeCalled = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.IN, detachedVertex -> { assertEquals(v1.id().toString(), detachedVertex.id().toString()); // lossy assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals("marko", detachedVertex.value("name")); vertexCalled.set(true); return null; }, detachedEdge -> { if (detachedEdge.id().toString().equals(e1.id().toString())) { // lossy assertEquals(e1.id().toString(), detachedEdge.id().toString()); // lossy assertEquals(v1.id().toString(), detachedEdge.iterators().vertices(Direction.IN).next().id().toString()); // lossy assertEquals(v2.id().toString(), detachedEdge.iterators().vertices(Direction.OUT).next().id().toString()); // lossy assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e1.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(0.5d, detachedEdge.value("weight"), 0.000001d); // lossy edgeCalled.set(true); } else { fail("An edge id generated that does not exist"); } return null; }); } assertTrue(edgeCalled.get()); assertTrue(vertexCalled.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithBOTHOUTEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); v2.addEdge("friends", v1, "weight", 0.5d); final Edge e2 = v1.addEdge("friends", v2, "weight", 1.0d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1, Direction.BOTH); final AtomicBoolean vertexCalled = new AtomicBoolean(false); final AtomicBoolean edgeCalled = new AtomicBoolean(false); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais,Direction.OUT,detachedVertex -> { assertEquals(v1.id(), detachedVertex.id()); assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals(v1.value("name"), detachedVertex.value("name").toString()); vertexCalled.set(true); return detachedVertex; }, detachedEdge -> { if (detachedEdge.id().equals(e2.id())) { assertEquals(v1.id(), detachedEdge.iterators().vertices(Direction.OUT).next().id()); assertEquals(v2.id(), detachedEdge.iterators().vertices(Direction.IN).next().id()); assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e2.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(1.0d, detachedEdge.value("weight"), 0.00001d); edgeCalled.set(true); } else { fail("An edge id generated that does not exist"); } return null; }); } assertTrue(vertexCalled.get()); assertTrue(edgeCalled.get()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithBOTHOUTEdgesToGraphSON() throws Exception { final Vertex v1 = g.addVertex("name", "marko", T.label, "person"); final Vertex v2 = g.addVertex(T.label, "person"); v2.addEdge("friends", v1, "weight", 0.5f); final Edge e2 = v1.addEdge("friends", v2, "weight", 1.0f); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final GraphSONWriter writer = GraphSONWriter.build().create(); writer.writeVertex(os, v1, Direction.BOTH); final AtomicBoolean vertexCalled = new AtomicBoolean(false); final AtomicBoolean edgeCalled = new AtomicBoolean(false); final GraphSONReader reader = GraphSONReader.build().create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.OUT, detachedVertex -> { assertEquals(v1.id().toString(), detachedVertex.id().toString()); // lossy assertEquals(v1.label(), detachedVertex.label()); assertEquals(0, StreamFactory.stream(detachedVertex.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedVertex.iterators().properties()).count()); assertEquals("marko", detachedVertex.value("name")); vertexCalled.set(true); return null; }, detachedEdge -> { if (detachedEdge.id().toString().equals(e2.id().toString())) { // lossy assertEquals(e2.id().toString(), detachedEdge.id().toString()); // lossy assertEquals(v2.id().toString(), detachedEdge.iterators().vertices(Direction.IN).next().id().toString()); // lossy assertEquals(v1.id().toString(), detachedEdge.iterators().vertices(Direction.OUT).next().id().toString()); // lossy assertEquals(v1.label(), detachedEdge.iterators().vertices(Direction.OUT).next().label()); assertEquals(v2.label(), detachedEdge.iterators().vertices(Direction.IN).next().label()); assertEquals(e2.label(), detachedEdge.label()); assertEquals(0, StreamFactory.stream(detachedEdge.iterators().hiddens()).count()); assertEquals(1, StreamFactory.stream(detachedEdge.iterators().properties()).count()); assertEquals(1.0d, detachedEdge.value("weight"), 0.000001d); // lossy edgeCalled.set(true); } else { fail("An edge id generated that does not exist"); } return null; }); } assertTrue(edgeCalled.get()); assertTrue(vertexCalled.get()); } } @Test(expected = IllegalStateException.class) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithOUTBOTHEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko"); final Vertex v2 = g.addVertex(); v1.addEdge("friends", v2, "weight", 0.5d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1, Direction.OUT); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.BOTH, detachedVertex -> null, detachedEdge -> null); } } } @Test(expected = IllegalStateException.class) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithINBOTHEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko"); final Vertex v2 = g.addVertex(); v2.addEdge("friends", v1, "weight", 0.5d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1, Direction.IN); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.BOTH, detachedVertex -> null, detachedEdge -> null); } } } @Test(expected = IllegalStateException.class) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithINOUTEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko"); final Vertex v2 = g.addVertex(); v2.addEdge("friends", v1, "weight", 0.5d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1, Direction.IN); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.OUT, detachedVertex -> null, detachedEdge -> null); } } } @Test(expected = IllegalStateException.class) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_DOUBLE_VALUES) public void shouldReadWriteVertexWithOUTINEdgesToKryo() throws Exception { final Vertex v1 = g.addVertex("name", "marko"); final Vertex v2 = g.addVertex(); v1.addEdge("friends", v2, "weight", 0.5d); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { final KryoWriter writer = KryoWriter.build().create(); writer.writeVertex(os, v1, Direction.IN); final KryoReader reader = KryoReader.build() .setWorkingDirectory(File.separator + "tmp").create(); try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { reader.readVertex(bais, Direction.OUT, detachedVertex -> null, detachedEdge -> null); } } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES) @FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES) public void shouldReadLegacyGraphSON() throws IOException { final GraphReader reader = LegacyGraphSONReader.build().build(); try (final InputStream stream = IoTest.class.getResourceAsStream(GRAPHSON_RESOURCE_PATH_PREFIX + "tinkerpop-classic-legacy.json")) { reader.readGraph(stream, g); } // the id is lossy in migration because TP2 treated ID as String assertToyGraph(g, false, true, false); } public static void assertToyGraph(final Graph g1, final boolean assertDouble, final boolean lossyForId, final boolean assertSpecificLabel) { assertEquals(new Long(6), g1.V().count().next()); assertEquals(new Long(6), g1.E().count().next()); final Vertex v1 = (Vertex) g1.V().has("name", "marko").next(); assertEquals(29, v1.<Integer>value("age").intValue()); assertEquals(2, v1.keys().size()); assertEquals(assertSpecificLabel ? "person" : Vertex.DEFAULT_LABEL, v1.label()); assertId(g1, lossyForId, v1, 1); final List<Edge> v1Edges = v1.bothE().toList(); assertEquals(3, v1Edges.size()); v1Edges.forEach(e -> { if (e.inV().value("name").next().equals("vadas")) { assertEquals("knows", e.label()); if (assertDouble) assertEquals(0.5d, e.value("weight"), 0.0001d); else assertEquals(0.5f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 7); } else if (e.inV().value("name").next().equals("josh")) { assertEquals("knows", e.label()); if (assertDouble) assertEquals(1.0, e.value("weight"), 0.0001d); else assertEquals(1.0f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 8); } else if (e.inV().value("name").next().equals("lop")) { assertEquals("created", e.label()); if (assertDouble) assertEquals(0.4d, e.value("weight"), 0.0001d); else assertEquals(0.4f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 9); } else { fail("Edge not expected"); } }); final Vertex v2 = (Vertex) g1.V().has("name", "vadas").next(); assertEquals(27, v2.<Integer>value("age").intValue()); assertEquals(2, v2.keys().size()); assertEquals(assertSpecificLabel ? "person" : Vertex.DEFAULT_LABEL, v2.label()); assertId(g1, lossyForId, v2, 2); final List<Edge> v2Edges = v2.bothE().toList(); assertEquals(1, v2Edges.size()); v2Edges.forEach(e -> { if (e.outV().value("name").next().equals("marko")) { assertEquals("knows", e.label()); if (assertDouble) assertEquals(0.5d, e.value("weight"), 0.0001d); else assertEquals(0.5f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 7); } else { fail("Edge not expected"); } }); final Vertex v3 = (Vertex) g1.V().has("name", "lop").next(); assertEquals("java", v3.<String>value("lang")); assertEquals(2, v2.keys().size()); assertEquals(assertSpecificLabel ? "software" : Vertex.DEFAULT_LABEL, v3.label()); assertId(g1, lossyForId, v3, 3); final List<Edge> v3Edges = v3.bothE().toList(); assertEquals(3, v3Edges.size()); v3Edges.forEach(e -> { if (e.outV().value("name").next().equals("peter")) { assertEquals("created", e.label()); if (assertDouble) assertEquals(0.2d, e.value("weight"), 0.0001d); else assertEquals(0.2f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 12); } else if (e.outV().next().value("name").equals("josh")) { assertEquals("created", e.label()); if (assertDouble) assertEquals(0.4d, e.value("weight"), 0.0001d); else assertEquals(0.4f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 11); } else if (e.outV().value("name").next().equals("marko")) { assertEquals("created", e.label()); if (assertDouble) assertEquals(0.4d, e.value("weight"), 0.0001d); else assertEquals(0.4f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 9); } else { fail("Edge not expected"); } }); final Vertex v4 = (Vertex) g1.V().has("name", "josh").next(); assertEquals(32, v4.<Integer>value("age").intValue()); assertEquals(2, v4.keys().size()); assertEquals(assertSpecificLabel ? "person" : Vertex.DEFAULT_LABEL, v4.label()); assertId(g1, lossyForId, v4, 4); final List<Edge> v4Edges = v4.bothE().toList(); assertEquals(3, v4Edges.size()); v4Edges.forEach(e -> { if (e.inV().value("name").next().equals("ripple")) { assertEquals("created", e.label()); if (assertDouble) assertEquals(1.0d, e.value("weight"), 0.0001d); else assertEquals(1.0f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 10); } else if (e.inV().value("name").next().equals("lop")) { assertEquals("created", e.label()); if (assertDouble) assertEquals(0.4d, e.value("weight"), 0.0001d); else assertEquals(0.4f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 11); } else if (e.outV().value("name").next().equals("marko")) { assertEquals("knows", e.label()); if (assertDouble) assertEquals(1.0d, e.value("weight"), 0.0001d); else assertEquals(1.0f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 8); } else { fail("Edge not expected"); } }); final Vertex v5 = (Vertex) g1.V().has("name", "ripple").next(); assertEquals("java", v5.<String>value("lang")); assertEquals(2, v5.keys().size()); assertEquals(assertSpecificLabel ? "software" : Vertex.DEFAULT_LABEL, v5.label()); assertId(g1, lossyForId, v5, 5); final List<Edge> v5Edges = v5.bothE().toList(); assertEquals(1, v5Edges.size()); v5Edges.forEach(e -> { if (e.outV().value("name").next().equals("josh")) { assertEquals("created", e.label()); if (assertDouble) assertEquals(1.0d, e.value("weight"), 0.0001d); else assertEquals(1.0f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 10); } else { fail("Edge not expected"); } }); final Vertex v6 = (Vertex) g1.V().has("name", "peter").next(); assertEquals(35, v6.<Integer>value("age").intValue()); assertEquals(2, v6.keys().size()); assertEquals(assertSpecificLabel ? "person" : Vertex.DEFAULT_LABEL, v6.label()); assertId(g1, lossyForId, v6, 6); final List<Edge> v6Edges = v6.bothE().toList(); assertEquals(1, v6Edges.size()); v6Edges.forEach(e -> { if (e.inV().value("name").next().equals("lop")) { assertEquals("created", e.label()); if (assertDouble) assertEquals(0.2d, e.value("weight"), 0.0001d); else assertEquals(0.2f, e.value("weight"), 0.0001f); assertEquals(1, e.keys().size()); assertId(g1, lossyForId, e, 12); } else { fail("Edge not expected"); } }); } private static void assertId(final Graph g, final boolean lossyForId, final Element e, final Object expected) { if (g.features().edge().supportsUserSuppliedIds()) { if (lossyForId) assertEquals(expected.toString(), e.id().toString()); else assertEquals(expected, e.id()); } } private void validateXmlAgainstGraphMLXsd(final File file) throws Exception { final Source xmlFile = new StreamSource(file); final SchemaFactory schemaFactory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory.newSchema(IoTest.class.getResource(GRAPHML_RESOURCE_PATH_PREFIX + "graphml-1.1.xsd")); final Validator validator = schema.newValidator(); validator.validate(xmlFile); } private static void readGraphMLIntoGraph(final Graph g) throws IOException { final GraphReader reader = GraphMLReader.build().create(); try (final InputStream stream = IoTest.class.getResourceAsStream(GRAPHML_RESOURCE_PATH_PREFIX + "tinkerpop-classic.xml")) { reader.readGraph(stream, g); } } private String streamToString(final InputStream in) throws IOException { final Writer writer = new StringWriter(); final char[] buffer = new char[1024]; try (final Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"))) { int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } return writer.toString(); } public static class CustomId { private String cluster; private UUID elementId; private CustomId() { // required no-arg for kryo serialization } public CustomId(final String cluster, final UUID elementId) { this.cluster = cluster; this.elementId = elementId; } public String getCluster() { return cluster; } public UUID getElementId() { return elementId; } static class CustomIdJacksonSerializer extends StdSerializer<CustomId> { public CustomIdJacksonSerializer() { super(CustomId.class); } @Override public void serialize(final CustomId customId, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException, JsonGenerationException { ser(customId, jsonGenerator, false); } @Override public void serializeWithType(final CustomId customId, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider, final TypeSerializer typeSerializer) throws IOException, JsonProcessingException { ser(customId, jsonGenerator, true); } private void ser(final CustomId customId, final JsonGenerator jsonGenerator, final boolean includeType) throws IOException { jsonGenerator.writeStartObject(); if (includeType) jsonGenerator.writeStringField(GraphSONTokens.CLASS, CustomId.class.getName()); jsonGenerator.writeObjectField("cluster", customId.getCluster()); jsonGenerator.writeObjectField("elementId", customId.getElementId().toString()); jsonGenerator.writeEndObject(); } } static class CustomIdJacksonDeserializer extends StdDeserializer<CustomId> { public CustomIdJacksonDeserializer() { super(CustomId.class); } @Override public CustomId deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException { String cluster = null; UUID id = null; while (!jsonParser.getCurrentToken().isStructEnd()) { if (jsonParser.getText().equals("cluster")) { jsonParser.nextToken(); cluster = jsonParser.getText(); } else if (jsonParser.getText().equals("elementId")) { jsonParser.nextToken(); id = UUID.fromString(jsonParser.getText()); } else jsonParser.nextToken(); } if (!Optional.ofNullable(cluster).isPresent()) throw deserializationContext.mappingException("Could not deserialze CustomId: 'cluster' is required"); if (!Optional.ofNullable(id).isPresent()) throw deserializationContext.mappingException("Could not deserialze CustomId: 'id' is required"); return new CustomId(cluster, id); } } } }
package soot.jimple.infoflow.taintWrappers; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Value; import soot.jimple.AssignStmt; import soot.jimple.InstanceInvokeExpr; import soot.jimple.StaticInvokeExpr; import soot.jimple.Stmt; import soot.jimple.infoflow.data.AccessPath; import soot.jimple.infoflow.util.SootMethodRepresentationParser; import soot.jimple.internal.JAssignStmt; /** * A list of methods is passed which contains signatures of instance methods * that taint their base objects if they are called with a tainted parameter. * When a base object is tainted, all return values are tainted, too. * For static methods, only the return value is assumed to be tainted when * the method is called with a tainted parameter value. * * @author Christian Fritz, Steven Arzt * */ public class EasyTaintWrapper implements ITaintPropagationWrapper { private final Map<String, List<String>> classList; private final Map<String, List<String>> excludeList; private final Map<String, List<String>> killList; public EasyTaintWrapper(HashMap<String, List<String>> classList){ this.classList = classList; this.excludeList = new HashMap<String, List<String>>(); this.killList = new HashMap<String, List<String>>(); } public EasyTaintWrapper(HashMap<String, List<String>> classList, HashMap<String, List<String>> excludeList) { this.classList = classList; this.excludeList = excludeList; this.killList = new HashMap<String, List<String>>(); } public EasyTaintWrapper(HashMap<String, List<String>> classList, HashMap<String, List<String>> excludeList, HashMap<String, List<String>> killList) { this.classList = classList; this.excludeList = excludeList; this.killList = killList; } public EasyTaintWrapper(File f) throws IOException{ BufferedReader reader = null; try{ FileReader freader = new FileReader(f); reader = new BufferedReader(freader); String line = reader.readLine(); List<String> methodList = new LinkedList<String>(); List<String> excludeList = new LinkedList<String>(); List<String> killList = new LinkedList<String>(); while(line != null){ if (!line.isEmpty() && !line.startsWith("%")) if (line.startsWith("~")) excludeList.add(line.substring(1)); else if (line.startsWith("-")) killList.add(line.substring(1)); else methodList.add(line); line = reader.readLine(); } this.classList = SootMethodRepresentationParser.v().parseClassNames(methodList, true); this.excludeList = SootMethodRepresentationParser.v().parseClassNames(excludeList, true); this.killList = SootMethodRepresentationParser.v().parseClassNames(killList, true); System.out.println("Loaded wrapper entries for " + classList.size() + " classes " + "and " + excludeList.size() + " exclusions."); } finally { if (reader != null) reader.close(); } } @Override public Set<AccessPath> getTaintsForMethod(Stmt stmt, AccessPath taintedPath) { if (!stmt.containsInvokeExpr()) return Collections.emptySet(); Set<AccessPath> taints = new HashSet<AccessPath>(); if (stmt.getInvokeExpr() instanceof InstanceInvokeExpr) { InstanceInvokeExpr iiExpr = (InstanceInvokeExpr) stmt.getInvokeExpr(); if (iiExpr.getBase().equals(taintedPath.getPlainValue())) { // If the base object is tainted, we have to check whether we must kill the taint List<String> killMethods = this.killList.get(stmt.getInvokeExpr().getMethod().getDeclaringClass().getName()); if (killMethods != null && killMethods.contains(stmt.getInvokeExpr().getMethod().getSubSignature())) return Collections.emptySet(); // If the base object is tainted, all calls to its methods always return // tainted values if (stmt instanceof JAssignStmt) { AssignStmt assign = (AssignStmt) stmt; // Check for exclusions List<String> excludedMethods = this.excludeList.get(assign.getInvokeExpr().getMethod().getDeclaringClass().getName()); if (excludedMethods == null || !excludedMethods.contains (assign.getInvokeExpr().getMethod().getSubSignature())) taints.add(new AccessPath(assign.getLeftOp())); } // If the base object is tainted, we pass this taint on taints.add(taintedPath); } } //if param is tainted && classList contains classname && if list. contains signature of method -> add propagation for (Value param : stmt.getInvokeExpr().getArgs()) if (param.equals(taintedPath.getPlainValue())) { SootMethod method = stmt.getInvokeExpr().getMethod(); List<String> methodList = getMethodsForClass(method.getDeclaringClass()); if(methodList.contains(method.getSubSignature())) { // If we call a method on an instance, this instance is assumed to be tainted if(stmt.getInvokeExprBox().getValue() instanceof InstanceInvokeExpr) { taints.add(new AccessPath(((InstanceInvokeExpr) stmt.getInvokeExprBox().getValue()).getBase())); // If make sure to also taint the left side of an assignment // if the object just got tainted if(stmt instanceof JAssignStmt) taints.add(new AccessPath(((JAssignStmt)stmt).getLeftOp())); } else if (stmt.getInvokeExprBox().getValue() instanceof StaticInvokeExpr) if (stmt instanceof JAssignStmt) taints.add(new AccessPath(((JAssignStmt)stmt).getLeftOp())); } // The parameter as such stays tainted taints.add(taintedPath); } return taints; } private List<String> getMethodsForClass(SootClass c){ List<String> methodList = new LinkedList<String>(); if(classList.containsKey(c.getName())){ methodList.addAll(classList.get(c.getName())); } if(!c.isInterface()) { // We have to walk up the hierarchy to also include all methods // registered for superclasses List<SootClass> superclasses = Scene.v().getActiveHierarchy().getSuperclassesOf(c); for(SootClass sclass : superclasses){ if(classList.containsKey(sclass.getName())) methodList.addAll(getMethodsForClass(sclass)); } } // If we implement interfaces, we also need to check whether they in // turn are in our method list for (SootClass ifc : c.getInterfaces()) methodList.addAll(getMethodsForClass(ifc)); return methodList; } @Override public boolean isExclusive(Stmt stmt, AccessPath taintedPath) { SootMethod method = stmt.getInvokeExpr().getMethod(); return !getMethodsForClass(method.getDeclaringClass()).isEmpty(); } }
package io.github.ihongs.serv.matrix; import io.github.ihongs.Cnst; import io.github.ihongs.Core; import io.github.ihongs.HongsException; import io.github.ihongs.HongsExemption; import io.github.ihongs.action.FormSet; import io.github.ihongs.db.DB; import io.github.ihongs.db.Model; import io.github.ihongs.db.Table; import io.github.ihongs.dh.search.SearchEntity; import io.github.ihongs.util.Synt; import io.github.ihongs.util.Tool; import java.io.File; import java.util.Collection; import java.util.LinkedHashMap; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.lucene.document.Document; /** * * @author Hongs */ public class Data extends SearchEntity { protected final String comf; protected final String conf; protected final String form; protected long time = 0; /** * * @param conf * @param form * @param comf * @param path * @param name */ protected Data(String conf, String form, String comf, String path, String name) { super(null, path, name); this.comf = comf; this.conf = conf; this.form = form; } /** * * @param conf * @param form */ public Data(String conf, String form) { this( conf , form , conf.replaceFirst("^(centre)/", "centra/") , conf.replaceFirst("^(centre|centra)/", "") , conf+"."+form ); } /** * * Core * @param conf * @param form * @return */ public static Data getInstance(String conf, String form) { Data inst; Core core = Core.getInstance(); String name = Data.class.getName() +":"+ conf +":"+ form; if (core.containsKey(name)) { inst = (Data) core.got(name); } else { inst = new Data( conf, form); core.put ( name, inst); } return inst; } /** * * * * 0x1104 * @return */ @Override public Map getFields() { try { return super.getFields(); } catch (NullPointerException ex) { // Nothing todo } Map fields, fieldx; /** * centra/data * centre/data * * * */ try { if (! new File( Core.CONF_PATH + "/"+ conf + Cnst.FORM_EXT +".xml" ).exists()) { throw new HongsExemption(0x1104, "Data form conf '" + conf + "' is not exists") .setLocalizedOptions(conf); } fields = FormSet.getInstance(conf).getForm(form); if (! comf.equals(conf)) { if (! new File( Core.CONF_PATH + "/"+ comf + Cnst.FORM_EXT +".xml" ).exists()) { throw new HongsExemption(0x1104, "Data form conf '" + comf + "' is not exists") .setLocalizedOptions(comf); } fieldx = FormSet.getInstance(comf).getForm(form); fieldx = new LinkedHashMap(fieldx); fieldx.putAll( fields ); fields = fieldx; } } catch (HongsException ex) { throw ex.toExemption( ); } setFields(fields); return fields; } public String getFormId() { return Synt.declare(getParams().get("form_id"), form ); } public Model getModel() throws HongsException { String tn = Synt.declare(getParams().get("db-table"), "matrix.data"); if ("".equals(tn) || "none".equals(tn)) { return null; } return DB.getInstance("matrix").getModel(tn); } public Table getTable() throws HongsException { String tn = Synt.declare(getParams().get("db-table"), "matrix.data"); if ("".equals(tn) || "none".equals(tn)) { return null; } return DB.getInstance("matrix").getTable(tn); } /** * * @param rd * @return id,name(dispCols) * @throws HongsException */ @Override public Map create(Map rd) throws HongsException { long ct = System.currentTimeMillis() / 1000; rd.put("_time" , ct); String id = Core.newIdentity(); save ( id , rd ); call ( id , "create", ct); Set<String> fs = getListable(); if (null != fs && ! fs.isEmpty( )) { Map sd = new LinkedHashMap( ); for(String fn : fs) { if ( ! fn.contains( "." )) { sd.put( fn, rd.get(fn) ); } } sd.put(Cnst.ID_KEY, id); return sd; } else { rd.put(Cnst.ID_KEY, id); return rd; } } /** * * @param rd * @return * @throws HongsException */ @Override public int update(Map rd) throws HongsException { long ct = System.currentTimeMillis() / 1000; rd.put("_time" , ct); Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet()); permit (rd, ids , 0x1096); for(String id : ids) { save(id, rd ); call(id, "update", ct); } return ids.size(); } /** * * @param rd * @return * @throws HongsException */ @Override public int delete(Map rd) throws HongsException { long ct = System.currentTimeMillis() / 1000; rd.put("_time" , ct); Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet()); permit (rd, ids , 0x1097); for(String id : ids) { drop(id, rd ); call(id, "delete", ct); } return ids.size(); } public void save(String id, Map rd) throws HongsException { Table table = getTable( ); String fid = getFormId(); String uid = (String) rd.get( "user_id" ); String where = "`id`=? AND `form_id`=? AND `etime`=?"; Object[] param = new String [ ] { id , fid , "0"}; long ctime = Synt.declare(rd.get("_time"), 0L); if (0 == ctime) ctime = System.currentTimeMillis()/1000; Map dd = get( id ); if (! dd.isEmpty()) { if (table != null) { Map od = table.fetchCase() .filter( where, param) .select("ctime") .getOne( ); if (! od.isEmpty( )) { if ( Synt.declare ( od.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } } } } else { if (table != null) { Map od = table.fetchCase() .filter( where, param) .select("ctime, data") .getOne(); if (! od.isEmpty( )) { if ( Synt.declare ( od.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } dd = (Map) io.github.ihongs.util.Data.toObject(od.get("data").toString()); } } } int i = 0; Map<String,Map> fields = getFields(); for(String fn : fields.keySet()) { if ( "id". equals(fn)) { dd.put(fn , id); } else if (rd.containsKey(fn)) { Object fr = Synt.defoult(rd.get(fn), ""); Object fo = Synt.defoult(dd.get(fn), ""); dd.put(fn , fr); if (!equals(fr,fo) && !fn.equals("muser" ) && !fn.equals("mtime")) { i ++; } } } if (i == 0) { return; } dd.put("name", getName(dd)); dd.put("word", getWord(dd)); / if (table != null) { Map ud = new HashMap(); ud.put("etime", ctime); Map nd = new HashMap(); nd.put("ctime", ctime); nd.put("etime", 0 ); nd.put("id", id ); nd.put("form_id", fid); nd.put("user_id", uid); nd.put("memo", rd.get("memo")); nd.put("name", dd.get("name")); nd.put("data", io.github.ihongs.util.Data.toString(dd)); table.update(ud, where, param); table.insert(nd); } / Document doc = new Document(); dd.put(Cnst.ID_KEY, id); docAdd(doc, dd); setDoc(id, doc); } public void drop(String id, Map rd) throws HongsException { Table table = getTable( ); String fid = getFormId(); String uid = (String) rd.get( "user_id" ); String where = "`id`=? AND `form_id`=? AND `etime`=?"; Object[] param = new String [ ] { id , fid , "0"}; long ctime = Synt.declare(rd.get("_time"), 0L); if (0 == ctime) ctime = System.currentTimeMillis()/1000; if (table != null) { Map dd = table.fetchCase() .filter( where, param) .select("ctime, state, data, name") .getOne( ); if (dd.isEmpty()) { delDoc( id ); return; // throw new HongsException(0x1104, ""); } if ( Synt.declare ( dd.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } Map ud = new HashMap(); ud.put("etime", ctime); Map nd = new HashMap(); nd.put("ctime", ctime); nd.put("etime", 0 ); ud.put("state", 0 ); nd.put("id", id ); nd.put("form_id", fid); nd.put("user_id", uid); nd.put("memo", rd.get("memo")); nd.put("name", dd.get("name")); nd.put("data", dd.get("data")); table.update(ud, where, param); table.insert(nd); } / delDoc(id); } public void redo(String id, Map rd) throws HongsException { Table table = getTable( ); String fid = getFormId(); String uid = (String) rd.get( "user_id" ); String where = "`id`=? AND `form_id`=? AND `ctime`=?"; long rtime = Synt.declare(rd.get("rtime"), 0L); long ctime = Synt.declare(rd.get("ctime"), 0L); Object[] param = new Object [ ] { id, fid, rtime }; if (0 == ctime) ctime = System.currentTimeMillis()/1000; / if (table == null) { throw new HongsException(0x1100, ""); } Map dd = table.fetchCase() .filter( where, param) .select("etime, state, data, name") .getOne( ); if (dd.isEmpty()) { throw new HongsException(0x1100, ""); } if ( Synt.declare ( dd.get("etime"), 0L ) == 0L ) { throw new HongsException(0x1100, ""); } if ( Synt.declare ( dd.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } / Map ud = new HashMap(); ud.put("etime", ctime); rd.put("ctime", ctime); rd.put("rtime", rtime); rd.put("etime", 0 ); rd.put("form_id", fid); rd.put("user_id", uid); rd.put("name" , dd.get("name")); rd.put("data" , dd.get("data")); where = "`id`=? AND `form_id`=? AND `etime`=?"; param = new Object[]{id, fid,0}; table.update(ud , where, param); table.insert(rd); / dd = (Map) io.github.ihongs.util.Data.toObject(dd.get("data").toString()); Document doc = new Document( ); dd.put(Cnst.ID_KEY, id); docAdd(doc, dd); setDoc(id, doc); } public void call(String id, String act, long now) throws HongsException { String url = (String) getParams().get("callback"); if (url == null || "".equals(url)) { return; } String fid = getFormId(); url = Tool.inject(url,Synt.mapOf( "id" , id , "action", act, "entity", fid, "time" , now )); DataCaller.getInstance().add(url); } protected boolean equals(Object fo, Object fr) { return fo.equals(fr); } private Set<String> wdCols = null; private Set<String> nmCols = null; @Override public Set<String> getSrchable() { if (null != wdCols) { return wdCols; } Map fs = (Map) getFields().get("word"); if (fs != null && !Synt.declare(fs.get("readonly"), false)) { wdCols = Synt.setOf ( "word" ); } else { wdCols = getCaseNames("srchable"); wdCols.remove("word"); } return wdCols; } public Set<String> getNameable() { if (null != nmCols) { return nmCols; } Map fs = (Map) getFields().get("name"); if (fs != null && !Synt.declare(fs.get("readonly"), false)) { nmCols = Synt.setOf ( "name" ); } else { nmCols = getCaseNames("nameable"); nmCols.remove("name"); } return nmCols; } /** * * @param dd * @return * @throws HongsException */ protected String getWord(Map dd) throws HongsException { StringBuilder nn = new StringBuilder(); Set < String> ns = getSrchable( ); for ( String fn : ns ) { Object fv = dd.get(fn); if (fv == null) continue ; if (fv instanceof Collection) for (Object fw : (Collection) fv ) { nn.append(fw).append(' '); } else { nn.append(fv).append(' '); } } String nm = nn.toString().trim( ); if (! ns.contains("word") && ! ns.contains("id") ) { return dd.get("id") +" "+ nm ; } else { return nm; } } /** * * @param dd * @return * @throws HongsException */ protected String getName(Map dd) throws HongsException { StringBuilder nn = new StringBuilder(); Set < String> ns = getNameable( ); for ( String fn : ns ) { Object fv = dd.get(fn); if (fv == null) continue ; if (fv instanceof Collection) for (Object fw : (Collection) fv ) { nn.append(fw).append(' '); } else { nn.append(fv).append(' '); } } String nm = nn.toString().trim( ); if (! ns.contains("name") && 99 < nm.length( ) ) { return nm.substring(0, 99) + "..."; } else { return nm; } } }
package org.ibase4j.core.base; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.shiro.authz.UnauthorizedException; import org.ibase4j.core.Constants; import org.ibase4j.core.exception.BaseException; import org.ibase4j.core.exception.IllegalParameterException; import org.ibase4j.core.support.HttpCode; import org.ibase4j.core.util.InstanceUtil; import org.ibase4j.core.util.WebUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ExceptionHandler; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.baomidou.mybatisplus.plugins.Page; /** * * * @author ShenHuaJie * @version 2016520 3:47:58 */ public abstract class BaseController { protected final Logger logger = LogManager.getLogger(this.getClass()); @Autowired protected BaseProvider provider; protected Long getCurrUser() { return WebUtil.getCurrentUser(); } protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap) { return setSuccessModelMap(modelMap, null); } protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap, Object data) { return setModelMap(modelMap, HttpCode.OK, data); } protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code) { return setModelMap(modelMap, code, null); } protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code, Object data) { Map<String, Object> map = InstanceUtil.newLinkedHashMap(); map.putAll(modelMap); modelMap.clear(); for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) { String key = iterator.next(); if (!key.startsWith("org.springframework.validation.BindingResult") && !key.equals("void")) { modelMap.put(key, map.get(key)); } } if (data != null) { if (data instanceof Page) { Page<?> page = (Page<?>) data; modelMap.put("data", page.getRecords()); modelMap.put("current", page.getCurrent()); modelMap.put("size", page.getSize()); modelMap.put("pages", page.getPages()); modelMap.put("iTotalRecords", page.getTotal()); modelMap.put("iTotalDisplayRecords", page.getTotal()); } else if (data instanceof List<?>) { modelMap.put("data", data); modelMap.put("iTotalRecords", ((List<?>) data).size()); modelMap.put("iTotalDisplayRecords", ((List<?>) data).size()); } else { modelMap.put("data", data); } } modelMap.put("httpCode", code.value()); modelMap.put("msg", code.msg()); modelMap.put("timestamp", System.currentTimeMillis()); return ResponseEntity.ok(modelMap); } @ExceptionHandler(Exception.class) public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception { logger.error(Constants.Exception_Head, ex); ModelMap modelMap = new ModelMap(); if (ex instanceof BaseException) { ((BaseException) ex).handler(modelMap); } else if (ex instanceof IllegalArgumentException) { new IllegalParameterException(ex.getMessage()).handler(modelMap); } else if (ex instanceof UnauthorizedException) { modelMap.put("httpCode", HttpCode.FORBIDDEN.value()); modelMap.put("msg", StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.FORBIDDEN.msg())); } else { modelMap.put("httpCode", HttpCode.INTERNAL_SERVER_ERROR.value()); String msg = StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.INTERNAL_SERVER_ERROR.msg()); modelMap.put("msg", msg.length() > 100 ? ",." : msg); } response.setContentType("application/json;charset=UTF-8"); modelMap.put("timestamp", System.currentTimeMillis()); logger.info(JSON.toJSON(modelMap)); byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect); response.getOutputStream().write(bytes); } public abstract String getService(); public Object query(ModelMap modelMap, Map<String, Object> param) { Parameter parameter = new Parameter(getService(), "query").setMap(param); Page<?> list = provider.execute(parameter).getPage(); return setSuccessModelMap(modelMap, list); } public Object queryList(ModelMap modelMap, Map<String, Object> param) { Parameter parameter = new Parameter(getService(), "queryList").setMap(param); List<?> list = provider.execute(parameter).getList(); return setSuccessModelMap(modelMap, list); } public Object get(ModelMap modelMap, BaseModel param) { Parameter parameter = new Parameter(getService(), "queryById").setId(param.getId()); BaseModel result = provider.execute(parameter).getModel(); return setSuccessModelMap(modelMap, result); } public Object update(ModelMap modelMap, BaseModel param) { Long userId = getCurrUser(); if (param.getId() == null) { param.setCreateBy(userId); } param.setUpdateBy(userId); Parameter parameter = new Parameter(getService(), "update").setModel(param); provider.execute(parameter); return setSuccessModelMap(modelMap); } public Object delete(ModelMap modelMap, BaseModel param) { Parameter parameter = new Parameter(getService(), "delete").setId(param.getId()); provider.execute(parameter); return setSuccessModelMap(modelMap); } }
package com.inepex.ineFrame.shared.util; import java.util.Date; import com.inepex.ineFrame.client.i18n.IneFrameI18n; public class DateHelper { public static final long secondInMs = 1000; public static final long minuteInMs = 60 * secondInMs; public static final long hourInMs = 60 * minuteInMs; public static final long dayInMs = 24 * hourInMs; @SuppressWarnings("deprecation") public static int getYear(Date date) { if (date == null) throw new IllegalArgumentException(); return date.getYear() + 1900; } @SuppressWarnings("deprecation") public static int getMonth(Date date) { if (date == null) throw new IllegalArgumentException(); return date.getMonth() + 1; } @SuppressWarnings("deprecation") public static Date resetHourMinuteSecond(Date date) { if (date == null) return date; date.setHours(0); date.setMinutes(0); date.setSeconds(0); return date; } @SuppressWarnings("deprecation") public static long getFirstMSOfDay(long date) { Date d = new Date(date); d.setHours(0); d.setMinutes(0); d.setSeconds(0); return (d.getTime()/1000)*1000+1; } @SuppressWarnings("deprecation") public static long getNoon(long date) { Date d = new Date(date); d.setHours(12); d.setMinutes(0); d.setSeconds(0); return (d.getTime()/1000)*1000; } @SuppressWarnings("deprecation") public static long getLastMSOfDay(long date) { Date d = new Date(date); d.setHours(23); d.setMinutes(59); d.setSeconds(59); return (d.getTime()/1000)*1000+999; } @SuppressWarnings("deprecation") public static Date resetSecond(Date date) { if (date == null) return date; date.setSeconds(0); date.setTime((date.getTime() / 1000L) * 1000L); return date; } /** * * WARNING! The methods behave changed... doesn't modify param date anymore * */ @SuppressWarnings("deprecation") public static Date addDaysSafe(Date date, int days) { if (date == null) return date; int day = date.getDate(); Date dateCopy = new Date(date.getTime()); dateCopy.setDate(day + days); // the Date class handles it correctly even if the month doesn't have that many days as it is set in the argument (it adjusts the year, month and day if necessary) return dateCopy; } public static Date addHours(Date date, int hours) { return addHours(date, (long)hours); } public static Date addHours(Date date, long hours) { if (date == null) return date; return new Date(date.getTime() + hours * hourInMs); } public static Date addMinutes(Date date, int minutes) { return addMinutes(date, (long)minutes); } public static Date addMinutes(Date date, long minutes) { if (date == null) return date; return new Date(date.getTime() + minutes * minuteInMs); } public static Date addSeconds(Date date, int seconds) { return addSeconds(date, (long)seconds); } public static Date addSeconds(Date date, long seconds) { if (date == null) return date; return new Date(date.getTime() + seconds * secondInMs); } @SuppressWarnings("deprecation") public static Date getDate(int year, int month, int day, int hour, int minute, int second) { return new Date(year - 1900, month - 1, day, hour, minute, second); } public static Date copyDate(Date date) { return new Date(date.getTime()); } public static Long diffMillis(Date startDate, Date endDate) { if (endDate == null || startDate == null) return null; return endDate.getTime() - startDate.getTime(); } public static Long diffMinutes(Date startDate, Date endDate) { Long diffMillis = diffMillis(startDate, endDate); if (diffMillis == null) return null; return Math.round((double)diffMillis / minuteInMs); } public static Long diffHours(Date startDate, Date endDate) { Long diffMillis = diffMillis(startDate, endDate); if (diffMillis == null) return null; return Math.round((double)diffMillis / hourInMs); } public static Long diffMillis(Long startDateLong, Long endDateLong) { if (endDateLong == null || startDateLong == null) return null; return endDateLong - startDateLong; } public static Long diffMinutes(Long startDateLong, Long endDateLong) { Long diffMillis = diffMillis(startDateLong, endDateLong); if (diffMillis == null) return null; return Math.round((double)diffMillis / minuteInMs); } public static Long diffHours(Long startDateLong, Long endDateLong) { Long diffMillis = diffMillis(startDateLong, endDateLong); if (diffMillis == null) return null; return Math.round((double)diffMillis / hourInMs); } /** * example: * * 2010.11.17-2010.11.17 1 day * 2010.11.17-2010.11.18 2 days */ public static Long diffDaysInclusive(Date startDate, Date endDate) { Long diffMillis = diffMillis(resetHourMinuteSecond(startDate), resetHourMinuteSecond(endDate)); if (diffMillis == null) return null; return Math.round((double)diffMillis / dayInMs) + 1; } /** * example: * <br/> * 2010.11.17-2010.11.17 1 day <br/> * 2010.11.17-2010.11.18 2 days <br/> */ public static Long diffDaysInclusive(Long startDateLong, Long endDateLong) { return diffDaysInclusive(new Date(startDateLong), new Date(endDateLong)); } @SuppressWarnings("deprecation") public static Date setHours(Date date, int hours) { if (date != null) date.setHours(hours); return date; } @SuppressWarnings("deprecation") public static Date resetHoursMinsSecsMillis(Date d){ Date rounded = new Date(d.getYear(), d.getMonth(), d.getDate()); return rounded; } @SuppressWarnings("deprecation") public static Date getNextWeekend(Date from){ Date date = resetHoursMinsSecsMillis(from); date = addDaysSafe(date, 1); while (date.getDay() != 6){ date = addDaysSafe(date, 1); } return date; } @SuppressWarnings("deprecation") public static Date getNextWeekStartDate(Date from){ Date date = resetHoursMinsSecsMillis(from); date = addDaysSafe(date, 1); while (date.getDay() != 1){ date = addDaysSafe(date, 1); } return date; } @SuppressWarnings("deprecation") public static Date getThisWeekStartDate(Date from){ Date date = resetHoursMinsSecsMillis(from); while (date.getDay() != 1){ date = addDaysSafe(date, -1); } return date; } @SuppressWarnings("deprecation") public static Date getPrevWeekStartDate(Date from){ Date date = resetHoursMinsSecsMillis(from); date = addDaysSafe(date, -7); while (date.getDay() != 1){ date = addDaysSafe(date, -1); } return date; } @SuppressWarnings("deprecation") public static Date getNextMonthStartDate(Date from){ Date date = resetHoursMinsSecsMillis(from); date.setMonth(date.getMonth() + 1); date.setDate(1); return date; } @SuppressWarnings("deprecation") public static Date getThisMonthStartDate(Date from){ Date date = resetHoursMinsSecsMillis(from); date.setDate(1); return date; } @SuppressWarnings("deprecation") public static Date getPrevMonthStartDate(Date from){ Date date = resetHoursMinsSecsMillis(from); date.setMonth(date.getMonth() - 1); date.setDate(1); return date; } @SuppressWarnings("deprecation") public static Date getMonthEndDate(Date dateInMonth){ Date endDate = resetHoursMinsSecsMillis(dateInMonth); int month = endDate.getMonth(); do { endDate = addDaysSafe(endDate, 1); } while (endDate.getMonth() == month); endDate = addDaysSafe(endDate, -1); return endDate; } @SuppressWarnings("deprecation") public static Date getNextQuarterStart(Date from){ int nextQuarter = getQuarterOfDate(from) + 1; int year = from.getYear(); if (nextQuarter == 5) { nextQuarter = 1; year++; } switch (nextQuarter){ case 1: return new Date(year, 0, 1); case 2: return new Date(year, 3, 1); case 3: return new Date(year, 6, 1); case 4: return new Date(year, 9, 1); default: return null; } } public static int getNextQuarterOfDate(Date d){ int nextQuarter = getQuarterOfDate(d) + 1; if (nextQuarter == 5) { nextQuarter = 1; } return nextQuarter; } @SuppressWarnings("deprecation") public static int getQuarterOfDate(Date d){ switch (d.getMonth()){ case 0: return 1; case 1: return 1; case 2: return 1; case 3: return 2; case 4: return 2; case 5: return 2; case 6: return 3; case 7: return 3; case 8: return 3; case 9: return 4; case 10: return 4; case 11: return 4; default: return -1; } } @SuppressWarnings("deprecation") public static Date getNextHalfYearStartDate(Date from){ int nextHalf = getHalfYearOfDate(from) + 1; int year = from.getYear(); if (nextHalf == 3) { nextHalf = 1; year++; } switch (nextHalf){ case 1: return new Date(year, 0, 1); case 2: return new Date(year, 6, 1); default: return null; } } @SuppressWarnings("deprecation") public static int getHalfYearOfDate(Date d){ if (d.getMonth() <=5) return 1; else return 2; } @SuppressWarnings("deprecation") public static Date addMonth(Date date, int months) { if (date == null) return date; Date tmpDate = new Date(date.getTime()); tmpDate.setMonth(date.getMonth()+ months); int monthsOfYearDiff = (tmpDate.getYear() - date.getYear()) * 12; while ((tmpDate.getMonth() + monthsOfYearDiff) != date.getMonth() + months){ tmpDate.setDate(tmpDate.getDate() - 1); } return tmpDate; } public static Long nowLong() { return new Date().getTime(); } /** * * @param duration * @return formatted duration, like 3h 34m */ public static String formatDuration(long duration, boolean showSec){ int second = 1000; int minute = second * 60; int hour = minute * 60; int day = hour * 24; int days = 0; int hours = 0; int minutes = 0; int seconds = 0; days = (int) (duration / day); duration -= days * day; hours = (int) (duration / hour); duration -= hours * hour; minutes = (int) (duration / minute); duration -= minutes * minute; seconds = (int) (duration / second); StringBuffer sb = new StringBuffer(); if (days > 0) { sb.append(days); sb.append(IneFrameI18n.dayShort()); sb.append(" "); } if (hours > 0 || days > 0) { sb.append(hours); sb.append(IneFrameI18n.hourShort()); sb.append(" "); } sb.append(minutes); sb.append(IneFrameI18n.minShort()); if (showSec) { sb.append(" "); sb.append(seconds); sb.append(IneFrameI18n.secShort()); } return sb.toString(); } public static Date getDayEndDate(Date date){ date = resetHoursMinsSecsMillis(date); date = addDaysSafe(date, 1); date.setTime(date.getTime() - 1); return date; } public static Date getToday(DateProvider dateProvider){ Date today = dateProvider.whatMeansTyped(new Date().getTime()); today.setHours(12); today.setMinutes(1); return today; } }
package org.intermine.template; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.LinkedHashMap; import java.util.Map; import java.util.NoSuchElementException; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.lang.StringEscapeUtils; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathConstraintLookup; import org.intermine.pathquery.PathConstraintLoop; import org.intermine.pathquery.PathConstraintSubclass; import org.intermine.pathquery.PathQuery; import org.intermine.template.xml.TemplateQueryBinding; /** * A template query, which consists of a PathQuery, description, category, * short name. * * @author Mark Woodbridge * @author Thomas Riley * @author Alex Kalderimis */ public class TemplateQuery extends PathQuery { /** Template query name. */ protected String name; /** The private comment for this query. */ protected String comment; /** Whether this is an edited version of another template. */ protected boolean edited = false; /** List of those Constraints that are editable */ protected List<PathConstraint> editableConstraints = new ArrayList<PathConstraint>(); /** Descriptions of constraints */ protected Map<PathConstraint, String> constraintDescriptions = new HashMap<PathConstraint, String>(); /** Configuration for switch-off-ability of constraints */ protected Map<PathConstraint, SwitchOffAbility> constraintSwitchOffAbility = new HashMap<PathConstraint, SwitchOffAbility>(); /** * Construct a new instance of TemplateQuery. * * @param name the name of the template * @param title the short title of this template for showing in list * @param comment an optional private comment for this template * @param query the query itself */ public TemplateQuery(String name, String title, String comment, PathQuery query) { super(query); this.name = name; this.comment = comment; setTitle(title); } /** * Copy constructor. * Construct a new template that is the same in all respects as the one * passed to the constructor. * @param prototype The template to copy. */ public TemplateQuery(TemplateQuery prototype) { super(prototype); setTitle(prototype.getTitle()); this.name = prototype.name; this.comment = prototype.comment; this.edited = prototype.edited; this.editableConstraints = new ArrayList<PathConstraint>(prototype.editableConstraints); this.constraintDescriptions = new HashMap<PathConstraint, String>(prototype.constraintDescriptions); this.constraintSwitchOffAbility = new HashMap<PathConstraint, SwitchOffAbility>(prototype.constraintSwitchOffAbility); } /** * Clone this TemplateQuery. * * @return a TemplateQuery */ @Override public synchronized TemplateQuery clone() { super.clone(); return new TemplateQuery(this); } /** * Fetch the PathQuery to execute for this template. The returned query excludes any optional * constraints that have been sbitched off before the template is executed. * @return the PathQuery that should be executed for this query */ @Override public PathQuery getQueryToExecute() { TemplateQuery queryToExecute = this.clone(); for (PathConstraint con : queryToExecute.getEditableConstraints()) { if (SwitchOffAbility.OFF.equals(getSwitchOffAbility(con))) { queryToExecute.removeConstraint(con); } } return queryToExecute; } /** * Sets a constraint to be editable or not. If setting a constraint to be editable, and it is * not already editable, then the constraint will be added to the end of the editable * constraints list. * * @param constraint the PathConstraint to mark * @param editable whether the constraint should be editable * @throws NullPointerException if constraint is null * @throws NoSuchElementException if the constraint is not in the query */ public synchronized void setEditable(PathConstraint constraint, boolean editable) { if (constraint == null) { throw new NullPointerException("Cannot set null constraint to be editable"); } if (!getConstraints().containsKey(constraint)) { throw new NoSuchElementException("Constraint " + constraint + " is not in the query"); } if (editable) { if (!editableConstraints.contains(constraint)) { editableConstraints.add(constraint); } } else { editableConstraints.remove(constraint); } } /** * Returns whether a constraint is editable. * * @param constraint the PathConstraint to check * @return true if the constraint is editable * @throws NullPointerException if constraint is null * @throws NoSuchElementException if constraint is not in the query at all */ public synchronized boolean isEditable(PathConstraint constraint) { if (constraint == null) { throw new NullPointerException("Cannot fetch editable status of null constraint"); } if (!getConstraints().containsKey(constraint)) { throw new NoSuchElementException("Constraint " + constraint + " is not in the query"); } return editableConstraints.contains(constraint); } /** * Returns whether a constraint is optional. This is the logical inverse of isRequired() * * @param constraint the PathConstraint to check * @return true if the constraint is optional * @throws NullPointerException if the constraint is null * @throws NoSuchElementException if constraint is not in the query at all */ public synchronized boolean isOptional(PathConstraint constraint) { return !isRequired(constraint); } /** * Returns whether a constraint is required. This is the logical inverse of isOptional() * * @param constraint the PathConstraint to check * @return true if the constraint is required * @throws NullPointerException if the constraint is null * @throws NoSuchElementException if constraint is not in the query at all */ public synchronized boolean isRequired(PathConstraint constraint) { if (constraint == null) { throw new NullPointerException("Cannot fetch editable status of null constraint"); } if (!getConstraints().containsKey(constraint)) { throw new NoSuchElementException("Constraint " + constraint + " is not in the query"); } boolean isRequired = SwitchOffAbility.LOCKED.equals(getSwitchOffAbility(constraint)); return isRequired; } /** * Sets the list of editable constraints to exactly that provided, in the given order. * Previously-editable constraints are discarded. * * @param editable a List of editable constraints to replace the existing list * @throws NoSuchElementException if the argument contains a constraint that is not in the query */ public synchronized void setEditableConstraints(List<PathConstraint> editable) { for (PathConstraint constraint : editable) { if (!getConstraints().containsKey(constraint)) { throw new NoSuchElementException("Constraint " + constraint + " is not in the query"); } } sortConstraints(editable); editableConstraints = new ArrayList<PathConstraint>(editable); } /** * For a path with editable constraints, get all the editable constraints as a List, or the * empty list if there are no editable constraints on that path. * * @param path a String of a path * @return List of editable constraints for the path */ public synchronized List<PathConstraint> getEditableConstraints(String path) { List<PathConstraint> ecs = new ArrayList<PathConstraint>(); for (PathConstraint constraint : editableConstraints) { if (path.equals(constraint.getPath())) { ecs.add(constraint); } } return ecs; } /** * Returns the constraint SwitchOffAbility for this query. The return value of this method is an * unmodifiable copy of the data in this query, so it will not change to reflect changes in this * query. * * @return a Map of constraintSwitchOffAbility */ public synchronized Map<PathConstraint, SwitchOffAbility> getConstraintSwitchOffAbility() { return Collections.unmodifiableMap(new HashMap<PathConstraint, SwitchOffAbility>( constraintSwitchOffAbility)); } /** * Sets the description for a constraint. To remove a description, call this method with * a null description. * * @param constraint the constraint to attach the description to * @param description a String * @throws NullPointerException if the constraint is null * @throws NoSuchElementException if the constraint is not in the query */ public synchronized void setConstraintDescription(PathConstraint constraint, String description) { if (constraint == null) { throw new NullPointerException("Cannot set description on null constraint"); } if (!getConstraints().containsKey(constraint)) { throw new NoSuchElementException("Constraint " + constraint + " is not in the query"); } if (description == null) { constraintDescriptions.remove(constraint); } else { constraintDescriptions.put(constraint, description); } } /** * Returns the description attached to the given constraint. Returns null if no description is * present. * * @param constraint the constraint to fetch the description of * @return a String description * @throws NullPointerException is the constraint is null * @throws NoSuchElementException if the constraint is not in the query */ public synchronized String getConstraintDescription(PathConstraint constraint) { if (constraint == null) { throw new NullPointerException("Cannot set description on null constraint"); } if (!getConstraints().containsKey(constraint)) { throw new NoSuchElementException("Constraint " + constraint + " is not in the query"); } return constraintDescriptions.get(constraint); } /** * Returns the constraint descriptions for this query. The return value of this method is an * unmodifiable copy of the data in this query, so it will not change to reflect changes in this * query. * * @return a Map from PathConstraint to String description */ public synchronized Map<PathConstraint, String> getConstraintDescriptions() { return Collections.unmodifiableMap(new HashMap<PathConstraint, String>( constraintDescriptions)); } /** * Sets the sbitch-off-ability of a constraint. * * @param constraint the constraint to set the switch-off-ability on * @param sbitchOffAbility a SwitchOffAbility instance * @throws NullPointerException if the constraint or sbitchOffAbility is null * @throws NoSuchElementException if the constraint is not in the query */ public synchronized void setSwitchOffAbility(PathConstraint constraint, SwitchOffAbility sbitchOffAbility) { if (constraint == null) { throw new NullPointerException("Cannot set sbitch-off-ability on null constraint"); } if (sbitchOffAbility == null) { throw new NullPointerException("Cannot set null sbitch-off-ability on constraint " + constraint); } if (!getConstraints().containsKey(constraint)) { throw new NoSuchElementException("Constraint " + constraint + " is not in the query"); } constraintSwitchOffAbility.put(constraint, sbitchOffAbility); } /** * Gets the sbitch-off-ability of a constraint. * * @param constraint the constraint to get the sbitch-off-ability for * @return a SwitchOffAbility instance * @throws NullPointerException is the constraint is null * @throws NoSuchElementException if the constraint is not in the query */ public synchronized SwitchOffAbility getSwitchOffAbility(PathConstraint constraint) { if (constraint == null) { throw new NullPointerException("Cannot set sbitch-off-ability on null constraint"); } if (!getConstraints().containsKey(constraint)) { throw new NoSuchElementException("Constraint " + constraint + " is not in the query"); } SwitchOffAbility sbitchOffAbility = constraintSwitchOffAbility.get(constraint); if (sbitchOffAbility == null) { return SwitchOffAbility.LOCKED; } return sbitchOffAbility; } /** * Returns the list of all editable constraints. The return value of this method is an * unmodifiable copy of the data in this query, so it will not change to reflect changes in this * query. * * @return a List of PathConstraint */ public synchronized List<PathConstraint> getEditableConstraints() { return Collections.unmodifiableList(new ArrayList<PathConstraint>(editableConstraints)); } /** * Returns the list of all editable constraints. The return value of this method is a * copy of the data in this query, so it will not change to reflect changes in this * query. Please only use this method if you are going to resubmit the list to the * setEditableConstraints() method, as any changes made in this list will not be otherwise * copied to this TemplateQuery object. For other uses, use the getEditableConstraints() method, * which will prevent modification, which could catch a bug or two. * * @return a List of PathConstraint */ public synchronized List<PathConstraint> getModifiableEditableConstraints() { return new ArrayList<PathConstraint>(editableConstraints); } /** * {@inheritDoc} */ @Override public synchronized void replaceConstraint(PathConstraint old, PathConstraint replacement) { super.replaceConstraint(old, replacement); if (editableConstraints.contains(old)) { if ((replacement instanceof PathConstraintSubclass) || (replacement instanceof PathConstraintLoop)) { editableConstraints.remove(editableConstraints.indexOf(old)); } else { editableConstraints.set(editableConstraints.indexOf(old), replacement); } } String description = constraintDescriptions.remove(old); if (description != null) { constraintDescriptions.put(replacement, description); } SwitchOffAbility sbitchOffAbility = constraintSwitchOffAbility.remove(old); if (sbitchOffAbility != null) { constraintSwitchOffAbility.put(replacement, sbitchOffAbility); } } /** * {@inheritDoc} */ @Override public synchronized void removeConstraint(PathConstraint constraint) { super.removeConstraint(constraint); editableConstraints.remove(constraint); constraintDescriptions.remove(constraint); constraintSwitchOffAbility.remove(constraint); } /** * {@inheritDoc} */ @Override public synchronized void clearConstraints() { editableConstraints.clear(); constraintDescriptions.clear(); constraintSwitchOffAbility.clear(); } /** * Return a clone of this template query with all editable constraints * removed - i.e. a query that will return all possible results of executing * the template. The original template is left unaltered. * * @return a clone of the original template without editable constraints. */ public TemplateQuery cloneWithoutEditableConstraints() { TemplateQuery clone = clone(); List<PathConstraint> editable = new ArrayList<PathConstraint>(clone.editableConstraints); for (PathConstraint constraint : editable) { clone.removeConstraint(constraint); } return clone; } /** * Get the private comment for this template. * @return the comment */ public String getComment() { return comment; } /** * Return the template's title, or its name if it has no title. */ @Override public String getTitle() { String title = super.getTitle(); if (title == null || "".equals(title)) { return getName(); } return title; } /** * Get the paths of all editable constraints in this template. * * @return the nodes */ public synchronized List<String> getEditablePaths() { List<String> editablePaths = new ArrayList<String>(); for (PathConstraint constraint : editableConstraints) { if (!editablePaths.contains(constraint.getPath())) { editablePaths.add(constraint.getPath()); } } return editablePaths; } /** * Get the query short name. * * @return the query identifier string */ public String getName() { return name; } /** * Sets the query short name. * * @param name the template name */ public void setName(String name) { this.name = name; } /** * Set the private comment for this template. * @param comment the comment */ public void setComment(String comment) { this.comment = comment; } /** * Convert a template query to XML. * * @param version the version number of the XML format * @return this template query as XML. */ @Override public synchronized String toXml(int version) { StringWriter sw = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(sw); TemplateQueryBinding.marshal(this, writer, version); } catch (XMLStreamException e) { throw new RuntimeException(e); } return sw.toString(); } @Override public synchronized String toString() { String res = super.toString(); res = getClass().getName() + "{ name: " + getName() + ", title: " + getTitle() + ", comment: " + getComment() + ", description: " + getDescription() + ", " + res + "}"; return res; } public synchronized Map<PathConstraint, String> getRelevantConstraints() { Map<PathConstraint, String> retVal = new LinkedHashMap<PathConstraint, String>(getConstraints()); for (PathConstraint con: getConstraints().keySet()) { if (getSwitchOffAbility(con) == SwitchOffAbility.OFF) { retVal.remove(con); } } return retVal; } protected Map<String, Object> getHeadAttributes() { Map<String, Object> retVal = super.getHeadAttributes(); retVal.put("name", getName()); retVal.put("comment", getComment()); return retVal; } /** * Returns a JSON string representation of the template query. * TODO: !! fix confusion between toJson and toJSON !! * @return A string representation of the template query. */ public synchronized String toJSON() { StringBuffer sb = new StringBuffer("{"); addJsonProperty(sb, "name", getName()); addJsonProperty(sb, "title", getTitle()); addJsonProperty(sb, "description", getDescription()); addJsonProperty(sb, "comment", getComment()); addJsonProperty(sb, "view", getView()); sb.append(",\"constraints\":["); Iterator<PathConstraint> iter = getEditableConstraints().iterator(); Map<PathConstraint, String> codeForConstraint = getConstraints(); while (iter.hasNext()) { PathConstraint pc = iter.next(); StringBuffer pcw = new StringBuffer("{"); addJsonProperty(pcw, "path", pc.getPath()); addJsonProperty(pcw, "op", pc.getOp().toString()); addJsonProperty(pcw, "value", PathConstraint.getValue(pc)); addJsonProperty(pcw, "code", codeForConstraint.get(pc)); addJsonProperty(pcw, "extraValue", PathConstraint.getExtraValue(pc)); pcw.append("}"); sb.append(pcw.toString()); if (iter.hasNext()) { sb.append(","); } } sb.append("]"); sb.append("}"); return sb.toString(); } /** * Returns true if the TemplateQuery has been edited by the user and is therefore saved only in * the query history. * * @return a boolean */ public boolean isEdited() { return edited; } public void setEdited(boolean edited) { this.edited = edited; } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other instanceof TemplateQuery) { return ((TemplateQuery) other).toXml().equals(this.toXml()); } return false; } @Override public int hashCode() { return this.toXml().hashCode(); } /** * Verify templates don't contain non-editable lookup constraints * @param template to validate * @return true id the tempalte is valid */ public boolean validateLookupConstraints() { Map<PathConstraint, String> pathConstraints = getConstraints(); for (PathConstraint constraint : pathConstraints.keySet()) { if (constraint instanceof PathConstraintLookup && !editableConstraints.contains(constraint)) { return false; } } return true; } }
package ua.kiev.icyb.bio.alg.tree; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import ua.kiev.icyb.bio.AbstractLaunchable; import ua.kiev.icyb.bio.Representable; import ua.kiev.icyb.bio.SequenceSet; import ua.kiev.icyb.bio.res.Messages; public class RuleTreeGenerator extends AbstractLaunchable implements Representable { private static final long serialVersionUID = 1L; public static class Fitness implements Serializable { private static final long serialVersionUID = 1L; public final SequenceSet set; public final PartitionRule rule; public final double fitness; public final int iteration; public final int partitionIndex; public boolean isOptimal = false; public boolean isGloballyOptimal = false; private Fitness(SequenceSet set, PartitionRule rule, double fitness, int iteration, int partitionIndex) { this.set = set; this.rule = rule; this.fitness = fitness; this.iteration = iteration; this.partitionIndex = partitionIndex; } @Override public String toString() { return String.format("[iter=%d, part=%d: q(%s) = %.2f]", this.iteration, this.partitionIndex, this.rule, this.fitness); } } public int treeSize; public int order; public double[] percentages; public double minPartSize; public SequenceSet set; public Collection<FragmentSet> baseSets; public String treeFile; public PartitionRuleTree tree; private int[] partIdx; public final Collection<Fitness> computedFitness = new ArrayList<Fitness>(); private double[] maxFitness; private PartitionRule[] optRule; private int currentPart; private boolean rulesInferred = false; private List<PartitionRule> partRules; private Map<PartitionRule, Double> ruleFitness = null; public RuleTreeGenerator() { } private RuleEntropy getEntropy(SequenceSet set) { return new RuleEntropy(set, order); } private Map<PartitionRule, Double> getFitness(SequenceSet set, List<PartitionRule> rules) { if (this.ruleFitness == null) { this.ruleFitness = new HashMap<PartitionRule, Double>(); } for (PartitionRule rule : rules) { if (!ruleFitness.containsKey(rule)) { ruleFitness.put(rule, Double.NaN); } } ExecutorService executor = getEnv().executor(); RuleEntropy entropy = getEntropy(set); List<RuleTask> tasks = new ArrayList<RuleTask>(); for (Map.Entry<PartitionRule, Double> entry : this.ruleFitness.entrySet()) { if (entry.getValue().isNaN()) { tasks.add(new RuleTask(set, entropy, entry)); } } try { List<Future<Void>> futures = executor.invokeAll(tasks); for (int i = 0; i < futures.size(); i++) { futures.get(i).get(); } } catch (InterruptedException e) { getEnv().exception(e); } catch (ExecutionException e) { getEnv().exception(e); } return ruleFitness; } private List<PartitionRule> inferRules(SequenceSet set) { if (rulesInferred && (partRules != null)) { return partRules; } partRules = new ArrayList<PartitionRule>(); ExecutorService executor = getEnv().executor(); List<InferTask> tasks = new ArrayList<InferTask>(); for (FragmentSet comb : baseSets) { tasks.add(new InferTask(set, comb, percentages)); } try { getEnv().debugInline(1, Messages.getString("tree.infer")); List<Future<List<PartitionRule>>> futures = executor.invokeAll(tasks); for (Future<List<PartitionRule>> future : futures) partRules.addAll(future.get()); getEnv().debug(1, ""); } catch (InterruptedException e) { getEnv().exception(e); } catch (ExecutionException e) { getEnv().exception(e); } rulesInferred = true; return partRules; } private final class InferTask implements Callable<List<PartitionRule>> { private final SequenceSet set; private final double[] percentages; private final FragmentSet comb; public InferTask(SequenceSet set, FragmentSet comb, double[] percentages) { this.percentages = percentages; this.set = set; this.comb = comb; } public List<PartitionRule> call() throws Exception { List<PartitionRule> rules = new ArrayList<PartitionRule>(); double[] vars = new double[set.size()]; for (int i = 0; i < set.size(); i++) vars[i] = comb.content(set.observed(i)); Arrays.sort(vars); for (int i = 0; i < percentages.length; i++) { int idx = (int) (set.size() * percentages[i]); PartitionRule r = new ContentPartitionRule(comb, vars[idx]); rules.add(r); } getEnv().debugInline(1, "."); return rules; } } private class RuleTask implements Callable<Void> { private final SequenceSet fullSet; private final RuleEntropy entropy; private final Map.Entry<PartitionRule, Double> entry; public RuleTask(SequenceSet set, RuleEntropy entropy, Map.Entry<PartitionRule, Double> entry) { this.fullSet = set; this.entropy = entropy; this.entry = entry; } @Override public Void call() throws Exception { final PartitionRule rule = entry.getKey(); boolean[] complies = rule.test(fullSet); SequenceSet subset = fullSet.filter(complies); double fitness = -1; if ((subset.size() < minPartSize) || (subset.size() > fullSet.size() - minPartSize)) { fitness = -1; getEnv().debug(1, Messages.format("tree.small_set", Messages.format("tree.rule", rule, subset.size()) )); } else { fitness = entropy.fitness(subset); getEnv().debug(1, Messages.format("misc.fitness", Messages.format("tree.rule", rule, subset.size()), fitness)); } entry.setValue(fitness); synchronized(computedFitness) { computedFitness.add(new Fitness(fullSet, rule, fitness, tree.size(), currentPart)); } return null; } } @Override protected void doRun() { if (minPartSize < 1) { minPartSize = set.size() * minPartSize; } getEnv().debug(1, this.repr()); if (tree == null) { tree = new PartitionRuleTree(); partIdx = new int[set.size()]; maxFitness = new double[treeSize]; Arrays.fill(maxFitness, Double.NEGATIVE_INFINITY); optRule = new PartitionRule[treeSize]; } while (tree.size() <= treeSize) { for (int p = this.currentPart; p < tree.size(); this.currentPart = ++p) { getEnv().debug(1, ""); getEnv().debug(1, Messages.format("tree.part", p + 1, tree.size())); if (maxFitness[p] > Double.NEGATIVE_INFINITY) { getEnv().debug(1, Messages.format("tree.opt_rule", p + 1, optRule[p], maxFitness[p])); continue; } boolean b[] = new boolean[set.size()]; for (int i = 0; i < b.length; i++) { b[i] = (partIdx[i] == p); } SequenceSet partSet = set.filter(b); List<PartitionRule> rules = inferRules(partSet); save(); Map<PartitionRule, Double> fitness = getFitness(partSet, rules); double partMax = Double.NEGATIVE_INFINITY; PartitionRule partMaxRule = null; for (Map.Entry<PartitionRule, Double> entry : fitness.entrySet()) { if (entry.getValue() > partMax) { partMax = entry.getValue(); partMaxRule = entry.getKey(); } } maxFitness[p] = partMax; optRule[p] = partMaxRule; getEnv().debug(1, Messages.format("tree.opt_rule", p + 1, optRule[p], maxFitness[p])); for (Fitness f: computedFitness) { if ((f.iteration == tree.size()) && (f.partitionIndex == p) && (f.fitness == maxFitness[p])) { f.isOptimal = true; } } rulesInferred = false; partRules.clear(); ruleFitness.clear(); save(); } addNewRule(); this.currentPart = 0; save(); } } private void addNewRule() { int maxPart = -1; double overallMax = Double.NEGATIVE_INFINITY; for (int p = 0; p < tree.size(); p++) { if (maxFitness[p] > overallMax) { overallMax = maxFitness[p]; maxPart = p; } } for (Fitness f: computedFitness) { if ((f.iteration <= tree.size()) && f.isOptimal && (f.fitness == overallMax)) { f.isGloballyOptimal = true; } } getEnv().debug(1, Messages.format("tree.g_opt_rule", maxPart + 1, optRule[maxPart], overallMax)); tree.add(optRule[maxPart], maxPart); boolean[] selector = new boolean[set.size()]; for (int i = 0; i < selector.length; i++) selector[i] = (partIdx[i] == maxPart); SequenceSet partSet = set.filter(selector); boolean[] partSelector = optRule[maxPart].test(partSet); for (int i = 0, ptr = 0; i < selector.length; i++) if (selector[i]) { selector[i] = partSelector[ptr]; ptr++; } int count = 0; for (int i = 0; i < selector.length; i++) if (selector[i]) { partIdx[i] = tree.size() - 1; count++; } maxFitness[maxPart] = Double.NEGATIVE_INFINITY; optRule[maxPart] = null; getEnv().debug(1, Messages.format("tree.new_part", count, partSelector.length, 1.0 * count/partSelector.length) + "\n"); saveTree(); } private void saveTree() { if (treeFile != null) { getEnv().debug(1, Messages.format("tree.save_tree", treeFile)); try { getEnv().save(tree, treeFile); } catch (IOException e) { getEnv().error(1, Messages.format("tree.e_save_tree", e)); } } } @Override public String repr() { String repr = ""; repr += Messages.format("tree.rules", this.treeSize) + "\n"; repr += Messages.format("tree.order", this.order) + "\n"; repr += Messages.format("tree.percentages", Arrays.toString(this.percentages)) + "\n"; repr += Messages.format("tree.min_part_size", this.minPartSize) + "\n"; repr += Messages.format("misc.dataset", this.set.repr()) + "\n"; repr += Messages.format("tree.bases", this.baseSets) + "\n"; repr += Messages.format("tree.tree_file", this.treeFile); if (tree != null) { repr += "\n" + Messages.format("tree.tree", tree.repr()); } return repr; } }
package org.intermine.web.logic.results; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.intermine.web.logic.Constants; /** * A pageable and configurable table of data. * * @author Andrew Varley * @author Kim Rutherford */ public class PagedTable { private WebTable webTable; private List<String> columnNames = null; private List<List<ResultElement>> resultElementRows = null; private int startRow = 0; private int pageSize = Constants.DEFAULT_TABLE_SIZE; private List<Column> columns; private String tableid; private List<List<Object>> rows = null; /** * Construct a PagedTable with a list of column names * @param webTable the WebTable that this PagedTable will display */ public PagedTable(WebTable webTable) { super(); this.webTable = webTable; } /** * Construct a PagedTable with a list of column names * @param webTable the WebTable that this PagedTable will display * @param pageSize the number of records to show on each page. Default value is 10. */ public PagedTable(WebTable webTable, int pageSize) { super(); this.webTable = webTable; this.pageSize = pageSize; } /** * Get the list of column configurations * * @return the List of columns in the order they are to be displayed */ public List<Column> getColumns() { return Collections.unmodifiableList(getColumnsInternal()); } private List<Column> getColumnsInternal() { if (columns == null) { columns = webTable.getColumns(); } return columns; } /** * Return the column names * @return the column names */ public List<String> getColumnNames() { if (columnNames == null) { columnNames = new ArrayList<String>(); Iterator<Column> iter = getColumns().iterator(); while (iter.hasNext()) { String columnName = iter.next().getName(); columnNames.add(columnName); } } return columnNames; } /** * Return the number of visible columns. Used by JSP pages. * @return the number of visible columns. */ public int getVisibleColumnCount() { int count = 0; for (Iterator<Column> i = getColumnsInternal().iterator(); i.hasNext();) { Column obj = i.next(); if (obj.isVisible()) { count++; } } return count; } /** * Move a column left * * @param index the index of the column to move */ public void moveColumnLeft(int index) { if (index > 0 && index <= getColumnsInternal().size() - 1) { getColumnsInternal().add(index - 1, getColumnsInternal().remove(index)); } } /** * Move a column right * * @param index the index of the column to move */ public void moveColumnRight(int index) { if (index >= 0 && index < getColumnsInternal().size() - 1) { getColumnsInternal().add(index + 1, getColumnsInternal().remove(index)); } } /** * Set the page size of the table * * @param pageSize the page size */ public void setPageSize(int pageSize) { this.pageSize = pageSize; startRow = (startRow / pageSize) * pageSize; updateResultElementRows(); } /** * Get the page size of the current page * * @return the page size */ public int getPageSize() { return pageSize; } /** * Get the index of the first row of this page * @return the index */ public int getStartRow() { return startRow; } /** * Get the page index. * @return current page index */ public int getPage() { return (startRow / pageSize); } /** * Set the page size and page together. * * @param page page number * @param size page size */ public void setPageAndPageSize(int page, int size) { this.pageSize = size; this.startRow = size * page; updateResultElementRows(); } /** * Get the index of the last row of this page * @return the index */ public int getEndRow() { return startRow + getResultElementRows().size() - 1; } /** * Go to the first page */ public void firstPage() { startRow = 0; updateResultElementRows(); } /** * Check if were are on the first page * @return true if we are on the first page */ public boolean isFirstPage() { return (startRow == 0); } /** * Go to the last page */ public void lastPage() { startRow = ((getExactSize() - 1) / pageSize) * pageSize; updateResultElementRows(); } /** * Check if we are on the last page * @return true if we are on the last page */ public boolean isLastPage() { return (!isSizeEstimate() && getEndRow() == getEstimatedSize() - 1); } /** * Go to the previous page */ public void previousPage() { if (startRow >= pageSize) { startRow -= pageSize; } updateResultElementRows(); } /** * Go to the next page */ public void nextPage() { startRow += pageSize; updateResultElementRows(); } /** * Return the currently visible rows of the table as a List of Lists of ResultElement objects. * @return the resultElementRows of the table */ public List<List<Object>> getRows() { if (rows == null) { updateRows(); } return rows; } /** * Return the currently visible rows of the table as a List of Lists of raw values/Objects. * @return the ResultElement of the table as rows */ public List<List<ResultElement>> getResultElementRows() { if (resultElementRows == null) { updateResultElementRows(); } return resultElementRows; } /** * Return all the resultElementRows of the table as a List of Lists. * * @return all the resultElementRows of the table */ public WebTable getAllRows() { return webTable; } /** * Temporary hack to let table.jsp get the type of the WebTable. * @return the Class of the WebTable for this PagedTable */ public Class<? extends WebTable> getWebTableClass() { return webTable.getClass(); } /** * Get the (possibly estimated) number of resultElementRows of this table * @return the number of resultElementRows */ public int getEstimatedSize() { return webTable.getEstimatedSize(); } /** * Check whether the result of getSize is an estimate * @return true if the size is an estimate */ public boolean isSizeEstimate() { return webTable.isSizeEstimate(); } /** * Get the exact number of resultElementRows of this table * @return the number of resultElementRows */ public int getExactSize() { return webTable.size(); } /** * Set the rows fields to be a List of Lists of values from ResultElement objects from * getResultElementRows(). */ private void updateRows() { rows = new ArrayList<List<Object>>(); for (int i = getStartRow(); i < getStartRow() + getPageSize(); i++) { try { List<Object> newRow = (List<Object>) getAllRows().get(i); rows.add(newRow); } catch (IndexOutOfBoundsException e) { // we're probably at the end of the results object, so stop looping break; } } } /** * Update the internal row list */ private void updateResultElementRows() { List<List<ResultElement>> newRows = new ArrayList<List<ResultElement>>(); if (getStartRow() < 0 || getStartRow() > getExactSize()) { throw new PageOutOfRangeException("Invalid start row of table."); } for (int i = getStartRow(); i < getStartRow() + getPageSize(); i++) { try { List<ResultElement> resultsRow = getAllRows().getResultElements(i); newRows.add(resultsRow); } catch (IndexOutOfBoundsException e) { // we're probably at the end of the results object, so stop looping break; } } this.resultElementRows = newRows; // clear so that getRows() recreates it this.rows = null; } /** * Return the maximum retrievable index for this PagedTable. This will only ever return less * than getExactSize() if the underlying data source has a restriction on the maximum index * that can be retrieved. * @return the maximum retrieved index */ public int getMaxRetrievableIndex() { return webTable.getMaxRetrievableIndex(); } /** * Return the class from the data model for the data displayed in indexed column. * This may be the parent class of a field e.g. if column displays A.field where * field is a String and A is a class in the model this method will return A. * @param index of column to find type for * @return the class or parent class for the indexed column */ public Class getTypeForColumn(int index) { return webTable.getColumns().get(index).getType(); } /** * Set the column names * @param columnNames a list of Strings */ public void setColumnNames(List<String> columnNames) { this.columnNames = columnNames; } /** * @return the webTable */ public WebTable getWebTable() { return webTable; } /** * @return the tableid */ public String getTableid() { return tableid; } /** * @param tableid the tableid to set */ public void setTableid(String tableid) { this.tableid = tableid; } private List rearrangedResults = null; /** * Returns a List containing the results, with the columns rearranged. * * @return a List of rows, each of which is a List */ public List getRearrangedResults() { if (rearrangedResults == null) { rearrangedResults = new RearrangedList(); } return rearrangedResults; } private class RearrangedList extends AbstractList { int columnOrder[]; public RearrangedList() { List columns = getColumns(); List<Integer> columnOrderList = new ArrayList(); for (int i = 0; i < columns.size(); i++) { Column column = (Column) columns.get(i); if (column.isVisible()) { columnOrderList.add(new Integer(column.getIndex())); } } columnOrder = new int[columnOrderList.size()]; for (int i = 0; i < columnOrderList.size(); i++) { columnOrder[i] = columnOrderList.get(i).intValue(); } } public List get(int index) { List row = (List) webTable.get(index); return translateRow(row); } private List translateRow(List row) { List realRow = new ArrayList(); for (int columnIndex = 0; columnIndex < row.size(); columnIndex++) { int realColumnIndex = columnOrder[columnIndex]; Object o = row.get(realColumnIndex); realRow.add(o); } return realRow; } public int size() { return webTable.size(); } public Iterator iterator() { return new Iter(); } private class Iter implements Iterator { private Iterator subIter = webTable.iterator(); public boolean hasNext() { return subIter.hasNext(); } public Object next() { List originalRow = (List) subIter.next(); return translateRow(originalRow); } public void remove() { throw (new UnsupportedOperationException()); } } } }
package building_blocks.primitives; import org.junit.Test; public class PrimitivesTest { private static byte BYTE = 1; private static short SHORT = 2; private static int INT = 3; private static long LONG = 4; private static float FLOAT = 5; private static double DOUBLE = 6; private static boolean BOOLEAN = true; private static char CHAR = 'c'; @Test public void createBytePrimitive() { byte b1 = 100; // You can assign integer literal byte b2 = BYTE; // Assignments below do not compile // byte b3 = SHORT; // Possible loss of precision // byte b4 = INT; // Possible loss of precision // byte b5 = LONG; // Possible loss of precision // byte b6 = FLOAT; // You can't assign decimal value to integer primitive // byte b7 = DOUBLE; // You can't assign decimal value to integer primitive // byte b8 = BOOLEAN; // You can't assign boolean value to integer primitive // byte b9 = CHAR; // Possible loss of precision } @Test public void createShortPrimitive() { short s1 = 100; // You can assign integer literal short s2 = BYTE; short s3 = SHORT; // Assignments below do not compile // short s4 = INT; // Possible loss of precision // short s5 = LONG; // Possible loss of precision // short s6 = FLOAT; // You can't assign decimal value to integer primitive // short s7 = DOUBLE; // You can't assign decimal value to integer primitive // short s8 = BOOLEAN; // You can't assign boolean value to integer primitive // short s9 = CHAR; // Possible loss of precision } @Test public void createIntPrimitive() { int i1 = 100; // You can assign integer literal int i2 = BYTE; int i3 = SHORT; int i4 = INT; int i9 = CHAR; // Assignments below do not compile // int i5 = LONG; // Possible loss of precision // int i6 = FLOAT; // You can't assign decimal value to integer primitive // int i7 = DOUBLE; // You can't assign decimal value to integer primitive // int i8 = BOOLEAN; // You can't assign boolean value to integer primitive } @Test public void createLongPrimitive() { long l1 = 100; // You can assign integer literal long l2 = BYTE; long l3 = SHORT; long l4 = INT; long l5 = LONG; long l9 = CHAR; // Assignments below do not compile // long l6 = FLOAT; // You can't assign decimal value to integer primitive // long l7 = DOUBLE; // You can't assign decimal value to integer primitive // long l8 = BOOLEAN; // You can't assign boolean value to integer primitive } @Test public void createFloatPrimitive() { float f1 = 100; // You can assign integer literal float f2 = BYTE; float f3 = SHORT; float f4 = INT; float f5 = LONG; float f6 = FLOAT; float f9 = CHAR; // Assignments below do not compile // float f7 = DOUBLE; // You can't assign decimal value to integer primitive // float f8 = BOOLEAN; // You can't assign boolean value to integer primitive } @Test public void createDoublePrimitive() { double d1 = 100; // You can assign integer literal double d2 = BYTE; double d3 = SHORT; double d4 = INT; double d5 = LONG; double d6 = FLOAT; double d7 = DOUBLE; double d9 = CHAR; // Assignments below do not compile // double d8 = BOOLEAN; // You can't assign boolean value to integer primitive } @Test public void createBooleanPrimitive() { // Assignments below do not compile // boolean b1 = 100; // You can't assign integer value to boolean // boolean b2 = BYTE; // You can't assign integer value to boolean // boolean b3 = SHORT; // You can't assign integer value to boolean // boolean b4 = INT; // You can't assign integer value to boolean // boolean b5 = LONG; // You can't assign integer value to boolean // boolean b6 = FLOAT; // You can't assign decimal value to boolean // boolean b7 = DOUBLE; // You can't assign decimal value to boolean // boolean b9 = CHAR; // You can't assign integer value to boolean boolean b8 = BOOLEAN; } }
package com.wonderkiln.blurkit; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.util.AttributeSet; import android.view.Choreographer; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import java.lang.ref.WeakReference; /** * A {@link ViewGroup} that blurs all content behind it. Automatically creates bitmap of parent content * and finds its relative position to the top parent to draw properly regardless of where the layout is * placed. */ public class BlurLayout extends FrameLayout { public static final float DEFAULT_DOWNSCALE_FACTOR = 0.12f; public static final int DEFAULT_BLUR_RADIUS = 12; public static final int DEFAULT_FPS = 60; // Customizable attributes /** Factor to scale the view bitmap with before blurring. */ private float mDownscaleFactor; /** Blur radius passed directly to stackblur library. */ private int mBlurRadius; /** Number of blur invalidations to do per second. */ private int mFPS; /** Is blur running? */ private boolean mRunning; /** Is window attached? */ private boolean mAttachedToWindow; /** Do we need to recalculate the position each invalidation? */ private boolean mPositionLocked; /** Do we need to regenerate the view bitmap each invalidation? */ private boolean mViewLocked; // Calculated class dependencies /** ImageView to show the blurred content. */ private ImageView mImageView; /** Reference to View for top-parent. For retrieval see {@link #getActivityView() getActivityView}. */ private WeakReference<View> mActivityView; /** A saved point to re-use when {@link #lockPosition()} called. */ private Point mLockedPoint; /** A saved bitmap for the view to re-use when {@link #lockView()} called. */ private Bitmap mLockedBitmap; public BlurLayout(Context context) { super(context, null); } public BlurLayout(Context context, AttributeSet attrs) { super(context, attrs); BlurKit.init(context); TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.BlurLayout, 0, 0); try { mDownscaleFactor = a.getFloat(R.styleable.BlurLayout_blk_downscaleFactor, DEFAULT_DOWNSCALE_FACTOR); mBlurRadius = a.getInteger(R.styleable.BlurLayout_blk_blurRadius, DEFAULT_BLUR_RADIUS); mFPS = a.getInteger(R.styleable.BlurLayout_blk_fps, DEFAULT_FPS); } finally { a.recycle(); } mImageView = new ImageView(getContext()); mImageView.setScaleType(ImageView.ScaleType.FIT_XY); addView(mImageView); } /** Choreographer callback that re-draws the blur and schedules another callback. */ private Choreographer.FrameCallback invalidationLoop = new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { invalidate(); Choreographer.getInstance().postFrameCallbackDelayed(this, 1000 / mFPS); } }; /** Start BlurLayout continuous invalidation. **/ public void startBlur() { if (mRunning) { return; } if (mFPS > 0) { mRunning = true; Choreographer.getInstance().postFrameCallback(invalidationLoop); } } /** Pause BlurLayout continuous invalidation. **/ public void pauseBlur() { if (!mRunning) { return; } mRunning = false; Choreographer.getInstance().removeFrameCallback(invalidationLoop); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mAttachedToWindow = true; startBlur(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mAttachedToWindow = false; pauseBlur(); } /** * {@inheritDoc} */ @Override public void invalidate() { super.invalidate(); Bitmap bitmap = blur(); if (bitmap != null) { mImageView.setImageBitmap(bitmap); } } /** * Recreates blur for content and sets it as the background. */ private Bitmap blur() { if (getContext() == null) { return null; } // Check the reference to the parent view. // If not available, attempt to make it. if (mActivityView == null || mActivityView.get() == null) { mActivityView = new WeakReference<>(getActivityView()); if (mActivityView.get() == null) { return null; } } Point pointRelativeToActivityView; if (mPositionLocked) { // Generate a locked point if null. if (mLockedPoint == null) { mLockedPoint = getPositionInScreen(); } // Use locked point. pointRelativeToActivityView = mLockedPoint; } else { // Calculate the relative point to the parent view. pointRelativeToActivityView = getPositionInScreen(); } // Set alpha to 0 before creating the parent view bitmap. // The blur view shouldn't be visible in the created bitmap. setAlpha(0); // Screen sizes for bound checks int screenWidth = mActivityView.get().getWidth(); int screenHeight = mActivityView.get().getHeight(); // The final dimensions of the blurred bitmap. int width = (int) (getWidth() * mDownscaleFactor); int height = (int) (getHeight() * mDownscaleFactor); // The X/Y position of where to crop the bitmap. int x = (int) (pointRelativeToActivityView.x * mDownscaleFactor); int y = (int) (pointRelativeToActivityView.y * mDownscaleFactor); // Padding to add to crop pre-blur. // Blurring straight to edges has side-effects so padding is added. int xPadding = getWidth() / 8; int yPadding = getHeight() / 8; // Calculate padding independently for each side, checking edges. int leftOffset = -xPadding; leftOffset = x + leftOffset >= 0 ? leftOffset : 0; int rightOffset = xPadding; rightOffset = x + getWidth() + rightOffset <= screenWidth ? rightOffset : screenWidth - getWidth() - x; int topOffset = -yPadding; topOffset = y + topOffset >= 0 ? topOffset : 0; int bottomOffset = yPadding; bottomOffset = y + height + bottomOffset <= screenHeight ? bottomOffset : 0; // Parent view bitmap, downscaled with mDownscaleFactor Bitmap bitmap; if (mViewLocked) { // It's possible for mLockedBitmap to be null here even with view locked. // lockView() should always properly set mLockedBitmap if this code is reached // (it passed previous checks), so recall lockView and assume it's good. if (mLockedBitmap == null) { lockView(); } if (width == 0 || height == 0) { return null; } bitmap = Bitmap.createBitmap(mLockedBitmap, x, y, width, height); } else { try { // Create parent view bitmap, cropped to the BlurLayout area with above padding. bitmap = getDownscaledBitmapForView( mActivityView.get(), new Rect( pointRelativeToActivityView.x + leftOffset, pointRelativeToActivityView.y + topOffset, pointRelativeToActivityView.x + getWidth() + Math.abs(leftOffset) + rightOffset, pointRelativeToActivityView.y + getHeight() + Math.abs(topOffset) + bottomOffset ), mDownscaleFactor ); } catch (BlurKitException e) { return null; } catch (NullPointerException e) { return null; } } if (!mViewLocked) { // Blur the bitmap. bitmap = BlurKit.getInstance().blur(bitmap, mBlurRadius); //Crop the bitmap again to remove the padding. bitmap = Bitmap.createBitmap( bitmap, (int) (Math.abs(leftOffset) * mDownscaleFactor), (int) (Math.abs(topOffset) * mDownscaleFactor), width, height ); } // Make self visible again. setAlpha(1); // Set background as blurred bitmap. return bitmap; } /** * Casts context to Activity and attempts to create a view reference using the window decor view. * @return View reference for whole activity. */ private View getActivityView() { Activity activity; try { activity = (Activity) getContext(); } catch (ClassCastException e) { return null; } return activity.getWindow().getDecorView().findViewById(android.R.id.content); } /** * Returns the position in screen. Left abstract to allow for specific implementations such as * caching behavior. */ private Point getPositionInScreen() { PointF pointF = getPositionInScreen(this); return new Point((int) pointF.x, (int) pointF.y); } /** * Finds the Point of the parent view, and offsets result by self getX() and getY(). * @return Point determining position of the passed in view inside all of its ViewParents. */ private PointF getPositionInScreen(View view) { if (getParent() == null) { return new PointF(); } ViewGroup parent; try { parent = (ViewGroup) view.getParent(); } catch (Exception e) { return new PointF(); } if (parent == null) { return new PointF(); } PointF point = getPositionInScreen(parent); point.offset(view.getX(), view.getY()); return point; } /** * Users a View reference to create a bitmap, and downscales it using the passed in factor. * Uses a Rect to crop the view into the bitmap. * @return Bitmap made from view, downscaled by downscaleFactor. * @throws NullPointerException */ private Bitmap getDownscaledBitmapForView(View view, Rect crop, float downscaleFactor) throws BlurKitException, NullPointerException { View screenView = view.getRootView(); int width = (int) (crop.width() * downscaleFactor); int height = (int) (crop.height() * downscaleFactor); if (screenView.getWidth() <= 0 || screenView.getHeight() <= 0 || width <= 0 || height <= 0) { throw new BlurKitException("No screen available (width or height = 0)"); } float dx = -crop.left * downscaleFactor; float dy = -crop.top * downscaleFactor; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(bitmap); Matrix matrix = new Matrix(); matrix.preScale(downscaleFactor, downscaleFactor); matrix.postTranslate(dx, dy); canvas.setMatrix(matrix); screenView.draw(canvas); return bitmap; } /** * Sets downscale factor to use pre-blur. * See {@link #mDownscaleFactor}. */ public void setDownscaleFactor(float downscaleFactor) { this.mDownscaleFactor = downscaleFactor; // This field is now bad (it's pre-scaled with downscaleFactor so will need to be re-made) this.mLockedBitmap = null; invalidate(); } /** * Sets blur radius to use on downscaled bitmap. * See {@link #mBlurRadius}. */ public void setBlurRadius(int blurRadius) { this.mBlurRadius = blurRadius; // This field is now bad (it's pre-blurred with blurRadius so will need to be re-made) this.mLockedBitmap = null; invalidate(); } /** * Sets FPS to invalidate blur with. * See {@link #mFPS}. */ public void setFPS(int fps) { if (mRunning) { pauseBlur(); } this.mFPS = fps; if (mAttachedToWindow) { startBlur(); } } /** * Save the view bitmap to be re-used each frame instead of regenerating. */ public void lockView() { mViewLocked = true; if (mActivityView != null && mActivityView.get() != null) { View view = mActivityView.get().getRootView(); try { setAlpha(0f); mLockedBitmap = getDownscaledBitmapForView(view, new Rect(0, 0, view.getWidth(), view.getHeight()), mDownscaleFactor); setAlpha(1f); mLockedBitmap = BlurKit.getInstance().blur(mLockedBitmap, mBlurRadius); } catch (Exception e) { // ignore } } } /** * Stop using saved view bitmap. View bitmap will now be re-made each frame. */ public void unlockView() { mViewLocked = false; mLockedBitmap = null; } /** * Save the view position to be re-used each frame instead of regenerating. */ public void lockPosition() { mPositionLocked = true; mLockedPoint = getPositionInScreen(); } /** * Stop using saved point. Point will now be re-made each frame. */ public void unlockPosition() { mPositionLocked = false; mLockedPoint = null; } }
package com.io7m.smfj.tests.format.obj; import com.io7m.jlexing.core.LexicalPosition; import com.io7m.smfj.core.SMFAttribute; import com.io7m.smfj.core.SMFFormatVersion; import com.io7m.smfj.core.SMFHeader; import com.io7m.smfj.format.obj.SMFFormatOBJ; import com.io7m.smfj.parser.api.SMFParseError; import com.io7m.smfj.parser.api.SMFParserEventsType; import com.io7m.smfj.parser.api.SMFParserSequentialType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; public final class FOBJ { private static final Logger LOG; static { LOG = LoggerFactory.getLogger(FOBJ.class); } private FOBJ() { } public static void main(final String[] args) throws IOException { final SMFFormatOBJ fmt = new SMFFormatOBJ(); final Path path = Paths.get("test.obj"); try (final InputStream is = Files.newInputStream(path)) { try (final SMFParserSequentialType p = fmt.parserCreateSequential(new SMFParserEventsType() { @Override public void onHeaderParsed(final SMFHeader header) { LOG.debug("header parsed: {}", header); } @Override public void onStart() { LOG.debug("parser started"); } @Override public void onError( final SMFParseError e) { final LexicalPosition<Path> lexical = e.lexical(); final Optional<Path> opt = lexical.file(); if (opt.isPresent()) { LOG.error( "{}:{}:{}: {}", opt.get(), Integer.valueOf(lexical.line()), Integer.valueOf(lexical.column()), e.message()); } else { LOG.error( "{}:{}: {}", Integer.valueOf(lexical.line()), Integer.valueOf(lexical.column()), e.message()); } } @Override public void onVersionReceived( final SMFFormatVersion version) { LOG.info("version: {}", version); } @Override public void onDataAttributeStart( final SMFAttribute attribute) { LOG.debug("data start: {}", attribute); } @Override public void onDataAttributeValueIntegerSigned1( final long x) { LOG.debug( "data signed 1: {}", Long.valueOf(x)); } @Override public void onDataAttributeValueIntegerSigned2( final long x, final long y) { LOG.debug( "data signed 2: {} {}", Long.valueOf(x), Long.valueOf(y)); } @Override public void onDataAttributeValueIntegerSigned3( final long x, final long y, final long z) { LOG.debug( "data signed 3: {} {} {}", Long.valueOf(x), Long.valueOf(y), Long.valueOf(z)); } @Override public void onDataAttributeValueIntegerSigned4( final long x, final long y, final long z, final long w) { LOG.debug( "data signed 4: {} {} {} {}", Long.valueOf(x), Long.valueOf(y), Long.valueOf(z), Long.valueOf(w)); } @Override public void onDataAttributeValueIntegerUnsigned1( final long x) { LOG.debug( "data unsigned 1: {}", Long.valueOf(x)); } @Override public void onDataAttributeValueIntegerUnsigned2( final long x, final long y) { LOG.debug( "data unsigned 2: {} {}", Long.valueOf(x), Long.valueOf(y)); } @Override public void onDataAttributeValueIntegerUnsigned3( final long x, final long y, final long z) { LOG.debug( "data unsigned 3: {} {} {}", Long.valueOf(x), Long.valueOf(y), Long.valueOf(z)); } @Override public void onDataAttributeValueIntegerUnsigned4( final long x, final long y, final long z, final long w) { LOG.debug( "data unsigned 4: {} {} {} {}", Long.valueOf(x), Long.valueOf(y), Long.valueOf(z), Long.valueOf(w)); } @Override public void onDataAttributeValueFloat1( final double x) { LOG.debug( "data float 1: {}", Double.valueOf(x)); } @Override public void onDataAttributeValueFloat2( final double x, final double y) { LOG.debug( "data float 2: {} {}", Double.valueOf(x), Double.valueOf(y)); } @Override public void onDataAttributeValueFloat3( final double x, final double y, final double z) { LOG.debug( "data float 3: {} {} {}", Double.valueOf(x), Double.valueOf(y), Double.valueOf(z)); } @Override public void onDataAttributeValueFloat4( final double x, final double y, final double z, final double w) { LOG.debug( "data float 4: {} {} {} {}", Double.valueOf(x), Double.valueOf(y), Double.valueOf(z), Double.valueOf(w)); } @Override public void onDataAttributeFinish( final SMFAttribute attribute) { LOG.debug("data finish: {}", attribute); } @Override public void onDataTrianglesStart() { LOG.debug("triangles start"); } @Override public void onDataTriangle( final long v0, final long v1, final long v2) { LOG.debug( "triangle: {} {} {}", Long.valueOf(v0), Long.valueOf(v1), Long.valueOf(v2)); } @Override public void onDataTrianglesFinish() { LOG.debug("triangles finish"); } @Override public void onFinish() { LOG.debug("parser finished"); } }, path, is)) { p.parse(); } } } }
package com.github.fabienrenaud.jjb; import com.github.fabienrenaud.jjb.model.Users; import com.github.fabienrenaud.jjb.support.Api; import com.github.fabienrenaud.jjb.support.BenchSupport; import com.github.fabienrenaud.jjb.support.Library; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; public abstract class JsonBenchmark<T> { public static JsonBench BENCH; public static BenchSupport BENCH_SUPPORT; public static Api BENCH_API; private static final int ITERATIONS = 3; protected void test(final Library lib, final Object o) { if (o == null) { // means it shouldn't be supported. assertFalse("Library '" + lib + "' for api '" + BENCH_API + " returned null", supports(lib)); return; } if (o instanceof Users) { testPojo((T) o); } else if (o instanceof com.cedarsoftware.util.io.JsonObject) { String v = com.cedarsoftware.util.io.JsonWriter.objectToJson(o, BENCH.JSON_SOURCE.provider().jsonioStreamOptions()); testString(v); } else { testString(o.toString()); } } private void testString(String v) { try { testPojo(BENCH.JSON_SOURCE.provider().jackson().readValue(v, pojoType())); } catch (IOException ex) { fail(ex.getMessage()); } } private boolean supports(final Library lib) { return BENCH_SUPPORT.libapis().stream() .anyMatch((l) -> l.lib() == lib && l.api().contains(BENCH_API)); } protected abstract void testPojo(T obj); protected abstract Class<T> pojoType(); @Test public void gson() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.GSON, BENCH.gson()); } } @Test public void jackson() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.JACKSON, BENCH.jackson()); } } @Test public void jackson_afterburner() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.JACKSON_AFTERBURNER, BENCH.jackson_afterburner()); } } @Test public void orgjson() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.ORGJSON, BENCH.orgjson()); } } @Test public void genson() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.GENSON, BENCH.genson()); } } @Test public void javaxjson() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.JAVAXJSON, BENCH.javaxjson()); } } @Test @Ignore public void flexjson() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.FLEXJSON, BENCH.flexjson()); } } @Test public void fastjson() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.FASTJSON, BENCH.fastjson()); } } @Test public void jsonio() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.JSONIO, BENCH.jsonio()); } } @Test public void boon() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.BOON, BENCH.boon()); } } @Test public void johnson() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.JOHNZON, BENCH.johnzon()); } } @Test public void jsonsmart() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.JSONSMART, BENCH.jsonsmart()); } } @Test public void dsljson() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.DSLJSON, BENCH.dsljson()); } } @Test public void logansquare() throws Exception { for (int i = 0; i < ITERATIONS; i++) { test(Library.LOGANSQUARE, BENCH.logansquare()); } } }
package com.ociweb.hazelcast.stage; import java.util.concurrent.TimeUnit; import com.ociweb.hazelcast.HazelcastConfigurator; import org.junit.*; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeConfig; import com.ociweb.pronghorn.pipe.RawDataSchema; import com.ociweb.pronghorn.stage.PronghornStage; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.stage.scheduling.ThreadPerStageScheduler; import com.ociweb.pronghorn.stage.test.ConsoleJSONDumpStage; import com.ociweb.pronghorn.stage.test.PipeCleanerStage; public class ConnectionTest { private static HazelcastInstance memberInstance; @BeforeClass public static void startupClusterMember() { Config config = new Config(); config.getNetworkConfig().getJoin().getTcpIpConfig().addMember("127.0.0.1"); memberInstance = Hazelcast.newHazelcastInstance(config); if (0 == memberInstance.getAtomicLong("MyLock").getAndIncrement()) { System.out.println("Starting Connection Tets"); } } @AfterClass public static void shutdownClusterMember() { System.out.println("shutting down cluster"); memberInstance.shutdown(); } @Test public void simpleAuthTest() { GraphManager gm = new GraphManager(); PipeConfig<RawDataSchema> inputConfig = new PipeConfig(RawDataSchema.instance); PipeConfig<RequestResponseSchema> outputConfig = new PipeConfig(RequestResponseSchema.instance); Pipe<RawDataSchema> input = new Pipe<>(inputConfig); Pipe<RequestResponseSchema> output = new Pipe<>(outputConfig); HazelcastConfigurator conf = new HazelcastConfigurator(); GeneratorStage gs = new GeneratorStage(gm, input, false); ConnectionStage cs = new TestConnectionStageWrapper(gm, input, output, conf, true); //shutdown is done here GraphManager.addNota(gm, GraphManager.PRODUCER, GraphManager.PRODUCER, cs);//need to kill this quickly PipeCleanerStage pc = new PipeCleanerStage(gm, output); ThreadPerStageScheduler scheduler = new ThreadPerStageScheduler(gm); scheduler.startup(); scheduler.awaitTermination(3000, TimeUnit.SECONDS); } @Test public void simpleAuthAndPartitionRequestTest() { GraphManager gm = new GraphManager(); PipeConfig<RawDataSchema> inputConfig = new PipeConfig(RawDataSchema.instance); PipeConfig<RequestResponseSchema> outputConfig = new PipeConfig(RequestResponseSchema.instance); Pipe<RawDataSchema> input = new Pipe<>(inputConfig); Pipe<RequestResponseSchema> output = new Pipe<>(outputConfig); HazelcastConfigurator conf = new HazelcastConfigurator(); GeneratorStage gs = new GeneratorStage(gm, input, true); //shutdown is done here ConnectionStage cs = new TestConnectionStageWrapper(gm, input, output, conf, false); ConsoleJSONDumpStage<RequestResponseSchema> pc = new ConsoleJSONDumpStage<RequestResponseSchema>(gm, output); ThreadPerStageScheduler scheduler = new ThreadPerStageScheduler(gm); scheduler.startup(); //this is time is a hack because I do not have a design yet to make this test exit exactly when the data shows up. try { Thread.sleep(3_000); } catch (InterruptedException e) { } scheduler.shutdown(); scheduler.awaitTermination(60, TimeUnit.SECONDS); } public class TestConnectionStageWrapper extends ConnectionStage { private final boolean shutDownAfterAuth; protected TestConnectionStageWrapper(GraphManager graphManager, Pipe<RawDataSchema> input, Pipe<RequestResponseSchema> output, HazelcastConfigurator conf, boolean shutDownAfterAuth) { super(graphManager, input, output, conf); this.shutDownAfterAuth = shutDownAfterAuth; } @Override public void run() { super.run(); if (shutDownAfterAuth && isAuthenticated) { Assert.assertTrue(authUUIDLen > 10); System.out.println("IP & GUID:" + authResponse); requestShutdown(); } } } public class GeneratorStage extends PronghornStage { private boolean requestPartitions; private Pipe<RawDataSchema> output; protected GeneratorStage(GraphManager graphManager, Pipe<RawDataSchema> output, boolean requestPartitions) { super(graphManager, NONE, output); GraphManager.addNota(graphManager, GraphManager.PRODUCER, GraphManager.PRODUCER, this); this.output = output; this.supportsBatchedPublish = false; this.supportsBatchedRelease = false; this.requestPartitions = requestPartitions; } @Override public void run() { if (requestPartitions) { byte[] request = new byte[128]; //this is all zeros so zero length is allready set int messageType = 0x8; //request partitions // Curious -- I'm not sure why this sleep is necessary, but I(cas) don't have time to track it down // at the moment. If I take this out, the cluster gets an NPE in OnData. It may have something to // do with the platform I'm testing on -- it shows up in the Cloudbee's build as well, though --, // but a 3 second delay seems to provide enough time for the server -- or something -- to get set // up enough to handle the partition request. Curious, indeed. try { Thread.sleep(3_000); } catch (InterruptedException ie) { } int len = ConnectionStage.writeHeader(request, 0, 42, -1, messageType); request[0] = (byte) len; Pipe.addMsgIdx(output, RawDataSchema.MSG_CHUNKEDSTREAM_1); Pipe.addByteArray(request, 0, len, output); System.err.println("ConnectionTest: send partition request"); Pipe.publishWrites(output); requestPartitions = false; } } } }
package com.studiomediatech.wickject; import javax.inject.Inject; import com.studiomediatech.wickject.Wickject.Wickjection; import org.apache.wicket.injection.Injector; import org.apache.wicket.util.tester.WicketTester; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class WickjectTest { private WicketTester tester; @Before public void setUp() { this.tester = new WicketTester(); } @Test(expected = IllegalArgumentException.class) public void ensureWickjectAddInjectorThrowsOnNullParameter() throws Exception { Wickject.addInjector(null); } @Test(expected = IllegalArgumentException.class) public void ensureWickjectorThrowsWhenPassedNullType() throws Exception { Wickject.addInjector(this.tester).provides(this, null); } @Test public void ensureFieldIsNotInjectedWhenNothingProvided() { Wickject.addInjector(this.tester); FooService injectedService = new Foo().foo; Assert.assertNull("Was injected", injectedService); } @Test public void ensureFieldIsInjectedWhenProvidesObjectForType() { Wickjection injector = Wickject.addInjector(this.tester); FooService mockedService = Mockito.mock(FooService.class); injector.provides(mockedService, FooService.class); FooService injectedService = new Foo().foo; Assert.assertNotNull("Not injected", injectedService); Assert.assertEquals("Not injected with same mock", mockedService, injectedService); } @Test public void ensureFieldIsNotInjectedWhenProvidesObjectForOtherTypeOnly() throws Exception { Wickjection injector = Wickject.addInjector(this.tester); BarService mockedService = Mockito.mock(BarService.class); injector.provides(mockedService, BarService.class); FooService injectedService = new Foo().foo; Assert.assertNull("Was injected", injectedService); } @Test public void ensureBothFieldsInjectedWhenProvidesBothTypes() throws Exception { Wickjection injector = Wickject.addInjector(this.tester); FooService fooMock = Mockito.mock(FooService.class); BarService barMock = Mockito.mock(BarService.class); injector.provides(fooMock, FooService.class); injector.provides(barMock, BarService.class); Foobar foobar = new Foobar(); Assert.assertNotNull("Not injected", foobar.foo); Assert.assertEquals("Not injected with same mock", fooMock, foobar.foo); Assert.assertNotNull("Not injected", foobar.bar); Assert.assertEquals("Not injected with same mock", barMock, foobar.bar); } private interface FooService { void foo(); } private interface BarService { void bar(); } private class Foo { @Inject private FooService foo; public Foo() { Injector.get().inject(this); } } private class Foobar { @Inject private FooService foo; @Inject private BarService bar; public Foobar() { Injector.get().inject(this); } } }
package info.guardianproject.otr; import info.guardianproject.bouncycastle.util.encoders.Hex; import info.guardianproject.otr.app.im.R; import info.guardianproject.otr.app.im.app.ImApp; import info.guardianproject.otr.app.im.engine.Address; import info.guardianproject.util.LogCleaner; import info.guardianproject.util.Version; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPrivateKey; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.Vector; import net.java.otr4j.OtrKeyManager; import net.java.otr4j.OtrKeyManagerListener; import net.java.otr4j.OtrKeyManagerStore; import net.java.otr4j.crypto.OtrCryptoEngineImpl; import net.java.otr4j.crypto.OtrCryptoException; import net.java.otr4j.session.SessionID; import org.jivesoftware.smack.util.Base64; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; public class OtrAndroidKeyManagerImpl extends IOtrKeyManager.Stub implements OtrKeyManager { private static final boolean REGENERATE_LOCAL_PUBLIC_KEY = false; private SimplePropertiesStore store; private OtrCryptoEngineImpl cryptoEngine; private final static String KEY_ALG = "DSA"; private final static int KEY_SIZE = 1024; private final static Version CURRENT_VERSION = new Version("2.0.0"); private static OtrAndroidKeyManagerImpl _instance; private static final String FILE_KEYSTORE_ENCRYPTED = "otr_keystore.ofc"; private static final String FILE_KEYSTORE_UNENCRYPTED = "otr_keystore"; private final static String STORE_ALGORITHM = "PBEWITHMD5AND256BITAES-CBC-OPENSSL"; private static String mKeyStorePassword = null; public static void setKeyStorePassword (String keyStorePassword) { mKeyStorePassword = keyStorePassword; } public static synchronized OtrAndroidKeyManagerImpl getInstance(Context context) throws IOException { if (_instance == null && mKeyStorePassword != null) { File f = new File(context.getApplicationContext().getFilesDir(), FILE_KEYSTORE_ENCRYPTED); _instance = new OtrAndroidKeyManagerImpl(f,mKeyStorePassword); } return _instance; } private OtrAndroidKeyManagerImpl(File filepath, String password) throws IOException { this.store = new SimplePropertiesStore(filepath, password, false); // upgradeStore(); cryptoEngine = new OtrCryptoEngineImpl(); } /* private void upgradeStore() { String version = store.getPropertyString("version"); if (version == null || new Version(version).compareTo(new Version("1.0.0")) < 0) { // Add verified=false entries for TOFU sync purposes Set<Object> keys = Sets.newHashSet(store.getKeySet()); for (Object keyObject : keys) { String key = (String)keyObject; if (key.endsWith(".fingerprint")) { String fullUserId = key.replaceAll(".fingerprint$", ""); String fingerprint = store.getPropertyString(key); String verifiedKey = buildPublicKeyVerifiedId(fullUserId, fingerprint); if (!store.hasProperty(verifiedKey)) { // Avoid save store.setProperty(verifiedKey, "false"); } } } File fileOldKeystore = new File(FILE_KEYSTORE_UNENCRYPTED); if (fileOldKeystore.exists()) { try { SimplePropertiesStore storeOldKeystore = new SimplePropertiesStore(fileOldKeystore); Enumeration<Object> enumKeys = storeOldKeystore.getKeys(); while(enumKeys.hasMoreElements()) { String key = (String)enumKeys.nextElement(); store.setProperty(key, storeOldKeystore.getPropertyString(key)); } store.save(); fileOldKeystore.delete(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // This will save store.setProperty("version", CURRENT_VERSION.toString()); } }*/ static class SimplePropertiesStore implements OtrKeyManagerStore { private Properties mProperties = new Properties(); private File mStoreFile; private String mPassword; public SimplePropertiesStore(File storeFile) throws IOException { mStoreFile = storeFile; mProperties.clear(); mProperties.load(new FileInputStream(mStoreFile)); } public SimplePropertiesStore(File storeFile, final String password, boolean isImportFromKeySync) throws IOException { OtrDebugLogger.log("Loading store from encrypted file"); mStoreFile = storeFile; mProperties.clear(); if (password == null) throw new IOException ("invalid password"); mPassword = password; if (isImportFromKeySync) loadAES(password); else loadOpenSSL(password); } public void reload () throws IOException { loadOpenSSL(mPassword); } private void loadAES(final String password) throws IOException { String decoded; decoded = AES_256_CBC.decrypt(mStoreFile, password); mProperties.load(new ByteArrayInputStream(decoded.getBytes())); } public void setProperty(String id, String value) { mProperties.setProperty(id, value); } public void setProperty(String id, boolean value) { mProperties.setProperty(id, Boolean.toString(value)); } public boolean save () { try { saveOpenSSL (mPassword, mStoreFile); return true; } catch (IOException e) { LogCleaner.error(ImApp.LOG_TAG, "error saving keystore", e); return false; } } public boolean export (String password, File storeFile) { try { saveOpenSSL (password, storeFile); return true; } catch (IOException e) { LogCleaner.error(ImApp.LOG_TAG, "error saving keystore", e); return false; } } private void saveOpenSSL (String password, File fileStore) throws IOException { // Encrypt these bytes ByteArrayOutputStream baos = new ByteArrayOutputStream(); OpenSSLPBEOutputStream encOS = new OpenSSLPBEOutputStream(baos, STORE_ALGORITHM, 1, password.toCharArray()); mProperties.store(encOS, null); encOS.flush(); FileOutputStream fos = new FileOutputStream(fileStore); fos.write(baos.toByteArray()); fos.flush(); fos.close(); } private void loadOpenSSL(String password) throws IOException { if (!mStoreFile.exists()) return; if (mStoreFile.length() == 0) return; FileInputStream fis = null; try { fis = new FileInputStream(mStoreFile); // Decrypt the bytes OpenSSLPBEInputStream encIS = new OpenSSLPBEInputStream(fis, STORE_ALGORITHM, 1, password.toCharArray()); mProperties.load(encIS); } catch (FileNotFoundException fnfe) { OtrDebugLogger.log("Properties store file not found: First time?"); mStoreFile.getParentFile().mkdirs(); } } public void setProperty(String id, byte[] value) { mProperties.setProperty(id, new String(Base64.encodeBytes(value))); } // Store as hex bytes public void setPropertyHex(String id, byte[] value) { mProperties.setProperty(id, new String(Hex.encode(value))); } public void removeProperty(String id) { mProperties.remove(id); } public String getPropertyString(String id) { return mProperties.getProperty(id); } public byte[] getPropertyBytes(String id) { String value = mProperties.getProperty(id); if (value != null) return Base64.decode(value); return null; } // Load from hex bytes public byte[] getPropertyHexBytes(String id) { String value = mProperties.getProperty(id); if (value != null) return Hex.decode(value); return null; } public boolean getPropertyBoolean(String id, boolean defaultValue) { try { return Boolean.valueOf(mProperties.get(id).toString()); } catch (Exception e) { return defaultValue; } } public boolean hasProperty(String id) { return mProperties.containsKey(id); } public Enumeration<Object> getKeys () { return mProperties.keys(); } public Set<Object> getKeySet () { return mProperties.keySet(); } } private List<OtrKeyManagerListener> listeners = new Vector<OtrKeyManagerListener>(); public void addListener(OtrKeyManagerListener l) { synchronized (listeners) { if (!listeners.contains(l)) listeners.add(l); } } public void removeListener(OtrKeyManagerListener l) { synchronized (listeners) { listeners.remove(l); } } public void generateLocalKeyPair(SessionID sessionID) { if (sessionID == null) return; String accountID = sessionID.getAccountID(); generateLocalKeyPair(accountID); } public void regenerateLocalPublicKey(KeyFactory factory, String fullUserId, DSAPrivateKey privKey) { String userId = Address.stripResource(fullUserId); BigInteger x = privKey.getX(); DSAParams params = privKey.getParams(); BigInteger y = params.getG().modPow(x, params.getP()); DSAPublicKeySpec keySpec = new DSAPublicKeySpec(y, params.getP(), params.getQ(), params.getG()); PublicKey pubKey; try { pubKey = factory.generatePublic(keySpec); } catch (InvalidKeySpecException e) { throw new RuntimeException(e); } storeLocalPublicKey(userId, pubKey); } public void generateLocalKeyPair(String fullUserId) { String userId = Address.stripResource(fullUserId); OtrDebugLogger.log("generating local key pair for: " + userId); KeyPair keyPair; try { KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALG); kpg.initialize(KEY_SIZE); keyPair = kpg.genKeyPair(); } catch (NoSuchAlgorithmException e) { OtrDebugLogger.log("no such algorithm", e); return; } OtrDebugLogger.log("SUCCESS! generating local key pair for: " + userId); // Store Private Key. PrivateKey privKey = keyPair.getPrivate(); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privKey.getEncoded()); this.store.setProperty(userId + ".privateKey", pkcs8EncodedKeySpec.getEncoded()); // Store Public Key. PublicKey pubKey = keyPair.getPublic(); storeLocalPublicKey(userId, pubKey); store.save(); } private void storeLocalPublicKey(String fullUserId, PublicKey pubKey) { String userId = Address.stripResource(fullUserId); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKey.getEncoded()); this.store.setProperty(userId + ".publicKey", x509EncodedKeySpec.getEncoded()); // Stash fingerprint for consistency. try { String fingerprintString = new OtrCryptoEngineImpl().getFingerprint(pubKey); this.store.setPropertyHex(userId + ".fingerprint", Hex.decode(fingerprintString)); } catch (OtrCryptoException e) { e.printStackTrace(); } store.save(); } public boolean importKeyStore(String filePath, String password, boolean overWriteExisting, boolean deleteImportedFile) throws IOException { SimplePropertiesStore storeNew = null; File fileOtrKeystore = new File(filePath); if (fileOtrKeystore.getName().endsWith(".ofcaes")) { //TODO implement GUI to get password via QR Code, and handle wrong password storeNew = new SimplePropertiesStore(fileOtrKeystore, password, true); deleteImportedFile = true; // once its imported, its no longer needed } else { return false; } Enumeration<Object> enumKeys = storeNew.getKeys(); String key; while (enumKeys.hasMoreElements()) { key = (String)enumKeys.nextElement(); boolean hasKey = store.hasProperty(key); if (!hasKey || overWriteExisting) store.setProperty(key, storeNew.getPropertyString(key)); } store.save(); if (deleteImportedFile) fileOtrKeystore.delete(); return true; } public String getLocalFingerprint(SessionID sessionID) { return getLocalFingerprint(sessionID.getAccountID()); } public String getLocalFingerprint(String fullUserId) { String userId = Address.stripResource(fullUserId); KeyPair keyPair = loadLocalKeyPair(userId); if (keyPair == null) return null; PublicKey pubKey = keyPair.getPublic(); try { String fingerprint = cryptoEngine.getFingerprint(pubKey); OtrDebugLogger.log("got fingerprint for: " + userId + "=" + fingerprint); return fingerprint; } catch (OtrCryptoException e) { e.printStackTrace(); return null; } } public String getRemoteFingerprint(SessionID sessionID) { return getRemoteFingerprint(sessionID.getFullUserID()); } public String getRemoteFingerprint(String fullUserId) { if (!Address.hasResource(fullUserId)) return null; byte[] fingerprint = this.store.getPropertyHexBytes(fullUserId + ".fingerprint"); if (fingerprint != null) { // If we have a fingerprint stashed, assume it is correct. return new String(Hex.encode(fingerprint, 0, fingerprint.length)); } PublicKey remotePublicKey = loadRemotePublicKeyFromStore(fullUserId); if (remotePublicKey == null) return null; try { // Store the fingerprint, for posterity. String fingerprintString = new OtrCryptoEngineImpl().getFingerprint(remotePublicKey); this.store.setPropertyHex(fullUserId + ".fingerprint", Hex.decode(fingerprintString)); store.save(); return fingerprintString; } catch (OtrCryptoException e) { OtrDebugLogger.log("OtrCryptoException getting remote fingerprint",e); return null; } } public String[] getRemoteFingerprints(String userId) { Enumeration<Object> keys = store.getKeys(); ArrayList<String> results = new ArrayList<String>(); while (keys.hasMoreElements()) { String key = (String)keys.nextElement(); if (key.startsWith(userId + '/') && key.endsWith(".fingerprint")) { byte[] fingerprint = this.store.getPropertyHexBytes(userId + ".fingerprint"); if (fingerprint != null) { // If we have a fingerprint stashed, assume it is correct. results.add(new String(Hex.encode(fingerprint, 0, fingerprint.length))); } } } String[] resultsString = new String[results.size()]; return results.toArray(resultsString); } public boolean isVerified(SessionID sessionID) { if (sessionID == null) return false; String userId = sessionID.getUserID(); String fullUserID = sessionID.getFullUserID(); String remoteFingerprint =getRemoteFingerprint(fullUserID); if (remoteFingerprint != null) { String pubKeyVerifiedToken = buildPublicKeyVerifiedId(userId, remoteFingerprint); return this.store.getPropertyBoolean(pubKeyVerifiedToken, false); } else { return false; } } public boolean isVerifiedUser(String fullUserId) { String userId = Address.stripResource(fullUserId); String remoteFingerprint = getRemoteFingerprint(fullUserId); if (remoteFingerprint != null) { String pubKeyVerifiedToken = buildPublicKeyVerifiedId(userId, remoteFingerprint); return this.store.getPropertyBoolean(pubKeyVerifiedToken, false); } else return false; } public KeyPair loadLocalKeyPair(SessionID sessionID) { if (sessionID == null) return null; String accountID = sessionID.getAccountID(); return loadLocalKeyPair(accountID); } private KeyPair loadLocalKeyPair(String fullUserId) { PublicKey publicKey; PrivateKey privateKey; String userId = Address.stripResource(fullUserId); try { // Load Private Key. byte[] b64PrivKey = this.store.getPropertyBytes(userId + ".privateKey"); if (b64PrivKey == null) return null; PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64PrivKey); // Generate KeyPair. KeyFactory keyFactory; keyFactory = KeyFactory.getInstance(KEY_ALG); privateKey = keyFactory.generatePrivate(privateKeySpec); if (REGENERATE_LOCAL_PUBLIC_KEY) { regenerateLocalPublicKey(keyFactory, userId, (DSAPrivateKey)privateKey); } // Load Public Key. byte[] b64PubKey = this.store.getPropertyBytes(userId + ".publicKey"); if (b64PubKey == null) return null; X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey); publicKey = keyFactory.generatePublic(publicKeySpec); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } catch (InvalidKeySpecException e) { e.printStackTrace(); return null; } return new KeyPair(publicKey, privateKey); } public PublicKey loadRemotePublicKey(SessionID sessionID) { return loadRemotePublicKeyFromStore(sessionID.getFullUserID()); } private PublicKey loadRemotePublicKeyFromStore(String fullUserId) { if (!Address.hasResource(fullUserId)) return null; byte[] b64PubKey = this.store.getPropertyBytes(fullUserId + ".publicKey"); if (b64PubKey == null) { return null; } X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey); // Generate KeyPair from spec KeyFactory keyFactory; try { keyFactory = KeyFactory.getInstance(KEY_ALG); return keyFactory.generatePublic(publicKeySpec); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } catch (InvalidKeySpecException e) { e.printStackTrace(); return null; } } public void savePublicKey(SessionID sessionID, PublicKey pubKey) { if (sessionID == null) return; X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKey.getEncoded()); String fullUserId = sessionID.getFullUserID(); if (!Address.hasResource(fullUserId)) return; this.store.setProperty(fullUserId + ".publicKey", x509EncodedKeySpec.getEncoded()); // Stash the associated fingerprint. This saves calculating it in the future // and is useful for transferring rosters to other apps. try { String fingerprintString = new OtrCryptoEngineImpl().getFingerprint(pubKey); String verifiedToken = buildPublicKeyVerifiedId(fullUserId, fingerprintString.toLowerCase()); if (!this.store.hasProperty(verifiedToken)) this.store.setProperty(verifiedToken, false); this.store.setPropertyHex(fullUserId + ".fingerprint", Hex.decode(fingerprintString)); store.save(); } catch (OtrCryptoException e) { e.printStackTrace(); } } public void unverify(SessionID sessionID) { if (sessionID == null) return; if (!isVerified(sessionID)) return; unverifyUser(sessionID.getFullUserID()); for (OtrKeyManagerListener l : listeners) l.verificationStatusChanged(sessionID); } public void unverifyUser(String fullUserId) { if (!isVerifiedUser(fullUserId)) return; store.setProperty(buildPublicKeyVerifiedId(fullUserId, getRemoteFingerprint(fullUserId)), false); store.save(); } public void verify(SessionID sessionID) { if (sessionID == null) return; if (this.isVerified(sessionID)) return; verifyUser(sessionID.getFullUserID()); } public void remoteVerifiedUs(SessionID sessionID) { if (sessionID == null) return; for (OtrKeyManagerListener l : listeners) l.remoteVerifiedUs(sessionID); } private static String buildPublicKeyVerifiedId(String userId, String fingerprint) { if (fingerprint == null) return null; return Address.stripResource(userId) + "." + fingerprint + ".publicKey.verified"; } public void verifyUser(String userId) { if (userId == null) return; if (this.isVerifiedUser(userId)) return; this.store .setProperty(buildPublicKeyVerifiedId(userId, getRemoteFingerprint(userId)), true); store.save(); //for (OtrKeyManagerListener l : listeners) //l.verificationStatusChanged(userId); } public boolean doKeyStoreExport (String password) { // if otr_keystore.ofcaes is in the SDCard root, import it File otrKeystoreAES = new File(Environment.getExternalStorageDirectory(), "otr_keystore.ofcaes"); return store.export(password, otrKeystoreAES); } public static boolean checkForKeyImport (Intent intent, Activity activity) { boolean doKeyStoreImport = false; // if otr_keystore.ofcaes is in the SDCard root, import it File otrKeystoreAES = new File(Environment.getExternalStorageDirectory(), "otr_keystore.ofcaes"); if (otrKeystoreAES.exists()) { //Log.i(TAG, "found " + otrKeystoreAES + "to import"); doKeyStoreImport = true; importOtrKeyStore(otrKeystoreAES, activity); } else if (intent.getData() != null) { Uri uriData = intent.getData(); String path = null; if(uriData.getScheme() != null && uriData.getScheme().equals("file")) { path = uriData.toString().replace("file: File file = new File(path); doKeyStoreImport = true; importOtrKeyStore(file, activity); } } else { Toast.makeText(activity, R.string.otr_keysync_warning_message, Toast.LENGTH_LONG).show(); } return doKeyStoreImport; } public static void importOtrKeyStore (final File fileOtrKeyStore, final Activity activity) { try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext()); prefs.edit().putString("keystoreimport", fileOtrKeyStore.getCanonicalPath()).commit(); } catch (IOException ioe) { Log.e("TAG","problem importing key store",ioe); return; } Dialog.OnClickListener ocl = new Dialog.OnClickListener () { @Override public void onClick(DialogInterface dialog, int which) { //launch QR code intent IntentIntegrator.initiateScan(activity); } }; new AlertDialog.Builder(activity).setTitle(R.string.confirm) .setMessage(R.string.detected_Otr_keystore_import) .setPositiveButton(R.string.yes, ocl) // default button .setNegativeButton(R.string.no, null).setCancelable(true).show(); } public boolean importOtrKeyStoreWithPassword (String fileOtrKeyStore, String importPassword) { boolean overWriteExisting = true; boolean deleteImportedFile = true; try { return importKeyStore(fileOtrKeyStore, importPassword, overWriteExisting, deleteImportedFile); } catch (IOException e) { OtrDebugLogger.log("error importing key store",e); return false; } } public static boolean handleKeyScanResult (int requestCode, int resultCode, Intent data, Activity activity) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (scanResult != null) { String otrKeyPassword = scanResult.getContents(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext()); String otrKeyStorePath = prefs.getString("keystoreimport", null); Log.d("OTR","got password: " + otrKeyPassword + " for path: " + otrKeyStorePath); if (otrKeyPassword != null && otrKeyStorePath != null) { otrKeyPassword = otrKeyPassword.replace("\n","").replace("\r", ""); //remove any padding, newlines, etc try { File otrKeystoreAES = new File(otrKeyStorePath); if (otrKeystoreAES.exists()) { try { IOtrKeyManager keyMan = ((ImApp)activity.getApplication()).getRemoteImService().getOtrKeyManager(); return keyMan.importOtrKeyStoreWithPassword(otrKeystoreAES.getCanonicalPath(), otrKeyPassword); } catch (Exception e) { OtrDebugLogger.log("error getting keyman",e); return false; } } } catch (Exception e) { Toast.makeText(activity, "unable to open keystore for import", Toast.LENGTH_LONG).show(); return false; } } else { Log.d("OTR","no key store path saved"); return false; } } return false; } }
package liv; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import properties.Einstellungen; import eingaben.Konsoleneingabe; /** * Project: LIV - Lebensmittelinhaltsstoffverifizierer * * class Filter zeigt die moeglichen einzustellenden Filter und laesst diese * setzen oder entfernen * * @author team equal-IT / Team-Abend * @mail team@equal-it.de * @version 00.00.10 2016/06/20 * */ public class Filter { static Einstellungen einstellungen = new Einstellungen(); public static Set<Inhaltsstoff> setFilter() { Set<Inhaltsstoff> inhaltsstoffe = new HashSet<>(); Set<Inhaltsstoff> aktuellerFilter = einstellungen.leseAktuellenFilter(); inhaltsstoffe = aktuellerFilter; String auswahl = null; do { ausgabe.FiltermenueAusgabe.FilterHauptmenueAusgabe(); auswahl = Konsoleneingabe.leseKonsoleFuer(Arrays .asList(new String[] { liv.Inhaltsstoff.LAKTOSE.code(), liv.Inhaltsstoff.GLUTEN.code(), liv.Inhaltsstoff.NUSS.code(), ausgabe.FiltermenueEintrage.FILTERANZEIGE.code(), ausgabe.FiltermenueEintrage.HAUPTMENUE.code() })); if (auswahl != null) { if (auswahl.equals(ausgabe.FiltermenueEintrage.FILTERANZEIGE .code())) { System.out .println("\n System.out.println("\nAktiv gesetzte Filter: " + inhaltsstoffe.toString() + ""); } else { Inhaltsstoff inhaltsstoff = Inhaltsstoff .inhaltstoffFuerCode(auswahl); switch (inhaltsstoff) { case LAKTOSE: setzeOderEntferneFilter(inhaltsstoffe, inhaltsstoff); break; case GLUTEN: setzeOderEntferneFilter(inhaltsstoffe, inhaltsstoff); break; case NUSS: setzeOderEntferneFilter(inhaltsstoffe, inhaltsstoff); case UNBEKANNT: break; } } } } while (!ausgabe.FiltermenueEintrage.HAUPTMENUE.code().equals(auswahl)); return inhaltsstoffe; } private static void setzeOderEntferneFilter( Set<Inhaltsstoff> inhaltsstoffe, Inhaltsstoff inhaltsstoff) { String eingabeSetFilter; System.out.println("\n System.out.println("Filter '" + inhaltsstoff.anzeigename() + "' setzen oder entfernen?"); System.out.println("\n1 - Filter setzen"); System.out.println("2 - Filter entfernen"); System.out.println("\n eingabeSetFilter = Konsoleneingabe.leseKonsoleFuer(Arrays .asList(new String[] { "1", "2" })); if (eingabeSetFilter != null) { switch (eingabeSetFilter) { case "1": inhaltsstoffe.add(inhaltsstoff); System.out.println("\nFilter '" + inhaltsstoff.anzeigename() + "' wurde hinzugefuegt."); break; case "2": inhaltsstoffe.remove(inhaltsstoff); System.out.println("\nFilter '" + inhaltsstoff.anzeigename() + "' wurde entfernt."); break; default: System.out .println("\nFalsche Eingabe, bitte waehle einen Filter aus!"); break; } einstellungen.schreibeAktuellenFilter(inhaltsstoffe); } } }
package com.taskadapter.redmineapi; import com.taskadapter.redmineapi.bean.Changeset; import com.taskadapter.redmineapi.bean.CustomFieldDefinition; import com.taskadapter.redmineapi.bean.CustomFieldFactory; import com.taskadapter.redmineapi.bean.Issue; import com.taskadapter.redmineapi.bean.IssueCategory; import com.taskadapter.redmineapi.bean.IssueCategoryFactory; import com.taskadapter.redmineapi.bean.IssueFactory; import com.taskadapter.redmineapi.bean.IssueRelation; import com.taskadapter.redmineapi.bean.IssueStatus; import com.taskadapter.redmineapi.bean.Journal; import com.taskadapter.redmineapi.bean.JournalDetail; import com.taskadapter.redmineapi.bean.Project; import com.taskadapter.redmineapi.bean.SavedQuery; import com.taskadapter.redmineapi.bean.Tracker; import com.taskadapter.redmineapi.bean.User; import com.taskadapter.redmineapi.bean.Version; import com.taskadapter.redmineapi.bean.VersionFactory; import com.taskadapter.redmineapi.bean.Watcher; import com.taskadapter.redmineapi.bean.WatcherFactory; import com.taskadapter.redmineapi.internal.ResultsWrapper; import org.apache.http.client.HttpClient; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import static com.taskadapter.redmineapi.CustomFieldResolver.getCustomFieldByName; import static com.taskadapter.redmineapi.IssueHelper.createIssue; import static com.taskadapter.redmineapi.IssueHelper.createIssues; import com.taskadapter.redmineapi.bean.CustomField; import com.taskadapter.redmineapi.bean.Group; import com.taskadapter.redmineapi.bean.GroupFactory; import com.taskadapter.redmineapi.bean.Role; import com.taskadapter.redmineapi.bean.RoleFactory; import java.util.Arrays; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class IssueManagerIT { private static IssueManager issueManager; private static ProjectManager projectManager; private static MembershipManager membershipManager; private static Project project; private static int projectId; private static String projectKey; private static Project project2; private static String projectKey2; private static RedmineManager mgr; private static UserManager userManager; private static Group demoGroup; @BeforeClass public static void oneTimeSetup() throws RedmineException { mgr = IntegrationTestHelper.createRedmineManager(); userManager = mgr.getUserManager(); issueManager = mgr.getIssueManager(); projectManager = mgr.getProjectManager(); membershipManager = mgr.getMembershipManager(); project = IntegrationTestHelper.createProject(mgr); projectId = project.getId(); projectKey = project.getIdentifier(); project2 = IntegrationTestHelper.createProject(mgr); projectKey2 = project2.getIdentifier(); Group g = GroupFactory.create(); g.setName("Group" + System.currentTimeMillis()); demoGroup = userManager.createGroup(g); // Add membership of group for the demo projects Collection<Role> allRoles = Arrays.asList(new Role[] { RoleFactory.create(3), // Manager RoleFactory.create(4), // Developer RoleFactory.create(5) // Reporter }); membershipManager.createMembershipForGroup(project.getId(), demoGroup.getId(), allRoles); membershipManager.createMembershipForGroup(project2.getId(), demoGroup.getId(), allRoles); } @AfterClass public static void oneTimeTearDown() throws RedmineException { IntegrationTestHelper.deleteProject(mgr, project.getIdentifier()); IntegrationTestHelper.deleteProject(mgr, project2.getIdentifier()); userManager.deleteGroup(demoGroup); } @Test public void issueCreated() throws RedmineException { Issue issueToCreate = IssueFactory.create(projectId, "test zzx"); Calendar startCal = Calendar.getInstance(); // have to clear them because they are ignored by Redmine and // prevent from comparison later startCal.clear(Calendar.HOUR_OF_DAY); startCal.clear(Calendar.MINUTE); startCal.clear(Calendar.SECOND); startCal.clear(Calendar.MILLISECOND); startCal.add(Calendar.DATE, 5); issueToCreate.setStartDate(startCal.getTime()); Calendar due = Calendar.getInstance(); due.add(Calendar.MONTH, 1); issueToCreate.setDueDate(due.getTime()); User ourUser = IntegrationTestHelper.getOurUser(); issueToCreate.setAssigneeId(ourUser.getId()); String description = "This is the description for the new task." + "\nIt has several lines." + "\nThis is the last line."; issueToCreate.setDescription(description); float estimatedHours = 44; issueToCreate.setEstimatedHours(estimatedHours); Issue newIssue = issueManager.createIssue(issueToCreate); assertNotNull("Checking returned result", newIssue); assertNotNull("New issue must have some ID", newIssue.getId()); // check startDate Calendar returnedStartCal = Calendar.getInstance(); returnedStartCal.setTime(newIssue.getStartDate()); assertEquals(startCal.get(Calendar.YEAR), returnedStartCal.get(Calendar.YEAR)); assertEquals(startCal.get(Calendar.MONTH), returnedStartCal.get(Calendar.MONTH)); assertEquals(startCal.get(Calendar.DAY_OF_MONTH), returnedStartCal.get(Calendar.DAY_OF_MONTH)); // check dueDate Calendar returnedDueCal = Calendar.getInstance(); returnedDueCal.setTime(newIssue.getDueDate()); assertEquals(due.get(Calendar.YEAR), returnedDueCal.get(Calendar.YEAR)); assertEquals(due.get(Calendar.MONTH), returnedDueCal.get(Calendar.MONTH)); assertEquals(due.get(Calendar.DAY_OF_MONTH), returnedDueCal.get(Calendar.DAY_OF_MONTH)); // check ASSIGNEE assertThat(ourUser.getId()).isEqualTo(newIssue.getAssigneeId()); // check AUTHOR Integer EXPECTED_AUTHOR_ID = IntegrationTestHelper.getOurUser().getId(); assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthorId()); // check ESTIMATED TIME assertEquals((Float) estimatedHours, newIssue.getEstimatedHours()); // check multi-line DESCRIPTION String regexpStripExtra = "\\r|\\n|\\s"; description = description.replaceAll(regexpStripExtra, ""); String actualDescription = newIssue.getDescription(); actualDescription = actualDescription.replaceAll(regexpStripExtra, ""); assertEquals(description, actualDescription); // PRIORITY assertNotNull(newIssue.getPriorityId()); assertTrue(newIssue.getPriorityId() > 0); } @Test public void issueWithParentCreated() throws RedmineException { Issue parentIssue = IssueFactory.create(projectId, "parent 1"); Issue newParentIssue = issueManager.createIssue(parentIssue); assertNotNull("Checking parent was created", newParentIssue); assertNotNull("Checking ID of parent issue is not null", newParentIssue.getId()); // Integer parentId = 46; Integer parentId = newParentIssue.getId(); Issue childIssue = IssueFactory.create(projectId, "child 1"); childIssue.setParentId(parentId); Issue newChildIssue = issueManager.createIssue(childIssue); assertEquals("Checking parent ID of the child issue", parentId, newChildIssue.getParentId()); } @Test public void parentIdCanBeErased() throws RedmineException { Issue parentIssue = IssueFactory.create(projectId, "parent task"); Issue newParentIssue = issueManager.createIssue(parentIssue); Integer parentId = newParentIssue.getId(); Issue childIssue = IssueFactory.create(projectId, "child task"); childIssue.setParentId(parentId); Issue newChildIssue = issueManager.createIssue(childIssue); assertThat(newChildIssue.getParentId()).isEqualTo(parentId); newChildIssue.setParentId(null); issueManager.update(newChildIssue); final Issue reloadedIssue = issueManager.getIssueById(newChildIssue.getId()); assertThat(reloadedIssue.getParentId()).isNull(); } @Test public void testUpdateIssue() throws RedmineException { String originalSubject = "Issue " + new Date(); Issue issue = IssueFactory.create(projectId, originalSubject); Issue newIssue = issueManager.createIssue(issue); String changedSubject = "changed subject"; newIssue.setSubject(changedSubject); issueManager.update(newIssue); Issue reloadedFromRedmineIssue = issueManager.getIssueById(newIssue.getId()); assertEquals("Checking if 'update issue' operation changed 'subject' field", changedSubject, reloadedFromRedmineIssue.getSubject()); } /** * Tests the retrieval of an {@link Issue} by its ID. * * @throws com.taskadapter.redmineapi.RedmineException * thrown in case something went wrong in Redmine * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws com.taskadapter.redmineapi.NotFoundException * thrown in case the objects requested for could not be found */ @Test public void testGetIssueById() throws RedmineException { String originalSubject = "Issue " + new Date(); Issue issue = IssueFactory.create(projectId, originalSubject); Issue newIssue = issueManager.createIssue(issue); Issue reloadedFromRedmineIssue = issueManager.getIssueById(newIssue.getId()); assertEquals( "Checking if 'get issue by ID' operation returned issue with same 'subject' field", originalSubject, reloadedFromRedmineIssue.getSubject()); Tracker tracker = reloadedFromRedmineIssue.getTracker(); assertNotNull("Tracker of issue should not be null", tracker); assertNotNull("ID of tracker of issue should not be null", tracker.getId()); assertNotNull("Name of tracker of issue should not be null", tracker.getName()); } @Test public void testGetIssues() throws RedmineException { // create at least 1 issue Issue issueToCreate = IssueFactory.create(projectId, "testGetIssues: " + new Date()); Issue newIssue = issueManager.createIssue(issueToCreate); List<Issue> issues = issueManager.getIssues(projectKey, null); assertTrue(issues.size() > 0); boolean found = false; for (Issue issue : issues) { if (issue.getId().equals(newIssue.getId())) { found = true; break; } } if (!found) { fail("getIssues() didn't return the issue we just created. The query " + " must have returned all issues created during the last 2 days"); } } @Test(expected = NotFoundException.class) public void testGetIssuesInvalidQueryId() throws RedmineException { Integer invalidQueryId = 9999999; issueManager.getIssues(projectKey, invalidQueryId); } @Test public void testCreateIssueNonUnicodeSymbols() throws RedmineException { String nonLatinSymbols = "Example with accents Ao"; Issue toCreate = IssueFactory.create(projectId, nonLatinSymbols); Issue created = issueManager.createIssue(toCreate); assertEquals(nonLatinSymbols, created.getSubject()); } @Test public void testCreateIssueSummaryOnly() throws RedmineException { Issue issueToCreate = IssueFactory.create(projectId, "This is the summary line 123"); Issue newIssue = issueManager.createIssue(issueToCreate); assertNotNull("Checking returned result", newIssue); assertNotNull("New issue must have some ID", newIssue.getId()); // check AUTHOR Integer EXPECTED_AUTHOR_ID = IntegrationTestHelper.getOurUser().getId(); assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthorId()); } @Test public void privateFlagIsRespectedWhenCreatingIssues() throws RedmineException { Issue privateIssueToCreate = IssueFactory.create(projectId, "private issue"); privateIssueToCreate.setPrivateIssue(true); Issue newIssue = issueManager.createIssue(privateIssueToCreate); assertThat(newIssue.isPrivateIssue()).isTrue(); Issue publicIssueToCreate = IssueFactory.create(projectId, "public issue"); publicIssueToCreate.setPrivateIssue(false); Issue newPublicIssue = issueManager.createIssue(publicIssueToCreate); assertThat(newPublicIssue.isPrivateIssue()).isFalse(); // default value for "is private" should be false Issue newDefaultIssue = issueManager.createIssue(IssueFactory.create(projectId, "default public issue")); assertThat(newDefaultIssue.isPrivateIssue()).isFalse(); } /* this test fails with Redmine 3.0.0-3.0.3 because Redmine 3.0.x started * returning "not authorized" instead of "not found" for projects with unknown Ids. * This worked differently with Redmine 2.6.x. * <p> * This test is not critical for the release of Redmine Java API library. I am marking it as "ignored" for now. */ @Ignore @Test(expected = NotFoundException.class) public void creatingIssueWithNonExistingProjectIdGivesNotFoundException() throws RedmineException { int nonExistingProjectId = 99999999; // hopefully this does not exist :) Issue issueToCreate = IssueFactory.create(nonExistingProjectId, "Summary line 100"); issueManager.createIssue(issueToCreate); } @Test(expected = NotFoundException.class) public void retrievingIssueWithNonExistingIdGivesNotFoundException() throws RedmineException { int someNonExistingID = 999999; issueManager.getIssueById(someNonExistingID); } @Test(expected = NotFoundException.class) public void updatingIssueWithNonExistingIdGivesNotFoundException() throws RedmineException { int nonExistingId = 999999; Issue issue = IssueFactory.create(nonExistingId); issueManager.update(issue); } @Test public void testGetIssuesPaging() throws RedmineException { // create 27 issues. default page size is 25. createIssues(issueManager, projectId, 27); List<Issue> issues = issueManager.getIssues(projectKey, null); assertThat(issues.size()).isGreaterThan(26); // check that there are no duplicates in the list. Set<Issue> issueSet = new HashSet<>(issues); assertThat(issueSet.size()).isEqualTo(issues.size()); } @Test public void canControlLimitAndOffsetDirectly() throws RedmineException { // create 27 issues. default Redmine page size is usually 25 (unless changed in the server settings). createIssues(issueManager, projectId, 27); Map<String, String> params = new HashMap<>(); params.put("limit", "3"); params.put("offset", "0"); params.put("project_id", projectId + ""); List<Issue> issues = issueManager.getIssues(params).getResults(); // only the requested number of issues is loaded, not all result pages. assertThat(issues.size()).isEqualTo(3); } @Test(expected = NotFoundException.class) public void testDeleteIssue() throws RedmineException { Issue issue = createIssues(issueManager, projectId, 1).get(0); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); issueManager.deleteIssue(issue.getId()); issueManager.getIssueById(issue.getId()); } @Test public void testUpdateIssueSpecialXMLtags() throws Exception { Issue issue = createIssues(issueManager, projectId, 1).get(0); String newSubject = "\"text in quotes\" and <xml> tags"; String newDescription = "<taghere>\"abc\"</here>"; issue.setSubject(newSubject); issue.setDescription(newDescription); issueManager.update(issue); Issue updatedIssue = issueManager.getIssueById(issue.getId()); assertEquals(newSubject, updatedIssue.getSubject()); assertEquals(newDescription, updatedIssue.getDescription()); } @Test public void testCreateRelation() throws RedmineException { List<Issue> issues = createIssues(issueManager, projectId, 2); Issue src = issues.get(0); Issue target = issues.get(1); String relationText = IssueRelation.TYPE.precedes.toString(); IssueRelation r = issueManager.createRelation(src.getId(), target.getId(), relationText); assertEquals(src.getId(), r.getIssueId()); assertEquals(target.getId(), r.getIssueToId()); assertEquals(relationText, r.getType()); } private IssueRelation createTwoRelatedIssues() throws RedmineException { List<Issue> issues = createIssues(issueManager, projectId, 2); Issue src = issues.get(0); Issue target = issues.get(1); String relationText = IssueRelation.TYPE.precedes.toString(); return issueManager.createRelation(src.getId(), target.getId(), relationText); } @Test public void issueRelationsAreCreatedAndLoadedOK() throws RedmineException { IssueRelation relation = createTwoRelatedIssues(); Issue issue = issueManager.getIssueById(relation.getIssueId(), Include.relations); Issue issueTarget = issueManager.getIssueById(relation.getIssueToId(), Include.relations); assertThat(issue.getRelations().size()).isEqualTo(1); assertThat(issueTarget.getRelations().size()).isEqualTo(1); IssueRelation relation1 = issue.getRelations().iterator().next(); assertThat(relation1.getIssueId()).isEqualTo(issue.getId()); assertThat(relation1.getIssueToId()).isEqualTo(issueTarget.getId()); assertThat(relation1.getType()).isEqualTo("precedes"); assertThat(relation1.getDelay()).isEqualTo((Integer) 0); IssueRelation reverseRelation = issueTarget.getRelations().iterator().next(); // both forward and reverse relations are the same! assertThat(reverseRelation).isEqualTo(relation1); } @Test public void issueRelationIsDeleted() throws RedmineException { IssueRelation relation = createTwoRelatedIssues(); issueManager.deleteRelation(relation.getId()); Issue issue = issueManager.getIssueById(relation.getIssueId(), Include.relations); assertThat(issue.getRelations()).isEmpty(); } @Test public void testIssueRelationsDelete() throws RedmineException { List<Issue> issues = createIssues(issueManager, projectId, 3); Issue src = issues.get(0); Issue target = issues.get(1); String relationText = IssueRelation.TYPE.precedes.toString(); issueManager.createRelation(src.getId(), target.getId(), relationText); target = issues.get(2); issueManager.createRelation(src.getId(), target.getId(), relationText); src = issueManager.getIssueById(src.getId(), Include.relations); issueManager.deleteIssueRelations(src); Issue issue = issueManager.getIssueById(src.getId(), Include.relations); assertTrue(issue.getRelations().isEmpty()); } /** * Requires Redmine 2.3 */ @Test public void testAddIssueWatcher() throws RedmineException { final Issue issue = createIssues(issueManager, projectId, 1).get(0); final Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); try { Watcher watcher = WatcherFactory.create(newUser.getId()); issueManager.addWatcherToIssue(watcher, issue); } finally { userManager.deleteUser(newUser.getId()); } issueManager.getIssueById(issue.getId()); } /** * Requires Redmine 2.3 */ @Test public void testDeleteIssueWatcher() throws RedmineException { final Issue issue = createIssues(issueManager, projectId, 1).get(0); final Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); try { Watcher watcher = WatcherFactory.create(newUser.getId()); issueManager.addWatcherToIssue(watcher, issue); issueManager.deleteWatcherFromIssue(watcher, issue); } finally { userManager.deleteUser(newUser.getId()); } issueManager.deleteIssue(issue.getId()); } /** * Requires Redmine 2.3 */ @Test public void testGetIssueWatcher() throws RedmineException { final Issue issue = createIssues(issueManager, projectId, 1).get(0); final Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); try { Watcher watcher = WatcherFactory.create(newUser.getId()); issueManager.addWatcherToIssue(watcher, issue); final Issue includeWatcherIssue = issueManager.getIssueById(issue.getId(), Include.watchers); if (!includeWatcherIssue.getWatchers().isEmpty()) { Watcher watcher1 = includeWatcherIssue.getWatchers().iterator().next(); assertThat(watcher1.getId()).isEqualTo(newUser.getId()); } } finally { userManager.deleteUser(newUser.getId()); } issueManager.getIssueById(issue.getId()); } @Test public void testAddIssueWithWatchers() throws RedmineException { final Issue issue = IssueHelper.generateRandomIssue(projectId); final User newUserWatcher = userManager.createUser(UserGenerator.generateRandomUser()); try { List<Watcher> watchers = new ArrayList<>(); Watcher watcher = WatcherFactory.create(newUserWatcher.getId()); watchers.add(watcher); issue.addWatchers(watchers); final Issue retrievedIssue = issueManager.createIssue(issue); final Issue retrievedIssueWithWatchers = issueManager.getIssueById(retrievedIssue.getId(), Include.watchers); assertNotNull(retrievedIssueWithWatchers); assertNotNull(retrievedIssueWithWatchers.getWatchers()); assertEquals(watchers.size(), retrievedIssueWithWatchers.getWatchers().size()); assertEquals(watcher.getId(), retrievedIssueWithWatchers.getWatchers().iterator().next().getId()); } finally { userManager.deleteUser(newUserWatcher.getId()); } } @Test public void testGetIssuesBySummary() throws RedmineException { String summary = "issue with subject ABC"; Issue issue = IssueFactory.create(projectId, summary); User ourUser = IntegrationTestHelper.getOurUser(); issue.setAssigneeId(ourUser.getId()); Issue newIssue = issueManager.createIssue(issue); assertNotNull("Checking returned result", newIssue); assertNotNull("New issue must have some ID", newIssue.getId()); List<Issue> foundIssues = issueManager.getIssuesBySummary(projectKey, summary); assertNotNull("Checking if search results is not NULL", foundIssues); assertTrue("Search results must be not empty", !(foundIssues.isEmpty())); Issue loadedIssue1 = RedmineTestUtils.findIssueInList(foundIssues, newIssue.getId()); assertNotNull(loadedIssue1); assertEquals(summary, loadedIssue1.getSubject()); } @Test public void findByNonExistingSummaryReturnsEmptyList() throws RedmineException { String summary = "some summary here for issue which does not exist"; List<Issue> foundIssues = issueManager.getIssuesBySummary(projectKey, summary); assertNotNull("Search result must be not null", foundIssues); assertTrue("Search result list must be empty", foundIssues.isEmpty()); } @Test(expected = RedmineAuthenticationException.class) public void noAPIKeyOnCreateIssueThrowsAE() throws Exception { TestConfig testConfig = new TestConfig(); final HttpClient httpClient = IntegrationTestHelper.getHttpClientForTestServer(); RedmineManager redmineMgrEmpty = RedmineManagerFactory.createUnauthenticated(testConfig.getURI(), httpClient); Issue issue = IssueFactory.create(projectId, "test zzx"); redmineMgrEmpty.getIssueManager().createIssue(issue); } @Test(expected = RedmineAuthenticationException.class) public void wrongAPIKeyOnCreateIssueThrowsAE() throws Exception { TestConfig testConfig = new TestConfig(); final HttpClient httpClient = IntegrationTestHelper.getHttpClientForTestServer(); RedmineManager redmineMgrInvalidKey = RedmineManagerFactory.createWithApiKey( testConfig.getURI(), "wrong_key", httpClient); Issue issue = IssueFactory.create(projectId, "test zzx"); redmineMgrInvalidKey.getIssueManager().createIssue(issue); } @Test public void testIssueDoneRatio() throws RedmineException { Issue issue = IssueFactory.create(projectId, "Issue " + new Date()); Issue createdIssue = issueManager.createIssue(issue); assertEquals("Initial 'done ratio' must be 0", (Integer) 0, createdIssue.getDoneRatio()); Integer doneRatio = 50; createdIssue.setDoneRatio(doneRatio); issueManager.update(createdIssue); Integer issueId = createdIssue.getId(); Issue reloadedFromRedmineIssue = issueManager.getIssueById(issueId); assertEquals( "Checking if 'update issue' operation changed 'done ratio' field", doneRatio, reloadedFromRedmineIssue.getDoneRatio()); Integer invalidDoneRatio = 130; reloadedFromRedmineIssue.setDoneRatio(invalidDoneRatio); try { issueManager.update(reloadedFromRedmineIssue); } catch (RedmineProcessingException e) { assertEquals("Must be 1 error", 1, e.getErrors().size()); assertEquals("Checking error text", "% Done is not included in the list", e.getErrors() .get(0)); } Issue reloadedFromRedmineIssueUnchanged = issueManager.getIssueById(issueId); assertEquals( "'done ratio' must have remained unchanged after invalid value", doneRatio, reloadedFromRedmineIssueUnchanged.getDoneRatio()); } @Test public void nullDescriptionErasesItOnServer() throws RedmineException { Issue issue = new Issue(); String subject = "Issue " + new Date(); String descr = "Some description"; issue.setSubject(subject); issue.setDescription(descr); issue.setProjectId(projectId); Issue createdIssue = issueManager.createIssue(issue); assertThat(createdIssue.getDescription()).isEqualTo(descr); createdIssue.setDescription(null); issueManager.update(createdIssue); Integer issueId = createdIssue.getId(); Issue reloadedFromRedmineIssue = issueManager.getIssueById(issueId); assertThat(reloadedFromRedmineIssue.getDescription()).isNull(); } @Test public void testIssueJournals() throws RedmineException { // create at least 1 issue Issue issueToCreate = new Issue(); issueToCreate.setSubject("testGetIssues: " + new Date()); issueToCreate.setProjectId(projectId); Issue newIssue = issueManager.createIssue(issueToCreate); Issue loadedIssueWithJournals = issueManager.getIssueById(newIssue.getId(), Include.journals); assertTrue(loadedIssueWithJournals.getJournals().isEmpty()); String commentDescribingTheUpdate = "some comment describing the issue update"; loadedIssueWithJournals.setSubject("new subject"); loadedIssueWithJournals.setNotes(commentDescribingTheUpdate); issueManager.update(loadedIssueWithJournals); Issue loadedIssueWithJournals2 = issueManager.getIssueById(newIssue.getId(), Include.journals); assertEquals(1, loadedIssueWithJournals2.getJournals() .size()); Journal journalItem = loadedIssueWithJournals2.getJournals().iterator().next(); assertEquals(commentDescribingTheUpdate, journalItem.getNotes()); User ourUser = IntegrationTestHelper.getOurUser(); // can't compare User objects because either of them is not // completely filled assertEquals(ourUser.getId(), journalItem.getUser().getId()); assertEquals(ourUser.getFirstName(), journalItem.getUser() .getFirstName()); assertEquals(ourUser.getLastName(), journalItem.getUser() .getLastName()); assertEquals(1, journalItem.getDetails().size()); final JournalDetail journalDetail = journalItem.getDetails().get(0); assertEquals("new subject", journalDetail.getNewValue()); assertEquals("subject", journalDetail.getName()); assertEquals("attr", journalDetail.getProperty()); Issue loadedIssueWithoutJournals = issueManager.getIssueById(newIssue.getId()); assertTrue(loadedIssueWithoutJournals.getJournals().isEmpty()); } @Test public void updateIssueDescription() throws RedmineException { Issue issue = IssueFactory.create(projectId, "test123"); final Issue iss1 = issueManager.createIssue(issue); final Issue iss2 = IssueFactory.create(iss1.getId()); iss2.setProjectId(projectId); iss2.setDescription("This is a test"); issueManager.update(iss2); final Issue iss3 = issueManager.getIssueById(iss2.getId()); assertEquals("test123", iss3.getSubject()); assertEquals("This is a test", iss3.getDescription()); } @Test public void updateIssueTitle() throws RedmineException { Issue issue = IssueFactory.create(projectId, "test123"); issue.setDescription("Original description"); final Issue iss1 = issueManager.createIssue(issue); final Issue iss2 = IssueFactory.create(iss1.getId()); iss2.setSubject("New subject"); iss2.setProjectId(projectId); issueManager.update(iss2); final Issue iss3 = issueManager.getIssueById(iss2.getId()); assertEquals("New subject", iss3.getSubject()); assertEquals("Original description", iss3.getDescription()); } @Test public void testIssuePriorities() throws RedmineException { assertTrue(issueManager.getIssuePriorities().size() > 0); } @Test public void issueTargetVersionIsSetWhenCreatingOrUpdatingIssues() throws Exception { final String version1Name = "1.0"; final String version2Name = "2.0"; final Issue issueToCreate = IssueHelper.generateRandomIssue(projectId); Version version1 = createVersion(version1Name); issueToCreate.setTargetVersion(version1); issueToCreate.setProjectId(project.getId()); final Issue createdIssue = issueManager.createIssue(issueToCreate); assertNotNull(createdIssue.getTargetVersion()); assertEquals(createdIssue.getTargetVersion().getName(), version1Name); Version version2 = createVersion(version2Name); createdIssue.setTargetVersion(version2); issueManager.update(createdIssue); Issue updatedIssue = issueManager.getIssueById(createdIssue.getId()); assertThat(updatedIssue.getTargetVersion().getName()).isEqualTo(version2Name); createdIssue.setTargetVersion(null); issueManager.update(createdIssue); updatedIssue = issueManager.getIssueById(createdIssue.getId()); assertThat(updatedIssue.getTargetVersion()).isNull(); } private Version createVersion(String versionName) throws RedmineException { final Version version = VersionFactory.create(1); version.setName(versionName); version.setProjectId(projectId); return mgr.getProjectManager().createVersion(version); } @Test public void testUpdateIssueDoesNotChangeEstimatedTime() throws RedmineException { String originalSubject = "Issue " + new Date(); Issue issue = IssueFactory.create(projectId, originalSubject); Issue newIssue = issueManager.createIssue(issue); assertEquals("Estimated hours must be NULL", null, newIssue.getEstimatedHours()); issueManager.update(newIssue); Issue reloadedFromRedmineIssue = issueManager.getIssueById(newIssue.getId()); assertEquals("Estimated hours must be NULL", null, reloadedFromRedmineIssue.getEstimatedHours()); } /** * tests the retrieval of statuses. * * @throws RedmineProcessingException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testGetStatuses() throws RedmineException { // TODO we should create some statuses first, but the Redmine Java API // does not support this presently List<IssueStatus> statuses = issueManager.getStatuses(); assertFalse("Expected list of statuses not to be empty", statuses.isEmpty()); for (IssueStatus issueStatus : statuses) { // asserts on status assertNotNull("ID of status must not be null", issueStatus.getId()); assertNotNull("Name of status must not be null", issueStatus.getName()); } } /** * tests the creation and deletion of a {@link com.taskadapter.redmineapi.bean.IssueCategory}. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testCreateAndDeleteIssueCategory() throws RedmineException { Project project = projectManager.getProjectByKey(projectKey); IssueCategory category = IssueCategoryFactory.create(project.getId(), "Category" + new Date().getTime()); category.setAssigneeId(IntegrationTestHelper.getOurUser().getId()); IssueCategory newIssueCategory = issueManager.createCategory(category); assertNotNull("Expected new category not to be null", newIssueCategory); assertNotNull("Expected projectId of new category not to be null", newIssueCategory.getProjectId()); assertNotNull("Expected assignee of new category not to be null", newIssueCategory.getAssigneeId()); assertThat(newIssueCategory.getAssigneeId()).isEqualTo(IntegrationTestHelper.getOurUser().getId()); // now delete category issueManager.deleteCategory(newIssueCategory); // assert that the category is gone List<IssueCategory> categories = issueManager.getCategories(project.getId()); assertTrue( "List of categories of test project must be empty now but is " + categories, categories.isEmpty()); } /** * tests the creation and deletion of a {@link com.taskadapter.redmineapi.bean.IssueCategory} * with the group as assignee * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testCreateAndDeleteIssueCategoryGroupAssignee() throws RedmineException { Project project = projectManager.getProjectByKey(projectKey); IssueCategory category = IssueCategoryFactory.create(project.getId(), "Category" + new Date().getTime()); category.setAssigneeId(demoGroup.getId()); IssueCategory newIssueCategory = issueManager.createCategory(category); assertNotNull("Expected new category not to be null", newIssueCategory); assertNotNull("Expected projectId of new category not to be null", newIssueCategory.getProjectId()); assertNotNull("Expected assignee of new category not to be null", newIssueCategory.getAssigneeId()); assertThat(newIssueCategory.getAssigneeId()).isEqualTo(demoGroup.getId()); assertThat(newIssueCategory.getAssigneeName()).isEqualTo(demoGroup.getName()); // now delete category issueManager.deleteCategory(newIssueCategory); // assert that the category is gone List<IssueCategory> categories = issueManager.getCategories(project.getId()); assertTrue( "List of categories of test project must be empty now but is " + categories, categories.isEmpty()); } /** * tests the retrieval of {@link IssueCategory}s. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testGetIssueCategories() throws RedmineException { Project project = projectManager.getProjectByKey(projectKey); // create some categories IssueCategory testIssueCategory1 = IssueCategoryFactory.create(project.getId(), "Category" + new Date().getTime()); Integer ourUserId = IntegrationTestHelper.getOurUser().getId(); testIssueCategory1.setAssigneeId(ourUserId); IssueCategory newIssueCategory1 = issueManager.createCategory(testIssueCategory1); IssueCategory testIssueCategory2 = IssueCategoryFactory.create(project.getId(), "Category" + new Date().getTime()); testIssueCategory2.setAssigneeId(ourUserId); IssueCategory newIssueCategory2 = issueManager.createCategory(testIssueCategory2); try { List<IssueCategory> categories = issueManager.getCategories(project.getId()); assertEquals("Wrong number of categories for project " + project.getName() + " delivered by Redmine Java API", 2, categories.size()); for (IssueCategory category : categories) { // assert category assertNotNull("ID of category must not be null", category.getId()); assertNotNull("Name of category must not be null", category.getName()); assertNotNull("ProjectId must not be null", category.getProjectId()); assertNotNull("Assignee of category must not be null", category.getAssigneeId()); } } finally { // scrub test categories if (newIssueCategory1 != null) { issueManager.deleteCategory(newIssueCategory1); } if (newIssueCategory2 != null) { issueManager.deleteCategory(newIssueCategory2); } } } /** * tests the creation of an invalid {@link IssueCategory}. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test(expected = IllegalArgumentException.class) public void testCreateInvalidIssueCategory() throws RedmineException { IssueCategory category = IssueCategoryFactory.create(null, "InvalidCategory" + new Date().getTime()); issueManager.createCategory(category); } /** * tests the deletion of an invalid {@link IssueCategory}. Expects a * {@link NotFoundException} to be thrown. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test(expected = NotFoundException.class) public void testDeleteInvalidIssueCategory() throws RedmineException { // create new test category IssueCategory category = IssueCategoryFactory.create(-1); category.setName("InvalidCategory" + new Date().getTime()); // now try deleting the category issueManager.deleteCategory(category); } /** * Tests the creation and retrieval of an * {@link com.taskadapter.redmineapi.bean.Issue} with a * {@link IssueCategory}. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testCreateAndGetIssueWithCategory() throws RedmineException { IssueCategory newIssueCategory = null; Issue newIssue = null; try { Project project = projectManager.getProjectByKey(projectKey); // create an issue category IssueCategory category = IssueCategoryFactory.create(project.getId(), "Category_" + new Date().getTime()); category.setAssigneeId(IntegrationTestHelper.getOurUser().getId()); newIssueCategory = issueManager.createCategory(category); // create an issue Issue issueToCreate = IssueFactory.create(projectId, "getIssueWithCategory_" + UUID.randomUUID()); issueToCreate.setCategory(newIssueCategory); newIssue = issueManager.createIssue(issueToCreate); // retrieve issue Issue retrievedIssue = issueManager.getIssueById(newIssue.getId()); // assert retrieved category of issue IssueCategory retrievedCategory = retrievedIssue.getCategory(); assertNotNull("Category retrieved for issue " + newIssue.getId() + " should not be null", retrievedCategory); assertEquals("ID of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getId(), retrievedCategory.getId()); assertEquals("Name of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getName(), retrievedCategory.getName()); retrievedIssue.setCategory(null); issueManager.update(retrievedIssue); Issue updatedIssue = issueManager.getIssueById(newIssue.getId()); assertThat(updatedIssue.getCategory()).isNull(); } finally { if (newIssue != null) { issueManager.deleteIssue(newIssue.getId()); } if (newIssueCategory != null) { issueManager.deleteCategory(newIssueCategory); } } } @Test public void nullStartDateIsPreserved() throws RedmineException { Issue issue = IssueFactory.create(projectId, "test start date"); issue.setStartDate(null); Issue newIssue = issueManager.createIssue(issue); Issue loadedIssue = issueManager.getIssueById(newIssue.getId()); assertNull(loadedIssue.getStartDate()); } @Test public void testCustomFields() throws Exception { Issue issue = createIssue(issueManager, projectId); // TODO this needs to be reworked, when Redmine gains a real CRUD interface for custom fields // To test right now the test system needs: // Custom Field with ID 1 needs to be: // name: my_custom_1 // format: Text (string) // for all project, for all trackers // Custom Field with ID 2 needs to be: // name: custom_boolean_1 // format: Boolean (bool) // Custom Field with ID 3 needs to be: // name: custom_multi_list // format: List (list) // multiple values: enabled // possible values: V1, V2, V3 // default value: V2 // All fields: need to be issue fields, for all project, for all trackers List<CustomFieldDefinition> customFieldDefinitions = mgr.getCustomFieldManager().getCustomFieldDefinitions(); CustomFieldDefinition customField1 = getCustomFieldByName(customFieldDefinitions, "my_custom_1"); CustomFieldDefinition customField2 = getCustomFieldByName(customFieldDefinitions, "custom_boolean_1"); issue.clearCustomFields(); String custom1Value = "some value 123"; String custom2Value = "true"; issue.addCustomField(CustomFieldFactory.create(customField1.getId(), customField1.getName(), custom1Value)); issue.addCustomField(CustomFieldFactory.create(customField2.getId(), customField2.getName(), custom2Value)); issueManager.update(issue); Issue updatedIssue = issueManager.getIssueById(issue.getId()); assertThat(updatedIssue.getCustomFieldByName(customField1.getName()).getValue()).isEqualTo(custom1Value); assertThat(updatedIssue.getCustomFieldByName(customField2.getName()).getValue()).isEqualTo(custom2Value); } @Test public void defaultValueUsedWhenCustomFieldNotProvidedWhenCreatingIssue() throws Exception { Issue newIssue = IssueFactory.create(projectId, "test for custom multi fields"); Issue createdIssue = issueManager.createIssue(newIssue); CustomField customField = createdIssue.getCustomFieldByName("custom_multi_list"); assertThat(customField).isNotNull(); assertThat(customField.getValues().size()).isEqualTo(1); assertThat(customField.getValues().get(0)).isEqualTo("V2"); issueManager.deleteIssue(createdIssue.getId()); } @Test public void setOneValueForMultiLineCustomField() throws Exception { Issue newIssue = IssueFactory.create(projectId, "test for custom multi fields - set one value"); CustomFieldDefinition multiFieldDefinition = loadMultiLineCustomFieldDefinition(); CustomField customField = CustomFieldFactory.create(multiFieldDefinition.getId()); String defaultValue = multiFieldDefinition.getDefaultValue(); customField.setValues(Collections.singletonList(defaultValue)); newIssue.addCustomField(customField); Issue createdIssue = issueManager.createIssue(newIssue); customField = createdIssue.getCustomFieldByName("custom_multi_list"); assertThat(customField).isNotNull(); assertThat(customField.getValues().size()).isEqualTo(1); assertThat(customField.getValues().get(0)).isEqualTo(defaultValue); issueManager.deleteIssue(createdIssue.getId()); } @Test public void setMultiValuesForMultiLineCustomField() throws Exception { Issue issue = IssueFactory.create(projectId, "test for custom multi fields - set multiple values"); CustomFieldDefinition multiFieldDefinition = loadMultiLineCustomFieldDefinition(); CustomField customField = CustomFieldFactory.create(multiFieldDefinition.getId()); customField.setValues(Arrays.asList("V1", "V3")); issue.addCustomField(customField); Issue createdIssue = issueManager.createIssue(issue); CustomField loadedCustomField = createdIssue.getCustomFieldByName("custom_multi_list"); assertThat(loadedCustomField).isNotNull(); assertThat(loadedCustomField.getValues().size()).isEqualTo(2); List<String> values = new ArrayList<>(loadedCustomField.getValues()); Collections.sort(values); assertThat(loadedCustomField.getValues().get(0)).isEqualTo("V1"); assertThat(loadedCustomField.getValues().get(1)).isEqualTo("V3"); issueManager.deleteIssue(createdIssue.getId()); } /** * This is to make sure we have a workaround for a known bug in redmine 2.6. */ @Test public void createIssueWithEmptyListInMultilineCustomFields() throws Exception { Issue newIssue = IssueFactory.create(projectId, "test for custom multi fields - set multiple values"); CustomFieldDefinition multiFieldDefinition = loadMultiLineCustomFieldDefinition(); CustomField customField = CustomFieldFactory.create(multiFieldDefinition.getId()); customField.setValues(Collections.EMPTY_LIST); newIssue.addCustomField(customField); Issue createdIssue = issueManager.createIssue(newIssue); customField = createdIssue.getCustomFieldByName("custom_multi_list"); assertThat(customField).isNotNull(); assertThat(customField.getValues().size()).isEqualTo(0); issueManager.deleteIssue(createdIssue.getId()); } private static CustomFieldDefinition loadMultiLineCustomFieldDefinition() throws RedmineException { List<CustomFieldDefinition> customFieldDefinitions = mgr.getCustomFieldManager().getCustomFieldDefinitions(); return getCustomFieldByName(customFieldDefinitions, "custom_multi_list"); } @Ignore @Test public void testChangesets() throws RedmineException { final Issue issue = issueManager.getIssueById(89, Include.changesets); assertThat(issue.getChangesets().size()).isEqualTo(2); final Changeset firstChange = issue.getChangesets().iterator().next(); assertNotNull(firstChange.getComments()); } /** * Tests the retrieval of {@link Tracker}s. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testGetTrackers() throws RedmineException { List<Tracker> trackers = issueManager.getTrackers(); assertNotNull("List of trackers returned should not be null", trackers); assertFalse("List of trackers returned should not be empty", trackers.isEmpty()); for (Tracker tracker : trackers) { assertNotNull("Tracker returned should not be null", tracker); assertNotNull("ID of tracker returned should not be null", tracker.getId()); assertNotNull("Name of tracker returned should not be null", tracker.getName()); } } @Test public void getSavedQueriesDoesNotFailForTempProject() throws RedmineException { issueManager.getSavedQueries(projectKey); } @Test public void getSavedQueriesDoesNotFailForNULLProject() throws RedmineException { issueManager.getSavedQueries(null); } @Ignore("This test requires a specific project configuration") @Test public void testSavedQueries() throws RedmineException { final Collection<SavedQuery> queries = issueManager.getSavedQueries("test"); assertTrue(queries.size() > 0); } @Test public void statusIsUpdated() throws RedmineException { Issue issue = createIssues(issueManager, projectId, 1).get(0); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); Integer initialStatusId = retrievedIssue.getStatusId(); List<IssueStatus> statuses = issueManager.getStatuses(); // get some status ID that is not equal to the initial one Integer newStatusId = null; for (IssueStatus status : statuses) { if (!status.getId().equals(initialStatusId)) { newStatusId = status.getId(); break; } } if (newStatusId == null) { throw new RuntimeException("can't run this test: no Issue Statuses are available except for the initial one"); } retrievedIssue.setStatusId(newStatusId); issueManager.update(retrievedIssue); Issue issueWithUpdatedStatus = issueManager.getIssueById(retrievedIssue.getId()); assertThat(issueWithUpdatedStatus.getStatusId()).isEqualTo(newStatusId); } @Test public void changeProject() throws RedmineException { Project project1 = mgr.getProjectManager().getProjectByKey(projectKey); Project project2 = mgr.getProjectManager().getProjectByKey(projectKey2); Issue issue = createIssue(issueManager, projectId); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertThat(retrievedIssue.getProjectId()).isEqualTo(project1.getId()); issue.setProjectId(project2.getId()); issueManager.update(issue); retrievedIssue = issueManager.getIssueById(issue.getId()); assertThat(retrievedIssue.getProjectId()).isEqualTo(project2.getId()); deleteIssueIfNotNull(issue); } @Test public void issueAssignmentUserAndGroup() throws RedmineException { Issue issue = createIssue(issueManager, projectId); assertNull(issue.getAssigneeId()); issue.setAssigneeId(IntegrationTestHelper.getOurUser().getId()); issueManager.update(issue); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); // User assignment succeeded assertThat(retrievedIssue.getAssigneeId()).isEqualTo(IntegrationTestHelper.getOurUser().getId()); issue.setAssigneeId(demoGroup.getId()); issueManager.update(issue); retrievedIssue = issueManager.getIssueById(issue.getId()); // Group assignment succeeded assertThat(retrievedIssue.getAssigneeId()).isEqualTo(demoGroup.getId()); deleteIssueIfNotNull(issue); } @Test public void issueCanBeCreatedOnBehalfOfAnotherUser() throws RedmineException { final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); Issue issue = null; try { RedmineManager managerOnBehalfOfUser = IntegrationTestHelper.createRedmineManager(); managerOnBehalfOfUser.setOnBehalfOfUser(newUser.getLogin()); issue = createIssue(managerOnBehalfOfUser.getIssueManager(), projectId); assertThat(issue.getAuthorName()).isEqualTo(newUser.getFullName()); } finally { userManager.deleteUser(newUser.getId()); deleteIssueIfNotNull(issue); } } @Test public void issuesCanBeFoundByFreeFormSearch() throws RedmineException { // create some random issues in the project createIssues(issueManager, projectId, 3); final String subject = "test for free_form_search."; final Issue issueToCreate = IssueFactory.create(projectId, subject); Integer createdIssueId = null; try { createdIssueId = issueManager.createIssue(issueToCreate).getId(); Map<String, String> params = new HashMap<>(); params.put("project_id", Integer.toString(projectId)); params.put("subject", "~free_form_search"); List<Issue> issues = issueManager.getIssues(params).getResults(); assertThat(issues.size()).isEqualTo(1); final Issue loaded = issues.get(0); assertThat(loaded.getSubject()).isEqualTo(subject); } finally { issueManager.deleteIssue(createdIssueId); } } @Test public void issuesCanBeFoundByMultiQuerySearch() throws RedmineException { final Issue issue1 = IssueFactory.create(projectId, "summary 1 here"); issueManager.createIssue(issue1); final Issue issue2 = IssueFactory.create(projectId, "summary 2 here"); issueManager.createIssue(issue2); // have some random subject to avoid collisions with other tests String subject = "another" + new Random().nextInt(); final Issue issue3 = IssueFactory.create(projectId, subject); issueManager.createIssue(issue3); final User currentUser = userManager.getCurrentUser(); Params params = new Params() .add("set_filter", "1") .add("f[]", "subject") .add("op[subject]", "~") .add("v[subject][]", subject) .add("f[]", "author_id") .add("op[author_id]", "=") .add("v[author_id][]", currentUser.getId()+""); final ResultsWrapper<Issue> list = issueManager.getIssues(params); // only 1 issue must be found assertThat(list.getResults()).hasSize(1); } private void deleteIssueIfNotNull(Issue issue) throws RedmineException { if (issue != null) { issueManager.deleteIssue(issue.getId()); } } }
package com.taskadapter.redmineapi; import com.taskadapter.redmineapi.bean.Changeset; import com.taskadapter.redmineapi.bean.CustomFieldDefinition; import com.taskadapter.redmineapi.bean.CustomFieldFactory; import com.taskadapter.redmineapi.bean.Issue; import com.taskadapter.redmineapi.bean.IssueCategory; import com.taskadapter.redmineapi.bean.IssueCategoryFactory; import com.taskadapter.redmineapi.bean.IssueFactory; import com.taskadapter.redmineapi.bean.IssueRelation; import com.taskadapter.redmineapi.bean.IssueStatus; import com.taskadapter.redmineapi.bean.Journal; import com.taskadapter.redmineapi.bean.JournalDetail; import com.taskadapter.redmineapi.bean.Project; import com.taskadapter.redmineapi.bean.SavedQuery; import com.taskadapter.redmineapi.bean.Tracker; import com.taskadapter.redmineapi.bean.User; import com.taskadapter.redmineapi.bean.Version; import com.taskadapter.redmineapi.bean.VersionFactory; import com.taskadapter.redmineapi.bean.Watcher; import com.taskadapter.redmineapi.bean.WatcherFactory; import com.taskadapter.redmineapi.internal.ResultsWrapper; import org.apache.http.client.HttpClient; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import static com.taskadapter.redmineapi.CustomFieldResolver.getCustomFieldByName; import static com.taskadapter.redmineapi.IssueHelper.createIssue; import static com.taskadapter.redmineapi.IssueHelper.createIssues; import com.taskadapter.redmineapi.bean.CustomField; import com.taskadapter.redmineapi.bean.Group; import com.taskadapter.redmineapi.bean.GroupFactory; import com.taskadapter.redmineapi.bean.Role; import com.taskadapter.redmineapi.bean.RoleFactory; import java.util.Arrays; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class IssueManagerIT { private static IssueManager issueManager; private static ProjectManager projectManager; private static MembershipManager membershipManager; private static Project project; private static int projectId; private static String projectKey; private static Project project2; private static String projectKey2; private static RedmineManager mgr; private static UserManager userManager; private static Group demoGroup; @BeforeClass public static void oneTimeSetup() throws RedmineException { mgr = IntegrationTestHelper.createRedmineManager(); userManager = mgr.getUserManager(); issueManager = mgr.getIssueManager(); projectManager = mgr.getProjectManager(); membershipManager = mgr.getMembershipManager(); project = IntegrationTestHelper.createProject(mgr); projectId = project.getId(); projectKey = project.getIdentifier(); project2 = IntegrationTestHelper.createProject(mgr); projectKey2 = project2.getIdentifier(); Group g = GroupFactory.create(); g.setName("Group" + System.currentTimeMillis()); demoGroup = userManager.createGroup(g); // Add membership of group for the demo projects Collection<Role> allRoles = Arrays.asList(new Role[] { RoleFactory.create(3), // Manager RoleFactory.create(4), // Developer RoleFactory.create(5) // Reporter }); membershipManager.createMembershipForGroup(project.getId(), demoGroup.getId(), allRoles); membershipManager.createMembershipForGroup(project2.getId(), demoGroup.getId(), allRoles); } @AfterClass public static void oneTimeTearDown() throws RedmineException { IntegrationTestHelper.deleteProject(mgr, project.getIdentifier()); IntegrationTestHelper.deleteProject(mgr, project2.getIdentifier()); userManager.deleteGroup(demoGroup); } @Test public void issueCreated() throws RedmineException { Issue issueToCreate = IssueFactory.create(projectId, "test zzx"); Calendar startCal = Calendar.getInstance(); // have to clear them because they are ignored by Redmine and // prevent from comparison later startCal.clear(Calendar.HOUR_OF_DAY); startCal.clear(Calendar.MINUTE); startCal.clear(Calendar.SECOND); startCal.clear(Calendar.MILLISECOND); startCal.add(Calendar.DATE, 5); issueToCreate.setStartDate(startCal.getTime()); Calendar due = Calendar.getInstance(); due.add(Calendar.MONTH, 1); issueToCreate.setDueDate(due.getTime()); User ourUser = IntegrationTestHelper.getOurUser(); issueToCreate.setAssigneeId(ourUser.getId()); String description = "This is the description for the new task." + "\nIt has several lines." + "\nThis is the last line."; issueToCreate.setDescription(description); float estimatedHours = 44; issueToCreate.setEstimatedHours(estimatedHours); Issue newIssue = issueManager.createIssue(issueToCreate); assertNotNull("Checking returned result", newIssue); assertNotNull("New issue must have some ID", newIssue.getId()); // check startDate Calendar returnedStartCal = Calendar.getInstance(); returnedStartCal.setTime(newIssue.getStartDate()); assertEquals(startCal.get(Calendar.YEAR), returnedStartCal.get(Calendar.YEAR)); assertEquals(startCal.get(Calendar.MONTH), returnedStartCal.get(Calendar.MONTH)); assertEquals(startCal.get(Calendar.DAY_OF_MONTH), returnedStartCal.get(Calendar.DAY_OF_MONTH)); // check dueDate Calendar returnedDueCal = Calendar.getInstance(); returnedDueCal.setTime(newIssue.getDueDate()); assertEquals(due.get(Calendar.YEAR), returnedDueCal.get(Calendar.YEAR)); assertEquals(due.get(Calendar.MONTH), returnedDueCal.get(Calendar.MONTH)); assertEquals(due.get(Calendar.DAY_OF_MONTH), returnedDueCal.get(Calendar.DAY_OF_MONTH)); // check ASSIGNEE assertThat(ourUser.getId()).isEqualTo(newIssue.getAssigneeId()); // check AUTHOR Integer EXPECTED_AUTHOR_ID = IntegrationTestHelper.getOurUser().getId(); assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthorId()); // check ESTIMATED TIME assertEquals((Float) estimatedHours, newIssue.getEstimatedHours()); // check multi-line DESCRIPTION String regexpStripExtra = "\\r|\\n|\\s"; description = description.replaceAll(regexpStripExtra, ""); String actualDescription = newIssue.getDescription(); actualDescription = actualDescription.replaceAll(regexpStripExtra, ""); assertEquals(description, actualDescription); // PRIORITY assertNotNull(newIssue.getPriorityId()); assertTrue(newIssue.getPriorityId() > 0); } @Test public void issueWithParentCreated() throws RedmineException { Issue parentIssue = IssueFactory.create(projectId, "parent 1"); Issue newParentIssue = issueManager.createIssue(parentIssue); assertNotNull("Checking parent was created", newParentIssue); assertNotNull("Checking ID of parent issue is not null", newParentIssue.getId()); // Integer parentId = 46; Integer parentId = newParentIssue.getId(); Issue childIssue = IssueFactory.create(projectId, "child 1"); childIssue.setParentId(parentId); Issue newChildIssue = issueManager.createIssue(childIssue); assertEquals("Checking parent ID of the child issue", parentId, newChildIssue.getParentId()); } @Test public void parentIdCanBeErased() throws RedmineException { Issue parentIssue = IssueFactory.create(projectId, "parent task"); Issue newParentIssue = issueManager.createIssue(parentIssue); Integer parentId = newParentIssue.getId(); Issue childIssue = IssueFactory.create(projectId, "child task"); childIssue.setParentId(parentId); Issue newChildIssue = issueManager.createIssue(childIssue); assertThat(newChildIssue.getParentId()).isEqualTo(parentId); newChildIssue.setParentId(null); issueManager.update(newChildIssue); final Issue reloadedIssue = issueManager.getIssueById(newChildIssue.getId()); assertThat(reloadedIssue.getParentId()).isNull(); } @Test public void testUpdateIssue() throws RedmineException { String originalSubject = "Issue " + new Date(); Issue issue = IssueFactory.create(projectId, originalSubject); Issue newIssue = issueManager.createIssue(issue); String changedSubject = "changed subject"; newIssue.setSubject(changedSubject); issueManager.update(newIssue); Issue reloadedFromRedmineIssue = issueManager.getIssueById(newIssue.getId()); assertEquals("Checking if 'update issue' operation changed 'subject' field", changedSubject, reloadedFromRedmineIssue.getSubject()); } /** * Tests the retrieval of an {@link Issue} by its ID. * * @throws com.taskadapter.redmineapi.RedmineException * thrown in case something went wrong in Redmine * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws com.taskadapter.redmineapi.NotFoundException * thrown in case the objects requested for could not be found */ @Test public void testGetIssueById() throws RedmineException { String originalSubject = "Issue " + new Date(); Issue issue = IssueFactory.create(projectId, originalSubject); Issue newIssue = issueManager.createIssue(issue); Issue reloadedFromRedmineIssue = issueManager.getIssueById(newIssue.getId()); assertEquals( "Checking if 'get issue by ID' operation returned issue with same 'subject' field", originalSubject, reloadedFromRedmineIssue.getSubject()); Tracker tracker = reloadedFromRedmineIssue.getTracker(); assertNotNull("Tracker of issue should not be null", tracker); assertNotNull("ID of tracker of issue should not be null", tracker.getId()); assertNotNull("Name of tracker of issue should not be null", tracker.getName()); } @Test public void testGetIssues() throws RedmineException { // create at least 1 issue Issue issueToCreate = IssueFactory.create(projectId, "testGetIssues: " + new Date()); Issue newIssue = issueManager.createIssue(issueToCreate); List<Issue> issues = issueManager.getIssues(projectKey, null); assertTrue(issues.size() > 0); boolean found = false; for (Issue issue : issues) { if (issue.getId().equals(newIssue.getId())) { found = true; break; } } if (!found) { fail("getIssues() didn't return the issue we just created. The query " + " must have returned all issues created during the last 2 days"); } } @Test(expected = NotFoundException.class) public void testGetIssuesInvalidQueryId() throws RedmineException { Integer invalidQueryId = 9999999; issueManager.getIssues(projectKey, invalidQueryId); } @Test public void testCreateIssueNonUnicodeSymbols() throws RedmineException { String nonLatinSymbols = "Example with accents Ao"; Issue toCreate = IssueFactory.create(projectId, nonLatinSymbols); Issue created = issueManager.createIssue(toCreate); assertEquals(nonLatinSymbols, created.getSubject()); } @Test public void testCreateIssueSummaryOnly() throws RedmineException { Issue issueToCreate = IssueFactory.create(projectId, "This is the summary line 123"); Issue newIssue = issueManager.createIssue(issueToCreate); assertNotNull("Checking returned result", newIssue); assertNotNull("New issue must have some ID", newIssue.getId()); // check AUTHOR Integer EXPECTED_AUTHOR_ID = IntegrationTestHelper.getOurUser().getId(); assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthorId()); } @Test public void privateFlagIsRespectedWhenCreatingIssues() throws RedmineException { Issue privateIssueToCreate = IssueFactory.create(projectId, "private issue"); privateIssueToCreate.setPrivateIssue(true); Issue newIssue = issueManager.createIssue(privateIssueToCreate); assertThat(newIssue.isPrivateIssue()).isTrue(); Issue publicIssueToCreate = IssueFactory.create(projectId, "public issue"); publicIssueToCreate.setPrivateIssue(false); Issue newPublicIssue = issueManager.createIssue(publicIssueToCreate); assertThat(newPublicIssue.isPrivateIssue()).isFalse(); // default value for "is private" should be false Issue newDefaultIssue = issueManager.createIssue(IssueFactory.create(projectId, "default public issue")); assertThat(newDefaultIssue.isPrivateIssue()).isFalse(); } /* this test fails with Redmine 3.0.0-3.0.3 because Redmine 3.0.x started * returning "not authorized" instead of "not found" for projects with unknown Ids. * This worked differently with Redmine 2.6.x. * <p> * This test is not critical for the release of Redmine Java API library. I am marking it as "ignored" for now. */ @Ignore @Test(expected = NotFoundException.class) public void creatingIssueWithNonExistingProjectIdGivesNotFoundException() throws RedmineException { int nonExistingProjectId = 99999999; // hopefully this does not exist :) Issue issueToCreate = IssueFactory.create(nonExistingProjectId, "Summary line 100"); issueManager.createIssue(issueToCreate); } @Test(expected = NotFoundException.class) public void retrievingIssueWithNonExistingIdGivesNotFoundException() throws RedmineException { int someNonExistingID = 999999; issueManager.getIssueById(someNonExistingID); } @Test(expected = NotFoundException.class) public void updatingIssueWithNonExistingIdGivesNotFoundException() throws RedmineException { int nonExistingId = 999999; Issue issue = IssueFactory.create(nonExistingId); issueManager.update(issue); } @Test public void testGetIssuesPaging() throws RedmineException { // create 27 issues. default page size is 25. createIssues(issueManager, projectId, 27); List<Issue> issues = issueManager.getIssues(projectKey, null); assertThat(issues.size()).isGreaterThan(26); // check that there are no duplicates in the list. Set<Issue> issueSet = new HashSet<>(issues); assertThat(issueSet.size()).isEqualTo(issues.size()); } @Test public void canControlLimitAndOffsetDirectly() throws RedmineException { // create 27 issues. default Redmine page size is usually 25 (unless changed in the server settings). createIssues(issueManager, projectId, 27); Map<String, String> params = new HashMap<>(); params.put("limit", "3"); params.put("offset", "0"); params.put("project_id", projectId + ""); List<Issue> issues = issueManager.getIssues(params).getResults(); // only the requested number of issues is loaded, not all result pages. assertThat(issues.size()).isEqualTo(3); } @Test(expected = NotFoundException.class) public void testDeleteIssue() throws RedmineException { Issue issue = createIssues(issueManager, projectId, 1).get(0); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); issueManager.deleteIssue(issue.getId()); issueManager.getIssueById(issue.getId()); } @Test public void testUpdateIssueSpecialXMLtags() throws Exception { Issue issue = createIssues(issueManager, projectId, 1).get(0); String newSubject = "\"text in quotes\" and <xml> tags"; String newDescription = "<taghere>\"abc\"</here>"; issue.setSubject(newSubject); issue.setDescription(newDescription); issueManager.update(issue); Issue updatedIssue = issueManager.getIssueById(issue.getId()); assertEquals(newSubject, updatedIssue.getSubject()); assertEquals(newDescription, updatedIssue.getDescription()); } @Test public void testCreateRelation() throws RedmineException { List<Issue> issues = createIssues(issueManager, projectId, 2); Issue src = issues.get(0); Issue target = issues.get(1); String relationText = IssueRelation.TYPE.precedes.toString(); IssueRelation r = issueManager.createRelation(src.getId(), target.getId(), relationText); assertEquals(src.getId(), r.getIssueId()); assertEquals(target.getId(), r.getIssueToId()); assertEquals(relationText, r.getType()); } private IssueRelation createTwoRelatedIssues() throws RedmineException { List<Issue> issues = createIssues(issueManager, projectId, 2); Issue src = issues.get(0); Issue target = issues.get(1); String relationText = IssueRelation.TYPE.precedes.toString(); return issueManager.createRelation(src.getId(), target.getId(), relationText); } @Test public void issueRelationsAreCreatedAndLoadedOK() throws RedmineException { IssueRelation relation = createTwoRelatedIssues(); Issue issue = issueManager.getIssueById(relation.getIssueId(), Include.relations); Issue issueTarget = issueManager.getIssueById(relation.getIssueToId(), Include.relations); assertThat(issue.getRelations().size()).isEqualTo(1); assertThat(issueTarget.getRelations().size()).isEqualTo(1); IssueRelation relation1 = issue.getRelations().iterator().next(); assertThat(relation1.getIssueId()).isEqualTo(issue.getId()); assertThat(relation1.getIssueToId()).isEqualTo(issueTarget.getId()); assertThat(relation1.getType()).isEqualTo("precedes"); assertThat(relation1.getDelay()).isEqualTo((Integer) 0); IssueRelation reverseRelation = issueTarget.getRelations().iterator().next(); // both forward and reverse relations are the same! assertThat(reverseRelation).isEqualTo(relation1); } @Test public void issueRelationIsDeleted() throws RedmineException { IssueRelation relation = createTwoRelatedIssues(); issueManager.deleteRelation(relation.getId()); Issue issue = issueManager.getIssueById(relation.getIssueId(), Include.relations); assertThat(issue.getRelations()).isEmpty(); } @Test public void testIssueRelationsDelete() throws RedmineException { List<Issue> issues = createIssues(issueManager, projectId, 3); Issue src = issues.get(0); Issue target = issues.get(1); String relationText = IssueRelation.TYPE.precedes.toString(); issueManager.createRelation(src.getId(), target.getId(), relationText); target = issues.get(2); issueManager.createRelation(src.getId(), target.getId(), relationText); src = issueManager.getIssueById(src.getId(), Include.relations); issueManager.deleteIssueRelations(src); Issue issue = issueManager.getIssueById(src.getId(), Include.relations); assertTrue(issue.getRelations().isEmpty()); } /** * Requires Redmine 2.3 */ @Test public void testAddIssueWatcher() throws RedmineException { final Issue issue = createIssues(issueManager, projectId, 1).get(0); final Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); try { Watcher watcher = WatcherFactory.create(newUser.getId()); issueManager.addWatcherToIssue(watcher, issue); } finally { userManager.deleteUser(newUser.getId()); } issueManager.getIssueById(issue.getId()); } /** * Requires Redmine 2.3 */ @Test public void testDeleteIssueWatcher() throws RedmineException { final Issue issue = createIssues(issueManager, projectId, 1).get(0); final Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); try { Watcher watcher = WatcherFactory.create(newUser.getId()); issueManager.addWatcherToIssue(watcher, issue); issueManager.deleteWatcherFromIssue(watcher, issue); } finally { userManager.deleteUser(newUser.getId()); } issueManager.deleteIssue(issue.getId()); } /** * Requires Redmine 2.3 */ @Test public void testGetIssueWatcher() throws RedmineException { final Issue issue = createIssues(issueManager, projectId, 1).get(0); final Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); try { Watcher watcher = WatcherFactory.create(newUser.getId()); issueManager.addWatcherToIssue(watcher, issue); final Issue includeWatcherIssue = issueManager.getIssueById(issue.getId(), Include.watchers); if (!includeWatcherIssue.getWatchers().isEmpty()) { Watcher watcher1 = includeWatcherIssue.getWatchers().iterator().next(); assertThat(watcher1.getId()).isEqualTo(newUser.getId()); } } finally { userManager.deleteUser(newUser.getId()); } issueManager.getIssueById(issue.getId()); } @Test public void testAddIssueWithWatchers() throws RedmineException { final Issue issue = IssueHelper.generateRandomIssue(projectId); final User newUserWatcher = userManager.createUser(UserGenerator.generateRandomUser()); try { List<Watcher> watchers = new ArrayList<>(); Watcher watcher = WatcherFactory.create(newUserWatcher.getId()); watchers.add(watcher); issue.addWatchers(watchers); final Issue retrievedIssue = issueManager.createIssue(issue); final Issue retrievedIssueWithWatchers = issueManager.getIssueById(retrievedIssue.getId(), Include.watchers); assertNotNull(retrievedIssueWithWatchers); assertNotNull(retrievedIssueWithWatchers.getWatchers()); assertEquals(watchers.size(), retrievedIssueWithWatchers.getWatchers().size()); assertEquals(watcher.getId(), retrievedIssueWithWatchers.getWatchers().iterator().next().getId()); } finally { userManager.deleteUser(newUserWatcher.getId()); } } @Test public void testGetIssuesBySummary() throws RedmineException { String summary = "issue with subject ABC"; Issue issue = IssueFactory.create(projectId, summary); User ourUser = IntegrationTestHelper.getOurUser(); issue.setAssigneeId(ourUser.getId()); Issue newIssue = issueManager.createIssue(issue); assertNotNull("Checking returned result", newIssue); assertNotNull("New issue must have some ID", newIssue.getId()); List<Issue> foundIssues = issueManager.getIssuesBySummary(projectKey, summary); assertNotNull("Checking if search results is not NULL", foundIssues); assertTrue("Search results must be not empty", !(foundIssues.isEmpty())); Issue loadedIssue1 = RedmineTestUtils.findIssueInList(foundIssues, newIssue.getId()); assertNotNull(loadedIssue1); assertEquals(summary, loadedIssue1.getSubject()); } @Test public void findByNonExistingSummaryReturnsEmptyList() throws RedmineException { String summary = "some summary here for issue which does not exist"; List<Issue> foundIssues = issueManager.getIssuesBySummary(projectKey, summary); assertNotNull("Search result must be not null", foundIssues); assertTrue("Search result list must be empty", foundIssues.isEmpty()); } @Test(expected = RedmineAuthenticationException.class) public void noAPIKeyOnCreateIssueThrowsAE() throws Exception { TestConfig testConfig = new TestConfig(); final HttpClient httpClient = IntegrationTestHelper.getHttpClientForTestServer(); RedmineManager redmineMgrEmpty = RedmineManagerFactory.createUnauthenticated(testConfig.getURI(), httpClient); Issue issue = IssueFactory.create(projectId, "test zzx"); redmineMgrEmpty.getIssueManager().createIssue(issue); } @Test(expected = RedmineAuthenticationException.class) public void wrongAPIKeyOnCreateIssueThrowsAE() throws Exception { TestConfig testConfig = new TestConfig(); final HttpClient httpClient = IntegrationTestHelper.getHttpClientForTestServer(); RedmineManager redmineMgrInvalidKey = RedmineManagerFactory.createWithApiKey( testConfig.getURI(), "wrong_key", httpClient); Issue issue = IssueFactory.create(projectId, "test zzx"); redmineMgrInvalidKey.getIssueManager().createIssue(issue); } @Test public void testIssueDoneRatio() throws RedmineException { Issue issue = IssueFactory.create(projectId, "Issue " + new Date()); Issue createdIssue = issueManager.createIssue(issue); assertEquals("Initial 'done ratio' must be 0", (Integer) 0, createdIssue.getDoneRatio()); Integer doneRatio = 50; createdIssue.setDoneRatio(doneRatio); issueManager.update(createdIssue); Integer issueId = createdIssue.getId(); Issue reloadedFromRedmineIssue = issueManager.getIssueById(issueId); assertEquals( "Checking if 'update issue' operation changed 'done ratio' field", doneRatio, reloadedFromRedmineIssue.getDoneRatio()); Integer invalidDoneRatio = 130; reloadedFromRedmineIssue.setDoneRatio(invalidDoneRatio); try { issueManager.update(reloadedFromRedmineIssue); } catch (RedmineProcessingException e) { assertEquals("Must be 1 error", 1, e.getErrors().size()); assertEquals("Checking error text", "% Done is not included in the list", e.getErrors() .get(0)); } Issue reloadedFromRedmineIssueUnchanged = issueManager.getIssueById(issueId); assertEquals( "'done ratio' must have remained unchanged after invalid value", doneRatio, reloadedFromRedmineIssueUnchanged.getDoneRatio()); } @Test public void nullDescriptionErasesItOnServer() throws RedmineException { Issue issue = new Issue(); String subject = "Issue " + new Date(); String descr = "Some description"; issue.setSubject(subject); issue.setDescription(descr); issue.setProjectId(projectId); Issue createdIssue = issueManager.createIssue(issue); assertThat(createdIssue.getDescription()).isEqualTo(descr); createdIssue.setDescription(null); issueManager.update(createdIssue); Integer issueId = createdIssue.getId(); Issue reloadedFromRedmineIssue = issueManager.getIssueById(issueId); assertThat(reloadedFromRedmineIssue.getDescription()).isNull(); } @Test public void testIssueJournals() throws RedmineException { // create at least 1 issue Issue issueToCreate = new Issue(); issueToCreate.setSubject("testGetIssues: " + new Date()); issueToCreate.setProjectId(projectId); Issue newIssue = issueManager.createIssue(issueToCreate); Issue loadedIssueWithJournals = issueManager.getIssueById(newIssue.getId(), Include.journals); assertTrue(loadedIssueWithJournals.getJournals().isEmpty()); String commentDescribingTheUpdate = "some comment describing the issue update"; loadedIssueWithJournals.setSubject("new subject"); loadedIssueWithJournals.setNotes(commentDescribingTheUpdate); issueManager.update(loadedIssueWithJournals); Issue loadedIssueWithJournals2 = issueManager.getIssueById(newIssue.getId(), Include.journals); assertEquals(1, loadedIssueWithJournals2.getJournals() .size()); Journal journalItem = loadedIssueWithJournals2.getJournals().iterator().next(); assertEquals(commentDescribingTheUpdate, journalItem.getNotes()); User ourUser = IntegrationTestHelper.getOurUser(); // can't compare User objects because either of them is not // completely filled assertEquals(ourUser.getId(), journalItem.getUser().getId()); assertEquals(ourUser.getFirstName(), journalItem.getUser() .getFirstName()); assertEquals(ourUser.getLastName(), journalItem.getUser() .getLastName()); assertEquals(1, journalItem.getDetails().size()); final JournalDetail journalDetail = journalItem.getDetails().get(0); assertEquals("new subject", journalDetail.getNewValue()); assertEquals("subject", journalDetail.getName()); assertEquals("attr", journalDetail.getProperty()); Issue loadedIssueWithoutJournals = issueManager.getIssueById(newIssue.getId()); assertTrue(loadedIssueWithoutJournals.getJournals().isEmpty()); } @Test public void updateIssueDescription() throws RedmineException { Issue issue = IssueFactory.create(projectId, "test123"); final Issue iss1 = issueManager.createIssue(issue); final Issue iss2 = IssueFactory.create(iss1.getId()); iss2.setProjectId(projectId); iss2.setDescription("This is a test"); issueManager.update(iss2); final Issue iss3 = issueManager.getIssueById(iss2.getId()); assertEquals("test123", iss3.getSubject()); assertEquals("This is a test", iss3.getDescription()); } @Test public void updateIssueTitle() throws RedmineException { Issue issue = IssueFactory.create(projectId, "test123"); issue.setDescription("Original description"); final Issue iss1 = issueManager.createIssue(issue); final Issue iss2 = IssueFactory.create(iss1.getId()); iss2.setSubject("New subject"); iss2.setProjectId(projectId); issueManager.update(iss2); final Issue iss3 = issueManager.getIssueById(iss2.getId()); assertEquals("New subject", iss3.getSubject()); assertEquals("Original description", iss3.getDescription()); } @Test public void testIssuePriorities() throws RedmineException { assertTrue(issueManager.getIssuePriorities().size() > 0); } @Test public void issueTargetVersionIsSetWhenCreatingOrUpdatingIssues() throws Exception { final String version1Name = "1.0"; final String version2Name = "2.0"; final Issue issueToCreate = IssueHelper.generateRandomIssue(projectId); Version version1 = createVersion(version1Name); issueToCreate.setTargetVersion(version1); issueToCreate.setProjectId(project.getId()); final Issue createdIssue = issueManager.createIssue(issueToCreate); assertNotNull(createdIssue.getTargetVersion()); assertEquals(createdIssue.getTargetVersion().getName(), version1Name); Version version2 = createVersion(version2Name); createdIssue.setTargetVersion(version2); issueManager.update(createdIssue); Issue updatedIssue = issueManager.getIssueById(createdIssue.getId()); assertThat(updatedIssue.getTargetVersion().getName()).isEqualTo(version2Name); createdIssue.setTargetVersion(null); issueManager.update(createdIssue); updatedIssue = issueManager.getIssueById(createdIssue.getId()); assertThat(updatedIssue.getTargetVersion()).isNull(); } private Version createVersion(String versionName) throws RedmineException { final Version version = VersionFactory.create(1); version.setName(versionName); version.setProjectId(projectId); return mgr.getProjectManager().createVersion(version); } @Test public void testUpdateIssueDoesNotChangeEstimatedTime() throws RedmineException { String originalSubject = "Issue " + new Date(); Issue issue = IssueFactory.create(projectId, originalSubject); Issue newIssue = issueManager.createIssue(issue); assertEquals("Estimated hours must be NULL", null, newIssue.getEstimatedHours()); issueManager.update(newIssue); Issue reloadedFromRedmineIssue = issueManager.getIssueById(newIssue.getId()); assertEquals("Estimated hours must be NULL", null, reloadedFromRedmineIssue.getEstimatedHours()); } /** * tests the retrieval of statuses. * * @throws RedmineProcessingException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testGetStatuses() throws RedmineException { // TODO we should create some statuses first, but the Redmine Java API // does not support this presently List<IssueStatus> statuses = issueManager.getStatuses(); assertFalse("Expected list of statuses not to be empty", statuses.isEmpty()); for (IssueStatus issueStatus : statuses) { // asserts on status assertNotNull("ID of status must not be null", issueStatus.getId()); assertNotNull("Name of status must not be null", issueStatus.getName()); } } /** * tests the creation and deletion of a {@link com.taskadapter.redmineapi.bean.IssueCategory}. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testCreateAndDeleteIssueCategory() throws RedmineException { Project project = projectManager.getProjectByKey(projectKey); IssueCategory category = IssueCategoryFactory.create(project.getId(), "Category" + new Date().getTime()); category.setAssigneeId(IntegrationTestHelper.getOurUser().getId()); IssueCategory newIssueCategory = issueManager.createCategory(category); assertNotNull("Expected new category not to be null", newIssueCategory); assertNotNull("Expected projectId of new category not to be null", newIssueCategory.getProjectId()); assertNotNull("Expected assignee of new category not to be null", newIssueCategory.getAssigneeId()); assertThat(newIssueCategory.getAssigneeId()).isEqualTo(IntegrationTestHelper.getOurUser().getId()); // now delete category issueManager.deleteCategory(newIssueCategory); // assert that the category is gone List<IssueCategory> categories = issueManager.getCategories(project.getId()); assertTrue( "List of categories of test project must be empty now but is " + categories, categories.isEmpty()); } /** * tests the creation and deletion of a {@link com.taskadapter.redmineapi.bean.IssueCategory} * with the group as assignee * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testCreateAndDeleteIssueCategoryGroupAssignee() throws RedmineException { Project project = projectManager.getProjectByKey(projectKey); IssueCategory category = IssueCategoryFactory.create(project.getId(), "Category" + new Date().getTime()); category.setAssigneeId(demoGroup.getId()); IssueCategory newIssueCategory = issueManager.createCategory(category); assertNotNull("Expected new category not to be null", newIssueCategory); assertNotNull("Expected projectId of new category not to be null", newIssueCategory.getProjectId()); assertNotNull("Expected assignee of new category not to be null", newIssueCategory.getAssigneeId()); assertThat(newIssueCategory.getAssigneeId()).isEqualTo(demoGroup.getId()); assertThat(newIssueCategory.getAssigneeName()).isEqualTo(demoGroup.getName()); // now delete category issueManager.deleteCategory(newIssueCategory); // assert that the category is gone List<IssueCategory> categories = issueManager.getCategories(project.getId()); assertTrue( "List of categories of test project must be empty now but is " + categories, categories.isEmpty()); } /** * tests the retrieval of {@link IssueCategory}s. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testGetIssueCategories() throws RedmineException { Project project = projectManager.getProjectByKey(projectKey); // create some categories IssueCategory testIssueCategory1 = IssueCategoryFactory.create(project.getId(), "Category" + new Date().getTime()); Integer ourUserId = IntegrationTestHelper.getOurUser().getId(); testIssueCategory1.setAssigneeId(ourUserId); IssueCategory newIssueCategory1 = issueManager.createCategory(testIssueCategory1); IssueCategory testIssueCategory2 = IssueCategoryFactory.create(project.getId(), "Category" + new Date().getTime()); testIssueCategory2.setAssigneeId(ourUserId); IssueCategory newIssueCategory2 = issueManager.createCategory(testIssueCategory2); try { List<IssueCategory> categories = issueManager.getCategories(project.getId()); assertEquals("Wrong number of categories for project " + project.getName() + " delivered by Redmine Java API", 2, categories.size()); for (IssueCategory category : categories) { // assert category assertNotNull("ID of category must not be null", category.getId()); assertNotNull("Name of category must not be null", category.getName()); assertNotNull("ProjectId must not be null", category.getProjectId()); assertNotNull("Assignee of category must not be null", category.getAssigneeId()); } } finally { // scrub test categories if (newIssueCategory1 != null) { issueManager.deleteCategory(newIssueCategory1); } if (newIssueCategory2 != null) { issueManager.deleteCategory(newIssueCategory2); } } } /** * tests the creation of an invalid {@link IssueCategory}. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test(expected = IllegalArgumentException.class) public void testCreateInvalidIssueCategory() throws RedmineException { IssueCategory category = IssueCategoryFactory.create(null, "InvalidCategory" + new Date().getTime()); issueManager.createCategory(category); } /** * tests the deletion of an invalid {@link IssueCategory}. Expects a * {@link NotFoundException} to be thrown. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test(expected = NotFoundException.class) public void testDeleteInvalidIssueCategory() throws RedmineException { // create new test category IssueCategory category = IssueCategoryFactory.create(-1); category.setName("InvalidCategory" + new Date().getTime()); // now try deleting the category issueManager.deleteCategory(category); } /** * Tests the creation and retrieval of an * {@link com.taskadapter.redmineapi.bean.Issue} with a * {@link IssueCategory}. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testCreateAndGetIssueWithCategory() throws RedmineException { IssueCategory newIssueCategory = null; Issue newIssue = null; try { Project project = projectManager.getProjectByKey(projectKey); // create an issue category IssueCategory category = IssueCategoryFactory.create(project.getId(), "Category_" + new Date().getTime()); category.setAssigneeId(IntegrationTestHelper.getOurUser().getId()); newIssueCategory = issueManager.createCategory(category); // create an issue Issue issueToCreate = IssueFactory.create(projectId, "getIssueWithCategory_" + UUID.randomUUID()); issueToCreate.setCategory(newIssueCategory); newIssue = issueManager.createIssue(issueToCreate); // retrieve issue Issue retrievedIssue = issueManager.getIssueById(newIssue.getId()); // assert retrieved category of issue IssueCategory retrievedCategory = retrievedIssue.getCategory(); assertNotNull("Category retrieved for issue " + newIssue.getId() + " should not be null", retrievedCategory); assertEquals("ID of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getId(), retrievedCategory.getId()); assertEquals("Name of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getName(), retrievedCategory.getName()); retrievedIssue.setCategory(null); issueManager.update(retrievedIssue); Issue updatedIssue = issueManager.getIssueById(newIssue.getId()); assertThat(updatedIssue.getCategory()).isNull(); } finally { if (newIssue != null) { issueManager.deleteIssue(newIssue.getId()); } if (newIssueCategory != null) { issueManager.deleteCategory(newIssueCategory); } } } @Test public void nullStartDateIsPreserved() throws RedmineException { Issue issue = IssueFactory.create(projectId, "test start date"); issue.setStartDate(null); Issue newIssue = issueManager.createIssue(issue); Issue loadedIssue = issueManager.getIssueById(newIssue.getId()); assertNull(loadedIssue.getStartDate()); } @Test public void testCustomFields() throws Exception { Issue issue = createIssue(issueManager, projectId); // TODO this needs to be reworked, when Redmine gains a real CRUD interface for custom fields // To test right now the test system needs: // Custom Field with ID 1 needs to be: // name: my_custom_1 // format: Text (string) // for all project, for all trackers // Custom Field with ID 2 needs to be: // name: custom_boolean_1 // format: Boolean (bool) // Custom Field with ID 3 needs to be: // name: custom_multi_list // format: List (list) // multiple values: enabled // possible values: V1, V2, V3 // default value: V2 // All fields: need to be issue fields, for all project, for all trackers List<CustomFieldDefinition> customFieldDefinitions = mgr.getCustomFieldManager().getCustomFieldDefinitions(); CustomFieldDefinition customField1 = getCustomFieldByName(customFieldDefinitions, "my_custom_1"); CustomFieldDefinition customField2 = getCustomFieldByName(customFieldDefinitions, "custom_boolean_1"); // default empty values assertThat(issue.getCustomFields().size()).isEqualTo(3); issue.clearCustomFields(); String custom1Value = "some value 123"; String custom2Value = "true"; issue.addCustomField(CustomFieldFactory.create(customField1.getId(), customField1.getName(), custom1Value)); issue.addCustomField(CustomFieldFactory.create(customField2.getId(), customField2.getName(), custom2Value)); issueManager.update(issue); Issue updatedIssue = issueManager.getIssueById(issue.getId()); assertThat(updatedIssue.getCustomFields().size()).isEqualTo(3); assertThat(updatedIssue.getCustomFieldByName(customField1.getName()).getValue()).isEqualTo(custom1Value); assertThat(updatedIssue.getCustomFieldByName(customField2.getName()).getValue()).isEqualTo(custom2Value); } @Test public void defaultValueUsedWhenCustomFieldNotProvidedWhenCreatingIssue() throws Exception { Issue newIssue = IssueFactory.create(projectId, "test for custom multi fields"); Issue createdIssue = issueManager.createIssue(newIssue); CustomField customField = createdIssue.getCustomFieldByName("custom_multi_list"); assertThat(customField).isNotNull(); assertThat(customField.getValues().size()).isEqualTo(1); assertThat(customField.getValues().get(0)).isEqualTo("V2"); issueManager.deleteIssue(createdIssue.getId()); } @Test public void setOneValueForMultiLineCustomField() throws Exception { Issue newIssue = IssueFactory.create(projectId, "test for custom multi fields - set one value"); CustomFieldDefinition multiFieldDefinition = loadMultiLineCustomFieldDefinition(); CustomField customField = CustomFieldFactory.create(multiFieldDefinition.getId()); String defaultValue = multiFieldDefinition.getDefaultValue(); customField.setValues(Collections.singletonList(defaultValue)); newIssue.addCustomField(customField); Issue createdIssue = issueManager.createIssue(newIssue); customField = createdIssue.getCustomFieldByName("custom_multi_list"); assertThat(customField).isNotNull(); assertThat(customField.getValues().size()).isEqualTo(1); assertThat(customField.getValues().get(0)).isEqualTo(defaultValue); issueManager.deleteIssue(createdIssue.getId()); } @Test public void setMultiValuesForMultiLineCustomField() throws Exception { Issue issue = IssueFactory.create(projectId, "test for custom multi fields - set multiple values"); CustomFieldDefinition multiFieldDefinition = loadMultiLineCustomFieldDefinition(); CustomField customField = CustomFieldFactory.create(multiFieldDefinition.getId()); customField.setValues(Arrays.asList("V1", "V3")); issue.addCustomField(customField); Issue createdIssue = issueManager.createIssue(issue); CustomField loadedCustomField = createdIssue.getCustomFieldByName("custom_multi_list"); assertThat(loadedCustomField).isNotNull(); assertThat(loadedCustomField.getValues().size()).isEqualTo(2); List<String> values = new ArrayList<>(loadedCustomField.getValues()); Collections.sort(values); assertThat(loadedCustomField.getValues().get(0)).isEqualTo("V1"); assertThat(loadedCustomField.getValues().get(1)).isEqualTo("V3"); issueManager.deleteIssue(createdIssue.getId()); } /** * This is to make sure we have a workaround for a known bug in redmine 2.6. */ @Test public void createIssueWithEmptyListInMultilineCustomFields() throws Exception { Issue newIssue = IssueFactory.create(projectId, "test for custom multi fields - set multiple values"); CustomFieldDefinition multiFieldDefinition = loadMultiLineCustomFieldDefinition(); CustomField customField = CustomFieldFactory.create(multiFieldDefinition.getId()); customField.setValues(Collections.EMPTY_LIST); newIssue.addCustomField(customField); Issue createdIssue = issueManager.createIssue(newIssue); customField = createdIssue.getCustomFieldByName("custom_multi_list"); assertThat(customField).isNotNull(); assertThat(customField.getValues().size()).isEqualTo(0); issueManager.deleteIssue(createdIssue.getId()); } private static CustomFieldDefinition loadMultiLineCustomFieldDefinition() throws RedmineException { List<CustomFieldDefinition> customFieldDefinitions = mgr.getCustomFieldManager().getCustomFieldDefinitions(); return getCustomFieldByName(customFieldDefinitions, "custom_multi_list"); } @Ignore @Test public void testChangesets() throws RedmineException { final Issue issue = issueManager.getIssueById(89, Include.changesets); assertThat(issue.getChangesets().size()).isEqualTo(2); final Changeset firstChange = issue.getChangesets().iterator().next(); assertNotNull(firstChange.getComments()); } /** * Tests the retrieval of {@link Tracker}s. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testGetTrackers() throws RedmineException { List<Tracker> trackers = issueManager.getTrackers(); assertNotNull("List of trackers returned should not be null", trackers); assertFalse("List of trackers returned should not be empty", trackers.isEmpty()); for (Tracker tracker : trackers) { assertNotNull("Tracker returned should not be null", tracker); assertNotNull("ID of tracker returned should not be null", tracker.getId()); assertNotNull("Name of tracker returned should not be null", tracker.getName()); } } @Test public void getSavedQueriesDoesNotFailForTempProject() throws RedmineException { issueManager.getSavedQueries(projectKey); } @Test public void getSavedQueriesDoesNotFailForNULLProject() throws RedmineException { issueManager.getSavedQueries(null); } @Ignore("This test requires a specific project configuration") @Test public void testSavedQueries() throws RedmineException { final Collection<SavedQuery> queries = issueManager.getSavedQueries("test"); assertTrue(queries.size() > 0); } @Test public void statusIsUpdated() throws RedmineException { Issue issue = createIssues(issueManager, projectId, 1).get(0); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); Integer initialStatusId = retrievedIssue.getStatusId(); List<IssueStatus> statuses = issueManager.getStatuses(); // get some status ID that is not equal to the initial one Integer newStatusId = null; for (IssueStatus status : statuses) { if (!status.getId().equals(initialStatusId)) { newStatusId = status.getId(); break; } } if (newStatusId == null) { throw new RuntimeException("can't run this test: no Issue Statuses are available except for the initial one"); } retrievedIssue.setStatusId(newStatusId); issueManager.update(retrievedIssue); Issue issueWithUpdatedStatus = issueManager.getIssueById(retrievedIssue.getId()); assertThat(issueWithUpdatedStatus.getStatusId()).isEqualTo(newStatusId); } @Test public void changeProject() throws RedmineException { Project project1 = mgr.getProjectManager().getProjectByKey(projectKey); Project project2 = mgr.getProjectManager().getProjectByKey(projectKey2); Issue issue = createIssue(issueManager, projectId); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertThat(retrievedIssue.getProjectId()).isEqualTo(project1.getId()); issue.setProjectId(project2.getId()); issueManager.update(issue); retrievedIssue = issueManager.getIssueById(issue.getId()); assertThat(retrievedIssue.getProjectId()).isEqualTo(project2.getId()); deleteIssueIfNotNull(issue); } @Test public void issueAssignmentUserAndGroup() throws RedmineException { Issue issue = createIssue(issueManager, projectId); assertNull(issue.getAssigneeId()); issue.setAssigneeId(IntegrationTestHelper.getOurUser().getId()); issueManager.update(issue); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); // User assignment succeeded assertThat(retrievedIssue.getAssigneeId()).isEqualTo(IntegrationTestHelper.getOurUser().getId()); issue.setAssigneeId(demoGroup.getId()); issueManager.update(issue); retrievedIssue = issueManager.getIssueById(issue.getId()); // Group assignment succeeded assertThat(retrievedIssue.getAssigneeId()).isEqualTo(demoGroup.getId()); deleteIssueIfNotNull(issue); } @Test public void issueCanBeCreatedOnBehalfOfAnotherUser() throws RedmineException { final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); Issue issue = null; try { RedmineManager managerOnBehalfOfUser = IntegrationTestHelper.createRedmineManager(); managerOnBehalfOfUser.setOnBehalfOfUser(newUser.getLogin()); issue = createIssue(managerOnBehalfOfUser.getIssueManager(), projectId); assertThat(issue.getAuthorName()).isEqualTo(newUser.getFullName()); } finally { userManager.deleteUser(newUser.getId()); deleteIssueIfNotNull(issue); } } @Test public void issuesCanBeFoundByFreeFormSearch() throws RedmineException { // create some random issues in the project createIssues(issueManager, projectId, 3); final String subject = "test for free_form_search."; final Issue issueToCreate = IssueFactory.create(projectId, subject); Integer createdIssueId = null; try { createdIssueId = issueManager.createIssue(issueToCreate).getId(); Map<String, String> params = new HashMap<>(); params.put("project_id", Integer.toString(projectId)); params.put("subject", "~free_form_search"); List<Issue> issues = issueManager.getIssues(params).getResults(); assertThat(issues.size()).isEqualTo(1); final Issue loaded = issues.get(0); assertThat(loaded.getSubject()).isEqualTo(subject); } finally { issueManager.deleteIssue(createdIssueId); } } @Test public void issuesCanBeFoundByMultiQuerySearch() throws RedmineException { final Issue issue1 = IssueFactory.create(projectId, "summary 1 here"); issueManager.createIssue(issue1); final Issue issue2 = IssueFactory.create(projectId, "summary 2 here"); issueManager.createIssue(issue2); // have some random subject to avoid collisions with other tests String subject = "another" + new Random().nextInt(); final Issue issue3 = IssueFactory.create(projectId, subject); issueManager.createIssue(issue3); final User currentUser = userManager.getCurrentUser(); Params params = new Params() .add("set_filter", "1") .add("f[]", "subject") .add("op[subject]", "~") .add("v[subject][]", subject) .add("f[]", "author_id") .add("op[author_id]", "~") .add("v[author_id][]", currentUser.getId()+""); final ResultsWrapper<Issue> list = issueManager.getIssues(params); // only 1 issue must be found assertThat(list.getResults()).hasSize(1); } private void deleteIssueIfNotNull(Issue issue) throws RedmineException { if (issue != null) { issueManager.deleteIssue(issue.getId()); } } }
package it.unibo.deis.lia.ramp.core.internode; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.net.DhcpInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; //import android.net.wifi.WifiManager.MulticastLock; import it.unibo.deis.lia.ramp.RampEntryPoint; import it.unibo.deis.lia.ramp.core.e2e.E2EComm; import org.apache.commons.net.util.SubnetUtils; import org.apache.commons.net.util.SubnetUtils.SubnetInfo; /** * * @author Carlo Giannelli */ public class Heartbeater extends Thread { private Hashtable<InetAddress, NeighborData> neighbors = new Hashtable<InetAddress, NeighborData>(); private HashSet<InetAddress> neighborsBlackList = new HashSet<InetAddress>(); private int heartbeatPeriod = 60 * 1000; // millis private byte[] heartbeatRequestBytes; private static Heartbeater heartbeater = null; // UPnP/SSDP group, but different port public static final String HEARTBEAT_MULTICAST_ADDRESS = "239.255.255.250"; public static synchronized Heartbeater getInstance(boolean forceStart) { if (forceStart && heartbeater == null) { heartbeater = new Heartbeater(); heartbeater.start(); } return heartbeater; } private Heartbeater() { try { neighborsBlackList.add(InetAddress.getByName("137.204.56.113")); // desktop Stefano neighborsBlackList.add(InetAddress.getByName("137.204.57.31")); // jacopo neighborsBlackList.add(InetAddress.getByName("137.204.57.170")); // relay server neighborsBlackList.add(InetAddress.getByName("137.204.57.172")); // portatile carlo, vm studente neighborsBlackList.add(InetAddress.getByName("137.204.57.183")); // desktop Carlo neighborsBlackList.add(InetAddress.getByName("137.204.57.192")); // Qnap neighborsBlackList.add(InetAddress.getByName("137.204.57.155")); // Macchina di prova neighborsBlackList.add(InetAddress.getByName("137.204.57.156")); // Macchina di prova neighborsBlackList.add(InetAddress.getByName("137.204.57.157")); // Macchina di prova } catch (UnknownHostException e1) { e1.printStackTrace(); } HeartbeatRequest hReq = new HeartbeatRequest(); try { // from object to byte[] heartbeatRequestBytes = E2EComm.serializePacket(hReq); } catch (Exception e) { e.printStackTrace(); } } private boolean active = true; public void stopHeartbeater() { System.out.println("Heartbeater.stopHeartbeater"); active = false; interrupt(); } @Override public void run() { try { System.out.println("Heartbeater START"); while (active) { sendHeartbeat(false); //sendHeartbeat(); sleep(heartbeatPeriod); } } catch (InterruptedException ie) { } catch (Exception e) { e.printStackTrace(); } heartbeater = null; System.out.println("Heartbeater END"); } public void sendHeartbeat(boolean force) { //System.out.println("Heartbeater.sendHeartbeat force="+force); //System.out.println("Heartbeater.sendHeartbeat"); Vector<String> localInterfaces = null; try { localInterfaces = Dispatcher.getLocalNetworkAddresses(force); } catch (Exception e1) { e1.printStackTrace(); } /*if (RampEntryPoint.getAndroidContext() != null) { WifiManager wifi = (WifiManager) RampEntryPoint.getAndroidContext().getSystemService(Context.WIFI_SERVICE); if (wifi != null) { wifiMulticastLock = wifi.createMulticastLock("UdpDispatcher-MulticastLock"); wifiMulticastLock.acquire(); } }*/ // multicast for (int i = 0; localInterfaces!=null && i < localInterfaces.size(); i++) { String anInterface = localInterfaces.elementAt(i); //for(int i=0; i<10; i++){ try{ MulticastSocket ms = new MulticastSocket(); ms.setReuseAddress(true); ms.setBroadcast(true); NetworkInterface netInt = NetworkInterface.getByInetAddress(InetAddress.getByName(anInterface)); ms.setNetworkInterface(netInt); //System.out.println("Heartbeater.sendHeartbeat: sending multicast via "+anInterface); // required to send even towards the multicast heartbeat address DatagramPacket dp = new DatagramPacket( heartbeatRequestBytes, heartbeatRequestBytes.length, InetAddress.getByName(Heartbeater.HEARTBEAT_MULTICAST_ADDRESS), Dispatcher.DISPATCHER_PORT ); //ms.setTimeToLive(1); ms.send(dp); ms.close(); } catch (Exception e) { e.printStackTrace(); } // just wait a bit... try { sleep(50); } catch (InterruptedException e) { //e.printStackTrace(); } } // end for /*if (RampEntryPoint.getAndroidContext() != null) { if (wifiMulticastLock != null && wifiMulticastLock.isHeld()) wifiMulticastLock.release(); }*/ // broadcast try { //Vector<String> localInterfaces = Dispatcher.getLocalNetworkAddresses(force); for (int i = 0; localInterfaces!=null && i < localInterfaces.size(); i++) { String anInterface = localInterfaces.elementAt(i); // System.out.println("Heartbeater: anInterface "+anInterface); try { InetAddress inetA = InetAddress.getByName(anInterface); NetworkInterface netA = NetworkInterface.getByInetAddress(inetA); // System.out.println("Heartbeater sending request via "+netA); Set<InetAddress> broadcastAddresses = new HashSet<InetAddress>(); if (RampEntryPoint.getAndroidContext() != null) { WifiManager wifiManager = (WifiManager) RampEntryPoint.getAndroidContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE); // Wi-Fi adapter is ON if (wifiManager.isWifiEnabled()) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); // Connected to an access point if (wifiInfo.getNetworkId() != -1) { DhcpInfo dhcp = wifiManager.getDhcpInfo(); // System.out.println("Heartbeater dhcp.netmask " + dhcp.netmask); // int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; // int broadcast = dhcp.ipAddress | ( ~dhcp.netmask ); byte[] ipaddressQuads = new byte[4]; for (int k = 0; k < 4; k++) { ipaddressQuads[k] = (byte) ((wifiManager.getConnectionInfo().getIpAddress() >> k * 8) & 0xFF); // System.out.println("Heartbeater ipaddressQuads["+k+"] " + ipaddressQuads[k]); } // System.out.println("Heartbeater InetAddress.getByAddress(ipaddressQuads) " + InetAddress.getByAddress(ipaddressQuads)); // broadcastAddresses.add(InetAddress.getByAddress(ipaddressQuads)); byte[] netmaskQuads = new byte[4]; for (int k = 0; k < 4; k++) { netmaskQuads[k] = (byte) ((dhcp.netmask >> k * 8) & 0xFF); // System.out.println("Heartbeater netmaskQuads["+k+"] " + netmaskQuads[k]); } // System.out.println("Heartbeater InetAddress.getByAddress(netmaskQuads) " + InetAddress.getByAddress(netmaskQuads)); // broadcastAddresses.add(InetAddress.getByAddress(netmaskQuads)); int broadcast = wifiManager.getConnectionInfo().getIpAddress() | (~dhcp.netmask); // System.out.println("Heartbeater broadcast " + broadcast); byte[] broadcastQuads = new byte[4]; for (int k = 0; k < 4; k++) { broadcastQuads[k] = (byte) ((broadcast >> k * 8) & 0xFF); // System.out.println("Heartbeater broadcast["+k+"] " + broadcastQuads[k]); } // System.out.println("Heartbeater InetAddress.getByAddress(broadcastQuads) " + InetAddress.getByAddress(broadcastQuads)); broadcastAddresses.add(InetAddress.getByAddress(broadcastQuads)); } } } else { // NOT Android List<InterfaceAddress> interfaceAddresses = netA.getInterfaceAddresses(); if (interfaceAddresses != null && interfaceAddresses.size() > 0) { // System.out.println(anInterface+": interfaceAddresses.size() = "+interfaceAddresses.size()); for (int j = 0; j < interfaceAddresses.size(); j++) { InterfaceAddress interfaceA = netA.getInterfaceAddresses().get(j); // System.out.println("Heartbeater interfaceA " + interfaceA); if (interfaceA != null && interfaceA.getBroadcast() != null) { // System.out.println("Heartbeater interfaceA.getBroadcast() " + interfaceA.getBroadcast()); // System.out.println("Heartbeater interfaceA.getNetworkPrefixLength() " + interfaceA.getNetworkPrefixLength()); broadcastAddresses.add(interfaceA.getBroadcast()); } } } } // System.out.println(anInterface+": broadcast = "+broadcastVector); DatagramSocket ds = new DatagramSocket(0, inetA); ds.setReuseAddress(true); ds.setBroadcast(true); // required to send even towards the multicast heartbeat address //broadcastAddresses.add(InetAddress.getByName(Heartbeater.HEARTBEAT_MULTICAST_ADDRESS)); if (anInterface.startsWith("10.")) { broadcastAddresses.add(InetAddress.getByName("255.255.255.255")); } if (broadcastAddresses.size() == 0) { broadcastAddresses.add(InetAddress.getByName("255.255.255.255")); //broadcastAddresses.add(InetAddress.getByName("192.168.180.49")); broadcastAddresses.add(InetAddress.getByName("192.168.255.255")); broadcastAddresses.add(InetAddress.getByName("192.255.255.255")); broadcastAddresses.add(InetAddress.getByName("192.168.180.255")); //broadcastAddresses.add(InetAddress.getByName("192.168.181.255")); broadcastAddresses.add(InetAddress.getByName("192.168.182.255")); broadcastAddresses.add(InetAddress.getByName("192.168.183.255")); } Iterator<InetAddress> it = broadcastAddresses.iterator(); while (it.hasNext()) { Thread.sleep(50); InetAddress broadcastAddress = it.next(); //System.out.println("Heartbeater: sending from " + inetA + " to " + broadcastAddress); DatagramPacket dp = new DatagramPacket( heartbeatRequestBytes, heartbeatRequestBytes.length, broadcastAddress, Dispatcher.DISPATCHER_PORT ); try { ds.send(dp); sleep(50); } catch (java.net.SocketException se) { // System.out.println("Heartbeater ds.send(dp) SocketException to "+broadcastAddress+": "+se.getMessage()); // se.printStackTrace(); // System.out.println("Heartbeater: sending to 255.255.255.255 instead of " + broadcastAddress); dp = new DatagramPacket( heartbeatRequestBytes, heartbeatRequestBytes.length, InetAddress.getByName("255.255.255.255"), Dispatcher.DISPATCHER_PORT ); ds.send(dp); } } ds.close(); Thread.sleep(100); } catch (Exception e) { System.out.println("Heartbeater Exception from " + anInterface + ": " + e.getMessage()); e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); System.out.println("Heartbeater " + e.getMessage()); // on debian/ubuntu, remember to change the file // "/etc/sysctl.d/bindv6only.conf" // from // "net.ipv6.bindv6only = 1" // "net.ipv6.bindv6only = 0" // and finally invoke // "invoke-rc.d procps restart" } //STEFANO LANZONE: Fare N Unicast //implement unicast-based discovery exploiting netmask... for (int i = 0; localInterfaces!=null && i < localInterfaces.size(); i++) { String anInterface = localInterfaces.elementAt(i); try { InetAddress inetA = InetAddress.getByName(anInterface); NetworkInterface netA = NetworkInterface.getByInetAddress(inetA); if (RampEntryPoint.getAndroidContext() != null) { WifiManager wifiManager = (WifiManager) RampEntryPoint.getAndroidContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE); // Wi-Fi adapter is ON if (wifiManager.isWifiEnabled()) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); // Connected to an access point if (wifiInfo.getNetworkId() != -1) { DhcpInfo dhcp = wifiManager.getDhcpInfo(); byte[] ipaddressQuads = new byte[4]; for (int k = 0; k < 4; k++) { ipaddressQuads[k] = (byte) ((wifiManager.getConnectionInfo().getIpAddress() >> k * 8) & 0xFF); } byte[] netmaskQuads = new byte[4]; for (int k = 0; k < 4; k++) { netmaskQuads[k] = (byte) ((dhcp.netmask >> k * 8) & 0xFF); } InetAddress ipaddress = InetAddress.getByAddress(ipaddressQuads); InetAddress netmask = InetAddress.getByAddress(netmaskQuads); DatagramSocket ds = new DatagramSocket(0, ipaddress); String ip = ipaddress.toString().replaceAll("/", "").split(":")[0]; SubnetUtils utils = new SubnetUtils(ip, netmask.toString().replaceAll("/", "").split(":")[0]); SubnetInfo info = utils.getInfo(); unicastDiscovery(ipaddress, ds, ip, info); } } // BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // // Temporary workaround // if (bluetoothAdapter != null) { // // Device support Bluetooth // if (bluetoothAdapter.isEnabled()) { // DatagramSocket ds = new DatagramSocket(0, inetA); // String ip = inetA.toString().replaceAll("/", "").split(":")[0]; // int prefixLength = 24; // String subnet = ip + "/" + prefixLength; // SubnetUtils utils = new SubnetUtils(subnet); // SubnetInfo info = utils.getInfo(); // System.out.println("Heartbeater - sendHeartbeat: inetAddress " + inetA); // System.out.println("Heartbeater - sendHeartbeat: ip " + ip + ", prefixLength: " + prefixLength); // System.out.println("Heartbeater - sendHeartbeat: subnet " + subnet); // System.out.println("Heartbeater - sendHeartbeat: info " + info); // unicastDiscovery(inetA, ds, ip, info); } else { // NOT Android for (InterfaceAddress address : netA.getInterfaceAddresses()) { InetAddress inetAddress = address.getAddress(); DatagramSocket ds = new DatagramSocket(0, inetAddress); String ip = inetAddress.toString().replaceAll("/", "").split(":")[0]; int prefixLength = address.getNetworkPrefixLength(); String subnet = ip + "/" + prefixLength; SubnetUtils utils = new SubnetUtils(subnet); SubnetInfo info = utils.getInfo(); unicastDiscovery(inetAddress, ds, ip, info); Thread.sleep(50); } } } catch (Exception e) { System.out.println("Heartbeater Exception from " + anInterface + ": " + e.getMessage()); e.printStackTrace(); } } } private void unicastDiscovery(InetAddress inetAddress, DatagramSocket ds, String ip, SubnetInfo info) throws UnknownHostException { if (info.getAddressCount() < 255) //Impostato limite sul numero di unicast... { for (String ipDest : info.getAllAddresses()) { if(!ip.equals(ipDest)) { DatagramPacket dp = new DatagramPacket( heartbeatRequestBytes, heartbeatRequestBytes.length, InetAddress.getByName(ipDest), Dispatcher.DISPATCHER_PORT ); try { // System.out.println("Heartbeater Unicast: sending from " + inetAddress + " to " + ipDest); ds.send(dp); //sleep(50); } catch (Exception e) { System.out.println("Heartbeater Unicast Error: sending from " + inetAddress + " to " + ipDest); e.printStackTrace(); } } } } ds.close(); } protected void addNeighbor(InetAddress neighborInetAddress, int nodeId) { if(!neighborsBlackList.contains(neighborInetAddress)){ neighbors.put( neighborInetAddress, new NeighborData( System.currentTimeMillis(), nodeId ) ); } } protected boolean isNeighbor(InetAddress neighborInetAddress) { return neighbors.containsKey(neighborInetAddress); } // public synchronized Vector<InetAddress> getNeighbors() throws Exception{ public Vector<InetAddress> getNeighbors() { // System.out.println("Heartbeater.getNeighbors start"); Vector<InetAddress> res = new Vector<InetAddress>(); Enumeration<InetAddress> keys = neighbors.keys(); while (keys.hasMoreElements()) { InetAddress address = keys.nextElement(); //Long lastUpdate = neighbors.get(address); NeighborData neighbor = neighbors.get(address); if( neighbor != null ){ Long lastUpdate = neighbor.getLastRefersh(); if (lastUpdate != null) { if (System.currentTimeMillis() - lastUpdate > heartbeatPeriod + (heartbeatPeriod / 2)) { neighbors.remove(address); } else { res.addElement(address); } } } } return res; } public Integer getNodeId(InetAddress address){ Integer res = null; NeighborData data = this.neighbors.get(address); if( data != null ){ res = data.getNodeId(); } return res; } public static class NeighborData { private long lastRefersh; private int nodeId; private NeighborData(long lastRefersh, int nodeId) { super(); this.lastRefersh = lastRefersh; this.nodeId = nodeId; } public long getLastRefersh() { return lastRefersh; } public int getNodeId() { return nodeId; } } }
package controller; import javafx.application.Platform; import javafx.scene.Node; import javafx.scene.control.ListView; import javafx.scene.input.KeyCode; import javafx.scene.input.MouseButton; import javafx.stage.Stage; import mockInterface.FileDialogInterface; import model.FileManager; import model.FileManagerInterface; import model.LineInterface; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.testfx.api.FxToolkit; import org.testfx.framework.junit.ApplicationTest; import org.testfx.matcher.base.NodeMatchers; import org.testfx.util.WaitForAsyncUtils; import utils.FxImageComparison; import utils.TestUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.util.concurrent.TimeoutException; import static org.easymock.EasyMock.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.testfx.api.FxAssert.verifyThat; public class ControlPaneSceneControllerTest extends ApplicationTest implements FxImageComparison { private Stage s; @Override public void init() throws Exception { FxToolkit.registerStage(Stage::new); } @Override public void start(Stage stage) { s = TestUtils.startStage(stage); } @Override public void stop() throws Exception { FxToolkit.cleanupStages(); FxToolkit.hideStage(); } @Before public void setUp() throws TimeoutException { FxToolkit.registerPrimaryStage(); } @Test public void controlPaneSceneInitialButtonClickTest(){ Node[] buttons = { find("#btnMergeLeft"), find("#btnMergeRight"), find("#btnCompare") }; // btnMergeLeft, btnMergeRight . verifyThat(buttons[0], NodeMatchers.isDisabled()); verifyThat(buttons[1], NodeMatchers.isDisabled()); verifyThat(buttons[2], NodeMatchers.isEnabled()); } @Test public void controlPaneSceneInitialMenuItemClickTest(){ Node[] menuItems = { find("#menuFile"), find("#menuEdit"), find("#menuHelps") }; for(Node node : menuItems){ clickOn(node); verifyThat(node, NodeMatchers.isEnabled()); } } @Test public void controlPaneSceneShortCutKeyClickTest(){ final KeyCode SHORTCUT = System.getProperty("os.name").toLowerCase().contains("mac") ? KeyCode.COMMAND : KeyCode.CONTROL; push(SHORTCUT, KeyCode.RIGHT); // Copy to right WaitForAsyncUtils.waitForFxEvents(); assertEquals(2, listWindows().size()); closeCurrentWindow(); push(SHORTCUT, KeyCode.LEFT); // Copy to left WaitForAsyncUtils.waitForFxEvents(); assertEquals(2, listWindows().size()); } @Test public void controlPaneSceneButtonCompareClickTest() throws IOException { Node btnCompare = find("#btnCompare"); String leftFile = getClass().getResource("../test1-1.txt").getPath(); String rightFile = getClass().getResource("../test1-2.txt").getPath(); FileDialogInterface fileDialogMock = createMock(FileDialogInterface.class); expect(fileDialogMock.getPath(FileManagerInterface.SideOfEditor.Left)).andReturn(leftFile); expect(fileDialogMock.getPath(FileManagerInterface.SideOfEditor.Right)).andReturn(rightFile); replay(fileDialogMock); Platform.runLater(()->{ try { FileManager.getFileManagerInterface().loadFile( fileDialogMock.getPath(FileManagerInterface.SideOfEditor.Right), FileManagerInterface.SideOfEditor.Right ); FileManager.getFileManagerInterface().loadFile( fileDialogMock.getPath(FileManagerInterface.SideOfEditor.Left), FileManagerInterface.SideOfEditor.Left ); verify(fileDialogMock); } catch (FileNotFoundException e) { e.printStackTrace(); } }); WaitForAsyncUtils.waitForFxEvents(); clickOn(btnCompare); Node leftSplit = s.getScene().lookup("#leftSplit"); Node rightSplit = s.getScene().lookup("#rightSplit"); HighlightEditorInterface leftEditor = (HighlightEditorInterface) leftSplit.lookup("#editor"); HighlightEditorInterface rightEditor = (HighlightEditorInterface) rightSplit.lookup("#editor"); verifyThat(leftEditor.getHighlightListView(), (ListView<LineInterface> listView) -> { int i = 0; LineInterface item = listView.getItems().get(i); switch (i){ case 0: case 19: return item.getHighlight() == LineInterface.LineHighlight.whitespace; case 1: case 20: return item.getHighlight() == LineInterface.LineHighlight.isDifferent; } return item.getHighlight() == LineInterface.LineHighlight.unHighlighted; }); verifyThat(rightEditor.getHighlightListView(), (ListView<LineInterface> listView) -> { int i = 0; LineInterface item = listView.getItems().get(i); switch (i){ case 0: case 19: return item.getHighlight() == LineInterface.LineHighlight.isDifferent; case 1: case 20: return item.getHighlight() == LineInterface.LineHighlight.whitespace; } return item.getHighlight() == LineInterface.LineHighlight.unHighlighted; }); // view Rendering Testing Node tPane = find("#tabPane"); assertNotNull("tabPane is null", tPane); assertSnapshotsEqual(getClass().getResource("../compareResult.png").getPath(), tPane, 1); assertEquals(FileManager.getFileManagerInterface().getComparing(), true); } @Test public void singleBlockSelectTest() throws IOException { controlPaneSceneButtonCompareClickTest(); clickOn(".isDifferent"); Node tPane = find("#tabPane"); assertNotNull("tabPane is null", tPane); assertSnapshotsEqual(getClass().getResource("../singleSelectedResult.png").getPath(), tPane, 1); } @Test public void manyBlockSelectTest() throws IOException { controlPaneSceneButtonCompareClickTest(); clickOn(".isDifferent"); clickOn(".isDifferent"); Node tPane = find("#tabPane"); assertNotNull("tabPane is null", tPane); assertSnapshotsEqual(getClass().getResource("../multiSelectedResult.png").getPath(), tPane, 1); } @Test public void manyBlockMergeTest() throws IOException { //given : controlPaneSceneButtonCompareClickTest(); //when : clickOn(".isDifferent"); clickOn(".isDifferent"); clickOn("#btnMergeRight"); Node tPane = find("#tabPane"); assertNotNull("tabPane is null", tPane); Node leftSplit = s.getScene().lookup("#leftSplit"); Node rightSplit = s.getScene().lookup("#rightSplit"); HighlightEditorInterface leftEditor = (HighlightEditorInterface) leftSplit.lookup("#editor"); HighlightEditorInterface rightEditor = (HighlightEditorInterface) rightSplit.lookup("#editor"); //then : // UI Testing assertSnapshotsEqual(getClass().getResource("../multiMergeResult.png").getPath(), tPane, 1); // System Testing assertEquals(leftEditor.getHighlightListView().getItems().get(0), rightEditor.getHighlightListView().getItems().get(0)); assertEquals(leftEditor.getHighlightListView().getItems().get(1), rightEditor.getHighlightListView().getItems().get(1)); assertEquals(leftEditor.getHighlightListView().getItems().get(17), rightEditor.getHighlightListView().getItems().get(17)); assertEquals(leftEditor.getHighlightListView().getItems().get(18), rightEditor.getHighlightListView().getItems().get(18)); } @Test public void resetTest() throws IOException { clickOn("#menuFile"); clickOn("#menuReset"); Node tPane = find("#tabPane"); assertNotNull("tabPane is null", tPane); assertSnapshotsEqual(getClass().getResource("../undecoratedRootScene.png").getPath(), tPane, 1); assertEquals(FileManager.getFileManagerInterface().getString(FileManagerInterface.SideOfEditor.Left), ""); assertEquals(FileManager.getFileManagerInterface().getString(FileManagerInterface.SideOfEditor.Right), ""); controlPaneSceneInitialButtonClickTest(); } @Test public void singleBlockMergeTest() throws IOException { controlPaneSceneButtonCompareClickTest(); clickOn(".isDifferent"); clickOn("#btnMergeRight"); Node tPane = find("#tabPane"); assertNotNull("tabPane is null", tPane); Node leftSplit = s.getScene().lookup("#leftSplit"); Node rightSplit = s.getScene().lookup("#rightSplit"); HighlightEditorInterface leftEditor = (HighlightEditorInterface) leftSplit.lookup("#editor"); HighlightEditorInterface rightEditor = (HighlightEditorInterface) rightSplit.lookup("#editor"); //then : // UI Testing assertSnapshotsEqual(getClass().getResource("../singleMergeResult.png").getPath(), tPane, 1); // System Testing assertEquals(leftEditor.getHighlightListView().getItems().get(0), rightEditor.getHighlightListView().getItems().get(0)); assertEquals(leftEditor.getHighlightListView().getItems().get(1), rightEditor.getHighlightListView().getItems().get(1)); } @After public void tearDown() throws TimeoutException { FxToolkit.cleanupStages(); FxToolkit.hideStage(); FileManager.getFileManagerInterface().resetModel(FileManagerInterface.SideOfEditor.Left); FileManager.getFileManagerInterface().resetModel(FileManagerInterface.SideOfEditor.Right); release(new KeyCode[] {}); release(new MouseButton[] {}); } private <T extends Node> T find(final String query) { return lookup(query).query(); } }
package org.xins.common.service; import java.util.Iterator; import org.xins.common.Log; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.TimeOutController; import org.xins.common.TimeOutException; import org.xins.common.Utils; /** * Abstraction of a service caller for a TCP-based service. Service caller * implementations can be used to perform a call to a service, and potentially * fail-over to other back-ends if one is not available. Additionally, * load-balancing and different types of time-outs are supported. * * <p>Back-ends are * represented by {@link TargetDescriptor} instances. Groups of back-ends are * represented by {@link GroupDescriptor} instances. * * <a name="section-lbfo"></a> * <h2>Load-balancing and fail-over</h2> * * <p>TODO: Describe load-balancing and fail-over. * * <a name="section-timeouts"></a> * <h2>Time-outs</h2> * * <p>TODO: Describe time-outs. * * <a name="section-callconfig"></a> * <h2>Call configuration</h2> * * <p>Some aspects of a call can be configured using a {@link CallConfig} * object. For example, the <code>CallConfig</code> base class indicates * whether fail-over is unconditionally allowed. Like this, some aspects of * the behaviour of the caller can be tweaked. * * <p>There are different places where a <code>CallConfig</code> can be * applied: * * <ul> * <li>stored in a <code>ServiceCaller</code>; * <li>stored in a <code>CallRequest</code>; * <li>passed with the call method. * </ul> * * <p>First of all, each <code>ServiceCaller</code> instance will have a * fall-back <code>CallConfig</code>. * * <p>Secondly, a {@link CallRequest} instance may have a * <code>CallConfig</code> associated with it as well. If it does, then this * overrides the one on the <code>ServiceCaller</code> instance. * * <p>Finally, a <code>CallConfig</code> can be passed as an argument to the * call method. If it is, then this overrides any other settings. * * <a name="section-implementations"></a> * <h2>Implementations</h2> * * <p>This class is abstract and is intended to be have service-specific * subclasses, e.g. for HTTP, FTP, JDBC, etc. * * <p>Normally, a subclass should be stick to the following rules: * * <ol> * <li>There should be a constructor that accepts only a {@link Descriptor} * object. This constructor should call * <code>super(descriptor, null)</code>. If this descriptor contains * any {@link TargetDescriptor} instances that have an unsupported * protocol, then an {@link UnsupportedProtocolException} should be * thrown. * <li>There should be a constructor that accepts both a * {@link Descriptor} and a service-specific call config object * (derived from {@link CallConfig}). This constructor should call * <code>super(descriptor, callConfig)</code>. If this descriptor * contains any {@link TargetDescriptor} instances that have an * unsupported protocol, then an {@link UnsupportedProtocolException} * should be thrown. * <li>There should be a <code>call</code> method that accepts only a * service-specific request object (derived from {@link CallRequest}). * It should call * {@link #doCall(CallRequest,CallConfig) doCall}<code>(request, null)</code>. * <li>There should be a <code>call</code> method that accepts both a * service-specific request object (derived from {@link CallRequest}). * and a service-specific call config object (derived from * {@link CallConfig}). It should call * {@link #doCall(CallRequest,CallConfig) doCall}<code>(request, callConfig)</code>. * <li>The method * {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)} must * be implemented as specified. * <li>The {@link #createCallResult(CallRequest,TargetDescriptor,long,CallExceptionList,Object) createCallResult} * method must be implemented as specified. * <li>To control when fail-over is applied, the method * {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)} * may also be implemented. The implementation can assume that * the passed {@link CallRequest} object is an instance of the * service-specific call request class and that the passed * {@link CallConfig} object is an instance of the service-specific * call config class. * </ol> * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ public abstract class ServiceCaller extends Object { // TODO: Describe typical implementation scenario, e.g. a // SpecificCallResult call(SpecificCallRequest, SpecificCallConfig) // method that calls doCall(CallRequest,CallConfig). // Class fields /** * The fully-qualified name of this class. */ private static final String CLASSNAME = ServiceCaller.class.getName(); // Class functions // Constructors protected ServiceCaller(Descriptor descriptor) throws IllegalArgumentException { final String THIS_METHOD = "<init>(" + Descriptor.class.getName() + ')'; // TRACE: Enter constructor Log.log_1000(CLASSNAME, null); // Check preconditions MandatoryArgumentChecker.check("descriptor", descriptor); // Set fields _newStyle = false; _descriptor = descriptor; _callConfig = null; _className = getClass().getName(); // Make sure the old-style (XINS 1.0) doCallImpl method is implemented try { doCallImpl((CallRequest) null, (TargetDescriptor) null); throw new Error(); } catch (Throwable t) { if (t instanceof MethodNotImplementedError) { final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + TargetDescriptor.class.getName() + ')'; final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since class uses old-style (XINS 1.0) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } } // Make sure the old-style (XINS 1.0) shouldFailOver method is implemented try { shouldFailOver((CallRequest) null, (Throwable) null); throw new Error(); } catch (Throwable t) { if (t instanceof MethodNotImplementedError) { final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + "java.lang.Throwable)"; final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since class uses old-style (XINS 1.0) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } } // Make sure the new-style (XINS 1.1) doCallImpl method is not implemented try { doCallImpl((CallRequest) null, (CallConfig) null, (TargetDescriptor) null); throw new Error(); } catch (Throwable t) { if (! (t instanceof MethodNotImplementedError)) { final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')'; final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since class uses old-style (XINS 1.0) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } } // Make sure the new-style (XINS 1.1) shouldFailOver method is not implemented try { shouldFailOver((CallRequest) null, (CallConfig) null, (CallExceptionList) null); throw new Error(); } catch (Throwable t) { if (! (t instanceof MethodNotImplementedError)) { final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + CallExceptionList.class.getName() + ')'; final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since class uses old-style (XINS 1.0) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } } // TRACE: Leave constructor Log.log_1002(CLASSNAME, null); } protected ServiceCaller(Descriptor descriptor, CallConfig callConfig) throws IllegalArgumentException { final String THIS_METHOD = "<init>(" + Descriptor.class.getName() + ',' + CallConfig.class.getName() + ')'; // TRACE: Enter constructor Log.log_1000(CLASSNAME, null); // Check preconditions MandatoryArgumentChecker.check("descriptor", descriptor); // Initialize all fields except callConfig _className = getClass().getName(); _newStyle = true; _descriptor = descriptor; // If no CallConfig is specified, then use a default one if (callConfig == null) { final String SUBJECT_METHOD = "getDefaultCallConfig()"; // Call getDefaultCallConfig() to get the default config... try { callConfig = getDefaultCallConfig(); // ...the method must be implemented... } catch (MethodNotImplementedError e) { final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since class uses new-style (XINS 1.1) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); // ...it should not throw any exception... } catch (Throwable t) { final String DETAIL = null; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL, t); } // ...and it should never return null. if (callConfig == null) { final String DETAIL = "Method returned null, although that is disallowed by the ServiceCaller.getDefaultCallConfig() contract."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } } // Set call configuration _callConfig = callConfig; // Make sure the old-style (XINS 1.0) doCallImpl method is not implemented try { doCallImpl((CallRequest) null, (TargetDescriptor) null); throw new Error(); } catch (Throwable t) { if (! (t instanceof MethodNotImplementedError)) { final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + TargetDescriptor.class.getName() + ')'; final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } } // Make sure the old-style (XINS 1.0) shouldFailOver method is not implemented try { shouldFailOver((CallRequest) null, (Throwable) null); throw new Error(); } catch (Throwable t) { if (! (t instanceof MethodNotImplementedError)) { final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + ',' + Throwable.class.getName() + ')'; final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } } // Make sure the new-style (XINS 1.1) doCallImpl method is implemented try { doCallImpl((CallRequest) null, (CallConfig) null, (TargetDescriptor) null); throw new Error(); } catch (Throwable t) { if (t instanceof MethodNotImplementedError) { final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')'; final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } } // Make sure the new-style (XINS 1.1) shouldFailOver method is implemented try { shouldFailOver((CallRequest) null, (CallConfig) null, (CallExceptionList) null); throw new Error(); } catch (Throwable t) { if (t instanceof MethodNotImplementedError) { final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + CallExceptionList.class.getName() + ')'; final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } } // TRACE: Leave constructor Log.log_1002(CLASSNAME, null); } // Fields /** * The name of the current (concrete) class. Never <code>null</code>. */ private final String _className; /** * Flag that indicates if the new-style (XINS 1.1) (since XINS 1.1.0) or the old-style (XINS 1.0) * (XINS 1.0.0) behavior is expected from the subclass. */ private final boolean _newStyle; /** * The descriptor for this service. Cannot be <code>null</code>. */ private final Descriptor _descriptor; /** * The fall-back call config object for this service caller. Can only be * <code>null</code> if this is an old-style service caller. */ private CallConfig _callConfig; // Methods /** * Returns the descriptor. * * @return * the descriptor for this service, never <code>null</code>. */ public final Descriptor getDescriptor() { return _descriptor; } protected final void setCallConfig(CallConfig config) throws IllegalArgumentException { final String THIS_METHOD = "setCallConfig(" + CallConfig.class.getName() + ')'; // Check argument MandatoryArgumentChecker.check("config", config); // This method should only be called if the subclass uses the new style if (! _newStyle) { final String SUBJECT_CLASS = Utils.getCallingClass(); final String SUBJECT_METHOD = Utils.getCallingMethod(); final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses old-style (XINS 1.0) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL); } _callConfig = config; } /** * Returns the <code>CallConfig</code> associated with this service caller. * * @return * the fall-back {@link CallConfig} object for this service caller, * never <code>null</code>. * * @since XINS 1.1.0 */ public final CallConfig getCallConfig() { return _callConfig; } /** * Returns a default <code>CallConfig</code> object. This method is called * by the <code>ServiceCaller</code> constructor if no * <code>CallConfig</code> object was given. * * <p>Subclasses that support the new service calling framework (introduced * in XINS 1.1.0) <em>must</em> override this method to return a more * suitable <code>CallConfig</code> instance. * * <p>This method should never be called by subclasses. * * @return * a new, appropriate, {@link CallConfig} instance, never * <code>null</code>. * * @since XINS 1.1.0 */ protected CallConfig getDefaultCallConfig() { throw new MethodNotImplementedError(); } protected final CallResult doCall(CallRequest request, CallConfig callConfig) throws IllegalArgumentException, CallException { final String THIS_METHOD = "doCall(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ')'; // TRACE: Enter method Log.log_1003(CLASSNAME, THIS_METHOD, null); // This method should only be called if the subclass uses the new style if (! _newStyle) { final String SUBJECT_CLASS = Utils.getCallingClass(); final String SUBJECT_METHOD = Utils.getCallingMethod(); final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses old-style (XINS 1.0) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL); } // Check preconditions MandatoryArgumentChecker.check("request", request); // Determine what config to use. The argument has priority, then the one // associated with the request and the fall-back is the one associated // with this service caller. if (callConfig == null) { callConfig = request.getCallConfig(); if (callConfig == null) { callConfig = _callConfig; } } // Keep a reference to the most recent CallException since // setNext(CallException) needs to be called on it to make it link to // the next one (if there is one) CallException lastException = null; // Maintain the list of CallExceptions // This is needed if a successful result (a CallResult object) is // returned, since it will contain references to the exceptions as well; // Note that this object is lazily initialized because this code is // performance- and memory-optimized for the successful case CallExceptionList exceptions = null; // Iterate over all targets Iterator iterator = _descriptor.iterateTargets(); // TODO: Improve performance, do not use an iterator? // There should be at least one target if (! iterator.hasNext()) { final String SUBJECT_CLASS = _descriptor.getClass().getName(); final String SUBJECT_METHOD = "iterateTargets()"; final String DETAIL = "Descriptor returns no target descriptors."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL); } // Loop over all TargetDescriptors boolean shouldContinue = true; while (shouldContinue) { // Get a reference to the next TargetDescriptor TargetDescriptor target = (TargetDescriptor) iterator.next(); // Call using this target Log.log_1301(target.getURL()); Object result = null; boolean succeeded = false; long start = System.currentTimeMillis(); try { // Attempt the call result = doCallImpl(request, callConfig, target); succeeded = true; // If the call to the target fails, store the exception and try the next } catch (Throwable exception) { Log.log_1302(target.getURL()); long duration = System.currentTimeMillis() - start; // If the caught exception is not a CallException, then // encapsulate it in one CallException currentException; if (exception instanceof CallException) { currentException = (CallException) exception; } else if (exception instanceof MethodNotImplementedError) { final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')'; final String DETAIL = "The method " + SUBJECT_METHOD + " is not implemented although it should be."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } else { currentException = new UnexpectedExceptionCallException(request, target, duration, null, exception); } // Link the previous exception (if there is one) to this one if (lastException != null) { lastException.setNext(currentException); } // Now set this exception as the most recent CallException lastException = currentException; // If this is the first exception being caught, then lazily // initialize the CallExceptionList and keep a reference to the // first exception if (exceptions == null) { exceptions = new CallExceptionList(); } // Store the failure exceptions.add(currentException); // Determine whether fail-over is allowed and whether we have // another target to fail-over to boolean failOver = shouldFailOver(request, callConfig, exceptions); boolean haveNext = iterator.hasNext(); // No more targets and no fail-over if (!haveNext && !failOver) { Log.log_1304(); shouldContinue = false; // No more targets but fail-over would be allowed } else if (!haveNext) { Log.log_1305(); shouldContinue = false; // More targets available but fail-over is not allowed } else if (!failOver) { Log.log_1306(); shouldContinue = false; // More targets available and fail-over is allowed } else { Log.log_1307(); shouldContinue = true; } } // The call succeeded if (succeeded) { long duration = System.currentTimeMillis() - start; // TRACE: Leave method Log.log_1005(CLASSNAME, THIS_METHOD, null); return createCallResult(request, target, duration, exceptions, result); } } // Loop ended, call failed completely Log.log_1303(); // Get the first exception from the list, this one should be thrown CallException first = exceptions.get(0); // TRACE: Leave method with exception Log.log_1004(first, CLASSNAME, THIS_METHOD, null); throw first; } protected final CallResult doCall(CallRequest request) throws IllegalArgumentException, CallException { final String THIS_METHOD = "doCall(" + CallRequest.class.getName() + ')'; // TRACE: Enter method Log.log_1003(CLASSNAME, THIS_METHOD, null); // This method should only be called if the subclass uses the old style if (_newStyle) { final String SUBJECT_CLASS = Utils.getCallingClass(); final String SUBJECT_METHOD = Utils.getCallingMethod(); final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses new-style (XINS 1.1) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL); } // Check preconditions MandatoryArgumentChecker.check("request", request); // Keep a reference to the most recent CallException since // setNext(CallException) needs to be called on it to make it link to // the next one (if there is one) CallException lastException = null; // Maintain the list of CallExceptions // This is needed if a successful result (a CallResult object) is // returned, since it will contain references to the exceptions as well; // Note that this object is lazily initialized because this code is // performance- and memory-optimized for the successful case CallExceptionList exceptions = null; // Iterate over all targets Iterator iterator = _descriptor.iterateTargets(); // There should be at least one target if (! iterator.hasNext()) { final String SUBJECT_CLASS = _descriptor.getClass().getName(); final String SUBJECT_METHOD = "iterateTargets()"; final String DETAIL = "Descriptor returns no target descriptors."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL); } // Loop over all TargetDescriptors boolean shouldContinue = true; while (shouldContinue) { // Get a reference to the next TargetDescriptor TargetDescriptor target = (TargetDescriptor) iterator.next(); // Call using this target Log.log_1301(target.getURL()); Object result = null; boolean succeeded = false; long start = System.currentTimeMillis(); try { // Attempt the call result = doCallImpl(request, target); succeeded = true; // If the call to the target fails, store the exception and try the next } catch (Throwable exception) { Log.log_1302(target.getURL()); long duration = System.currentTimeMillis() - start; // If the caught exception is not a CallException, then // encapsulate it in one CallException currentException; if (exception instanceof CallException) { currentException = (CallException) exception; } else if (exception instanceof MethodNotImplementedError) { // TODO: Detail message should be reviewed final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')'; final String DETAIL = "The method is not implemented although it should be."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL); } else { currentException = new UnexpectedExceptionCallException(request, target, duration, null, exception); } // Link the previous exception (if there is one) to this one if (lastException != null) { lastException.setNext(currentException); } // Now set this exception as the most recent CallException lastException = currentException; // If this is the first exception being caught, then lazily // initialize the CallExceptionList and keep a reference to the // first exception if (exceptions == null) { exceptions = new CallExceptionList(); } // Store the failure exceptions.add(currentException); // Determine whether fail-over is allowed and whether we have // another target to fail-over to boolean failOver = shouldFailOver(request, exception); boolean haveNext = iterator.hasNext(); // No more targets and no fail-over if (!haveNext && !failOver) { Log.log_1304(); shouldContinue = false; // No more targets but fail-over would be allowed } else if (!haveNext) { Log.log_1305(); shouldContinue = false; // More targets available but fail-over is not allowed } else if (!failOver) { Log.log_1306(); shouldContinue = false; // More targets available and fail-over is allowed } else { Log.log_1307(); shouldContinue = true; } } // The call succeeded if (succeeded) { long duration = System.currentTimeMillis() - start; // TRACE: Leave method Log.log_1005(CLASSNAME, THIS_METHOD, null); return createCallResult(request, target, duration, exceptions, result); } } // Loop ended, call failed completely Log.log_1303(); // Get the first exception from the list, this one should be thrown CallException first = exceptions.get(0); // TRACE: Leave method with exception Log.log_1004(first, CLASSNAME, THIS_METHOD, null); throw first; } protected Object doCallImpl(CallRequest request, CallConfig callConfig, TargetDescriptor target) throws ClassCastException, IllegalArgumentException, CallException { throw new MethodNotImplementedError(); } protected Object doCallImpl(CallRequest request, TargetDescriptor target) throws ClassCastException, IllegalArgumentException, CallException { throw new MethodNotImplementedError(); } /** * Constructs an appropriate <code>CallResult</code> object for a * successful call attempt. This method is called from * {@link #doCall(CallRequest)}. * * @param request * the {@link CallRequest} that was to be executed, never * <code>null</code> when called from {@link #doCall(CallRequest)}. * * @param succeededTarget * the {@link TargetDescriptor} for the service that was successfully * called, never <code>null</code> when called from * {@link #doCall(CallRequest)}. * * @param duration * the call duration in milliseconds, guaranteed to be a non-negative * number when called from {@link #doCall(CallRequest)}. * * @param exceptions * the list of {@link CallException} instances, or <code>null</code> if * there were no call failures. * * @param result * the result from the call, which is the object returned by * {@link #doCallImpl(CallRequest,TargetDescriptor)}, can be * <code>null</code>. * * @return * a {@link CallResult} instance, never <code>null</code>. * * @throws ClassCastException * if <code>request</code> and/or <code>result</code> are not of the * correct class. */ protected abstract CallResult createCallResult(CallRequest request, TargetDescriptor succeededTarget, long duration, CallExceptionList exceptions, Object result) throws ClassCastException; protected final void controlTimeOut(Runnable task, TargetDescriptor descriptor) throws IllegalArgumentException, IllegalThreadStateException, SecurityException, TimeOutException { // Check preconditions MandatoryArgumentChecker.check("task", task, "descriptor", descriptor); // Determine the total time-out int totalTimeOut = descriptor.getTotalTimeOut(); // If there is no total time-out, then execute the task on this thread if (totalTimeOut < 1) { task.run(); // Otherwise a time-out controller will be used } else { TimeOutController.execute(task, totalTimeOut); } } /** * Determines whether a call should fail-over to the next selected target. * This method should only be called from {@link #doCall(CallRequest)}. * * <p>This method is typically overridden by subclasses. Usually, a * subclass first calls this method in the superclass, and if that returns * <code>false</code> it does some additional checks, otherwise * <code>true</code> is immediately returned. * * <p>The implementation of this method in class {@link ServiceCaller} * returns <code>true</code> if and only if <code>exception instanceof * {@link ConnectionCallException}</code>. * * @param request * the request for the call, as passed to {@link #doCall(CallRequest)}, * should not be <code>null</code>. * * @param exception * the exception caught while calling the most recently called target, * should not be <code>null</code>. * * @return * <code>true</code> if the call should fail-over to the next target, or * <code>false</code> if it should not. * * @deprecated * Deprecated since XINS 1.1.0. Implement * {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)} * instead of this method. * This method is guaranteed not to be removed before XINS 2.0.0. */ protected boolean shouldFailOver(CallRequest request, Throwable exception) { if (_newStyle) { throw new MethodNotImplementedError(); } final String THIS_METHOD = "shouldFailOver(CallRequest,Throwable)"; // TRACE: Enter method Log.log_1003(CLASSNAME, THIS_METHOD, null); // Determine if fail-over is applicable boolean should = (exception instanceof ConnectionCallException); // TRACE: Leave method Log.log_1005(CLASSNAME, THIS_METHOD, null); return should; } /** * Determines whether a call should fail-over to the next selected target * based on a request, call configuration and exception list. * This method should only be called from * {@link #doCall(CallRequest,CallConfig)}. * * <p>This method is typically overridden by subclasses. Usually, a * subclass first calls this method in the superclass, and if that returns * <code>false</code> it does some additional checks, otherwise * <code>true</code> is immediately returned. * * <p>The implementation of this method in class {@link ServiceCaller} * returns <code>true</code> if and only if * <code>callConfig.{@link CallConfig#isFailOverAllowed() isFailOverAllowed()} || exception instanceof {@link ConnectionCallException}</code>. * * @param request * the request for the call, as passed to {@link #doCall(CallRequest)}, * should not be <code>null</code>. * * @param callConfig * the call config that is currently in use, never <code>null</code>. * * @param exceptions * the current list of {@link CallException}s; never * <code>null</code>; get the most recent one by calling * <code>exceptions.</code>{@link CallExceptionList#last() last()}. * * @return * <code>true</code> if the call should fail-over to the next target, or * <code>false</code> if it should not. * * @since XINS 1.1.0 */ protected boolean shouldFailOver(CallRequest request, CallConfig callConfig, CallExceptionList exceptions) { final String THIS_METHOD = "shouldFailOver(CallRequest,CallConfig,CallExceptionList)"; // TRACE: Enter method Log.log_1003(CLASSNAME, THIS_METHOD, null); // This method should only be called if the subclass uses the new style if (! _newStyle) { final String SUBJECT_CLASS = Utils.getCallingClass(); final String SUBJECT_METHOD = Utils.getCallingMethod(); final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses old-style (XINS 1.0) constructor."; throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL); } // Determine if fail-over is applicable boolean should = callConfig.isFailOverAllowed() || (exceptions.last() instanceof ConnectionCallException); // TRACE: Leave method Log.log_1005(CLASSNAME, THIS_METHOD, null); return should; } // Inner classes /** * Error used to indicate a method should be implemented in a subclass, but * is not. * * @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 MethodNotImplementedError extends Error { // Constructors /** * Constructs a new <code>MethodNotImplementedError</code>. */ private MethodNotImplementedError() { // empty } // Fields // Methods } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // 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 com.threerings.presents.server; import java.util.Calendar; import com.samskivert.util.Calendars; import com.samskivert.util.HashIntMap; import com.samskivert.util.Interval; import com.samskivert.util.ObserverList; import com.samskivert.util.StringUtil; import com.samskivert.util.Calendars.Builder; import com.threerings.util.MessageBundle; import com.threerings.presents.dobj.RootDObjectManager; import static com.threerings.presents.Log.log; /** * Handles scheduling and execution of automated server reboots. Note that this service simply * shuts down the server and assumes it will be automatically restarted by some external entity. It * is generally useful to run a server from a script that automatically restarts it when it * terminates. */ public abstract class RebootManager { /** * An interface for receiving notifications about pending automated shutdowns. */ public static interface PendingShutdownObserver { /** * Called prior to an automated shutdown. NOTE that the shutdown is not guaranteed to * happen, this interface is merely for notification purposes. * * @param warningsLeft The number of warnings left prior to the shutdown. This value will * be 0 on the last warning, usually 1-2 minutes prior to the actual shutdown. * @param msLeft the approximate number of milliseconds left prior to the shutdown. */ void shutdownPlanned (int warningsLeft, long msLeft); } /** * Finishes initialization of the manager. */ public void init () { scheduleRegularReboot(); } /** * Schedules our next regularly scheduled reboot. * * @return true if a reboot was scheduled, false if regularly scheduled reboots are disabled. */ public boolean scheduleRegularReboot () { // maybe schedule an automatic reboot based on our configuration int freq = getDayFrequency(); if (freq == -1) { return false; } Builder cal = Calendars.now().zeroTime().addHours(getRebootHour()).addDays(freq); // maybe avoid weekends if (getSkipWeekends()) { int dow = cal.get(Calendar.DAY_OF_WEEK); switch (dow) { case Calendar.SATURDAY: if (freq > 1) { cal.addDays(-1); } break; case Calendar.SUNDAY: if (freq > 2) { cal.addDays(-2); } break; } } scheduleReboot(cal.toTime(), AUTOMATIC_INITIATOR); return true; } /** * Is the manager planning a shutdown in the near future? */ public boolean willShutdownSoon () { return _rebootSoon; } /** * Add an observer to the observer list. */ public void addObserver (PendingShutdownObserver observer) { _observers.add(observer); } /** * Schedules a reboot for the specified time. */ public void scheduleReboot (long rebootTime, String initiator) { // if there's already a reboot scheduled, cancel it if (_interval != null) { _interval.cancel(); _interval = null; } // note our new reboot time and its initiator _nextReboot = rebootTime; _initiator = initiator; // see if the reboot is happening within the time specified by the // longest warning; if so, issue the appropriate warning long now = System.currentTimeMillis(); for (int ii = WARNINGS.length - 1; ii >= 0; ii long warnTime = WARNINGS[ii] * 60 * 1000; if (now + warnTime >= _nextReboot) { doWarning(ii); return; } } // otherwise, it's further off; schedule an interval to wake up when we // should issue the first pre-reboot warning _rebootSoon = false; long firstWarnTime = (_nextReboot - (WARNINGS[0] * 60 * 1000)) - now; _interval = _omgr.newInterval(new Runnable() { public void run () { doWarning(0); } }).schedule(firstWarnTime); } /** * Called by an entity that would like to prevent a reboot. */ public int preventReboot (String whereFrom) { if (whereFrom == null) { throw new IllegalArgumentException("whereFrom must be descriptive."); } int lockId = _nextRebootLockId++; _rebootLocks.put(lockId, whereFrom); return lockId; } /** * Release a reboot lock. */ public void allowReboot (int lockId) { if (null == _rebootLocks.remove(lockId)) { throw new IllegalArgumentException("no such lockId (" + lockId + ")"); } } /** * Provides us with our dependencies. */ protected RebootManager (PresentsServer server, RootDObjectManager omgr) { _server = server; _omgr = omgr; } /** * Broadcasts a message to everyone on the server. The following messages will be broadcast: * <ul><li> m.rebooting_now * <li> m.reboot_warning (minutes) (message or m.reboot_msg_standard) * <li> m.reboot_delayed * </ul> */ protected abstract void broadcast (String message); /** * Returns the frequency in days of our automatic reboots, or -1 to disable automatically * scheduled reboots. */ protected abstract int getDayFrequency (); /** * Returns the desired hour at which to perform our reboot. */ protected abstract int getRebootHour (); /** * Returns true if the reboot manager should avoid scheduling automated reboots on the * weekends. */ protected abstract boolean getSkipWeekends (); /** * Returns a custom message to be used when broadcasting a pending reboot. */ protected abstract String getCustomRebootMessage (); /** * Composes the given reboot message with the minutes and either the custom or standard details * about the pending reboot. */ protected String getRebootMessage (String key, int minutes) { String msg = getCustomRebootMessage(); if (StringUtil.isBlank(msg)) { msg = "m.reboot_msg_standard"; } return MessageBundle.compose(key, MessageBundle.taint("" + minutes), msg); } /** * Do a warning, schedule the next. */ protected void doWarning (final int level) { _rebootSoon = true; if (level == WARNINGS.length) { if (checkLocks()) { return; } // that's it! do the reboot log.info("Performing automatic server reboot/shutdown, as scheduled by: " + _initiator); broadcast("m.rebooting_now"); // wait 1 second, then do it new Interval() { // Note: This interval does not run on the dobj thread @Override public void expired () { _server.queueShutdown(); // this posts a LongRunnable } }.schedule(1000); return; } // issue the warning int minutes = WARNINGS[level]; broadcast(getRebootMessage("m.reboot_warning", minutes)); if (level < WARNINGS.length - 1) { minutes -= WARNINGS[level + 1]; } // schedule the next warning _interval = _omgr.newInterval(new Runnable() { public void run () { doWarning(level + 1); } }).schedule(minutes * 60 * 1000); notifyObservers(level); } /** * Check to see if there are outstanding reboot locks that may delay the reboot, returning * false if there are none. */ protected boolean checkLocks () { if (_rebootLocks.isEmpty()) { return false; } log.info("Reboot delayed due to outstanding locks", "locks", _rebootLocks.elements()); broadcast("m.reboot_delayed"); _interval = _omgr.newInterval(new Runnable() { public void run () { doWarning(WARNINGS.length); } }).schedule(60 * 1000); return true; } /** * Notify all PendingShutdownObservers of the pending shutdown! */ protected void notifyObservers (int level) { final int warningsLeft = WARNINGS.length - level - 1; final long msLeft = 1000L * 60L * WARNINGS[level]; _observers.apply(new ObserverList.ObserverOp<PendingShutdownObserver>() { public boolean apply (PendingShutdownObserver observer) { observer.shutdownPlanned(warningsLeft, msLeft); return true; } }); } /** The server that we're going to reboot. */ protected PresentsServer _server; /** Our distributed object manager. */ protected RootDObjectManager _omgr; /** The time at which our next reboot is scheduled or 0L. */ protected long _nextReboot; /** The entity that scheduled the reboot. */ protected String _initiator; /** True if the reboot is coming soon, within the earliest warning. */ protected boolean _rebootSoon = false; /** The interval scheduled to perform the next step the reboot process. */ protected Interval _interval; /** A list of PendingShutdownObservers. */ protected ObserverList<PendingShutdownObserver> _observers = ObserverList.newFastUnsafe(); /** The next reboot lock id. */ protected int _nextRebootLockId = 0; /** Things that can delay the reboot. */ protected HashIntMap<String> _rebootLocks = new HashIntMap<String>(); /** The minutes at which we give warnings. The last value is also the * minimum time at which we can possibly reboot after the value of the * nextReboot field is changed, to prevent accidentally causing instant * server reboots. */ public static final int[] WARNINGS = { 30, 20, 15, 10, 5, 2 }; protected static final String AUTOMATIC_INITIATOR = "automatic"; }
package com.jme3.network.base; import com.jme3.network.*; import com.jme3.network.kernel.Endpoint; import com.jme3.network.kernel.Kernel; import com.jme3.network.message.ChannelInfoMessage; import com.jme3.network.message.ClientRegistrationMessage; import com.jme3.network.message.DisconnectMessage; import com.jme3.network.service.HostedServiceManager; import com.jme3.network.service.serializer.ServerSerializerRegistrationsService; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; /** * A default implementation of the Server interface that delegates * its network connectivity to kernel.Kernel. * * @version $Revision$ * @author Paul Speed */ public class DefaultServer implements Server { static final Logger log = Logger.getLogger(DefaultServer.class.getName()); // First two channels are reserved for reliable and // unreliable private static final int CH_RELIABLE = 0; private static final int CH_UNRELIABLE = 1; private static final int CH_FIRST = 2; private boolean isRunning = false; private final AtomicInteger nextId = new AtomicInteger(0); private String gameName; private int version; private final KernelFactory kernelFactory = KernelFactory.DEFAULT; private KernelAdapter reliableAdapter; private KernelAdapter fastAdapter; private final List<KernelAdapter> channels = new ArrayList<KernelAdapter>(); private final List<Integer> alternatePorts = new ArrayList<Integer>(); private final Redispatch dispatcher = new Redispatch(); private final Map<Integer,HostedConnection> connections = new ConcurrentHashMap<Integer,HostedConnection>(); private final Map<Endpoint,HostedConnection> endpointConnections = new ConcurrentHashMap<Endpoint,HostedConnection>(); // Keeps track of clients for whom we've only received the UDP // registration message private final Map<Long,Connection> connecting = new ConcurrentHashMap<Long,Connection>(); private final MessageListenerRegistry<HostedConnection> messageListeners = new MessageListenerRegistry<HostedConnection>(); private final List<ConnectionListener> connectionListeners = new CopyOnWriteArrayList<ConnectionListener>(); private HostedServiceManager services; public DefaultServer( String gameName, int version, Kernel reliable, Kernel fast ) { if( reliable == null ) throw new IllegalArgumentException( "Default server reqiures a reliable kernel instance." ); this.gameName = gameName; this.version = version; this.services = new HostedServiceManager(this); addStandardServices(); reliableAdapter = new KernelAdapter( this, reliable, dispatcher, true ); channels.add( reliableAdapter ); if( fast != null ) { fastAdapter = new KernelAdapter( this, fast, dispatcher, false ); channels.add( fastAdapter ); } } protected void addStandardServices() { log.fine("Adding standard services..."); services.addService(new ServerSerializerRegistrationsService()); } @Override public String getGameName() { return gameName; } @Override public int getVersion() { return version; } @Override public HostedServiceManager getServices() { return services; } @Override public int addChannel( int port ) { if( isRunning ) throw new IllegalStateException( "Channels cannot be added once server is started." ); // Note: it does bug me that channels aren't 100% universal and // setup externally but it requires a more invasive set of changes // for "connection types" and some kind of registry of kernel and // connector factories. This really would be the best approach and // would allow all kinds of channel customization maybe... but for // now, we hard-code the standard connections and treat the +2 extras // differently. // Check for consistency with the channels list if( channels.size() - CH_FIRST != alternatePorts.size() ) throw new IllegalStateException( "Channel and port lists do not match." ); try { int result = alternatePorts.size(); alternatePorts.add(port); Kernel kernel = kernelFactory.createKernel(result, port); channels.add( new KernelAdapter(this, kernel, dispatcher, true) ); return result; } catch( IOException e ) { throw new RuntimeException( "Error adding channel for port:" + port, e ); } } protected void checkChannel( int channel ) { if( channel < MessageConnection.CHANNEL_DEFAULT_RELIABLE || channel >= alternatePorts.size() ) { throw new IllegalArgumentException( "Channel is undefined:" + channel ); } } @Override public void start() { if( isRunning ) throw new IllegalStateException( "Server is already started." ); // Initialize the kernels for( KernelAdapter ka : channels ) { ka.initialize(); } // Start em up for( KernelAdapter ka : channels ) { ka.start(); } isRunning = true; // Start the services services.start(); } @Override public boolean isRunning() { return isRunning; } @Override public void close() { if( !isRunning ) throw new IllegalStateException( "Server is not started." ); // First stop the services since we are about to // kill the connections they are using services.stop(); try { // Kill the adpaters, they will kill the kernels for( KernelAdapter ka : channels ) { ka.close(); } isRunning = false; // Now terminate all of the services services.terminate(); } catch( InterruptedException e ) { throw new RuntimeException( "Interrupted while closing", e ); } } @Override public void broadcast( Message message ) { broadcast( null, message ); } @Override public void broadcast( Filter<? super HostedConnection> filter, Message message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "broadcast({0}, {1})", new Object[]{filter, message}); } if( connections.isEmpty() ) return; ByteBuffer buffer = MessageProtocol.messageToBuffer(message, null); FilterAdapter adapter = filter == null ? null : new FilterAdapter(filter); if( message.isReliable() || fastAdapter == null ) { // Don't need to copy the data because message protocol is already // giving us a fresh buffer reliableAdapter.broadcast( adapter, buffer, true, false ); } else { fastAdapter.broadcast( adapter, buffer, false, false ); } } @Override public void broadcast( int channel, Filter<? super HostedConnection> filter, Message message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "broadcast({0}, {1}. {2})", new Object[]{channel, filter, message}); } if( connections.isEmpty() ) return; checkChannel(channel); ByteBuffer buffer = MessageProtocol.messageToBuffer(message, null); FilterAdapter adapter = filter == null ? null : new FilterAdapter(filter); channels.get(channel+CH_FIRST).broadcast( adapter, buffer, true, false ); } @Override public HostedConnection getConnection( int id ) { return connections.get(id); } @Override public boolean hasConnections() { return !connections.isEmpty(); } @Override public Collection<HostedConnection> getConnections() { return Collections.unmodifiableCollection((Collection<HostedConnection>)connections.values()); } @Override public void addConnectionListener( ConnectionListener listener ) { connectionListeners.add(listener); } @Override public void removeConnectionListener( ConnectionListener listener ) { connectionListeners.remove(listener); } @Override public void addMessageListener( MessageListener<? super HostedConnection> listener ) { messageListeners.addMessageListener( listener ); } @Override public void addMessageListener( MessageListener<? super HostedConnection> listener, Class... classes ) { messageListeners.addMessageListener( listener, classes ); } @Override public void removeMessageListener( MessageListener<? super HostedConnection> listener ) { messageListeners.removeMessageListener( listener ); } @Override public void removeMessageListener( MessageListener<? super HostedConnection> listener, Class... classes ) { messageListeners.removeMessageListener( listener, classes ); } protected void dispatch( HostedConnection source, Message m ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "{0} received:{1}", new Object[]{source, m}); } if( source == null ) { messageListeners.messageReceived( source, m ); } else { // A semi-heavy handed way to make sure the listener // doesn't get called at the same time from two different // threads for the same hosted connection. synchronized( source ) { messageListeners.messageReceived( source, m ); } } } protected void fireConnectionAdded( HostedConnection conn ) { for( ConnectionListener l : connectionListeners ) { l.connectionAdded( this, conn ); } } protected void fireConnectionRemoved( HostedConnection conn ) { for( ConnectionListener l : connectionListeners ) { l.connectionRemoved( this, conn ); } } protected int getChannel( KernelAdapter ka ) { return channels.indexOf(ka); } protected void registerClient( KernelAdapter ka, Endpoint p, ClientRegistrationMessage m ) { Connection addedConnection = null; // generally this will only be called by one thread but it's // important enough I won't take chances synchronized( this ) { // Grab the random ID that the client created when creating // its two registration messages long tempId = m.getId(); // See if we already have one Connection c = connecting.remove(tempId); if( c == null ) { c = new Connection(channels.size()); log.log( Level.FINE, "Registering client for endpoint, pass 1:{0}.", p ); } else { log.log( Level.FINE, "Refining client registration for endpoint:{0}.", p ); } // Fill in what we now know int channel = getChannel(ka); c.setChannel(channel, p); log.log( Level.FINE, "Setting up channel:{0}", channel ); // If it's channel 0 then this is the initial connection // and we will send the connection information if( channel == CH_RELIABLE ) { // Validate the name and version which is only sent // over the reliable connection at this point. if( !getGameName().equals(m.getGameName()) || getVersion() != m.getVersion() ) { log.log( Level.FINE, "Kicking client due to name/version mismatch:{0}.", c ); // Need to kick them off... I may regret doing this from within // the sync block but the alternative is more code c.close( "Server client mismatch, server:" + getGameName() + " v" + getVersion() + " client:" + m.getGameName() + " v" + m.getVersion() ); return; } // Else send the extra channel information to the client if( !alternatePorts.isEmpty() ) { ChannelInfoMessage cim = new ChannelInfoMessage( m.getId(), alternatePorts ); c.send(cim); } } if( c.isComplete() ) { // Then we are fully connected if( connections.put( c.getId(), c ) == null ) { for( Endpoint cp : c.channels ) { if( cp == null ) continue; endpointConnections.put( cp, c ); } addedConnection = c; } } else { // Need to keep getting channels so we'll keep it in // the map connecting.put(tempId, c); } } // Best to do this outside of the synch block to avoid // over synchronizing which is the path to deadlocks if( addedConnection != null ) { log.log( Level.FINE, "Client registered:{0}.", addedConnection ); // Send the ID back to the client letting it know it's // fully connected. m = new ClientRegistrationMessage(); m.setId( addedConnection.getId() ); m.setReliable(true); addedConnection.send(m); // Now we can notify the listeners about the // new connection. fireConnectionAdded( addedConnection ); // Send a second registration message with an invalid ID // to let the connection know that it can start its services m = new ClientRegistrationMessage(); m.setId(-1); m.setReliable(true); addedConnection.send(m); } } protected HostedConnection getConnection( Endpoint endpoint ) { return endpointConnections.get(endpoint); } protected void removeConnecting( Endpoint p ) { // No easy lookup for connecting Connections // from endpoint. for( Map.Entry<Long,Connection> e : connecting.entrySet() ) { if( e.getValue().hasEndpoint(p) ) { connecting.remove(e.getKey()); return; } } } protected void connectionClosed( Endpoint p ) { if( p.isConnected() ) { log.log( Level.FINE, "Connection closed:{0}.", p ); } else { log.log( Level.FINE, "Connection closed:{0}.", p ); } // Try to find the endpoint in all ways that it might // exist. Note: by this point the raw network channel is // closed already. // Also note: this method will be called multiple times per // HostedConnection if it has multiple endpoints. Connection removed; synchronized( this ) { // Just in case the endpoint was still connecting removeConnecting(p); // And the regular management removed = (Connection)endpointConnections.remove(p); if( removed != null ) { connections.remove( removed.getId() ); } log.log( Level.FINE, "Connections size:{0}", connections.size() ); log.log( Level.FINE, "Endpoint mappings size:{0}", endpointConnections.size() ); } // Better not to fire events while we hold a lock // so always do this outside the synch block. // Note: checking removed.closed just to avoid spurious log messages // since in general we are called back for every endpoint closing. if( removed != null && !removed.closed ) { log.log( Level.FINE, "Client closed:{0}.", removed ); removed.closeConnection(); } } protected class Connection implements HostedConnection { private final int id; private boolean closed; private Endpoint[] channels; private int setChannelCount = 0; private final Map<String,Object> sessionData = new ConcurrentHashMap<String,Object>(); public Connection( int channelCount ) { id = nextId.getAndIncrement(); channels = new Endpoint[channelCount]; } boolean hasEndpoint( Endpoint p ) { for( Endpoint e : channels ) { if( p == e ) { return true; } } return false; } void setChannel( int channel, Endpoint p ) { if( channels[channel] != null && channels[channel] != p ) { throw new RuntimeException( "Channel has already been set:" + channel + " = " + channels[channel] + ", cannot be set to:" + p ); } channels[channel] = p; if( p != null ) setChannelCount++; } boolean isComplete() { return setChannelCount == channels.length; } @Override public Server getServer() { return DefaultServer.this; } @Override public int getId() { return id; } @Override public String getAddress() { return channels[CH_RELIABLE] == null ? null : channels[CH_RELIABLE].getAddress(); } @Override public void send( Message message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "send({0})", message); } ByteBuffer buffer = MessageProtocol.messageToBuffer(message, null); if( message.isReliable() || channels[CH_UNRELIABLE] == null ) { channels[CH_RELIABLE].send( buffer ); } else { channels[CH_UNRELIABLE].send( buffer ); } } @Override public void send( int channel, Message message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "send({0}, {1})", new Object[]{channel, message}); } checkChannel(channel); ByteBuffer buffer = MessageProtocol.messageToBuffer(message, null); channels[channel+CH_FIRST].send(buffer); } protected void closeConnection() { if( closed ) return; closed = true; // Make sure all endpoints are closed. Note: reliable // should always already be closed through all paths that I // can conceive... but it doesn't hurt to be sure. for( Endpoint p : channels ) { if( p == null || !p.isConnected() ) continue; p.close(); } fireConnectionRemoved( this ); } @Override public void close( String reason ) { // Send a reason DisconnectMessage m = new DisconnectMessage(); m.setType( DisconnectMessage.KICK ); m.setReason( reason ); m.setReliable( true ); send( m ); // Just close the reliable endpoint // fast will be cleaned up as a side-effect // when closeConnection() is called by the // connectionClosed() endpoint callback. if( channels[CH_RELIABLE] != null ) { // Close with flush so we make sure our // message gets out channels[CH_RELIABLE].close(true); } } @Override public Object setAttribute( String name, Object value ) { if( value == null ) return sessionData.remove(name); return sessionData.put(name, value); } @SuppressWarnings("unchecked") @Override public <T> T getAttribute( String name ) { return (T)sessionData.get(name); } @Override public Set<String> attributeNames() { return Collections.unmodifiableSet(sessionData.keySet()); } @Override public String toString() { return "Connection[ id=" + id + ", reliable=" + channels[CH_RELIABLE] + ", fast=" + channels[CH_UNRELIABLE] + " ]"; } } protected class Redispatch implements MessageListener<HostedConnection> { @Override public void messageReceived( HostedConnection source, Message m ) { dispatch( source, m ); } } protected class FilterAdapter implements Filter<Endpoint> { private final Filter<? super HostedConnection> delegate; public FilterAdapter( Filter<? super HostedConnection> delegate ) { this.delegate = delegate; } @Override public boolean apply( Endpoint input ) { HostedConnection conn = getConnection( input ); if( conn == null ) return false; return delegate.apply(conn); } } }
package com.twitter.mesos.scheduler; import java.util.Collection; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; import javax.annotation.Nullable; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Atomics; import com.google.inject.Inject; import org.apache.mesos.Protos; import org.apache.mesos.Protos.SlaveID; import com.twitter.common.base.Closure; import com.twitter.common.stats.Stats; import com.twitter.common.util.Clock; import com.twitter.common.util.StateMachine; import com.twitter.mesos.Tasks; import com.twitter.mesos.gen.AssignedTask; import com.twitter.mesos.gen.Attribute; import com.twitter.mesos.gen.HostAttributes; import com.twitter.mesos.gen.JobConfiguration; import com.twitter.mesos.gen.ScheduleStatus; import com.twitter.mesos.gen.ScheduledTask; import com.twitter.mesos.gen.ShardUpdateResult; import com.twitter.mesos.gen.TaskEvent; import com.twitter.mesos.gen.TaskQuery; import com.twitter.mesos.gen.TwitterTaskInfo; import com.twitter.mesos.gen.UpdateResult; import com.twitter.mesos.gen.storage.JobUpdateConfiguration; import com.twitter.mesos.gen.storage.TaskUpdateConfiguration; import com.twitter.mesos.scheduler.StateManagerVars.MutableState; import com.twitter.mesos.scheduler.TransactionalStorage.SideEffect; import com.twitter.mesos.scheduler.TransactionalStorage.SideEffectWork; import com.twitter.mesos.scheduler.TransactionalStorage.TransactionFinalizer; import com.twitter.mesos.scheduler.configuration.ConfigurationManager; import com.twitter.mesos.scheduler.events.PubsubEvent; import com.twitter.mesos.scheduler.storage.Storage; import com.twitter.mesos.scheduler.storage.Storage.MutableStoreProvider; import com.twitter.mesos.scheduler.storage.Storage.StorageException; import com.twitter.mesos.scheduler.storage.Storage.StoreProvider; import com.twitter.mesos.scheduler.storage.Storage.Work; import com.twitter.mesos.scheduler.storage.TaskStore; import com.twitter.mesos.scheduler.storage.UpdateStore; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.transform; import static com.twitter.common.base.MorePreconditions.checkNotBlank; import static com.twitter.mesos.Tasks.SCHEDULED_TO_SHARD_ID; import static com.twitter.mesos.Tasks.jobKey; import static com.twitter.mesos.gen.ScheduleStatus.INIT; import static com.twitter.mesos.gen.ScheduleStatus.KILLING; import static com.twitter.mesos.gen.ScheduleStatus.PENDING; import static com.twitter.mesos.gen.ScheduleStatus.UNKNOWN; import static com.twitter.mesos.scheduler.Shards.GET_NEW_CONFIG; import static com.twitter.mesos.scheduler.Shards.GET_ORIGINAL_CONFIG; /** * Manager of all persistence-related operations for the scheduler. Acts as a controller for * persisted state machine transitions, and their side-effects. * * TODO(William Farner): Re-evaluate thread safety here, specifically risk of races that * modify managerState. */ public class StateManagerImpl implements StateManager { private static final Logger LOG = Logger.getLogger(StateManagerImpl.class.getName()); private static final Function<TaskUpdateConfiguration, Integer> GET_SHARD = new Function<TaskUpdateConfiguration, Integer>() { @Override public Integer apply(TaskUpdateConfiguration config) { return config.isSetOldConfig() ? config.getOldConfig().getShardId() : config.getNewConfig().getShardId(); } }; private static final Function<Protos.Attribute, String> ATTRIBUTE_NAME = new Function<org.apache.mesos.Protos.Attribute, String>() { @Override public String apply(Protos.Attribute attr) { return attr.getName(); } }; private static final Function<Protos.Attribute, String> VALUE_CONVERTER = new Function<Protos.Attribute, String>() { @Override public String apply(Protos.Attribute attribute) { switch (attribute.getType()) { case SCALAR: return String.valueOf(attribute.getScalar().getValue()); case TEXT: return attribute.getText().getValue(); default: LOG.finest("Unrecognized attribute type:" + attribute.getType() + " , ignoring."); return null; } } }; private static final AttributeConverter ATTRIBUTE_CONVERTER = new AttributeConverter() { @Override public Attribute apply(Entry<String, Collection<Protos.Attribute>> entry) { // Convert values and filter any that were ignored. Iterable<String> values = Iterables.filter( Iterables.transform(entry.getValue(), VALUE_CONVERTER), Predicates.notNull()); return new Attribute(entry.getKey(), ImmutableSet.copyOf(values)); } }; private static final Function<TwitterTaskInfo, TwitterTaskInfo> COPY_AND_RESET_START_COMMAND = new Function<TwitterTaskInfo, TwitterTaskInfo>() { @Override public TwitterTaskInfo apply(TwitterTaskInfo task) { TwitterTaskInfo copy = task.deepCopy(); ConfigurationManager.resetStartCommand(copy); return copy; } }; private final AtomicLong shardSanityCheckFails = Stats.exportLong("shard_sanity_check_failures"); private final TransactionalStorage txStorage; // TODO(William Farner): Eliminate this and update all callers to use Storage directly. interface ReadOnlyStorage { <T, E extends Exception> T doInTransaction(Work<T, E> work) throws StorageException, E; } private final ReadOnlyStorage readOnlyStorage; // Enforces lifecycle of the manager, ensuring proper call order. private final StateMachine<State> managerState = StateMachine.<State>builder("state_manager") .initialState(State.CREATED) .addState(State.CREATED, State.INITIALIZED) .addState(State.INITIALIZED, State.STARTED) .addState(State.STARTED, State.STOPPED) .build(); // Work queue to receive state machine side effect work. private final Queue<WorkEntry> workQueue = Lists.newLinkedList(); // Adapt the work queue into a sink. private final TaskStateMachine.WorkSink workSink = new TaskStateMachine.WorkSink() { @Override public void addWork(WorkCommand work, TaskStateMachine stateMachine, Closure<ScheduledTask> mutation) { workQueue.add(new WorkEntry(work, stateMachine, mutation)); } }; private final Function<TwitterTaskInfo, ScheduledTask> taskCreator = new Function<TwitterTaskInfo, ScheduledTask>() { @Override public ScheduledTask apply(TwitterTaskInfo task) { return new ScheduledTask() .setStatus(INIT) .setAssignedTask(new AssignedTask().setTaskId(generateTaskId(task)).setTask(task)); } }; private final Driver driver; private final Clock clock; /** * An item of work on the work queue. */ private static class WorkEntry { final WorkCommand command; final TaskStateMachine stateMachine; final Closure<ScheduledTask> mutation; WorkEntry( WorkCommand command, TaskStateMachine stateMachine, Closure<ScheduledTask> mutation) { this.command = command; this.stateMachine = stateMachine; this.mutation = mutation; } } @Inject StateManagerImpl( final Storage storage, final Clock clock, MutableState mutableState, Driver driver, Closure<PubsubEvent> taskEventSink) { checkNotNull(storage); this.clock = checkNotNull(clock); TransactionFinalizer finalizer = new TransactionFinalizer() { @Override public void finalize(SideEffectWork<?, ?> work, MutableStoreProvider store) { processWorkQueueInTransaction(work, store); } }; txStorage = new TransactionalStorage(storage, mutableState, finalizer, taskEventSink); readOnlyStorage = new ReadOnlyStorage() { @Override public <T, E extends Exception> T doInTransaction(Work<T, E> work) throws StorageException, E { return storage.doInTransaction(work); } }; this.driver = checkNotNull(driver); Stats.exportSize("work_queue_depth", workQueue); } @VisibleForTesting Function<TwitterTaskInfo, ScheduledTask> getTaskCreator() { return taskCreator; } /** * State manager lifecycle state. */ private enum State { CREATED, INITIALIZED, STARTED, STOPPED } /** * Prompts the state manager to prepare for possible activation in the leading scheduler process. */ void prepare() { txStorage.prepare(); } /** * Initializes the state manager, by starting the storage and fetching the persisted framework ID. * * @return The persisted framework ID, or {@code null} if no framework ID exists in the store. */ @Nullable String initialize() { managerState.transition(State.INITIALIZED); // Note: Do not attempt to mutate tasks here. Any task mutations made here will be // overwritten if a snapshot is applied. txStorage.start(txStorage.new NoResultSideEffectWork() { @Override public void execute(final MutableStoreProvider storeProvider) { for (ScheduledTask task : storeProvider.getTaskStore().fetchTasks(Query.GET_ALL)) { createStateMachine(this, task, task.getStatus()); } addSideEffect(new SideEffect() { @Override public void mutate(MutableState state) { state.getVars().beginExporting(); } }); } }); LOG.info("Storage initialization complete."); return getFrameworkId(); } private String getFrameworkId() { managerState.checkState(ImmutableSet.of(State.INITIALIZED, State.STARTED)); return readOnlyStorage.doInTransaction(new Work.Quiet<String>() { @Override public String apply(StoreProvider storeProvider) { return storeProvider.getSchedulerStore().fetchFrameworkId(); } }); } /** * Sets the framework ID that should be persisted. * * @param frameworkId Updated framework ID. */ void setFrameworkId(final String frameworkId) { checkNotNull(frameworkId); managerState.checkState(ImmutableSet.of(State.INITIALIZED, State.STARTED)); txStorage.doInWriteTransaction(txStorage.new NoResultSideEffectWork() { @Override protected void execute(MutableStoreProvider storeProvider) { storeProvider.getSchedulerStore().saveFrameworkId(frameworkId); } }); } private static Set<String> activeShards(TaskStore taskStore, String jobKey, int shardId) { TaskQuery query = new TaskQuery() .setStatuses(Tasks.ACTIVE_STATES) .setJobKey(jobKey) .setShardIds(ImmutableSet.of(shardId)); return taskStore.fetchTaskIds(query); } /** * Instructs the state manager to start. */ void start() { managerState.transition(State.STARTED); txStorage.doInWriteTransaction(txStorage.new NoResultSideEffectWork() { @Override protected void execute(final MutableStoreProvider storeProvider) { for (String id : storeProvider.getJobStore().fetchManagerIds()) { for (JobConfiguration job : storeProvider.getJobStore().fetchJobs(id)) { ConfigurationManager.applyDefaultsIfUnset(job); storeProvider.getJobStore().saveAcceptedJob(id, job); } } LOG.info("Performing shard uniqueness sanity check."); storeProvider.getTaskStore().mutateTasks(Query.GET_ALL, new Closure<ScheduledTask>() { @Override public void execute(final ScheduledTask task) { ConfigurationManager.applyDefaultsIfUnset(task.getAssignedTask().getTask()); TaskEvent latestEvent = task.isSetTaskEvents() ? Iterables.getLast(task.getTaskEvents(), null) : null; if ((latestEvent == null) || (latestEvent.getStatus() != task.getStatus())) { LOG.severe("Task " + Tasks.id(task) + " has no event for current status."); task.addToTaskEvents(new TaskEvent(clock.nowMillis(), task.getStatus()) .setMessage("Synthesized missing event.")); } if (Tasks.isActive(task.getStatus())) { // Perform a sanity check on the number of active shards. Set<String> activeTasksInShard = activeShards( storeProvider.getTaskStore(), Tasks.jobKey(task), Tasks.SCHEDULED_TO_SHARD_ID.apply(task)); if (activeTasksInShard.size() > 1) { shardSanityCheckFails.incrementAndGet(); LOG.severe("Active shard sanity check failed when loading " + Tasks.id(task) + ", active tasks found: " + activeTasksInShard); // We want to keep exactly one task from this shard, so sort the IDs and keep the // highest (newest) in the hopes that it is legitimately running. String newestTask = Iterables.getLast(Sets.newTreeSet(activeTasksInShard)); if (!Tasks.id(task).equals(newestTask)) { task.setStatus(ScheduleStatus.KILLED); task.addToTaskEvents(new TaskEvent(clock.nowMillis(), ScheduleStatus.KILLED) .setMessage("Killed duplicate shard.")); // TODO(wfarner); Circle back if this is necessary. Currently there's a race // condition between the time the scheduler is actually available without hitting // driver.killTask(Tasks.id(task)); addSideEffect(new SideEffect() { @Override public void mutate(MutableState state) { state.getVars().adjustCount( Tasks.jobKey(task), task.getStatus(), ScheduleStatus.KILLED); } }); } else { LOG.info("Retaining task " + Tasks.id(task)); } } } } }); } }); } /** * Checks whether the state manager is currently in the STARTED state. * * @return {@code true} if in the STARTED state, {@code false} otherwise. */ public boolean isStarted() { return managerState.getState() == State.STARTED; } /** * Instructs the state manager to stop, and shut down the backing storage. */ void stop() { managerState.transition(State.STOPPED); txStorage.stop(); } /** * Inserts new tasks into the store. * * @param tasks Tasks to insert. * @return Generated task IDs for the tasks inserted. */ Set<String> insertTasks(Set<TwitterTaskInfo> tasks) { checkNotNull(tasks); final Set<ScheduledTask> scheduledTasks = ImmutableSet.copyOf(transform(tasks, taskCreator)); txStorage.doInWriteTransaction(txStorage.new NoResultSideEffectWork() { @Override protected void execute(MutableStoreProvider storeProvider) { storeProvider.getTaskStore().saveTasks(scheduledTasks); for (ScheduledTask task : scheduledTasks) { createStateMachine(this, task).updateState(PENDING); } } }); return Tasks.ids(scheduledTasks); } /** * Thrown when an update fails. */ static class UpdateException extends Exception { public UpdateException(String msg) { super(msg); } public UpdateException(String msg, Throwable cause) { super(msg, cause); } } /** * Registers a new update. * * @param role Role to register an update for. * @param job Job to register an update for. * @param updatedTasks Updated Task information to be registered. * @throws UpdateException If no active tasks are found for the job, or if an update for the job * is already in progress. * @return A unique string identifying the update. */ String registerUpdate( final String role, final String job, final Set<TwitterTaskInfo> updatedTasks) throws UpdateException { checkNotBlank(role); checkNotBlank(job); checkNotBlank(updatedTasks); return txStorage.doInWriteTransaction(txStorage.new SideEffectWork<String, UpdateException>() { @Override public String apply(MutableStoreProvider storeProvider) throws UpdateException { String jobKey = Tasks.jobKey(role, job); Set<TwitterTaskInfo> existingTasks = ImmutableSet.copyOf(Iterables.transform( storeProvider.getTaskStore().fetchTasks(Query.activeQuery(jobKey)), Tasks.SCHEDULED_TO_INFO)); if (existingTasks.isEmpty()) { throw new UpdateException("No active tasks found for job " + jobKey); } UpdateStore.Mutable updateStore = storeProvider.getUpdateStore(); if (updateStore.fetchJobUpdateConfig(role, job).isPresent()) { throw new UpdateException("Update already in progress for " + jobKey); } Map<Integer, TwitterTaskInfo> oldShards = Maps.uniqueIndex(existingTasks, Tasks.INFO_TO_SHARD_ID); Map<Integer, TwitterTaskInfo> newShards = Maps.uniqueIndex(updatedTasks, Tasks.INFO_TO_SHARD_ID); ImmutableSet.Builder<TaskUpdateConfiguration> shardConfigBuilder = ImmutableSet.builder(); for (int shard : Sets.union(oldShards.keySet(), newShards.keySet())) { shardConfigBuilder.add( new TaskUpdateConfiguration(oldShards.get(shard), newShards.get(shard))); } String updateToken = UUID.randomUUID().toString(); updateStore.saveJobUpdateConfig( new JobUpdateConfiguration(role, job, updateToken, shardConfigBuilder.build())); return updateToken; } }); } /** * Completes an in-progress update. * * @param role Role owning the update to finish. * @param job Job to finish updating. * @param updateToken Token associated with the update. If present, the token must match the * the stored token for the update. * @param result The result of the update. * @param throwIfMissing If {@code true}, this throws UpdateException when the update is missing. * @return {@code true} if the update was finished, false if nonexistent. * @throws UpdateException If an update is not in-progress for the job, or the non-null token * does not match the stored token. */ boolean finishUpdate( final String role, final String job, final Optional<String> updateToken, final UpdateResult result, final boolean throwIfMissing) throws UpdateException { checkNotBlank(role); checkNotBlank(job); return txStorage.doInWriteTransaction(txStorage.new SideEffectWork<Boolean, UpdateException>() { @Override public Boolean apply(MutableStoreProvider storeProvider) throws UpdateException { UpdateStore.Mutable updateStore = storeProvider.getUpdateStore(); String jobKey = Tasks.jobKey(role, job); // Since we store all shards in a job with the same token, we can just check shard 0, // which is always guaranteed to exist for a job. Optional<JobUpdateConfiguration> jobConfig = updateStore.fetchJobUpdateConfig(role, job); if (!jobConfig.isPresent()) { if (throwIfMissing) { throw new UpdateException("Update does not exist for " + jobKey); } return false; } if (updateToken.isPresent() && !updateToken.get().equals(jobConfig.get().getUpdateToken())) { throw new UpdateException("Invalid update token for " + jobKey); } if (EnumSet.of(UpdateResult.SUCCESS, UpdateResult.FAILED).contains(result)) { // Kill any shards that were removed during the update or rollback. Function<TaskUpdateConfiguration, TwitterTaskInfo> removedSelector = (result == UpdateResult.SUCCESS) ? GET_NEW_CONFIG : GET_ORIGINAL_CONFIG; for (Integer shard : fetchRemovedShards(jobConfig.get(), removedSelector)) { changeState( Query.liveShard(jobKey, shard), KILLING, Optional.of("Removed during update.")); } } updateStore.removeShardUpdateConfigs(role, job); return true; } }); } private static final Function<TaskUpdateConfiguration, Integer> GET_SHARD_ID = new Function<TaskUpdateConfiguration, Integer>() { @Override public Integer apply(TaskUpdateConfiguration config) { TwitterTaskInfo task = (config.getOldConfig() != null) ? config.getOldConfig() : config.getNewConfig(); return task.getShardId(); } }; private Set<Integer> fetchRemovedShards( JobUpdateConfiguration jobConfig, Function<TaskUpdateConfiguration, TwitterTaskInfo> configSelector) { return FluentIterable.from(jobConfig.getConfigs()) .filter(Predicates.compose(Predicates.isNull(), configSelector)) .transform(GET_SHARD_ID) .toImmutableSet(); } /** * Typedef to make anonymous implementation more concise. */ private abstract static class AttributeConverter implements Function<Entry<String, Collection<Protos.Attribute>>, Attribute> { } @Override public void saveAttributesFromOffer( final String slaveHost, List<Protos.Attribute> attributes) { checkNotBlank(slaveHost); checkNotNull(attributes); // Group by attribute name. final Multimap<String, Protos.Attribute> valuesByName = Multimaps.index(attributes, ATTRIBUTE_NAME); // Convert groups into individual attributes. final Set<Attribute> attrs = Sets.newHashSet( Iterables.transform(valuesByName.asMap().entrySet(), ATTRIBUTE_CONVERTER)); txStorage.doInWriteTransaction(txStorage.new NoResultSideEffectWork() { @Override protected void execute(MutableStoreProvider storeProvider) { storeProvider.getAttributeStore().saveHostAttributes(new HostAttributes(slaveHost, attrs)); } }); } /** * An entity that may modify state of tasks by ID. */ interface StateChanger { /** * Changes the state of tasks. * * @param taskIds IDs of the tasks to modify. * @param state New state to apply to the tasks. * @param auditMessage Audit message to associate with the transition. */ void changeState(Set<String> taskIds, ScheduleStatus state, String auditMessage); } /** * A mutation performed on the results of a query. */ interface StateMutation<E extends Exception> { void execute(Set<ScheduledTask> tasks, StateChanger changer) throws E; /** * A state mutation that does not throw a checked exception. */ interface Quiet extends StateMutation<RuntimeException> { } } /** * Performs a simple state change, transitioning all tasks matching a query to the given * state. * No audit message will be applied with the transition. * * @param query Query to perform, the results of which will be modified. * @param newState State to move the resulting tasks into. * @return the number of successful state changes. */ @VisibleForTesting int changeState(TaskQuery query, ScheduleStatus newState) { return changeState(query, stateUpdater(newState)); } @Override public int changeState( TaskQuery query, ScheduleStatus newState, Optional<String> auditMessage) { return changeState(query, stateUpdaterWithAuditMessage(newState, auditMessage)); } @Override public AssignedTask assignTask( String taskId, String slaveHost, SlaveID slaveId, Set<Integer> assignedPorts) { checkNotBlank(taskId); checkNotBlank(slaveHost); checkNotNull(assignedPorts); TaskAssignMutation mutation = assignHost(slaveHost, slaveId, assignedPorts); changeState(Query.byId(taskId), mutation); return mutation.getAssignedTask(); } /** * Fetches all tasks that match a query. * TODO(William Farner): Remove this method and update callers to invoke storage directly. * * @param query Query to perform. * @return A read-only view of the tasks matching the query. */ public Set<ScheduledTask> fetchTasks(final TaskQuery query) { checkNotNull(query); managerState.checkState(ImmutableSet.of(State.INITIALIZED, State.STARTED)); return readOnlyStorage.doInTransaction(new Work.Quiet<Set<ScheduledTask>>() { @Override public Set<ScheduledTask> apply(StoreProvider storeProvider) { return storeProvider.getTaskStore().fetchTasks(query); } }); } @VisibleForTesting static void putResults( ImmutableMap.Builder<Integer, ShardUpdateResult> builder, ShardUpdateResult result, Iterable<Integer> shardIds) { for (int shardId : shardIds) { builder.put(shardId, result); } } private Set<Integer> getChangedShards(Set<ScheduledTask> tasks, Set<TwitterTaskInfo> compareTo) { Set<TwitterTaskInfo> oldTasks = ImmutableSet.copyOf(Iterables.transform(tasks, Functions.compose(COPY_AND_RESET_START_COMMAND, Tasks.SCHEDULED_TO_INFO))); Set<TwitterTaskInfo> changedTasks = Sets.difference(compareTo, oldTasks); return ImmutableSet.copyOf(Iterables.transform(changedTasks, Tasks.INFO_TO_SHARD_ID)); } Map<Integer, ShardUpdateResult> modifyShards( final String role, final String jobName, final Set<Integer> shards, final String updateToken, boolean updating) throws UpdateException { final Function<TaskUpdateConfiguration, TwitterTaskInfo> configSelector = updating ? GET_NEW_CONFIG : GET_ORIGINAL_CONFIG; final ScheduleStatus modifyingState = updating ? ScheduleStatus.UPDATING : ScheduleStatus.ROLLBACK; managerState.checkState(ImmutableSet.of(State.INITIALIZED, State.STARTED)); return txStorage.doInWriteTransaction( txStorage.new SideEffectWork<Map<Integer, ShardUpdateResult>, UpdateException>() { @Override public Map<Integer, ShardUpdateResult> apply( MutableStoreProvider store) throws UpdateException { ImmutableMap.Builder<Integer, ShardUpdateResult> result = ImmutableMap.builder(); String jobKey = Tasks.jobKey(role, jobName); Optional<JobUpdateConfiguration> updateConfig = store.getUpdateStore().fetchJobUpdateConfig(role, jobName); if (!updateConfig.isPresent()) { throw new UpdateException("No active update found for " + jobKey); } if (!updateConfig.get().getUpdateToken().equals(updateToken)) { throw new UpdateException("Invalid update token for " + jobKey); } Set<ScheduledTask> tasks = store.getTaskStore().fetchTasks(Query.liveShards(jobKey, shards)); // Extract any shard IDs that are being added as a part of this stage in the update. Set<Integer> newShardIds = Sets.difference(shards, ImmutableSet.copyOf(Iterables.transform(tasks, SCHEDULED_TO_SHARD_ID))); if (!newShardIds.isEmpty()) { Set<TwitterTaskInfo> newTasks = fetchTaskUpdateConfigs( updateConfig.get(), newShardIds, configSelector); Set<Integer> unrecognizedShards = Sets.difference(newShardIds, ImmutableSet.copyOf(Iterables.transform(newTasks, Tasks.INFO_TO_SHARD_ID))); if (!unrecognizedShards.isEmpty()) { throw new UpdateException( "Cannot update unrecognized shards " + unrecognizedShards); } // Create new tasks, so they will be moved into the PENDING state. insertTasks(newTasks); putResults(result, ShardUpdateResult.ADDED, newShardIds); } Set<Integer> updateShardIds = Sets.difference(shards, newShardIds); if (!updateShardIds.isEmpty()) { Set<TwitterTaskInfo> targetConfigs = fetchTaskUpdateConfigs( updateConfig.get(), updateShardIds, configSelector); Set<Integer> changedShards = getChangedShards(tasks, targetConfigs); if (!changedShards.isEmpty()) { // Initiate update on the existing shards. // TODO(William Farner): The additional query could be avoided here. // Consider allowing state changes on tasks by task ID. changeState(Query.liveShards(jobKey, changedShards), modifyingState); putResults(result, ShardUpdateResult.RESTARTING, changedShards); } putResults( result, ShardUpdateResult.UNCHANGED, Sets.difference(updateShardIds, changedShards)); } return result.build(); } }); } private Optional<TaskUpdateConfiguration> fetchShardUpdateConfig( UpdateStore updateStore, String role, String job, int shard) { Optional<JobUpdateConfiguration> optional = updateStore.fetchJobUpdateConfig(role, job); if (optional.isPresent()) { Set<TaskUpdateConfiguration> matches = fetchShardUpdateConfigs(optional.get(), ImmutableSet.of(shard)); return Optional.fromNullable(Iterables.getOnlyElement(matches, null)); } else { return Optional.absent(); } } private Set<TaskUpdateConfiguration> fetchShardUpdateConfigs( JobUpdateConfiguration config, Set<Integer> shards) { return ImmutableSet.copyOf(Iterables.filter(config.getConfigs(), Predicates.compose(Predicates.in(shards), GET_SHARD))); } /** * Fetches the task configurations for shards in the context of an in-progress job update. * * @param shards Shards within a job to fetch. * @return The task information of the shard. */ private Set<TwitterTaskInfo> fetchTaskUpdateConfigs( JobUpdateConfiguration config, final Set<Integer> shards, final Function<TaskUpdateConfiguration, TwitterTaskInfo> configSelector) { checkNotNull(config); checkNotBlank(shards); return FluentIterable .from(fetchShardUpdateConfigs(config, shards)) .transform(configSelector) .filter(Predicates.notNull()) .toImmutableSet(); } void abandonTasks(final Set<String> taskIds) throws IllegalStateException { checkNotBlank(taskIds); managerState.checkState(State.STARTED); txStorage.doInWriteTransaction(txStorage.new NoResultSideEffectWork() { @Override protected void execute(MutableStoreProvider storeProvider) { for (TaskStateMachine stateMachine : getStateMachines(taskIds).values()) { stateMachine.updateState(ScheduleStatus.UNKNOWN, Optional.of("Dead executor.")); } // Need to process the work queue first to ensure the tasks can be state changed prior // to deletion. processWorkQueueInTransaction(this, storeProvider); deleteTasks(taskIds); } }); } private int changeStateInTransaction( Set<String> taskIds, Function<TaskStateMachine, Boolean> stateChange) { int count = 0; for (TaskStateMachine stateMachine : getStateMachines(taskIds).values()) { if (stateChange.apply(stateMachine)) { ++count; } } return count; } private int changeState( final TaskQuery query, final Function<TaskStateMachine, Boolean> stateChange) { return txStorage.doInWriteTransaction(txStorage.new QuietSideEffectWork<Integer>() { @Override public Integer apply(MutableStoreProvider storeProvider) { return changeStateInTransaction( storeProvider.getTaskStore().fetchTaskIds(query), stateChange); } }); } private static Function<TaskStateMachine, Boolean> stateUpdater(final ScheduleStatus state) { return new Function<TaskStateMachine, Boolean>() { @Override public Boolean apply(TaskStateMachine stateMachine) { return stateMachine.updateState(state); } }; } private static Function<TaskStateMachine, Boolean> stateUpdaterWithAuditMessage( final ScheduleStatus state, final Optional<String> auditMessage) { checkNotNull(state); checkNotNull(auditMessage); return new Function<TaskStateMachine, Boolean>() { @Override public Boolean apply(TaskStateMachine stateMachine) { return stateMachine.updateState(state, auditMessage); } }; } private interface TaskAssignMutation extends Function<TaskStateMachine, Boolean> { AssignedTask getAssignedTask(); } @ThermosJank private TaskAssignMutation assignHost( final String slaveHost, final SlaveID slaveId, final Set<Integer> assignedPorts) { final Closure<ScheduledTask> mutation = new Closure<ScheduledTask>() { @Override public void execute(ScheduledTask task) { AssignedTask assigned; TwitterTaskInfo info = task.getAssignedTask().getTask(); // Length check is an artifact of thrift 0.5.0 NPE workaround from ConfigurationManager. // See MESOS-370. if (info.isSetThermosConfig() && (info.getThermosConfig().length > 0)) { assigned = task.getAssignedTask(); assigned.setAssignedPorts(CommandLineExpander.getNameMappedPorts( assigned.getTask().getRequestedPorts(), assignedPorts)); } else { assigned = CommandLineExpander.expand(task.getAssignedTask(), assignedPorts); } task.setAssignedTask(assigned); assigned.setSlaveHost(slaveHost) .setSlaveId(slaveId.getValue()); } }; return new TaskAssignMutation() { AtomicReference<AssignedTask> assignedTask = Atomics.newReference(); @Override public AssignedTask getAssignedTask() { return assignedTask.get(); } @Override public Boolean apply(final TaskStateMachine stateMachine) { Closure<ScheduledTask> wrapper = new Closure<ScheduledTask>() { @Override public void execute(ScheduledTask task) { mutation.execute(task); Preconditions.checkState( assignedTask.compareAndSet(null, task.getAssignedTask()), "More than one result was found for an identity query."); } }; return stateUpdaterWithMutation(ScheduleStatus.ASSIGNED, wrapper).apply(stateMachine); } }; } private static Function<TaskStateMachine, Boolean> stateUpdaterWithMutation( final ScheduleStatus state, final Closure<ScheduledTask> mutation) { return new Function<TaskStateMachine, Boolean>() { @Override public Boolean apply(TaskStateMachine stateMachine) { return stateMachine.updateState(state, mutation); } }; } // Supplier that checks if there is an active update for a job. private Supplier<Boolean> taskUpdateChecker(final String role, final String job) { return new Supplier<Boolean>() { @Override public Boolean get() { return readOnlyStorage.doInTransaction(new Work.Quiet<Boolean>() { @Override public Boolean apply(StoreProvider storeProvider) { return storeProvider.getUpdateStore().fetchJobUpdateConfig(role, job).isPresent(); } }); } }; } /** * Creates a new task ID that is permanently unique (not guaranteed, but highly confident), * and by default sorts in chronological order. * * @param task Task that an ID is being generated for. * @return New task ID. */ private String generateTaskId(TwitterTaskInfo task) { String sep = "-"; return new StringBuilder() .append(clock.nowMillis()) // Allows chronological sorting. .append(sep) .append(jobKey(task)) // Identification and collision prevention. .append(sep) .append(task.getShardId()) // Collision prevention within job. .append(sep) .append(UUID.randomUUID()) // Just-in-case collision prevention. .toString().replaceAll("[^\\w-]", sep); // Constrain character set. } private void processWorkQueueInTransaction( SideEffectWork<?, ?> sideEffectWork, MutableStoreProvider storeProvider) { managerState.checkState(ImmutableSet.of(State.INITIALIZED, State.STARTED)); for (final WorkEntry work : Iterables.consumingIterable(workQueue)) { final TaskStateMachine stateMachine = work.stateMachine; if (work.command == WorkCommand.KILL) { driver.killTask(stateMachine.getTaskId()); } else { TaskStore.Mutable taskStore = storeProvider.getTaskStore(); String taskId = stateMachine.getTaskId(); TaskQuery idQuery = Query.byId(taskId); switch (work.command) { case RESCHEDULE: ScheduledTask task = Iterables.getOnlyElement(taskStore.fetchTasks(idQuery)).deepCopy(); task.getAssignedTask().unsetSlaveId(); task.getAssignedTask().unsetSlaveHost(); task.getAssignedTask().unsetAssignedPorts(); ConfigurationManager.resetStartCommand(task.getAssignedTask().getTask()); task.unsetTaskEvents(); task.setAncestorId(taskId); String newTaskId = generateTaskId(task.getAssignedTask().getTask()); task.getAssignedTask().setTaskId(newTaskId); LOG.info("Task being rescheduled: " + taskId); taskStore.saveTasks(ImmutableSet.of(task)); createStateMachine(sideEffectWork, task) .updateState(PENDING, Optional.of("Rescheduled")); TwitterTaskInfo taskInfo = task.getAssignedTask().getTask(); sideEffectWork.addTaskEvent( new PubsubEvent.TaskRescheduled( taskInfo.getOwner().getRole(), taskInfo.getJobName(), taskInfo.getShardId())); break; case UPDATE: case ROLLBACK: maybeRescheduleForUpdate( sideEffectWork, storeProvider, taskId, work.command == WorkCommand.ROLLBACK); break; case UPDATE_STATE: taskStore.mutateTasks(idQuery, new Closure<ScheduledTask>() { @Override public void execute(ScheduledTask task) { task.setStatus(stateMachine.getState()); work.mutation.execute(task); } }); sideEffectWork.addSideEffect(new SideEffect() { @Override public void mutate(MutableState state) { state.getVars() .adjustCount(stateMachine.getJobKey(), stateMachine.getPreviousState(), stateMachine.getState()); } }); sideEffectWork.addTaskEvent( new PubsubEvent.TaskStateChange( stateMachine.getTaskId(), stateMachine.getPreviousState(), stateMachine.getState())); break; case DELETE: deleteTasks(ImmutableSet.of(taskId)); break; case INCREMENT_FAILURES: taskStore.mutateTasks(idQuery, new Closure<ScheduledTask>() { @Override public void execute(ScheduledTask task) { task.setFailureCount(task.getFailureCount() + 1); } }); break; default: LOG.severe("Unrecognized work command type " + work.command); } } } } /** * Deletes records of tasks from the task store. * This will not perform any state checking or state transitions, but will immediately remove * the tasks from the store. It will also silently ignore attempts to delete task IDs that do * not exist. * * @param taskIds IDs of tasks to delete. */ public void deleteTasks(final Set<String> taskIds) { txStorage.doInWriteTransaction(txStorage.new NoResultSideEffectWork() { @Override protected void execute(final MutableStoreProvider storeProvider) { final TaskStore.Mutable taskStore = storeProvider.getTaskStore(); final Iterable<ScheduledTask> tasks = taskStore.fetchTasks(Query.byId(taskIds)); addSideEffect(new SideEffect() { @Override public void mutate(MutableState state) { for (ScheduledTask task : tasks) { state.getVars().decrementCount(Tasks.jobKey(task), task.getStatus()); } } }); addTaskEvent(new PubsubEvent.TasksDeleted(ImmutableSet.copyOf(taskIds))); taskStore.deleteTasks(taskIds); } }); } private void maybeRescheduleForUpdate( SideEffectWork<?, ?> sideEffectWork, MutableStoreProvider storeProvider, String taskId, boolean rollingBack) { TaskStore.Mutable taskStore = storeProvider.getTaskStore(); TwitterTaskInfo oldConfig = Tasks.SCHEDULED_TO_INFO.apply( Iterables.getOnlyElement(taskStore.fetchTasks(Query.byId(taskId)))); Optional<TaskUpdateConfiguration> optional = fetchShardUpdateConfig( storeProvider.getUpdateStore(), oldConfig.getOwner().getRole(), oldConfig.getJobName(), oldConfig.getShardId()); // TODO(Sathya): Figure out a way to handle race condition when finish update is called // before ROLLBACK if (!optional.isPresent()) { LOG.warning("No update configuration found for key " + Tasks.jobKey(oldConfig) + " shard " + oldConfig.getShardId() + " : Assuming update has finished."); return; } TaskUpdateConfiguration updateConfig = optional.get(); TwitterTaskInfo newConfig = rollingBack ? updateConfig.getOldConfig() : updateConfig.getNewConfig(); if (newConfig == null) { // The updated configuration removed the shard, nothing to reschedule. return; } ConfigurationManager.resetStartCommand(newConfig); ScheduledTask newTask = taskCreator.apply(newConfig).setAncestorId(taskId); taskStore.saveTasks(ImmutableSet.of(newTask)); createStateMachine(sideEffectWork, newTask) .updateState( PENDING, Optional.of("Rescheduled after " + (rollingBack ? "rollback." : "update."))); } private Map<String, TaskStateMachine> getStateMachines(final Set<String> taskIds) { return readOnlyStorage.doInTransaction(new Work.Quiet<Map<String, TaskStateMachine>>() { @Override public Map<String, TaskStateMachine> apply(StoreProvider storeProvider) { Set<ScheduledTask> tasks = storeProvider.getTaskStore().fetchTasks(Query.byId(taskIds)); Map<String, ScheduledTask> existingTasks = Maps.uniqueIndex( tasks, new Function<ScheduledTask, String>() { @Override public String apply(ScheduledTask input) { return input.getAssignedTask().getTaskId(); } }); ImmutableMap.Builder<String, TaskStateMachine> builder = ImmutableMap.builder(); for (String taskId : taskIds) { // Pass null get() values through. builder.put(taskId, getStateMachine(taskId, existingTasks.get(taskId))); } return builder.build(); } }); } private TaskStateMachine getStateMachine(String taskId, ScheduledTask task) { if (task != null) { String role = task.getAssignedTask().getTask().getOwner().getRole(); String job = task.getAssignedTask().getTask().getJobName(); return new TaskStateMachine( Tasks.id(task), Tasks.jobKey(task), task, taskUpdateChecker(role, job), workSink, clock, task.getStatus()); } // The task is unknown, not present in storage. TaskStateMachine stateMachine = new TaskStateMachine( taskId, null, // The task is unknown, so there is no matching task to fetch. null, // Since the task doesn't exist, its job cannot be updating. Suppliers.ofInstance(false), workSink, clock, INIT); stateMachine.updateState(UNKNOWN); return stateMachine; } private TaskStateMachine createStateMachine( SideEffectWork<?, ?> sideEffectWork, ScheduledTask task) { return createStateMachine(sideEffectWork, task, INIT); } private TaskStateMachine createStateMachine( SideEffectWork<?, ?> sideEffectWork, final ScheduledTask task, final ScheduleStatus initialState) { final String taskId = Tasks.id(task); String role = task.getAssignedTask().getTask().getOwner().getRole(); String job = task.getAssignedTask().getTask().getJobName(); final String jobKey = Tasks.jobKey(task); TaskStateMachine stateMachine = new TaskStateMachine( taskId, jobKey, Iterables.getOnlyElement(fetchTasks(Query.byId(taskId))), taskUpdateChecker(role, job), workSink, clock, initialState); sideEffectWork.addSideEffect(new SideEffect() { @Override public void mutate(MutableState state) { state.getVars().incrementCount(jobKey, initialState); } }); return stateMachine; } }
package jsettlers.ai.highlevel; import static jsettlers.common.buildings.EBuildingType.BIG_TOWER; import static jsettlers.common.buildings.EBuildingType.CASTLE; import static jsettlers.common.buildings.EBuildingType.LUMBERJACK; import static jsettlers.common.buildings.EBuildingType.TOWER; import static jsettlers.common.mapobject.EMapObjectType.STONE; import static jsettlers.common.mapobject.EMapObjectType.TREE_ADULT; import static jsettlers.common.mapobject.EMapObjectType.TREE_GROWING; import static jsettlers.common.movable.EMovableType.SWORDSMAN_L1; import static jsettlers.common.movable.EMovableType.SWORDSMAN_L2; import static jsettlers.common.movable.EMovableType.SWORDSMAN_L3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Vector; import jsettlers.ai.highlevel.AiPositions.AiPositionFilter; import jsettlers.algorithms.construction.AbstractConstructionMarkableMap; import jsettlers.common.CommonConstants; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.buildings.IMaterialProductionSettings; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.landscape.EResourceType; import jsettlers.common.map.partition.IPartitionData; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.material.EMaterialType; import jsettlers.common.movable.EDirection; import jsettlers.common.movable.EMovableType; import jsettlers.common.movable.IMovable; import jsettlers.common.position.RelativePoint; import jsettlers.common.position.ShortPoint2D; import jsettlers.logic.buildings.Building; import jsettlers.logic.buildings.WorkAreaBuilding; import jsettlers.logic.map.grid.MainGrid; import jsettlers.logic.map.grid.flags.FlagsGrid; import jsettlers.logic.map.grid.landscape.LandscapeGrid; import jsettlers.logic.map.grid.movable.MovableGrid; import jsettlers.logic.map.grid.objects.AbstractHexMapObject; import jsettlers.logic.map.grid.objects.ObjectsGrid; import jsettlers.logic.map.grid.partition.PartitionsGrid; import jsettlers.logic.movable.Movable; import jsettlers.logic.player.Player; import jsettlers.logic.player.Team; /** * This class calculates statistics based on the grids which are used by highlevel and lowlevel KI. The statistics are calculated once and read * multiple times within one AiExecutor step triggerd by the game clock. * * @author codingberlin */ public class AiStatistics { private static final EBuildingType[] REFERENCE_POINT_FINDER_BUILDING_ORDER = {LUMBERJACK, TOWER, BIG_TOWER, CASTLE }; public static final int NEAR_STONE_DISTANCE = 5; private final Queue<Building> buildings; private final PlayerStatistic[] playerStatistics; private final Map<EMapObjectType, AiPositions> sortedCuttableObjectsInDefaultPartition; private final AiPositions[] sortedResourceTypes; private final AiPositions sortedRiversInDefaultPartition; private final MainGrid mainGrid; private final LandscapeGrid landscapeGrid; private final ObjectsGrid objectsGrid; private final PartitionsGrid partitionsGrid; private final MovableGrid movableGrid; private final FlagsGrid flagsGrid; private final AbstractConstructionMarkableMap constructionMarksGrid; private final AiMapInformation aiMapInformation; private final long[] resourceCountInDefaultPartition; public AiStatistics(MainGrid mainGrid) { this.buildings = Building.getAllBuildings(); this.mainGrid = mainGrid; this.landscapeGrid = mainGrid.getLandscapeGrid(); this.objectsGrid = mainGrid.getObjectsGrid(); this.partitionsGrid = mainGrid.getPartitionsGrid(); this.movableGrid = mainGrid.getMovableGrid(); this.flagsGrid = mainGrid.getFlagsGrid(); this.constructionMarksGrid = mainGrid.getConstructionMarksGrid(); this.playerStatistics = new PlayerStatistic[mainGrid.getGuiInputGrid().getNumberOfPlayers()]; this.aiMapInformation = new AiMapInformation(this.partitionsGrid); for (byte i = 0; i < mainGrid.getGuiInputGrid().getNumberOfPlayers(); i++) { this.playerStatistics[i] = new PlayerStatistic(); } sortedRiversInDefaultPartition = new AiPositions(); sortedCuttableObjectsInDefaultPartition = new HashMap<EMapObjectType, AiPositions>(); sortedResourceTypes = new AiPositions[EResourceType.VALUES.length]; for (int i = 0; i < sortedResourceTypes.length; i++) { sortedResourceTypes[i] = new AiPositions(); } resourceCountInDefaultPartition = new long[EResourceType.VALUES.length]; } public byte getFlatternEffortAtPositionForBuilding(final ShortPoint2D position, final EBuildingType buildingType) { byte flattenEffort = constructionMarksGrid.calculateConstructionMarkValue(position.x, position.y, buildingType.getProtectedTiles()); if (flattenEffort == -1) { return Byte.MAX_VALUE; } return flattenEffort; } public void updateStatistics() { for (PlayerStatistic playerStatistic : playerStatistics) { playerStatistic.clearAll(); } sortedRiversInDefaultPartition.clear(); sortedCuttableObjectsInDefaultPartition.clear(); for (AiPositions xCoordinatesMap : sortedResourceTypes) { xCoordinatesMap.clear(); } updateBuildingStatistics(); updateMapStatistics(); } private void updateBuildingStatistics() { for (Building building : buildings) { PlayerStatistic playerStatistic = playerStatistics[building.getPlayerId()]; EBuildingType type = building.getBuildingType(); updateNumberOfNotFinishedBuildings(playerStatistic, building); updateBuildingsNumbers(playerStatistic, building, type); updateBuildingPositions(playerStatistic, type, building); } } private void updateBuildingPositions(PlayerStatistic playerStatistic, EBuildingType type, Building building) { if (!playerStatistic.buildingPositions.containsKey(type)) { playerStatistic.buildingPositions.put(type, new ArrayList<ShortPoint2D>()); } playerStatistic.buildingPositions.get(type).add(building.getPos()); if (type == EBuildingType.WINEGROWER) { playerStatistic.wineGrowerWorkAreas.add(((WorkAreaBuilding) building).getWorkAreaCenter()); } else if (type == EBuildingType.FARM) { playerStatistic.farmWorkAreas.add(((WorkAreaBuilding) building).getWorkAreaCenter()); } } private void updateBuildingsNumbers(PlayerStatistic playerStatistic, Building building, EBuildingType type) { playerStatistic.totalBuildingsNumbers[type.ordinal]++; if (building.getStateProgress() == 1f) { playerStatistic.buildingsNumbers[type.ordinal]++; } } private void updateNumberOfNotFinishedBuildings(PlayerStatistic playerStatistic, Building building) { playerStatistic.numberOfTotalBuildings++; if (building.getStateProgress() < 1f) { playerStatistic.numberOfNotFinishedBuildings++; if (building.getBuildingType().isMilitaryBuilding()) { playerStatistic.numberOfNotOccupiedMilitaryBuildings++; } } else if (building.getBuildingType().isMilitaryBuilding()) { if (building.isOccupied()) { playerStatistic.isAlive = true; } else { playerStatistic.numberOfNotOccupiedMilitaryBuildings++; } } } private void updateMapStatistics() { aiMapInformation.clear(); updatePartitionIdsToBuildOn(); short width = mainGrid.getWidth(); short height = mainGrid.getHeight(); for (int i = 0; i < resourceCountInDefaultPartition.length; i++) { resourceCountInDefaultPartition[i] = 0; } for (short x = 0; x < width; x++) { for (short y = 0; y < height; y++) { Player player = partitionsGrid.getPlayerAt(x, y); int mapInformationPlayerId; if (player != null) { mapInformationPlayerId = player.playerId; } else { mapInformationPlayerId = aiMapInformation.resourceAndGrassCount.length - 1; } if (landscapeGrid.getResourceAmountAt(x, y) > 0) { EResourceType resourceType = landscapeGrid.getResourceTypeAt(x, y); sortedResourceTypes[resourceType.ordinal].addNoCollission(x, y); if (resourceType != EResourceType.FISH) { aiMapInformation.resourceAndGrassCount[mapInformationPlayerId][resourceType.ordinal]++; if (player != null) { playerStatistics[player.playerId].resourceCount[resourceType.ordinal]++; } else { resourceCountInDefaultPartition[resourceType.ordinal]++; } } else if (landscapeGrid.getLandscapeTypeAt(x, y) == ELandscapeType.WATER1) { int fishMapInformationPlayerId = mapInformationPlayerId; if (mapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition((short) (x + 3), y); if (fishMapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition((short) (x - 3), y); if (fishMapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition(x, (short) (y + 3)); if (fishMapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition(x, (short) (y - 3)); } } } } aiMapInformation.resourceAndGrassCount[fishMapInformationPlayerId][resourceType.ordinal]++; if (fishMapInformationPlayerId != aiMapInformation.resourceAndGrassCount.length - 1) { playerStatistics[fishMapInformationPlayerId].resourceCount[resourceType.ordinal]++; } else { resourceCountInDefaultPartition[resourceType.ordinal]++; } } } if (landscapeGrid.getLandscapeTypeAt(x, y).isGrass()) { aiMapInformation.resourceAndGrassCount[mapInformationPlayerId][aiMapInformation.GRASS_INDEX]++; } Movable movable = movableGrid.getMovableAt(x, y); if (movable != null) { byte movablePlayerId = movable.getPlayerId(); PlayerStatistic movablePlayerStatistic = playerStatistics[movablePlayerId]; EMovableType movableType = movable.getMovableType(); if (!movablePlayerStatistic.movablePositions.containsKey(movableType)) { movablePlayerStatistic.movablePositions.put(movableType, new Vector<ShortPoint2D>()); } movablePlayerStatistic.movablePositions.get(movableType).add(movable.getPos()); if (player != null && player.playerId != movablePlayerId && movableType.isSoldier() && getEnemiesOf(player.playerId).contains(movablePlayerId)) { playerStatistics[player.playerId].enemyTroopsInTown.addNoCollission(movable.getPos().x, movable.getPos().y); } } if (player == null) { updateFreeLand(x, y); } else if (partitionsGrid.getPartitionIdAt(x, y) == playerStatistics[player.playerId].partitionIdToBuildOn) { updatePlayerLand(x, y, player); } if (player != null && isBorderOf(x, y, player.playerId)) { if (partitionsGrid.getPartitionIdAt(x, y) == playerStatistics[player.playerId].partitionIdToBuildOn) { playerStatistics[player.playerId].border.add(x, y); } else { playerStatistics[player.playerId].otherPartitionBorder.add(x, y); } } } } } private int mapInformationPlayerIdOfPosition(short x, short y) { if (!mainGrid.isInBounds(x, y)) { return aiMapInformation.resourceAndGrassCount.length - 1; } byte playerId = mainGrid.getPartitionsGrid().getPlayerIdAt(x, y); if (playerId == -1) { return aiMapInformation.resourceAndGrassCount.length - 1; } return playerId; } private boolean isBorderOf(int x, int y, byte playerId) { return isIngestibleBy(x + 1, y + 1, playerId) || isIngestibleBy(x + 1, y - 1, playerId) || isIngestibleBy(x - 1, y + 1, playerId) || isIngestibleBy(x - 1, y - 1, playerId); } private boolean isIngestibleBy(int x, int y, byte playerId) { return mainGrid.isInBounds(x, y) && partitionsGrid.getPlayerIdAt(x, y) != playerId && !mainGrid.getLandscapeGrid().getLandscapeTypeAt(x, y).isBlocking && !partitionsGrid.isEnforcedByTower(x, y); } private void updatePlayerLand(short x, short y, Player player) { byte playerId = player.playerId; PlayerStatistic playerStatistic = playerStatistics[playerId]; playerStatistic.landToBuildOn.addNoCollission(x, y); AbstractHexMapObject o = objectsGrid.getObjectsAt(x, y); if (o != null) { if (o.hasCuttableObject(STONE) && isCuttableByPlayer(x, y, player.playerId)) { playerStatistic.stones.addNoCollission(x, y); } else if (o.hasMapObjectTypes(TREE_GROWING, TREE_ADULT) && isCuttableByPlayer(x, y, player.playerId)) { playerStatistic.trees.addNoCollission(x, y); } } ELandscapeType landscape = landscapeGrid.getLandscapeTypeAt(x, y); if (landscape.isRiver()) { playerStatistic.rivers.addNoCollission(x, y); } if (objectsGrid.hasMapObjectType(x, y, EMapObjectType.WINE_GROWING, EMapObjectType.WINE_HARVESTABLE)) { playerStatistic.wineCount++; } } private boolean isCuttableByPlayer(short x, short y, byte playerId) { byte[] playerIds = new byte[4]; playerIds[0] = partitionsGrid.getPlayerIdAt(x - 2, y - 2); playerIds[1] = partitionsGrid.getPlayerIdAt(x - 2, y + 2); playerIds[2] = partitionsGrid.getPlayerIdAt(x + 2, y - 2); playerIds[3] = partitionsGrid.getPlayerIdAt(x + 2, y + 2); for (byte positionPlayerId : playerIds) { if (positionPlayerId != playerId) { return false; } } return true; } private void updateFreeLand(short x, short y) { if (objectsGrid.hasCuttableObject(x, y, TREE_ADULT)) { AiPositions trees = sortedCuttableObjectsInDefaultPartition.get(TREE_ADULT); if (trees == null) { trees = new AiPositions(); sortedCuttableObjectsInDefaultPartition.put(TREE_ADULT, trees); } trees.addNoCollission(x, y); } if (objectsGrid.hasCuttableObject(x, y, STONE)) { AiPositions stones = sortedCuttableObjectsInDefaultPartition.get(STONE); if (stones == null) { stones = new AiPositions(); sortedCuttableObjectsInDefaultPartition.put(STONE, stones); } stones.addNoCollission(x, y); updateNearStones(x, y); } ELandscapeType landscape = landscapeGrid.getLandscapeTypeAt(x, y); if (landscape.isRiver()) { sortedRiversInDefaultPartition.addNoCollission(x, y); } } private void updateNearStones(short x, short y) { for (EDirection dir : EDirection.VALUES) { int dx = dir.getNextTileX(x, NEAR_STONE_DISTANCE); int dy = dir.getNextTileY(y, NEAR_STONE_DISTANCE); if (mainGrid.isInBounds(dx, dy)) { byte playerId = partitionsGrid.getPlayerIdAt(dx, dy); if (playerId != -1) { playerStatistics[playerId].stonesNearBy.addNoCollission(x, y); } } } } private void updatePartitionIdsToBuildOn() { for (byte playerId = 0; playerId < playerStatistics.length; playerId++) { ShortPoint2D referencePosition = null; for (EBuildingType referenceFinderBuildingType : REFERENCE_POINT_FINDER_BUILDING_ORDER) { if (getTotalNumberOfBuildingTypeForPlayer(referenceFinderBuildingType, playerId) > 0) { referencePosition = getBuildingPositionsOfTypeForPlayer(referenceFinderBuildingType, playerId).get(0); break; } } if (referencePosition != null) { playerStatistics[playerId].referencePosition = referencePosition; playerStatistics[playerId].partitionIdToBuildOn = partitionsGrid.getPartitionIdAt(referencePosition.x, referencePosition.y); playerStatistics[playerId].materialProduction = partitionsGrid.getMaterialProductionAt(referencePosition.x, referencePosition.y); playerStatistics[playerId].materials = partitionsGrid.getPartitionDataForManagerAt(referencePosition.x, referencePosition.y); } } } public Building getBuildingAt(ShortPoint2D point) { return (Building) objectsGrid.getMapObjectAt(point.x, point.y, EMapObjectType.BUILDING); } public ShortPoint2D getNearestResourcePointForPlayer(ShortPoint2D point, EResourceType resourceType, byte playerId, int searchDistance) { return getNearestPointInDefaultPartitionOutOfSortedMap(point, sortedResourceTypes[resourceType.ordinal], playerId, searchDistance); } public ShortPoint2D getNearestFishPointForPlayer(ShortPoint2D point, final byte playerId, int currentNearestPointDistance) { return sortedResourceTypes[EResourceType.FISH.ordinal].getNearestPoint(point, currentNearestPointDistance, new AiPositionFilter() { @Override public boolean contains(int x, int y) { return isPlayerThere(x + 3, y) || isPlayerThere(x - 3, y) || isPlayerThere(x, y + 3) || isPlayerThere(x, y - 3); } private boolean isPlayerThere(int x, int y) { return mainGrid.isInBounds(x, y) && partitionsGrid.getPartitionAt(x, y).getPlayerId() == playerId; } }); } public ShortPoint2D getNearestResourcePointInDefaultPartitionFor(ShortPoint2D point, EResourceType resourceType, int currentNearestPointDistance) { return getNearestResourcePointForPlayer(point, resourceType, (byte) -1, currentNearestPointDistance); } public ShortPoint2D getNearestCuttableObjectPointInDefaultPartitionFor(ShortPoint2D point, EMapObjectType cuttableObject, int searchDistance) { return getNearestCuttableObjectPointForPlayer(point, cuttableObject, searchDistance, (byte) -1); } public ShortPoint2D getNearestCuttableObjectPointForPlayer(ShortPoint2D point, EMapObjectType cuttableObject, int searchDistance, byte playerId) { AiPositions sortedResourcePoints = sortedCuttableObjectsInDefaultPartition.get(cuttableObject); if (sortedResourcePoints == null) { return null; } return getNearestPointInDefaultPartitionOutOfSortedMap(point, sortedResourcePoints, playerId, searchDistance); } private ShortPoint2D getNearestPointInDefaultPartitionOutOfSortedMap(ShortPoint2D point, AiPositions sortedPoints, final byte playerId, int searchDistance) { return sortedPoints.getNearestPoint(point, searchDistance, new AiPositionFilter() { @Override public boolean contains(int x, int y) { return partitionsGrid.getPartitionAt(x, y).getPlayerId() == playerId; } }); } public List<ShortPoint2D> getMovablePositionsByTypeForPlayer(EMovableType movableType, byte playerId) { if (!playerStatistics[playerId].movablePositions.containsKey(movableType)) { return Collections.emptyList(); } return playerStatistics[playerId].movablePositions.get(movableType); } public int getTotalNumberOfBuildingTypeForPlayer(EBuildingType type, byte playerId) { return playerStatistics[playerId].totalBuildingsNumbers[type.ordinal]; } public int getTotalWineCountForPlayer(byte playerId) { return playerStatistics[playerId].wineCount; } public int getNumberOfBuildingTypeForPlayer(EBuildingType type, byte playerId) { return playerStatistics[playerId].buildingsNumbers[type.ordinal]; } public int getNumberOfNotFinishedBuildingsForPlayer(byte playerId) { return playerStatistics[playerId].numberOfNotFinishedBuildings; } public int getNumberOfTotalBuildingsForPlayer(byte playerId) { return playerStatistics[playerId].numberOfTotalBuildings; } public List<ShortPoint2D> getBuildingPositionsOfTypeForPlayer(EBuildingType type, byte playerId) { if (!playerStatistics[playerId].buildingPositions.containsKey(type)) { return Collections.emptyList(); } return playerStatistics[playerId].buildingPositions.get(type); } public List<ShortPoint2D> getBuildingPositionsOfTypesForPlayer(EnumSet<EBuildingType> buildingTypes, byte playerId) { List<ShortPoint2D> buildingPositions = new Vector<ShortPoint2D>(); for (EBuildingType buildingType : buildingTypes) { buildingPositions.addAll(getBuildingPositionsOfTypeForPlayer(buildingType, playerId)); } return buildingPositions; } public AiPositions getStonesForPlayer(byte playerId) { return playerStatistics[playerId].stones; } public AiPositions getTreesForPlayer(byte playerId) { return playerStatistics[playerId].trees; } public AiPositions getLandForPlayer(byte playerId) { return playerStatistics[playerId].landToBuildOn; } public boolean blocksWorkingAreaOfOtherBuilding(ShortPoint2D point, byte playerId, EBuildingType buildingType) { for (ShortPoint2D workAreaCenter : playerStatistics[playerId].wineGrowerWorkAreas) { for (RelativePoint blockedPoint : buildingType.getBlockedTiles()) { if (workAreaCenter.getOnGridDistTo(blockedPoint.calculatePoint(point)) <= EBuildingType.WINEGROWER.getWorkRadius()) { return true; } } } for (ShortPoint2D workAreaCenter : playerStatistics[playerId].farmWorkAreas) { for (RelativePoint blockedPoint : buildingType.getBlockedTiles()) { if (workAreaCenter.getOnGridDistTo(blockedPoint.calculatePoint(point)) <= EBuildingType.FARM.getWorkRadius()) { return true; } } } return false; } public boolean southIsFreeForPlayer(ShortPoint2D point, byte playerId) { return pointIsFreeForPlayer(point.x, (short) (point.y + 12), playerId) && pointIsFreeForPlayer((short) (point.x + 5), (short) (point.y + 12), playerId) && pointIsFreeForPlayer((short) (point.x + 10), (short) (point.y + 12), playerId) && pointIsFreeForPlayer(point.x, (short) (point.y + 6), playerId) && pointIsFreeForPlayer((short) (point.x + 5), (short) (point.y + 6), playerId) && pointIsFreeForPlayer((short) (point.x + 10), (short) (point.y + 6), playerId); } private boolean pointIsFreeForPlayer(short x, short y, byte playerId) { return mainGrid.isInBounds(x, y) && partitionsGrid.getPlayerIdAt(x, y) == playerId && !objectsGrid.isBuildingAt(x, y) && !flagsGrid.isProtected(x, y) && landscapeGrid.areAllNeighborsOf(x, y, 0, 2, ELandscapeType.GRASS, ELandscapeType.EARTH); } public IMovable getNearestSwordsmanOf(ShortPoint2D targetPosition, byte playerId) { List<ShortPoint2D> soldierPositions = getMovablePositionsByTypeForPlayer(SWORDSMAN_L3, playerId); if (soldierPositions.size() == 0) { soldierPositions = getMovablePositionsByTypeForPlayer(SWORDSMAN_L2, playerId); } if (soldierPositions.size() == 0) { soldierPositions = getMovablePositionsByTypeForPlayer(SWORDSMAN_L1, playerId); } if (soldierPositions.size() == 0) { return null; } ShortPoint2D nearestSoldierPosition = detectNearestPointFromList(targetPosition, soldierPositions); return movableGrid.getMovableAt(nearestSoldierPosition.x, nearestSoldierPosition.y); } public static ShortPoint2D detectNearestPointFromList(ShortPoint2D referencePoint, List<ShortPoint2D> points) { if (points.isEmpty()) { return null; } return detectNearestPointsFromList(referencePoint, points, 1).get(0); } public static List<ShortPoint2D> detectNearestPointsFromList(final ShortPoint2D referencePoint, List<ShortPoint2D> points, int amountOfPointsToDetect) { if (amountOfPointsToDetect <= 0) { return Collections.emptyList(); } if (points.size() <= amountOfPointsToDetect) { return points; } Collections.sort(points, new Comparator<ShortPoint2D>() { @Override public int compare(ShortPoint2D o1, ShortPoint2D o2) { return o1.getOnGridDistTo(referencePoint) - o2.getOnGridDistTo(referencePoint); } }); return points.subList(0, amountOfPointsToDetect); } public int getNumberOfMaterialTypeForPlayer(EMaterialType type, byte playerId) { if (playerStatistics[playerId].materials == null) { return 0; } return playerStatistics[playerId].materials.getAmountOf(type); } public MainGrid getMainGrid() { return mainGrid; } public ShortPoint2D getNearestRiverPointInDefaultPartitionFor(ShortPoint2D referencePoint, int searchDistance) { return getNearestPointInDefaultPartitionOutOfSortedMap(referencePoint, sortedRiversInDefaultPartition, (byte) -1, searchDistance); } public int getNumberOfNotFinishedBuildingTypesForPlayer(EBuildingType buildingType, byte playerId) { return getTotalNumberOfBuildingTypeForPlayer(buildingType, playerId) - getNumberOfBuildingTypeForPlayer(buildingType, playerId); } public AiPositions getRiversForPlayer(byte playerId) { return playerStatistics[playerId].rivers; } public List<Byte> getEnemiesOf(byte playerId) { List<Byte> enemies = new ArrayList<Byte>(); for (Team team : partitionsGrid.getTeams()) { if (!team.isMember(playerId)) { for (Player player : team.getMembers()) { enemies.add(player.playerId); } } } return enemies; } public List<Byte> getAliveEnemiesOf(byte playerId) { List<Byte> aliveEnemies = new ArrayList<>(); for (byte enemyId : getEnemiesOf(playerId)) { if (isAlive(enemyId)) { aliveEnemies.add(enemyId); } } return aliveEnemies; } public ShortPoint2D calculateAveragePointFromList(List<ShortPoint2D> points) { int averageX = 0; int averageY = 0; for (ShortPoint2D point : points) { averageX += point.x; averageY += point.y; } return new ShortPoint2D(averageX / points.size(), averageY / points.size()); } public AiPositions getEnemiesInTownOf(byte playerId) { return playerStatistics[playerId].enemyTroopsInTown; } public IMaterialProductionSettings getMaterialProduction(byte playerId) { return playerStatistics[playerId].materialProduction; } public ShortPoint2D getPositionOfPartition(byte playerId) { return playerStatistics[playerId].referencePosition; } public AiPositions getBorderOf(byte playerId) { return playerStatistics[playerId].border; } public AiPositions getOtherPartitionBorderOf(byte playerId) { return playerStatistics[playerId].otherPartitionBorder; } public boolean isAlive(byte playerId) { return playerStatistics[playerId].isAlive; } public AiMapInformation getAiMapInformation() { return aiMapInformation; } public long resourceCountInDefaultPartition(EResourceType resourceType) { return resourceCountInDefaultPartition[resourceType.ordinal]; } public long resourceCountOfPlayer(EResourceType resourceType, byte playerId) { return playerStatistics[playerId].resourceCount[resourceType.ordinal]; } public List<ShortPoint2D> threatenedBorderOf(byte playerId) { if (playerStatistics[playerId].threatenedBorder == null) { AiPositions borderOfOtherPlayers = new AiPositions(); for (byte otherPlayerId = 0; otherPlayerId < playerStatistics.length; otherPlayerId++) { if (otherPlayerId == playerId || !isAlive(otherPlayerId)) { continue; } borderOfOtherPlayers.addAllNoCollision(getBorderOf(otherPlayerId)); } playerStatistics[playerId].threatenedBorder = new ArrayList<>(); AiPositions myBorder = getBorderOf(playerId); for (int i = 0; i < myBorder.size(); i += 10) { ShortPoint2D myBorderPosition = myBorder.get(i); if (mainGrid.getPartitionsGrid().getTowerCountAt(myBorderPosition.x, myBorderPosition.y) == 0 && borderOfOtherPlayers.getNearestPoint(myBorderPosition, CommonConstants.TOWER_RADIUS) != null) { playerStatistics[playerId].threatenedBorder.add(myBorderPosition); } } } return playerStatistics[playerId].threatenedBorder; } public AiPositions getStonesNearBy(byte playerId) { return playerStatistics[playerId].stonesNearBy; } private static class PlayerStatistic { ShortPoint2D referencePosition; boolean isAlive; final int[] totalBuildingsNumbers = new int[EBuildingType.NUMBER_OF_BUILDINGS]; final int[] buildingsNumbers = new int[EBuildingType.NUMBER_OF_BUILDINGS]; final Map<EBuildingType, List<ShortPoint2D>> buildingPositions = new HashMap<EBuildingType, List<ShortPoint2D>>(); final List<ShortPoint2D> farmWorkAreas = new Vector<ShortPoint2D>(); final List<ShortPoint2D> wineGrowerWorkAreas = new Vector<ShortPoint2D>(); short partitionIdToBuildOn; IPartitionData materials; final AiPositions landToBuildOn = new AiPositions(); final AiPositions border = new AiPositions(); final AiPositions otherPartitionBorder = new AiPositions(); final Map<EMovableType, List<ShortPoint2D>> movablePositions = new HashMap<EMovableType, List<ShortPoint2D>>(); final AiPositions stones = new AiPositions(); final AiPositions stonesNearBy = new AiPositions(); final AiPositions trees = new AiPositions(); final AiPositions rivers = new AiPositions(); final AiPositions enemyTroopsInTown = new AiPositions(); List<ShortPoint2D> threatenedBorder; final long[] resourceCount = new long[EResourceType.VALUES.length]; int numberOfNotFinishedBuildings; int numberOfTotalBuildings; int numberOfNotOccupiedMilitaryBuildings; int wineCount; IMaterialProductionSettings materialProduction; PlayerStatistic() { clearIntegers(); } public void clearAll() { isAlive = false; materials = null; buildingPositions.clear(); enemyTroopsInTown.clear(); stones.clear(); stonesNearBy.clear(); trees.clear(); rivers.clear(); landToBuildOn.clear(); border.clear(); otherPartitionBorder.clear(); movablePositions.clear(); farmWorkAreas.clear(); wineGrowerWorkAreas.clear(); threatenedBorder = null; clearIntegers(); } private void clearIntegers() { Arrays.fill(totalBuildingsNumbers, 0); Arrays.fill(buildingsNumbers, 0); Arrays.fill(resourceCount, 0); numberOfNotFinishedBuildings = 0; numberOfTotalBuildings = 0; numberOfNotOccupiedMilitaryBuildings = 0; wineCount = 0; partitionIdToBuildOn = Short.MIN_VALUE; } } }
package org.jaxen.function.ext; import java.util.Collections; import java.util.List; import org.jaxen.Context; import org.jaxen.ContextSupport; import org.jaxen.Function; import org.jaxen.FunctionCallException; import org.jaxen.Navigator; import org.jaxen.XPath; import org.jaxen.function.StringFunction; /** * <code><i>node-set</i> evaluate(<i>string</i>)</code> * * @author Erwin Bolwidt (ejb @ klomp.org) */ public class EvaluateFunction implements Function { public Object call( Context context, List args ) throws FunctionCallException { if ( args.size() == 1 ) { return evaluate( context, args.get(0)); } throw new FunctionCallException( "evaluate() requires one argument" ); } public static List evaluate (Context context, Object arg) throws FunctionCallException { List contextNodes = context.getNodeSet(); if (contextNodes.size() == 0) return Collections.EMPTY_LIST; Navigator nav = context.getNavigator(); String xpathString; if ( arg instanceof String ) xpathString = (String)arg; else xpathString = StringFunction.evaluate(arg, nav); try { XPath xpath = nav.parseXPath(xpathString); ContextSupport support = context.getContextSupport(); xpath.setVariableContext( support.getVariableContext() ); xpath.setFunctionContext( support.getFunctionContext() ); xpath.setNamespaceContext( support.getNamespaceContext() ); return xpath.selectNodes( context.duplicate() ); } catch ( org.jaxen.saxpath.SAXPathException e ) { throw new FunctionCallException(e.toString()); } } }
package etla.mod.etl.form; import etla.mod.SModConsts; import etla.mod.cfg.db.SDbConfig; import etla.mod.etl.db.SDbConfigAvista; import etla.mod.etl.db.SDbCustomer; import etla.mod.etl.db.SEtlConsts; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import sa.lib.SLibConsts; import sa.lib.SLibUtils; import sa.lib.db.SDbRegistry; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; import sa.lib.gui.SGuiUtils; import sa.lib.gui.SGuiValidation; import sa.lib.gui.bean.SBeanForm; /** * * @author Sergio Flores */ public class SFormCustomer extends SBeanForm implements ActionListener { private SDbCustomer moRegistry; /** * Creates new form SFormCustomer * @param client * @param title */ public SFormCustomer(SGuiClient client, String title) { setFormSettings(client, SGuiConsts.BEAN_FORM_EDIT, SModConsts.AU_CUS, SLibConsts.UNDEFINED, title); initComponents(); initComponentsCustom(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jlCode = new javax.swing.JLabel(); jtfCode = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); jlName = new javax.swing.JLabel(); jtfName = new javax.swing.JTextField(); jPanel6 = new javax.swing.JPanel(); jlSrcRequiredCurrency = new javax.swing.JLabel(); moKeySrcRequiredCurrency = new sa.lib.gui.bean.SBeanFieldKey(); jtfDefaultCurrency = new javax.swing.JTextField(); jPanel11 = new javax.swing.JPanel(); jlSrcRequiredUnitOfMeasure = new javax.swing.JLabel(); moKeySrcRequiredUnitOfMeasure = new sa.lib.gui.bean.SBeanFieldKey(); jtfDefaultUnitOfMeasure = new javax.swing.JTextField(); jPanel16 = new javax.swing.JPanel(); jlSrcCustomerSalesAgent = new javax.swing.JLabel(); moKeySrcCustomerSalesAgent = new sa.lib.gui.bean.SBeanFieldKey(); jPanel12 = new javax.swing.JPanel(); jlDesCustomerId = new javax.swing.JLabel(); moIntDesCustomerId = new sa.lib.gui.bean.SBeanFieldInteger(); jbEditDesCustomerId = new javax.swing.JButton(); jlSiie = new javax.swing.JLabel(); jPanel15 = new javax.swing.JPanel(); jlDesCustomerBranchId = new javax.swing.JLabel(); moIntDesCustomerBranchId = new sa.lib.gui.bean.SBeanFieldInteger(); jbEditDesCustomerBranchId = new javax.swing.JButton(); jlSiie1 = new javax.swing.JLabel(); jPanel13 = new javax.swing.JPanel(); jlDesRequiredPayMethod = new javax.swing.JLabel(); moKeyDesRequiredPayMethod = new sa.lib.gui.bean.SBeanFieldKey(); jtfDefaultPayMethod = new javax.swing.JTextField(); jPanel14 = new javax.swing.JPanel(); jlPayAccount = new javax.swing.JLabel(); moTextPayAccount = new sa.lib.gui.bean.SBeanFieldText(); jbSetUndefined = new javax.swing.JButton(); jPanel7 = new javax.swing.JPanel(); moBoolEtlIgnore = new sa.lib.gui.bean.SBeanFieldBoolean(); jLabel1 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del registro:")); jPanel1.setLayout(new java.awt.BorderLayout(0, 5)); jPanel2.setLayout(new java.awt.GridLayout(10, 1, 0, 5)); jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlCode.setText("Código:"); jlCode.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel3.add(jlCode); jtfCode.setEditable(false); jtfCode.setFocusable(false); jtfCode.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel3.add(jtfCode); jPanel2.add(jPanel3); jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlName.setText("Nombre:*"); jlName.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel4.add(jlName); jtfName.setEditable(false); jtfName.setFocusable(false); jtfName.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel4.add(jtfName); jPanel2.add(jPanel4); jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlSrcRequiredCurrency.setText("Moneda requerida:"); jlSrcRequiredCurrency.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel6.add(jlSrcRequiredCurrency); moKeySrcRequiredCurrency.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel6.add(moKeySrcRequiredCurrency); jtfDefaultCurrency.setEditable(false); jtfDefaultCurrency.setToolTipText("Moneda predeterminada"); jtfDefaultCurrency.setFocusable(false); jtfDefaultCurrency.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel6.add(jtfDefaultCurrency); jPanel2.add(jPanel6); jPanel11.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlSrcRequiredUnitOfMeasure.setText("Unidad requerida:"); jlSrcRequiredUnitOfMeasure.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel11.add(jlSrcRequiredUnitOfMeasure); moKeySrcRequiredUnitOfMeasure.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel11.add(moKeySrcRequiredUnitOfMeasure); jtfDefaultUnitOfMeasure.setEditable(false); jtfDefaultUnitOfMeasure.setToolTipText("Unidad predeterminada"); jtfDefaultUnitOfMeasure.setFocusable(false); jtfDefaultUnitOfMeasure.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel11.add(jtfDefaultUnitOfMeasure); jPanel2.add(jPanel11); jPanel16.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlSrcCustomerSalesAgent.setText("Agente ventas:"); jlSrcCustomerSalesAgent.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel16.add(jlSrcCustomerSalesAgent); moKeySrcCustomerSalesAgent.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel16.add(moKeySrcCustomerSalesAgent); jPanel2.add(jPanel16); jPanel12.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDesCustomerId.setText("ID asoc. negocios:*"); jlDesCustomerId.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel12.add(jlDesCustomerId); jPanel12.add(moIntDesCustomerId); jbEditDesCustomerId.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/lib/img/cmd_std_edit.gif"))); // NOI18N jbEditDesCustomerId.setToolTipText("Modificar"); jbEditDesCustomerId.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel12.add(jbEditDesCustomerId); jlSiie.setForeground(java.awt.Color.gray); jlSiie.setText("(Primary Key SIIE)"); jlSiie.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel12.add(jlSiie); jPanel2.add(jPanel12); jPanel15.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDesCustomerBranchId.setText("ID suc. matriz:*"); jlDesCustomerBranchId.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel15.add(jlDesCustomerBranchId); jPanel15.add(moIntDesCustomerBranchId); jbEditDesCustomerBranchId.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sa/lib/img/cmd_std_edit.gif"))); // NOI18N jbEditDesCustomerBranchId.setToolTipText("Modificar"); jbEditDesCustomerBranchId.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel15.add(jbEditDesCustomerBranchId); jlSiie1.setForeground(java.awt.Color.gray); jlSiie1.setText("(Primary Key SIIE)"); jlSiie1.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel15.add(jlSiie1); jPanel2.add(jPanel15); jPanel13.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDesRequiredPayMethod.setText("Método pago:"); jlDesRequiredPayMethod.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel13.add(jlDesRequiredPayMethod); moKeyDesRequiredPayMethod.setPreferredSize(new java.awt.Dimension(200, 23)); jPanel13.add(moKeyDesRequiredPayMethod); jtfDefaultPayMethod.setEditable(false); jtfDefaultPayMethod.setToolTipText("Método de pago predeterminado"); jtfDefaultPayMethod.setFocusable(false); jtfDefaultPayMethod.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel13.add(jtfDefaultPayMethod); jPanel2.add(jPanel13); jPanel14.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlPayAccount.setText("No. cuenta:"); jlPayAccount.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel14.add(jlPayAccount); moTextPayAccount.setPreferredSize(new java.awt.Dimension(200, 23)); jPanel14.add(moTextPayAccount); jbSetUndefined.setText("No identificado"); jbSetUndefined.setMargin(new java.awt.Insets(2, 0, 2, 0)); jbSetUndefined.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel14.add(jbSetUndefined); jPanel2.add(jPanel14); jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); moBoolEtlIgnore.setText("Ignorar en exportación a SIIE"); moBoolEtlIgnore.setPreferredSize(new java.awt.Dimension(175, 23)); jPanel7.add(moBoolEtlIgnore); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/etla/gui/img/icon_info.png"))); // NOI18N jLabel1.setToolTipText("Ignorar este cliente al exportar facturas a SIIE"); jLabel1.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel7.add(jLabel1); jPanel2.add(jPanel7); jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH); jPanel5.setLayout(new java.awt.BorderLayout(5, 0)); jPanel1.add(jPanel5, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel13; private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel16; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JButton jbEditDesCustomerBranchId; private javax.swing.JButton jbEditDesCustomerId; private javax.swing.JButton jbSetUndefined; private javax.swing.JLabel jlCode; private javax.swing.JLabel jlDesCustomerBranchId; private javax.swing.JLabel jlDesCustomerId; private javax.swing.JLabel jlDesRequiredPayMethod; private javax.swing.JLabel jlName; private javax.swing.JLabel jlPayAccount; private javax.swing.JLabel jlSiie; private javax.swing.JLabel jlSiie1; private javax.swing.JLabel jlSrcCustomerSalesAgent; private javax.swing.JLabel jlSrcRequiredCurrency; private javax.swing.JLabel jlSrcRequiredUnitOfMeasure; private javax.swing.JTextField jtfCode; private javax.swing.JTextField jtfDefaultCurrency; private javax.swing.JTextField jtfDefaultPayMethod; private javax.swing.JTextField jtfDefaultUnitOfMeasure; private javax.swing.JTextField jtfName; private sa.lib.gui.bean.SBeanFieldBoolean moBoolEtlIgnore; private sa.lib.gui.bean.SBeanFieldInteger moIntDesCustomerBranchId; private sa.lib.gui.bean.SBeanFieldInteger moIntDesCustomerId; private sa.lib.gui.bean.SBeanFieldKey moKeyDesRequiredPayMethod; private sa.lib.gui.bean.SBeanFieldKey moKeySrcCustomerSalesAgent; private sa.lib.gui.bean.SBeanFieldKey moKeySrcRequiredCurrency; private sa.lib.gui.bean.SBeanFieldKey moKeySrcRequiredUnitOfMeasure; private sa.lib.gui.bean.SBeanFieldText moTextPayAccount; // End of variables declaration//GEN-END:variables /* * Private methods */ private void initComponentsCustom() { SDbConfigAvista configAvista = ((SDbConfig) miClient.getSession().getConfigSystem()).getDbConfigAvista(); SGuiUtils.setWindowBounds(this, 640, 400); moKeySrcRequiredCurrency.setKeySettings(miClient, SGuiUtils.getLabelName(jlSrcRequiredCurrency), false); moKeySrcRequiredUnitOfMeasure.setKeySettings(miClient, SGuiUtils.getLabelName(jlSrcRequiredUnitOfMeasure), false); moKeySrcCustomerSalesAgent.setKeySettings(miClient, SGuiUtils.getLabelName(jlSrcCustomerSalesAgent), false); moIntDesCustomerId.setIntegerSettings(SGuiUtils.getLabelName(jlDesCustomerId), SGuiConsts.GUI_TYPE_INT_RAW, true); moIntDesCustomerBranchId.setIntegerSettings(SGuiUtils.getLabelName(jlDesCustomerBranchId), SGuiConsts.GUI_TYPE_INT_RAW, true); moKeyDesRequiredPayMethod.setKeySettings(miClient, SGuiUtils.getLabelName(jlDesRequiredPayMethod), false); moTextPayAccount.setTextSettings(SGuiUtils.getLabelName(jlPayAccount), 25, 0); moBoolEtlIgnore.setBooleanSettings(moBoolEtlIgnore.getText(), false); moFields.addField(moKeySrcRequiredCurrency); moFields.addField(moKeySrcRequiredUnitOfMeasure); moFields.addField(moKeySrcCustomerSalesAgent); moFields.addField(moIntDesCustomerId); moFields.addField(moIntDesCustomerBranchId); moFields.addField(moKeyDesRequiredPayMethod); moFields.addField(moTextPayAccount); moFields.addField(moBoolEtlIgnore); moFields.setFormButton(jbSave); jtfDefaultCurrency.setText((String) miClient.getSession().readField(SModConsts.AS_CUR, new int[] { configAvista.getFkSrcDefaultCurrencyId() }, SDbRegistry.FIELD_CODE)); jtfDefaultUnitOfMeasure.setText((String) miClient.getSession().readField(SModConsts.AS_UOM, new int[] { configAvista.getFkSrcDefaultUnitOfMeasureId() }, SDbRegistry.FIELD_CODE)); jtfDefaultPayMethod.setText((String) miClient.getSession().readField(SModConsts.AS_PAY_MET, new int[] { configAvista.getFkDesDefaultPayMethodId() }, SDbRegistry.FIELD_NAME)); jtfDefaultCurrency.setCaretPosition(0); jtfDefaultUnitOfMeasure.setCaretPosition(0); jtfDefaultPayMethod.setCaretPosition(0); } private void enableEditDesCustomerId(boolean enable) { moIntDesCustomerId.setEditable(enable); jbEditDesCustomerId.setEnabled(!enable); } private void enableEditDesCustomerBranchId(boolean enable) { moIntDesCustomerBranchId.setEditable(enable); jbEditDesCustomerBranchId.setEnabled(!enable); } private void actionEditDesCustomerId() { enableEditDesCustomerId(true); moIntDesCustomerId.requestFocus(); } private void actionEditDesCustomerBranchId() { enableEditDesCustomerBranchId(true); moIntDesCustomerBranchId.requestFocus(); } private void actionSetUndefined() { moTextPayAccount.setValue(SEtlConsts.SIIE_PAY_ACC_UNDEF); moTextPayAccount.requestFocus(); } /* * Public methods */ /* * Overriden methods */ @Override public void addAllListeners() { jbEditDesCustomerId.addActionListener(this); jbEditDesCustomerBranchId.addActionListener(this); jbSetUndefined.addActionListener(this); } @Override public void removeAllListeners() { jbEditDesCustomerId.removeActionListener(this); jbEditDesCustomerBranchId.removeActionListener(this); jbSetUndefined.removeActionListener(this); } @Override public void reloadCatalogues() { miClient.getSession().populateCatalogue(moKeySrcRequiredCurrency, SModConsts.AS_CUR, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeySrcRequiredUnitOfMeasure, SModConsts.AS_UOM, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeySrcCustomerSalesAgent, SModConsts.AU_SAL_AGT, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeyDesRequiredPayMethod, SModConsts.AS_PAY_MET, SLibConsts.UNDEFINED, null); } @Override public void setRegistry(SDbRegistry registry) throws Exception { moRegistry = (SDbCustomer) registry; mnFormResult = SLibConsts.UNDEFINED; mbFirstActivation = true; removeAllListeners(); reloadCatalogues(); if (moRegistry.isRegistryNew()) { jtfRegistryKey.setText(""); } else { jtfRegistryKey.setText(SLibUtils.textKey(moRegistry.getPrimaryKey())); } jtfCode.setText(moRegistry.getCode()); jtfCode.setCaretPosition(0); jtfName.setText(moRegistry.getName()); jtfName.setCaretPosition(0); moKeySrcRequiredCurrency.setValue(new int[] { moRegistry.getFkSrcRequiredCurrencyId_n() }); moKeySrcRequiredUnitOfMeasure.setValue(new int[] { moRegistry.getFkSrcRequiredUnitOfMeasureId_n() }); moKeySrcCustomerSalesAgent.setValue(new int[] { moRegistry.getFkSrcCustomerSalesAgentId_n() }); moIntDesCustomerId.setValue(moRegistry.getDesCustomerId()); moIntDesCustomerBranchId.setValue(moRegistry.getDesCustomerBranchId()); moKeyDesRequiredPayMethod.setValue(new int[] { moRegistry.getFkDesRequiredPayMethodId_n()} ); moTextPayAccount.setValue(moRegistry.getPayAccount()); moBoolEtlIgnore.setValue(moRegistry.isEtlIgnore()); setFormEditable(true); /** * Habilitar este campo solo para tipo de usuario 3 SUPER/ADMIN */ moBoolEtlIgnore.setEnabled(miClient.getSession().getUser().getFkUserTypeId()==3); enableEditDesCustomerId(false); enableEditDesCustomerBranchId(false); if (moRegistry.isRegistryNew()) { } else { } addAllListeners(); } @Override public SDbCustomer getRegistry() throws Exception { SDbCustomer registry = moRegistry.clone(); if (registry.isRegistryNew()) {} registry.setDesCustomerId(moIntDesCustomerId.getValue()); registry.setDesCustomerBranchId(moIntDesCustomerBranchId.getValue()); registry.setPayAccount(moTextPayAccount.getValue()); registry.setEtlIgnore(moBoolEtlIgnore.getValue()); registry.setSrcCustomerSalesAgentFk_n(moKeySrcCustomerSalesAgent.getSelectedIndex() <= 0 ? SLibConsts.UNDEFINED : (Integer) moKeySrcCustomerSalesAgent.getSelectedItem().getComplement()); registry.setSrcRequiredCurrencyFk_n(moKeySrcRequiredCurrency.getSelectedIndex() <= 0 ? SLibConsts.UNDEFINED : (Integer) moKeySrcRequiredCurrency.getSelectedItem().getComplement()); registry.setSrcRequiredUnitOfMeasureFk_n(moKeySrcRequiredUnitOfMeasure.getSelectedIndex() <= 0 ? "" : (String) moKeySrcRequiredUnitOfMeasure.getSelectedItem().getComplement()); registry.setFkSrcCustomerSalesAgentId_n(moKeySrcCustomerSalesAgent.getSelectedIndex() <= 0 ? SLibConsts.UNDEFINED : moKeySrcCustomerSalesAgent.getValue()[0]); registry.setFkSrcRequiredCurrencyId_n(moKeySrcRequiredCurrency.getSelectedIndex() <= 0 ? SLibConsts.UNDEFINED : moKeySrcRequiredCurrency.getValue()[0]); registry.setFkSrcRequiredUnitOfMeasureId_n(moKeySrcRequiredUnitOfMeasure.getSelectedIndex() <= 0 ? SLibConsts.UNDEFINED : moKeySrcRequiredUnitOfMeasure.getValue()[0]); registry.setFkDesRequiredPayMethodId_n(moKeyDesRequiredPayMethod.getSelectedIndex() <= 0 ? SLibConsts.UNDEFINED : moKeyDesRequiredPayMethod.getValue()[0]); return registry; } @Override public SGuiValidation validateForm() { SGuiValidation validation = moFields.validateFields(); return validation; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { JButton button = (JButton) e.getSource(); if (button == jbEditDesCustomerId) { actionEditDesCustomerId(); } else if (button == jbEditDesCustomerBranchId) { actionEditDesCustomerBranchId(); } else if (button == jbSetUndefined) { actionSetUndefined(); } } } }
package nl.b3p.viewer.stripes; import java.io.StringReader; import java.io.StringWriter; import java.util.List; import javax.persistence.NoResultException; import javax.xml.bind.JAXBElement; import javax.xml.bind.Marshaller; import javax.xml.namespace.QName; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.controller.LifecycleStage; import net.sourceforge.stripes.validation.Validate; import nl.b3p.geotools.data.arcgis.ArcGISFeatureReader; import nl.b3p.geotools.data.arcgis.ArcGISFeatureSource; import nl.b3p.geotools.data.arcims.FilterToArcXMLSQL; import nl.b3p.geotools.data.arcims.axl.ArcXML; import nl.b3p.geotools.data.arcims.axl.AxlSpatialQuery; import nl.b3p.geotools.filter.visitor.RemoveDistanceUnit; import nl.b3p.viewer.config.app.Application; import nl.b3p.viewer.config.app.ApplicationLayer; import nl.b3p.viewer.config.security.Authorizations; import nl.b3p.viewer.config.services.Layer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geotools.data.FeatureSource; import org.geotools.data.Query; import org.geotools.filter.text.cql2.CQL; import org.json.JSONException; import org.json.JSONObject; import org.opengis.filter.Filter; import org.stripesstuff.stripersist.Stripersist; // </editor-fold> /** * * @author Matthijs Laan */ @UrlBinding("/action/arcquery") @StrictBinding public class ArcQueryUtilActionBean implements ActionBean { private static final Log log = LogFactory.getLog(ArcQueryUtilActionBean.class); @Validate private String cql; @Validate private boolean whereOnly = false; @Validate private ApplicationLayer appLayer; @Validate private Application application; private boolean unauthorized; private Layer layer = null; private ActionBeanContext context; // <editor-fold defaultstate="collapsed" desc="Getters and Setters"> public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = context; } public String getCql() { return cql; } public void setCql(String cql) { this.cql = cql; } public boolean isWhereOnly() { return whereOnly; } public void setWhereOnly(boolean whereOnly) { this.whereOnly = whereOnly; } public ApplicationLayer getAppLayer() { return appLayer; } public void setAppLayer(ApplicationLayer appLayer) { this.appLayer = appLayer; } public Application getApplication() { return application; } public void setApplication(Application application) { this.application = application; } // </editor-fold> @After(stages = LifecycleStage.BindingAndValidation, on="!arcXML") public void loadLayer() { try { layer = (Layer) Stripersist.getEntityManager().createQuery("from Layer where service = :service and name = :n order by virtual desc").setParameter("service", appLayer.getService()).setParameter("n", appLayer.getLayerName()).setMaxResults(1).getSingleResult(); } catch (NoResultException nre) { } } @Before(stages = LifecycleStage.EventHandling) public void checkAuthorization() { if (application == null || appLayer == null || !Authorizations.isAppLayerReadAuthorized(application, appLayer, context.getRequest())) { unauthorized = true; } } @DefaultHandler public Resolution arcXML() throws JSONException { JSONObject json = new JSONObject(); try { AxlSpatialQuery aq = new AxlSpatialQuery(); FilterToArcXMLSQL visitor = new FilterToArcXMLSQL(aq); Filter filter = CQL.toFilter(cql); String where = visitor.encodeToString(filter); if(whereOnly) { json.put("where", where); } else { if (where.trim().length() > 0 && !where.trim().equals("1=1")) { aq.setWhere(where); } StringWriter sw = new StringWriter(); Marshaller m = ArcXML.getJaxbContext().createMarshaller(); m.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); m.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.setProperty(javax.xml.bind.Marshaller.JAXB_FRAGMENT, Boolean.TRUE); m.marshal(new JAXBElement( new QName(null, "SPATIALQUERY"), AxlSpatialQuery.class, aq), sw); sw.close(); json.put("SPATIALQUERY", sw.toString()); } json.put("success", true); } catch (Exception e) { json.put("success", false); String message = "Fout bij maken spatial query: " + e.toString(); Throwable cause = e.getCause(); while (cause != null) { message += "; " + cause.toString(); cause = cause.getCause(); } json.put("error", message); } return new StreamingResolution("application/json", new StringReader(json.toString(4))); } public Resolution getObjectIds() throws JSONException, Exception { JSONObject json = new JSONObject(); if (unauthorized) { json.put("success", false); json.put("message", "Not authorized"); return new StreamingResolution("application/json", new StringReader(json.toString(4))); } try { if (layer != null && layer.getFeatureType() != null) { FeatureSource fs; if (layer.getFeatureType().getFeatureSource() instanceof nl.b3p.viewer.config.services.ArcGISFeatureSource) { fs = layer.getFeatureType().openGeoToolsFeatureSource(); final Query q = new Query(fs.getName().toString()); setFilter(q); ArcGISFeatureReader agfr = new ArcGISFeatureReader((ArcGISFeatureSource) fs, q); List objIds = agfr.getObjectIds(); json.put("objectIds",objIds); json.put("objectIdFieldName",agfr.getObjectIdFieldName()); json.put("success",true); }else{ json.put("success",false); json.put("message","Featuresource not of correct type. Must be nl.b3p.viewer.config.services.ArcGisFeatureSource, but is " + layer.getFeatureType().getFeatureSource().getClass()); } } } catch (Exception e) { log.error("Error loading feature ids", e); json.put("success", false); String message = "Fout bij ophalen features: " + e.toString(); Throwable cause = e.getCause(); while (cause != null) { message += "; " + cause.toString(); cause = cause.getCause(); } json.put("message", message); } return new StreamingResolution("application/json", new StringReader(json.toString(4))); } private void setFilter(Query q) throws Exception { if (cql != null && cql.trim().length() > 0) { Filter f = CQL.toFilter(cql); f = (Filter) f.accept(new RemoveDistanceUnit(), null); q.setFilter(f); } } }
package ucar.nc2.iosp.mcidas; import edu.wisc.ssec.mcidas.*; import ucar.nc2.iosp.grid.*; import ucar.unidata.io.RandomAccessFile; import ucar.grid.GridIndex; import java.io.IOException; import java.util.*; /** * Read grid(s) from a McIDAS grid file */ public class McIDASGridReader { /** The file */ protected RandomAccessFile rf; /** An error message */ private String errorMessage; /** Grid index */ private GridIndex gridIndex; /** swap flag */ protected boolean needToSwap = false; /** hashMap of GridDefRecords */ private HashMap<String, McGridDefRecord> gdsMap = new HashMap<String, McGridDefRecord>(); /** * Bean ctor */ public McIDASGridReader() {} /** * Create a McIDASGrid Reader from the file * * @param filename filename * * @throws IOException problem reading file */ public McIDASGridReader(String filename) throws IOException { this(new RandomAccessFile(filename, "r", 2048)); } /** * Create a McIDASGrid Reader from the file * * @param raf RandomAccessFile * * @throws IOException problem reading file */ public McIDASGridReader(RandomAccessFile raf) throws IOException { init(raf); } /** * Initialize the file, read in all the metadata (ala DM_OPEN) * * @param raf RandomAccessFile to read. * * @throws IOException problem reading file */ public final void init(RandomAccessFile raf) throws IOException { rf = raf; raf.order(RandomAccessFile.BIG_ENDIAN); boolean ok = init(); if ( !ok) { throw new IOException("Unable to open McIDAS Grid file: " + errorMessage); } } /** * Initialize this reader. Get the Grid specific info * * @return true if successful * * @throws IOException problem reading the data */ protected boolean init() throws IOException { if (rf == null) { logError("File is null"); return false; } gridIndex = new GridIndex(); rf.order(RandomAccessFile.BIG_ENDIAN); int numEntries = Math.abs(readInt(10)); if (numEntries > 10000000) { needToSwap = true; numEntries = Math.abs(McIDASUtil.swbyt4(numEntries)); if (numEntries > 10000000) { return false; } } // System.out.println("need to Swap = " + needToSwap); // System.out.println("number entries="+numEntries); // go back to the beginning rf.seek(0); // read the fileheader String label = rf.readString(32); //System.out.println("label = " + label); int project = readInt(8); //System.out.println("Project = " + project); int date = readInt(9); //System.out.println("date = " + date); int[] entries = new int[numEntries]; for (int i = 0; i < numEntries; i++) { entries[i] = readInt(i + 11); // sanity check that this is indeed a McIDAS Grid file if (entries[i] < -1) { logError("bad grid offset " + i + ": " + entries[i]); return false; } } // Don't swap: rf.order(RandomAccessFile.BIG_ENDIAN); for (int i = 0; i < numEntries; i++) { if (entries[i] == -1) { continue; } int[] header = new int[64]; rf.seek(entries[i] * 4); rf.readInt(header, 0, 64); if (needToSwap) { swapGridHeader(header); } try { McIDASGridRecord gr = new McIDASGridRecord(entries[i], header); //if (gr.getGridDefRecordId().equals("CONF X:93 Y:65")) { //if (gr.getGridDefRecordId().equals("CONF X:54 Y:47")) { // figure out how to handle Mercator projections // if ( !(gr.getGridDefRecordId().startsWith("MERC"))) { gridIndex.addGridRecord(gr); if (gdsMap.get(gr.getGridDefRecordId()) == null) { McGridDefRecord mcdef = gr.getGridDefRecord(); //System.out.println("new nav " + mcdef.toString()); gdsMap.put(mcdef.toString(), mcdef); gridIndex.addHorizCoordSys(mcdef); } } catch (McIDASException me) { logError("problem creating grid dir"); return false; } } // check to see if there are any grids that we can handle if (gridIndex.getGridRecords().isEmpty()) { logError("no grids found"); return false; } return true; } /** * Swap the grid header, avoiding strings * * @param gh grid header to swap */ private void swapGridHeader(int[] gh) { McIDASUtil.flip(gh, 0, 5); McIDASUtil.flip(gh, 7, 7); McIDASUtil.flip(gh, 9, 10); McIDASUtil.flip(gh, 12, 14); McIDASUtil.flip(gh, 32, 51); } /** * Read the grid * * @param gr the grid record * * @return the data */ public float[] readGrid(McIDASGridRecord gr) { float[] data = null; try { int te = (gr.getOffsetToHeader() + 64) * 4; int rows = gr.getRows(); int cols = gr.getColumns(); rf.seek(te); float scale = (float) gr.getParamScale(); data = new float[rows * cols]; rf.order(needToSwap ? rf.LITTLE_ENDIAN : rf.BIG_ENDIAN); int n = 0; // store such that 0,0 is in lower left corner... for (int nc = 0; nc < cols; nc++) { for (int nr = 0; nr < rows; nr++) { int temp = rf.readInt(); // check for missing value data[(rows - nr - 1) * cols + nc] = (temp == McIDASUtil.MCMISSING) ? Float.NaN : ((float) temp) / scale; } } rf.order(rf.BIG_ENDIAN); } catch (Exception esc) { System.out.println(esc); } return data; } /** * to get the grid header corresponding to the last grid read * * @return McIDASGridDirectory of the last grid read */ public GridIndex getGridIndex() { return gridIndex; } /** * Read an integer * @param word word in file (0 based) to read * * @return int read * * @throws IOException problem reading file */ public int readInt(int word) throws IOException { if (rf == null) { throw new IOException("no file to read from"); } rf.seek(word * 4); // set the order if (needToSwap) { rf.order(RandomAccessFile.LITTLE_ENDIAN); // swap } else { rf.order(RandomAccessFile.BIG_ENDIAN); } int idata = rf.readInt(); rf.order(RandomAccessFile.BIG_ENDIAN); return idata; } /** * Log an error * * @param errMsg message to log */ private void logError(String errMsg) { errorMessage = errMsg; } /** * for testing purposes * * @param args file name * * @throws IOException problem reading file */ public static void main(String[] args) throws IOException { String file = "GRID2001"; if (args.length > 0) { file = args[0]; } McIDASGridReader mg = new McIDASGridReader(file); GridIndex gridIndex = mg.getGridIndex(); List grids = gridIndex.getGridRecords(); System.out.println("found " + grids.size() + " grids"); int num = Math.min(grids.size(), 10); for (int i = 0; i < num; i++) { System.out.println(grids.get(i)); } } }
package org.fiware.apps.marketplace.it; import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class SeleniumIT extends AbstractIT { private WebDriver driver; @Override public void specificSetUp() { driver = new FirefoxDriver(); } @After public void quitDriver() { driver.quit(); } private void registerUser(String displayName, String email, String password, String passwordConfirm) { // Access Sign Up page driver.findElement(By.cssSelector("span.text-plain")).click(); driver.findElement(By.name("displayName")).clear(); // Enter registration details driver.findElement(By.name("displayName")).sendKeys(displayName); driver.findElement(By.name("email")).clear(); driver.findElement(By.name("email")).sendKeys(email); driver.findElement(By.name("password")).clear(); driver.findElement(By.name("password")).sendKeys(password); driver.findElement(By.name("passwordConfirm")).clear(); driver.findElement(By.name("passwordConfirm")).sendKeys(passwordConfirm); driver.findElement(By.xpath("//button[@type='submit']")).click(); } private void logIn(String userNameOrMail, String password) { driver.findElement(By.name("username")).clear(); driver.findElement(By.name("username")).sendKeys(userNameOrMail); driver.findElement(By.name("password")).clear(); driver.findElement(By.name("password")).sendKeys(password); driver.findElement(By.xpath("//button[@type='submit']")).click(); } @Test public void testRegisterAndLogIn() { String displayName = "FIWARE Example"; String email = "fiware@fiware.com"; String password = "fiware1!"; // Access the URL driver.get(endPoint); registerUser(displayName, email, password, password); // When the user is properly registered, the system goes back to the log in page logIn(email, password); // Check that the user is logged in... assertThat(driver.findElement(By.id("toggle-right-sidebar")).getText()).isEqualTo(displayName); } }
package org.lightmare.utils.reflect; import org.junit.Test; public class MetaUtilsTest { @Test public void testDefaultValues() { System.out.println(MetaUtils.getDefault(byte.class)); System.out.println(MetaUtils.getDefault(boolean.class)); System.out.println(MetaUtils.getDefault(char.class)); System.out.println(MetaUtils.getDefault(short.class)); System.out.println(MetaUtils.getDefault(int.class)); } }
package fitnesse.slim; import fitnesse.slim.converters.MapEditor; import java.beans.PropertyEditorManager; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static java.lang.String.format; /** * This is the API for executing a SLIM statement. This class should not know about the syntax of a SLIM statement. */ public class StatementExecutor implements StatementExecutorInterface { private static final String SLIM_HELPER_LIBRARY_INSTANCE_NAME = "SlimHelperLibrary"; private boolean stopRequested = false; private SlimExecutionContext context; private List<MethodExecutor> executorChain = new ArrayList<MethodExecutor>(); public StatementExecutor() { this(null); } public StatementExecutor(SlimExecutionContext context) { PropertyEditorManager.registerEditor(Map.class, MapEditor.class); if (context == null) { this.context = new SlimExecutionContext(); } else { this.context = context; } executorChain.add(new FixtureMethodExecutor(this.context)); executorChain.add(new SystemUnderTestMethodExecutor(this.context)); executorChain.add(new LibraryMethodExecutor(this.context)); addSlimHelperLibraryToLibraries(); } private void addSlimHelperLibraryToLibraries() { SlimHelperLibrary slimHelperLibrary = new SlimHelperLibrary(); slimHelperLibrary.setStatementExecutor(this); context.addLibrary(new Library(SLIM_HELPER_LIBRARY_INSTANCE_NAME, slimHelperLibrary)); } @Override public Object getInstance(String instanceName) { return context.getInstance(instanceName); } @Override public void setInstance(final String actorInstanceName, final Object actor) { context.setInstance(actorInstanceName, actor); } @Override public void addPath(String path) throws SlimException { context.addPath(path); } @Override public void setVariable(String name, Object value) { context.setVariable(name, value); } @Override public void create(String instanceName, String className, Object... args) throws SlimException { try { context.create(instanceName, className, args); // TODO Hack for supporting SlimHelperLibrary, please remove. Object newInstance = context.getInstance(instanceName); if (newInstance instanceof StatementExecutorConsumer) { ((StatementExecutorConsumer) newInstance).setStatementExecutor(this); } } catch (SlimError e) { throw new SlimException(format("%s[%d]", className, args.length), e, SlimServer.COULD_NOT_INVOKE_CONSTRUCTOR, true); } catch (IllegalArgumentException e) { throw new SlimException(format("%s[%d]", className, args.length), e, SlimServer.COULD_NOT_INVOKE_CONSTRUCTOR, true); } catch (InvocationTargetException e) { throw new SlimException(e.getTargetException(), true); } catch (Throwable e) { checkExceptionForStop(e); throw new SlimException(e); } } @Override public Object call(String instanceName, String methodName, Object... args) throws SlimException { try { return getMethodExecutionResult(instanceName, methodName, args).returnValue(); } catch (Throwable e) { checkExceptionForStop(e); throw new SlimException(e); } } @Override public Object callAndAssign(String variable, String instanceName, String methodName, Object... args) throws SlimException { try { MethodExecutionResult result = getMethodExecutionResult(instanceName, methodName, args); context.setVariable(variable, result); return result.returnValue(); } catch (Throwable e) { checkExceptionForStop(e); throw new SlimException(e); } } private MethodExecutionResult getMethodExecutionResult(String instanceName, String methodName, Object... args) throws Throwable { MethodExecutionResults results = new MethodExecutionResults(); for (int i = 0; i < executorChain.size(); i++) { MethodExecutionResult result = executorChain.get(i).execute(instanceName, methodName, context.replaceSymbols(args)); if (result.hasResult()) { return result; } results.add(result); } return results.getFirstResult(); } private void checkExceptionForStop(Throwable exception) { if (exception.getClass().toString().contains("StopTest")) { stopRequested = true; } } @Override public boolean stopHasBeenRequested() { return stopRequested; } @Override public void reset() { stopRequested = false; } }
package org.apache.commons.fileupload; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; public abstract class FileUploadBase { /** * Utility method that determines whether the request contains multipart * content. * * @param req The servlet request to be evaluated. Must be non-null. * * @return <code>true</code> if the request is multipart; * <code>false</code> otherwise. */ public static final boolean isMultipartContent(HttpServletRequest req) { String contentType = req.getHeader(CONTENT_TYPE); if (contentType == null) { return false; } if (contentType.startsWith(MULTIPART)) { return true; } return false; } /** * HTTP content type header name. */ public static final String CONTENT_TYPE = "Content-type"; /** * HTTP content disposition header name. */ public static final String CONTENT_DISPOSITION = "Content-disposition"; /** * Content-disposition value for form data. */ public static final String FORM_DATA = "form-data"; /** * Content-disposition value for file attachment. */ public static final String ATTACHMENT = "attachment"; /** * Part of HTTP content type header. */ public static final String MULTIPART = "multipart/"; /** * HTTP content type header for multipart forms. */ public static final String MULTIPART_FORM_DATA = "multipart/form-data"; /** * HTTP content type header for multiple uploads. */ public static final String MULTIPART_MIXED = "multipart/mixed"; /** * The maximum length of a single header line that will be parsed * (1024 bytes). */ public static final int MAX_HEADER_SIZE = 1024; /** * The maximum size permitted for an uploaded file. A value of -1 indicates * no maximum. */ private long sizeMax = -1; /** * The content encoding to use when reading part headers. */ private String headerEncoding; /** * Returns the factory class used when creating file items. * * @return The factory class for new file items. */ public abstract FileItemFactory getFileItemFactory(); /** * Sets the factory class to use when creating file items. * * @param factory The factory class for new file items. */ public abstract void setFileItemFactory(FileItemFactory factory); /** * Returns the maximum allowed upload size. * * @return The maximum allowed size, in bytes. * * @see #setSizeMax(long) * */ public long getSizeMax() { return sizeMax; } /** * Sets the maximum allowed upload size. If negative, there is no maximum. * * @param sizeMax The maximum allowed size, in bytes, or -1 for no maximum. * * @see #getSizeMax() * */ public void setSizeMax(long sizeMax) { this.sizeMax = sizeMax; } /** * Retrieves the character encoding used when reading the headers of an * individual part. When not specified, or <code>null</code>, the platform * default encoding is used. * * @return The encoding used to read part headers. */ public String getHeaderEncoding() { return headerEncoding; } /** * Specifies the character encoding to be used when reading the headers of * individual parts. When not specified, or <code>null</code>, the platform * default encoding is used. * * @param encoding The encoding used to read part headers. */ public void setHeaderEncoding(String encoding) { headerEncoding = encoding; } public List /* FileItem */ parseRequest(HttpServletRequest req) throws FileUploadException { if (null == req) { throw new NullPointerException("req parameter"); } ArrayList items = new ArrayList(); String contentType = req.getHeader(CONTENT_TYPE); if ((null == contentType) || (!contentType.startsWith(MULTIPART))) { throw new InvalidContentTypeException( "the request doesn't contain a " + MULTIPART_FORM_DATA + " or " + MULTIPART_MIXED + " stream, content type header is " + contentType); } int requestSize = req.getContentLength(); if (requestSize == -1) { throw new UnknownSizeException( "the request was rejected because it's size is unknown"); } if (sizeMax >= 0 && requestSize > sizeMax) { throw new SizeLimitExceededException( "the request was rejected because " + "it's size exceeds allowed range"); } try { int boundaryIndex = contentType.indexOf("boundary="); if (boundaryIndex < 0) { throw new FileUploadException( "the request was rejected because " + "no multipart boundary was found"); } byte[] boundary = contentType.substring( boundaryIndex + 9).getBytes(); InputStream input = req.getInputStream(); MultipartStream multi = new MultipartStream(input, boundary); multi.setHeaderEncoding(headerEncoding); boolean nextPart = multi.skipPreamble(); while (nextPart) { Map headers = parseHeaders(multi.readHeaders()); String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = getHeader(headers, CONTENT_TYPE); if (subContentType != null && subContentType .startsWith(MULTIPART_MIXED)) { // Multiple files. byte[] subBoundary = subContentType.substring( subContentType .indexOf("boundary=") + 9).getBytes(); multi.setBoundary(subBoundary); boolean nextSubPart = multi.skipPreamble(); while (nextSubPart) { headers = parseHeaders(multi.readHeaders()); if (getFileName(headers) != null) { FileItem item = createItem(headers, false); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } items.add(item); } else { // Ignore anything but files inside // multipart/mixed. multi.discardBodyData(); } nextSubPart = multi.readBoundary(); } multi.setBoundary(boundary); } else { FileItem item = createItem(headers, getFileName(headers) == null); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } items.add(item); } } else { // Skip this part. multi.discardBodyData(); } nextPart = multi.readBoundary(); } } catch (IOException e) { throw new FileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage()); } return items; } /** * Retrieves the file name from the <code>Content-disposition</code> * header. * * @param headers A <code>Map</code> containing the HTTP request headers. * * @return The file name for the current <code>encapsulation</code>. */ protected String getFileName(Map /* String, String */ headers) { String fileName = null; String cd = getHeader(headers, CONTENT_DISPOSITION); if (cd.startsWith(FORM_DATA) || cd.startsWith(ATTACHMENT)) { int start = cd.indexOf("filename=\""); int end = cd.indexOf('"', start + 10); if (start != -1 && end != -1) { fileName = cd.substring(start + 10, end).trim(); } } return fileName; } /** * Retrieves the field name from the <code>Content-disposition</code> * header. * * @param headers A <code>Map</code> containing the HTTP request headers. * * @return The field name for the current <code>encapsulation</code>. */ protected String getFieldName(Map /* String, String */ headers) { String fieldName = null; String cd = getHeader(headers, CONTENT_DISPOSITION); if (cd != null && cd.startsWith(FORM_DATA)) { int start = cd.indexOf("name=\""); int end = cd.indexOf('"', start + 6); if (start != -1 && end != -1) { fieldName = cd.substring(start + 6, end); } } return fieldName; } /** * Creates a new {@link FileItem} instance. * * @param headers A <code>Map</code> containing the HTTP request * headers. * @param isFormField Whether or not this item is a form field, as * opposed to a file. * * @return A newly created <code>FileItem</code> instance. * * @exception FileUploadException if an error occurs. */ protected FileItem createItem(Map /* String, String */ headers, boolean isFormField) throws FileUploadException { return getFileItemFactory().createItem(getFieldName(headers), getHeader(headers, CONTENT_TYPE), isFormField, getFileName(headers)); } /** * <p> Parses the <code>header-part</code> and returns as key/value * pairs. * * <p> If there are multiple headers of the same names, the name * will map to a comma-separated list containing the values. * * @param headerPart The <code>header-part</code> of the current * <code>encapsulation</code>. * * @return A <code>Map</code> containing the parsed HTTP request headers. */ protected Map /* String, String */ parseHeaders(String headerPart) { Map headers = new HashMap(); char buffer[] = new char[MAX_HEADER_SIZE]; boolean done = false; int j = 0; int i; String header, headerName, headerValue; try { while (!done) { i = 0; // Copy a single line of characters into the buffer, // omitting trailing CRLF. while (i < 2 || buffer[i - 2] != '\r' || buffer[i - 1] != '\n') { buffer[i++] = headerPart.charAt(j++); } header = new String(buffer, 0, i - 2); if (header.equals("")) { done = true; } else { if (header.indexOf(':') == -1) { // This header line is malformed, skip it. continue; } headerName = header.substring(0, header.indexOf(':')) .trim().toLowerCase(); headerValue = header.substring(header.indexOf(':') + 1).trim(); if (getHeader(headers, headerName) != null) { // More that one heder of that name exists, // append to the list. headers.put(headerName, getHeader(headers, headerName) + ',' + headerValue); } else { headers.put(headerName, headerValue); } } } } catch (IndexOutOfBoundsException e) { // Headers were malformed. continue with all that was // parsed. } return headers; } /** * Returns the header with the specified name from the supplied map. The * header lookup is case-insensitive. * * @param headers A <code>Map</code> containing the HTTP request headers. * @param name The name of the header to return. * * @return The value of specified header, or a comma-separated list if * there were multiple headers of that name. */ protected final String getHeader(Map /* String, String */ headers, String name) { return (String) headers.get(name.toLowerCase()); } /** * Thrown to indicate that the request is not a multipart request. */ public static class InvalidContentTypeException extends FileUploadException { /** * Constructs a <code>InvalidContentTypeException</code> with no * detail message. */ public InvalidContentTypeException() { super(); } /** * Constructs an <code>InvalidContentTypeException</code> with * the specified detail message. * * @param message The detail message. */ public InvalidContentTypeException(String message) { super(message); } } /** * Thrown to indicate that the request size is not specified. */ public static class UnknownSizeException extends FileUploadException { /** * Constructs a <code>UnknownSizeException</code> with no * detail message. */ public UnknownSizeException() { super(); } /** * Constructs an <code>UnknownSizeException</code> with * the specified detail message. * * @param message The detail message. */ public UnknownSizeException(String message) { super(message); } } /** * Thrown to indicate that the request size exceeds the configured maximum. */ public static class SizeLimitExceededException extends FileUploadException { /** * Constructs a <code>SizeExceededException</code> with no * detail message. */ public SizeLimitExceededException() { super(); } /** * Constructs an <code>SizeExceededException</code> with * the specified detail message. * * @param message The detail message. */ public SizeLimitExceededException(String message) { super(message); } } }
package galileo.bmp; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import galileo.dataset.Coordinates; import galileo.dataset.Point; import galileo.dataset.SpatialRange; import galileo.util.GeoHash; public class GeoavailabilityGrid { private static final Logger logger = Logger.getLogger("galileo"); private int width, height; public Bitmap bmp = new Bitmap(); private SortedSet<Integer> pendingUpdates = new TreeSet<>(); private SpatialRange baseRange; private float xDegreesPerPixel; private float yDegreesPerPixel; public GeoavailabilityGrid(String baseGeohash, int precision) { this.baseRange = GeoHash.decodeHash(baseGeohash); /* * height, width calculated like so: * width = 2^(floor(precision / 2)) * height = 2^(ceil(precision / 2)) */ int w = precision / 2; int h = precision / 2; if (precision % 2 != 0) { h += 1; } this.width = (1 << w); this.height = (1 << h); /* Determine the number of degrees in the x and y directions for the * base spatial range this geoavailability grid represents */ float xDegrees = baseRange.getUpperBoundForLongitude() - baseRange.getLowerBoundForLongitude(); float yDegrees = baseRange.getLowerBoundForLatitude() - baseRange.getUpperBoundForLatitude(); /* Determine the number of degrees represented by each grid pixel */ xDegreesPerPixel = xDegrees / (float) this.width; yDegreesPerPixel = yDegrees / (float) this.width; if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, "Created geoavailability grid: " + "geohash={0}, precision={1}, " + "width={2}, height={3}, baseRange={6}, " + "xDegreesPerPixel={4}, yDegreesPerPixel={5}", new Object[] { baseGeohash, precision, width, height, xDegreesPerPixel, yDegreesPerPixel, baseRange}); } } /** * Adds a new point to this GeoavailabilityGrid. * * @param coords The location (coordinates in lat, lon) to add. * * @return true if the point could be added to grid, false otherwise (for * example, if the point falls outside the purview of the grid) */ public boolean addPoint(Coordinates coords) { Point<Integer> gridPoint = coordinatesToXY(coords); int index = XYtoIndex(gridPoint.X(), gridPoint.Y()); if (gridPoint.X() < 0 || gridPoint.X() >= this.width || gridPoint.Y() < 0 || gridPoint.Y() >= this.height) { return false; } if (this.bmp.set(index) == false) { /* Could not set the bits now; add to pending updates */ pendingUpdates.add(index); } return true; } /** * Converts a coordinate pair (defined with latitude, longitude in decimal * degrees) to an x, y location in the grid. * * @param coords the Coordinates to convert. * * @return Corresponding x, y location in the grid. */ public Point<Integer> coordinatesToXY(Coordinates coords) { /* Assuming (x, y) coordinates for the geoavailability grids, latitude * will decrease as y increases, and longitude will increase as x * increases. This is reflected in how we compute the differences * between the base points and the coordinates in question. */ float xDiff = coords.getLongitude() - baseRange.getLowerBoundForLongitude(); float yDiff = baseRange.getLowerBoundForLatitude() - coords.getLatitude(); int x = (int) (xDiff / xDegreesPerPixel); int y = (int) (yDiff / yDegreesPerPixel); return new Point<>(x, y); } /** * Converts X, Y coordinates to a particular index within the underlying * bitmap implementation. Essentially this converts a 2D index to a 1D * index. * * @param x The x coordinate to convert * @param y The y coorddinate to convert * * @return A single integer representing the bitmap location of the X, Y * coordinates. */ public int XYtoIndex(int x, int y) { return y * this.width + x; } /** * Converts a bitmap index to X, Y coordinates in the grid. */ public Point<Integer> indexToXY(int index) { int x = index % this.width; int y = index / this.width; return new Point<>(x, y); } /** * Converts an X, Y grid point to the corresponding SpatialRange that the * grid point spans. */ public SpatialRange XYtoSpatialRange(int x, int y) { if (x < 0 || x >= this.width || y < 0 || y >= this.height) { throw new IllegalArgumentException( "Out-of-bounds grid coordinates specified"); } float baseLon = baseRange.getLowerBoundForLongitude(); float baseLat = baseRange.getLowerBoundForLatitude(); float lowerLon = baseLon + (x * xDegreesPerPixel); float upperLon = lowerLon + xDegreesPerPixel; float lowerLat = baseLat - (y * yDegreesPerPixel); float upperLat = lowerLat - yDegreesPerPixel; return new SpatialRange(lowerLat, upperLat, lowerLon, upperLon); } /** * Converts a bitmap index location to a corresponding SpatialRange that * the indexed grid point spans. */ public SpatialRange indexToSpatialRange(int index) { Point<Integer> gridLocation = indexToXY(index); return XYtoSpatialRange(gridLocation.X(), gridLocation.Y()); } /** * Applies pending updates that have not yet been integrated into the * GeoavailabilityGrid instance. */ private void applyUpdates() { Bitmap updateBitmap = new Bitmap(); for (int i : pendingUpdates) { if (updateBitmap.set(i) == false) { logger.warning("Could not set update bit"); } } pendingUpdates.clear(); this.bmp = this.bmp.or(updateBitmap); } /** * Reports whether or not the supplied {@link GeoavailabilityQuery} * instance intersects with the bits set in this geoavailability grid. This * operation can be much faster than performing a full inspection of what * bits are actually set. * * @param query The query geometry to test for intersection. * * @return true if the supplied {@link GeoavailabilityQuery} intersects with * the data in the geoavailability grid. */ public boolean intersects(GeoavailabilityQuery query) throws BitmapException { applyUpdates(); Bitmap queryBitmap = QueryTransform.queryToGridBitmap(query, this); return this.bmp.intersects(queryBitmap); } /** * Queries the geoavailability grid, which involves performing a logical AND * operation and reporting the resulting Bitmap. * * @param query The query geometry to evaluate against the geoavailability * grid. * * @return An array of bitmap indices that matched the query. */ public int[] query(GeoavailabilityQuery query) throws BitmapException { applyUpdates(); Bitmap queryBitmap = QueryTransform.queryToGridBitmap(query, this); return this.bmp.and(queryBitmap).toArray(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } GeoavailabilityGrid g = (GeoavailabilityGrid) obj; Bitmap b1 = g.getBitmap(); Bitmap b2 = this.getBitmap(); return b1.equals(b2); } /** * Retrieves the underlying Bitmap instance backing this * GeoavailabilityGrid. */ protected Bitmap getBitmap() { applyUpdates(); return bmp; } /** * Retrieves the width of this GeoavailabilityGrid, in grid cells. */ public int getWidth() { return width; } /** * Retrieves the height of this GeoavailabilityGrid, in grid cells. */ public int getHeight() { return height; } /** * Retrieves the base SpatialRange that this GeoavailabilityGrid is * responsible for; the base range defines the geographic scope of this * GeoavailabilityGrid instance. * * @return {@link SpatialRange} representing this GeoavailabilityGrid's * scope. */ public SpatialRange getBaseRange() { return new SpatialRange(baseRange); } }
package galileo.fs; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import galileo.dataset.Block; import galileo.dataset.Coordinates; import galileo.dataset.Metadata; import galileo.dataset.SpatialProperties; import galileo.graph.FeaturePath; import galileo.graph.FeatureTypeMismatchException; import galileo.graph.MetadataGraph; import galileo.query.Query; import galileo.serialization.SerializationException; import galileo.serialization.Serializer; import galileo.util.GeoHash; import galileo.util.StackTraceToString; /** * Implements a {@link FileSystem} for Geospatial data. This file system * manager assumes that the information being stored has both space and time * properties. * <p> * Relevant system properties include * galileo.fs.GeospatialFileSystem.timeFormat and * galileo.fs.GeospatialFileSystem.geohashPrecision * to modify how the hierarchy is created. */ public class GeospatialFileSystem extends FileSystem { private static final Logger logger = Logger.getLogger("galileo"); private static final String DEFAULT_TIME_FORMAT = "yyyy/M/d"; private static final int DEFAULT_GEOHASH_PRECISION = 5; private static final String pathStore = "metadata.paths"; private MetadataGraph metadataGraph; private PathJournal pathJournal; private SimpleDateFormat timeFormatter; private String timeFormat; private int geohashPrecision; public GeospatialFileSystem(String storageDirectory) throws FileSystemException, IOException, SerializationException { super(storageDirectory); this.timeFormat = System.getProperty( "galileo.fs.GeospatialFileSystem.timeFormat", DEFAULT_TIME_FORMAT); this.geohashPrecision = Integer.parseInt(System.getProperty( "galileo.fs.GeospatialFileSystem.geohashPrecision", DEFAULT_GEOHASH_PRECISION + "")); timeFormatter = new SimpleDateFormat(); timeFormatter.applyPattern(timeFormat); pathJournal = new PathJournal(storageDirectory + "/" + pathStore); createMetadataGraph(); } /** * Initializes the Metadata Graph, either from a successful recovery from * the PathJournal, or by scanning all the {@link Block}s on disk. */ private void createMetadataGraph() throws IOException { metadataGraph = new MetadataGraph(); /* Recover the path index from the PathJournal */ List<FeaturePath<String>> graphPaths = new ArrayList<>(); boolean recoveryOk = pathJournal.recover(graphPaths); pathJournal.start(); if (recoveryOk == true) { for (FeaturePath<String> path : graphPaths) { try { metadataGraph.addPath(path); } catch (Exception e) { logger.log(Level.WARNING, "Failed to add path", e); recoveryOk = false; break; } } } if (recoveryOk == false) { logger.log(Level.SEVERE, "Failed to recover path journal!"); pathJournal.erase(); pathJournal.start(); fullRecovery(); } } @Override public String storeBlock(Block block) throws FileSystemException, IOException { String name = block.getMetadata().getName(); if (name.equals("")) { UUID blockUUID = UUID.nameUUIDFromBytes(block.getData()); name = blockUUID.toString(); } String blockDirPath = storageDirectory + "/" + getStorageDirectory(block); String blockPath = blockDirPath + "/" + name + FileSystem.BLOCK_EXTENSION; /* Ensure the storage directory is there. */ File blockDirectory = new File(blockDirPath); if (!blockDirectory.exists()) { if (!blockDirectory.mkdirs()) { throw new IOException("Failed to create directory (" + blockDirPath + ") for block."); } } FileOutputStream blockOutStream = new FileOutputStream(blockPath); byte[] blockData = Serializer.serialize(block); blockOutStream.write(blockData); blockOutStream.close(); Metadata meta = block.getMetadata(); FeaturePath<String> path = createPath(blockPath, meta); try { metadataGraph.addPath(path); } catch (Exception e) { throw new FileSystemException("Error storing block: " + e.getClass().getCanonicalName() + ":" + System.lineSeparator() + StackTraceToString.convert(e)); } return blockPath; } /** * Given a {@link Block}, determine its storage directory on disk. * * @param block The Block to inspect * * @return String representation of the directory on disk this Block should * be stored in. */ private String getStorageDirectory(Block block) { String directory = ""; Metadata meta = block.getMetadata(); Date date = meta.getTemporalProperties().getLowerBound(); directory = timeFormatter.format(date) + "/"; Coordinates coords = null; SpatialProperties spatialProps = meta.getSpatialProperties(); if (spatialProps.hasRange()) { coords = spatialProps.getSpatialRange().getCenterPoint(); } else { coords = spatialProps.getCoordinates(); } directory += GeoHash.encode(coords, geohashPrecision); return directory; } /** * Using the Feature attributes found in the provided Metadata, a * path is created for insertion into the Metadata Graph. */ protected FeaturePath<String> createPath( String physicalPath, Metadata meta) { FeaturePath<String> path = new FeaturePath<String>( physicalPath, meta.getAttributes().toArray()); System.out.println("Created path: " + path); return path; } @Override public void storeMetadata(Metadata metadata, String blockPath) throws FileSystemException, IOException { FeaturePath<String> path = createPath(blockPath, metadata); pathJournal.persistPath(path); storePath(path); } private void storePath(FeaturePath<String> path) throws FileSystemException { try { metadataGraph.addPath(path); } catch (Exception e) { throw new FileSystemException("Error storing metadata: " + e.getClass().getCanonicalName() + ":" + System.lineSeparator() + StackTraceToString.convert(e)); } } public MetadataGraph getMetadataGraph() { return metadataGraph; } public MetadataGraph query(Query query) { return metadataGraph.evaluateQuery(query); } @Override public void shutdown() { logger.info("FileSystem shutting down"); try { pathJournal.shutdown(); } catch (Exception e) { /* Everything is going down here, just print out the error */ e.printStackTrace(); } } }
package org.apache.fop.fo.flow; // FOP import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; import org.apache.fop.area.inline.ForeignObject; import org.apache.fop.area.inline.Viewport; import org.apache.fop.datatypes.Length; import org.apache.fop.fo.FONode; import org.apache.fop.fo.FObj; import org.apache.fop.fo.XMLObj; import org.apache.fop.fo.properties.DisplayAlign; import org.apache.fop.fo.properties.Overflow; import org.apache.fop.fo.properties.Scaling; import org.apache.fop.fo.properties.TextAlign; import org.apache.fop.layoutmgr.LeafNodeLayoutManager; import org.w3c.dom.Document; /** * The instream-foreign-object flow formatting object. * This is an atomic inline object that contains * xml data. */ public class InstreamForeignObject extends FObj { private Viewport areaCurrent; /** * constructs an instream-foreign-object object (called by Maker). * * @param parent the parent formatting object */ public InstreamForeignObject(FONode parent) { super(parent); } /** * Add the layout manager for this into the list. * @see org.apache.fop.fo.FObj#addLayoutManager(List) */ public void addLayoutManager(List list) { areaCurrent = getInlineArea(); if (areaCurrent != null) { LeafNodeLayoutManager lm = new LeafNodeLayoutManager(); lm.setUserAgent(getUserAgent()); lm.setFObj(this); lm.setCurrentArea(areaCurrent); lm.setAlignment(properties.get("vertical-align").getEnum()); lm.setLead(areaCurrent.getHeight()); list.add(lm); } } protected Viewport getInlineArea() { if (children == null) { return areaCurrent; } if (this.children.size() != 1) { // error return null; } FONode fo = (FONode)children.get(0); if (!(fo instanceof XMLObj)) { // error return null; } XMLObj child = (XMLObj)fo; // viewport size is determined by block-progression-dimension // and inline-progression-dimension // if replaced then use height then ignore block-progression-dimension //int h = this.properties.get("height").getLength().mvalue(); // use specified line-height then ignore dimension in height direction boolean hasLH = false;//properties.get("line-height").getSpecifiedValue() != null; Length len; int bpd = -1; int ipd = -1; boolean bpdauto = false; if (hasLH) { bpd = properties.get("line-height").getLength().getValue(); } else { // this property does not apply when the line-height applies // isn't the block-progression-dimension always in the same // direction as the line height? len = properties.get("block-progression-dimension.optimum").getLength(); if (!len.isAuto()) { bpd = len.getValue(); } else { len = properties.get("height").getLength(); if (!len.isAuto()) { bpd = len.getValue(); } } } len = properties.get("inline-progression-dimension.optimum").getLength(); if (!len.isAuto()) { ipd = len.getValue(); } else { len = properties.get("width").getLength(); if (!len.isAuto()) { ipd = len.getValue(); } } // if auto then use the intrinsic size of the content scaled // to the content-height and content-width int cwidth = -1; int cheight = -1; len = properties.get("content-width").getLength(); if (!len.isAuto()) { /*if(len.scaleToFit()) { if(ipd != -1) { cwidth = ipd; } } else {*/ cwidth = len.getValue(); } len = properties.get("content-height").getLength(); if (!len.isAuto()) { /*if(len.scaleToFit()) { if(bpd != -1) { cwidth = bpd; } } else {*/ cheight = len.getValue(); } Point2D csize = new Point2D.Float(cwidth == -1 ? -1 : cwidth / 1000f, cheight == -1 ? -1 : cheight / 1000f); Point2D size = child.getDimension(csize); if (size == null) { // error return null; } if (cwidth == -1) { cwidth = (int)size.getX() * 1000; } if (cheight == -1) { cheight = (int)size.getY() * 1000; } int scaling = properties.get("scaling").getEnum(); if (scaling == Scaling.UNIFORM) { // adjust the larger double rat1 = cwidth / (size.getX() * 1000f); double rat2 = cheight / (size.getY() * 1000f); if (rat1 < rat2) { // reduce cheight cheight = (int)(rat1 * size.getY() * 1000); } else { cwidth = (int)(rat2 * size.getX() * 1000); } } if (ipd == -1) { ipd = cwidth; } if (bpd == -1) { bpd = cheight; } boolean clip = false; if (cwidth > ipd || cheight > bpd) { int overflow = properties.get("overflow").getEnum(); if (overflow == Overflow.HIDDEN) { clip = true; } else if (overflow == Overflow.ERROR_IF_OVERFLOW) { getLogger().error("Instream foreign object overflows the viewport: clipping"); clip = true; } } int xoffset = computeXOffset(ipd, cwidth); int yoffset = computeYOffset(bpd, cheight); Rectangle2D placement = new Rectangle2D.Float(xoffset, yoffset, cwidth, cheight); Document doc = child.getDocument(); String ns = child.getDocumentNamespace(); children = null; ForeignObject foreign = new ForeignObject(doc, ns); areaCurrent = new Viewport(foreign); areaCurrent.setWidth(ipd); areaCurrent.setHeight(bpd); areaCurrent.setContentPosition(placement); areaCurrent.setClip(clip); areaCurrent.setOffset(0); return areaCurrent; } private int computeXOffset (int ipd, int cwidth) { int xoffset = 0; int ta = properties.get("text-align").getEnum(); switch (ta) { case TextAlign.CENTER: xoffset = (ipd - cwidth) / 2; break; case TextAlign.END: xoffset = ipd - cwidth; break; case TextAlign.START: break; case TextAlign.JUSTIFY: default: break; } return xoffset; } private int computeYOffset(int bpd, int cheight) { int yoffset = 0; int da = properties.get("display-align").getEnum(); switch (da) { case DisplayAlign.BEFORE: break; case DisplayAlign.AFTER: yoffset = bpd - cheight; break; case DisplayAlign.CENTER: yoffset = (bpd - cheight) / 2; break; case DisplayAlign.AUTO: default: break; } return yoffset; } /** * This flow object generates inline areas. * @see org.apache.fop.fo.FObj#generatesInlineAreas() * @return true */ public boolean generatesInlineAreas() { return true; } /* retrieve properties * int align = this.properties.get("text-align").getEnum(); int valign = this.properties.get("vertical-align").getEnum(); int overflow = this.properties.get("overflow").getEnum(); this.breakBefore = this.properties.get("break-before").getEnum(); this.breakAfter = this.properties.get("break-after").getEnum(); this.width = this.properties.get("width").getLength().mvalue(); this.height = this.properties.get("height").getLength().mvalue(); this.contwidth = this.properties.get("content-width").getLength().mvalue(); this.contheight = this.properties.get("content-height").getLength().mvalue(); this.wauto = this.properties.get("width").getLength().isAuto(); this.hauto = this.properties.get("height").getLength().isAuto(); this.cwauto = this.properties.get("content-width").getLength().isAuto(); this.chauto = this.properties.get("content-height").getLength().isAuto(); this.startIndent = this.properties.get("start-indent").getLength().mvalue(); this.endIndent = this.properties.get("end-indent").getLength().mvalue(); this.spaceBefore = this.properties.get("space-before.optimum").getLength().mvalue(); this.spaceAfter = this.properties.get("space-after.optimum").getLength().mvalue(); this.scaling = this.properties.get("scaling").getEnum(); */ }
package galileo.graph; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NavigableMap; import java.util.logging.Logger; import java.util.Map; import java.util.Queue; import java.util.Set; import galileo.dataset.feature.Feature; import galileo.dataset.feature.FeatureType; import galileo.query.Expression; import galileo.query.Operation; import galileo.query.PayloadFilter; import galileo.query.Query; import galileo.util.Pair; /** * A type-aware hierarchical graph implementation with each type occupying a * level in the hierarchy. * * @author malensek */ public class HierarchicalGraph<T> { private static final Logger logger = Logger.getLogger("galileo"); /** The root vertex. */ private Vertex<Feature, T> root = new Vertex<>(); /** Describes each level in the hierarchy. */ private Map<String, Level> levels = new HashMap<>(); /** * We maintain a separate Queue with Feature names inserted in * hierarchical order. While levels.keySet() contains the same information, * there is no contractual obligation for HashMap to return the keyset in * the original insertion order (although in practice, it probably does). */ private Queue<String> features = new LinkedList<>(); /** * Tracks information about each level in the graph hierarchy. */ private class Level { public Level(int order, FeatureType type) { this.order = order; this.type = type; } public int order; public FeatureType type; } public HierarchicalGraph() { } /** * Creates a HierarchicalGraph with a set Feature hierarchy. Features are * entered into the hierarchy in the order they are received. * * @param hierarchy Graph hierarchy represented as a * {@link FeatureHierarchy}. */ public HierarchicalGraph(FeatureHierarchy hierarchy) { for (Pair<String, FeatureType> feature : hierarchy) { getOrder(feature.a, feature.b); } } public List<Path<Feature, T>> evaluateQuery(Query query) { List<Path<Feature, T>> paths = null; for (Operation operation : query.getOperations()) { HierarchicalQueryTracker<T> tracker = new HierarchicalQueryTracker<>(root, features.size()); evaluateOperation(operation, tracker); List<Path<Feature, T>> opResult = tracker.getQueryResults(); if (paths == null) { paths = opResult; } else { paths.addAll(opResult); } } for (Path<Feature, T> path : paths) { removeNullFeatures(path); } return paths; } public List<Path<Feature, T>> evaluateQuery( Query query, PayloadFilter<T> filter) { List<Path<Feature, T>> paths = evaluateQuery(query); Iterator<Path<Feature, T>> it = paths.iterator(); while (it.hasNext()) { Path<Feature, T> path = it.next(); boolean empty = applyPayloadFilter(path, filter); if (empty) { it.remove(); } } return paths; } public void evaluateOperation(Operation operation, HierarchicalQueryTracker<T> tracker) { for (String feature : features) { tracker.nextLevel(); /* Find all expressions related to the current Feature (operand) */ List<Expression> expressions = operation.getOperand(feature); if (expressions == null) { /* No expressions deal with the current feature. Traverse all * neighbors. */ for (Path<Feature, T> path : tracker.getCurrentResults()) { Vertex<Feature, T> vertex = path.getTail(); tracker.addResults(path, vertex.getAllNeighbors()); } } else { /* Note that we are evaluating an Expression at this level */ tracker.markEvaluated(); for (Path<Feature, T> path : tracker.getCurrentResults()) { Vertex<Feature, T> vertex = path.getTail(); Collection<Vertex<Feature, T>> resultCollection = evaluateExpressions(expressions, vertex); tracker.addResults(path, resultCollection); } } } } /** * Evaluate query {@link Expression}s at a particular vertex. Neighboring * vertices that match the Expression will be traversed further. * * @param expressions List of {@link Expression}s that should be evaluated * against neighboring nodes * @param vertex {@link Vertex} to apply the Expression to. * * @return a collection of matching vertices. */ private Collection<Vertex<Feature, T>> evaluateExpressions( List<Expression> expressions, Vertex<Feature, T> vertex) { Set<Vertex<Feature, T>> resultSet = null; boolean firstResult = true; for (Expression expression : expressions) { Set<Vertex<Feature, T>> evalSet = new HashSet<>(); Feature value = expression.getValue(); switch (expression.getOperator()) { case EQUAL: { /* Select a particular neighboring vertex */ Vertex<Feature, T> equalTo = vertex.getNeighbor(value); if (equalTo == null) { /* There was no Vertex that matched the value given. */ break; } evalSet.add(equalTo); break; } case NOTEQUAL: { /* Add all the neighboring vertices, and then remove the * particular value specified. */ evalSet.addAll(vertex.getAllNeighbors()); evalSet.remove(vertex.getNeighbor(value)); break; } case LESS: { NavigableMap<Feature, Vertex<Feature, T>> neighbors = vertex.getNeighborsLessThan(value, false); removeWildcard(neighbors); evalSet.addAll(neighbors.values()); break; } case LESSEQUAL: { NavigableMap<Feature, Vertex<Feature, T>> neighbors = vertex.getNeighborsLessThan(value, true); removeWildcard(neighbors); evalSet.addAll(neighbors.values()); break; } case GREATER: { evalSet.addAll( vertex.getNeighborsGreaterThan(value, false) .values()); break; } case GREATEREQUAL: { evalSet.addAll( vertex.getNeighborsGreaterThan(value, true) .values()); break; } case UNKNOWN: default: logger.log(java.util.logging.Level.WARNING, "Invalid operator ({0}) in expression: {1}", new Object[] { expression.getOperator(), expression.toString()} ); } if (firstResult) { /* If this is the first Expression we've evaluated, then the * evaluation set becomes our result set that will be further * reduced as more Expressions are evaluated. */ resultSet = evalSet; } else { /* Remove all items from the result set that are not present in * this current evaluation set. This effectively drills down * through the results until we have our final query answer. */ resultSet.retainAll(evalSet); } } return resultSet; } /** * When a path does not contain a particular Feature, we use a null feature * (FeatureType.NULL) to act as a "wildcard" in the graph so that the path * stays linked together. The side effect of this is that 'less than' * comparisons may return wildcards, which are removed with this method. * * @param map The map to remove the first NULL element from. If the map has * no elements or the first element is not a NULL FeatureType, then no * modifications are made to the map. */ private void removeWildcard(NavigableMap<Feature, Vertex<Feature, T>> map) { Feature first = map.firstKey(); if (map.size() > 0 && first.getType() == FeatureType.NULL) { map.remove(first); } } /** * Adds a new {@link Path} to the Hierarchical Graph. */ public void addPath(Path<Feature, T> path) throws FeatureTypeMismatchException, GraphException { if (path.size() == 0) { throw new GraphException("Attempted to add empty path!"); } checkFeatureTypes(path); addNullFeatures(path); reorientPath(path); optimizePath(path); /* Ensure the path contains a payload. */ if (path.getPayload().size() == 0) { throw new GraphException("Attempted to add Path with no payload!"); } /* Place the path payload (traversal result) at the end of this path. */ path.get(path.size() - 1).addValues(path.getPayload()); root.addPath(path.iterator()); } /** * This method ensures that the Features in the path being added have the * same FeatureTypes as the current hierarchy. This ensures that different * FeatureTypes (such as an int and a double) get placed on the same level * in the hierarchy. * * @param path the Path to check for invalid FeatureTypes. * * @throws FeatureTypeMismatchException if an invalid type is found */ private void checkFeatureTypes(Path<Feature, T> path) throws FeatureTypeMismatchException { for (Feature feature : path.getLabels()) { /* If this feature is NULL, then it's effectively a wildcard. */ if (feature.getType() == FeatureType.NULL) { continue; } Level level = levels.get(feature.getName()); if (level != null) { if (level.type != feature.getType()) { throw new FeatureTypeMismatchException( "Feature insertion at graph level " + level.order + " is not possible due to a FeatureType mismatch. " + "Expected: " + level.type + ", " + "found: " + feature.getType() + "; " + "Feature: <" + feature + ">"); } } } } /** * For missing feature values, add a null feature to a path. This maintains * the graph structure for sparse schemas or cases where a feature reading * is not available. */ private void addNullFeatures(Path<Feature, T> path) { Set<String> unknownFeatures = new HashSet<>(levels.keySet()); for (Feature feature : path.getLabels()) { unknownFeatures.remove(feature.getName()); } /* Create null features for missing values */ for (String featureName : unknownFeatures) { Vertex<Feature, T> v = new Vertex<>(); v.setLabel(new Feature(featureName)); path.add(v); } } /** * Reorients a nonhierarchical path in place to match the current graph * hierarchy. */ private void reorientPath(Path<Feature, T> path) { if (path.size() == 1) { /* This doesn't need to be sorted... */ getOrder(path.get(0).getLabel()); return; } path.sort(new Comparator<Vertex<Feature, T>>() { public int compare(Vertex<Feature, T> a, Vertex<Feature, T> b) { int o2 = getOrder(b.getLabel()); int o1 = getOrder(a.getLabel()); return o1 - o2; } }); } /** * Perform optimizations on a path to reduce the number of vertices inserted * into the graph. */ private void optimizePath(Path<Feature, T> path) { /* Remove all trailing null features. During a traversal, trailing null * features are unnecessary to traverse. */ for (int i = path.size() - 1; i >= 0; --i) { if (path.get(i).getLabel().getType() == FeatureType.NULL) { path.remove(i); } else { break; } } } /** * Removes all null Features from a path. This includes any Features that * are the standard Java null, or Features with a NULL FeatureType. * * @param path Path to remove null Features from. */ private void removeNullFeatures(Path<Feature, T> path) { Iterator<Vertex<Feature, T>> it = path.iterator(); while (it.hasNext()) { Feature f = it.next().getLabel(); if (f == null || f.getType() == FeatureType.NULL) { it.remove(); } } } private boolean applyPayloadFilter(Path<Feature, T> path, PayloadFilter<T> filter) { Set<T> payload = path.getPayload(); if (filter.excludesItems() == false) { /* We only include the items in the filter */ payload.retainAll(filter.getItems()); } else { /* Excludes anything in the filter */ payload.removeAll(filter.getItems()); } return payload.isEmpty(); } /** * Determines the numeric order of a Feature based on the current * orientation of the graph. For example, humidity features may come first, * followed by temperature, etc. If the feature in question has not yet * been added to the graph, then it is connected to the current leaf nodes, * effectively placing it at the bottom of the hierarchy, and its order * number is set to the current number of feature types in the graph. * * @return int representing the list ordering of the Feature */ private int getOrder(String name, FeatureType type) { int order; Level level = levels.get(name); if (level != null) { order = level.order; } else { order = addNewFeature(name, type); } return order; } private int getOrder(Feature feature) { return getOrder(feature.getName(), feature.getType()); } /** * Update the hierarchy levels and known Feature list with a new Feature. */ private int addNewFeature(String name, FeatureType type) { logger.info("New feature: " + name + ", type: " + type); Integer order = levels.keySet().size(); levels.put(name, new Level(order, type)); features.offer(name); return order; } /** * Retrieves the ordering of Feature names in this graph hierarchy. */ public FeatureHierarchy getFeatureHierarchy() { FeatureHierarchy hierarchy = new FeatureHierarchy(); for (String feature : features) { try { hierarchy.addFeature(feature, levels.get(feature).type); } catch (GraphException e) { /* If a GraphException is thrown here, something is seriously * wrong. */ logger.severe("NULL FeatureType found in graph hierarchy!"); } } return hierarchy; } public List<Path<Feature, T>> getAllPaths() { List<Path<Feature, T>> paths = root.descendantPaths(); for (Path<Feature, T> path : paths) { removeNullFeatures(path); } return paths; } public Vertex<Feature, T> getRoot() { return root; } @Override public String toString() { return root.toString(); } }
package us.kbase.narrativejobservice.subjobs; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.SocketException; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import com.fasterxml.jackson.databind.ObjectMapper; import us.kbase.common.service.JacksonTupleModule; import us.kbase.common.service.JsonClientException; import us.kbase.common.service.JsonServerMethod; import us.kbase.common.service.JsonServerServlet; import us.kbase.common.service.JsonServerSyslog; import us.kbase.common.service.RpcContext; import us.kbase.common.service.UObject; import us.kbase.common.utils.ModuleMethod; import us.kbase.common.utils.NetUtils; import us.kbase.narrativejobservice.DockerRunner; import us.kbase.narrativejobservice.RunJobParams; import us.kbase.workspace.ProvenanceAction; import us.kbase.workspace.SubAction; public class CallbackServer extends JsonServerServlet { //TODO identical (or close to it) to kb_sdk call back server. // should probably go in java_common or make a common repo for shared // NJSW & KB_SDK code, since they're tightly coupled private static final long serialVersionUID = 1L; private final File mainJobDir; private final int callbackPort; private final Map<String, String> config; private final DockerRunner.LineLogger logger; private final ProvenanceAction prov = new ProvenanceAction(); private final static DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC(); // IMPORTANT: don't access outside synchronized block private final static Map<String, ModuleRunVersion> vers = Collections.synchronizedMap( new LinkedHashMap<String, ModuleRunVersion>()); public CallbackServer( final File mainJobDir, final int callbackPort, final Map<String, String> config, final DockerRunner.LineLogger logger, final ModuleRunVersion runver, final RunJobParams job) { super("CallbackServer"); this.mainJobDir = mainJobDir; this.callbackPort = callbackPort; this.config = config; this.logger = logger; vers.put(runver.getModuleMethod().getModule(), runver); prov.setTime(DATE_FORMATTER.print(new DateTime())); prov.setService(runver.getModuleMethod().getModule()); prov.setMethod(runver.getModuleMethod().getMethod()); prov.setDescription( "KBase SDK method run via the KBase Execution Engine"); prov.setMethodParams(job.getParams()); prov.setInputWsObjects(job.getSourceWsObjects()); prov.setServiceVer(runver.getVersionAndRelease()); initSilentJettyLogger(); } @JsonServerMethod(rpc = "CallbackServer.get_provenance") public List<ProvenanceAction> getProvenance() throws IOException, JsonClientException { /* Would be more efficient if provenance was updated online although I can't imagine this making a difference compared to serialization / transport */ final List<SubAction> sas = new LinkedList<SubAction>(); for (final ModuleRunVersion mrv: vers.values()) { sas.add(new SubAction() .withCodeUrl(mrv.getGitURL().toExternalForm()) .withCommit(mrv.getGitHash()) .withName(mrv.getModuleMethod().getModuleDotMethod()) .withVer(mrv.getVersionAndRelease())); } return new LinkedList<ProvenanceAction>(Arrays.asList( new ProvenanceAction() .withSubactions(sas) .withTime(prov.getTime()) .withService(prov.getService()) .withMethod(prov.getMethod()) .withDescription(prov.getDescription()) .withMethodParams(prov.getMethodParams()) .withInputWsObjects(prov.getInputWsObjects()) .withServiceVer(prov.getServiceVer()) )); } @JsonServerMethod(rpc = "CallbackServer.status") public UObject status() throws IOException, JsonClientException { Map<String, Object> data = new LinkedHashMap<String, Object>(); data.put("state", "OK"); return new UObject(data); } protected void processRpcCall(RpcCallData rpcCallData, String token, JsonServerSyslog.RpcInfo info, String requestHeaderXForwardedFor, ResponseStatusSetter response, OutputStream output, boolean commandLine) { System.out.println("In CallbackServer.processRpcCall"); if (rpcCallData.getMethod().startsWith("CallbackServer.")) { super.processRpcCall(rpcCallData, token, info, requestHeaderXForwardedFor, response, output, commandLine); } else { Map<String, Object> jsonRpcResponse = null; String errorMessage = null; try { final ModuleMethod modmeth = new ModuleMethod( rpcCallData.getMethod()); final SubsequentCallRunner runner = getJobRunner( rpcCallData.getContext(), modmeth); // update method name to get rid of suffixes rpcCallData.setMethod(modmeth.getModuleDotMethod()); if (modmeth.isStandard()) { System.out.println(String.format( "Warning: the callback server recieved a " + "request to synchronously run the method %s. " + "The callback server will block until the" + "method is completed.", modmeth.getModuleDotMethod())); // Run method in local docker container jsonRpcResponse = runner.run(rpcCallData); } } catch (Exception ex) { ex.printStackTrace(); errorMessage = ex.getMessage(); } try { if (jsonRpcResponse == null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (errorMessage == null) errorMessage = "Unknown server error"; Map<String, Object> error = new LinkedHashMap<String, Object>(); error.put("name", "JSONRPCError"); error.put("code", -32601); error.put("message", errorMessage); error.put("error", errorMessage); jsonRpcResponse = new LinkedHashMap<String, Object>(); jsonRpcResponse.put("version", "1.1"); jsonRpcResponse.put("error", error); } else { if (jsonRpcResponse.containsKey("error")) response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } final ObjectMapper mapper = new ObjectMapper().registerModule( new JacksonTupleModule()); mapper.writeValue(new UnclosableOutputStream(output), jsonRpcResponse); } catch (Exception ex) { ex.printStackTrace(); } } } private SubsequentCallRunner getJobRunner( final RpcContext rpcContext, final ModuleMethod modmeth) throws IOException, JsonClientException { final SubsequentCallRunner runner; synchronized(this) { final String serviceVer; if (vers.containsKey(modmeth.getModule())) { ModuleRunVersion v = vers.get(modmeth.getModule()); serviceVer = v.getGitHash(); System.out.println(String.format( "Warning: Module %s was already used once " + "for this job. Using cached " + "version:\n" + "url: %s\n" + "commit: %s\n" + "version: %s\n" + "release: %s\n", modmeth.getModule(), v.getGitURL(), v.getGitHash(), v.getVersion(), v.getRelease())); } else { serviceVer = rpcContext == null ? null : (String)rpcContext.getAdditionalProperties() .get("service_ver"); } // Request docker image name from Catalog runner = new SubsequentCallRunner( mainJobDir, modmeth, serviceVer, callbackPort, config, logger); if (!vers.containsKey(modmeth.getModule())) { vers.put(modmeth.getModule(), runner.getModuleRunVersion()); } } return runner; } public static String getCallbackUrl(int callbackPort) throws SocketException { List<String> hostIps = NetUtils.findNetworkAddresses("docker0", "vboxnet0"); String hostIp = null; if (hostIps.isEmpty()) { System.out.println("WARNING! No Docker host IP addresses was found. Subsequent local calls are not supported in test mode."); } else { hostIp = hostIps.get(0); if (hostIps.size() > 1) { System.out.println("WARNING! Several Docker host IP addresses are detected, first one is used: " + hostIp); } else { System.out.println("Docker host IP address is detected: " + hostIp); } } String callbackUrl = hostIp == null ? "" : ("http://" + hostIp + ":" + callbackPort); return callbackUrl; } public static void initSilentJettyLogger() { Log.setLog(new Logger() { @Override public void warn(String arg0, Object arg1, Object arg2) {} @Override public void warn(String arg0, Throwable arg1) {} @Override public void warn(String arg0) {} @Override public void setDebugEnabled(boolean arg0) {} @Override public boolean isDebugEnabled() { return false; } @Override public void info(String arg0, Object arg1, Object arg2) {} @Override public void info(String arg0) {} @Override public String getName() { return null; } @Override public Logger getLogger(String arg0) { return this; } @Override public void debug(String arg0, Object arg1, Object arg2) {} @Override public void debug(String arg0, Throwable arg1) {} @Override public void debug(String arg0) {} }); } private 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); } } }
package org.dellroad.stuff.spring; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.beans.factory.annotation.Autowire; /** * Indicates that the class is a candidate for configuration using the {@code ThreadConfigurableAspect} aspect. * * <p> * Works just like Spring's {@link org.springframework.beans.factory.annotation.Configurable @Configurable} annotation, * but whereas {@link org.springframework.beans.factory.annotation.Configurable @Configurable} autowires using a fixed * bean factory stored in a static variable, {@link ThreadConfigurable @ThreadConfigurable} allows the bean factory * that is used for autowiring beans to be changed on a per-thread basis, by invoking * {@link ThreadLocalBeanFactory#set ThreadLocalBeanFactory.set()} on the {@link ThreadLocalBeanFactory} * singleton instance (see {@link ThreadLocalBeanFactory#getInstance}). This allows the same * {@link ThreadConfigurable @ThreadConfigurable}-annotated beans to be instantiated and autowired by different * application contexts at the same time, where the application context chosen depends on the current thread. * </p> * * <p> * With {@link ThreadLocalBeanFactory} the configured bean factory is inherited by spawned child threads, * so typically this configuration need only be done once when starting new some process or operation, * even if that operation involves multiple threads. * </p> * * <p> * For example: * <blockquote><pre> * final BeanFactory otherBeanFactory = ... * Thread thread = new Thread() { * &#64;Override * public void run() { * ThreadLocalBeanFactory.getInstance().set(otherBeanFactory); * // now &#64;ThreadConfigurable beans will use "otherBeanFactory" for autowiring: * new SomeThreadConfigurableBean() ... * } * }; * </pre></blockquote> * * <p> * Note: to make this annotation behave like Spring's * {@link org.springframework.beans.factory.annotation.Configurable @Configurable} annotation, simply include the * {@link ThreadLocalBeanFactory} singleton instance in your bean factory: * <blockquote><pre> * &lt;bean class="org.dellroad.stuff.spring.ThreadLocalBeanFactory" factory-method="getInstance"/&gt; * </pre></blockquote> * This will set the containing bean factory as the default. This definition should be listed prior to any other * bean definitions that could result in {@link ThreadConfigurable @ThreadConfigurable}-annotated beans being * created during bean factory startup. * </p> * * <p> * Note: if a {@link ThreadConfigurable @ThreadConfigurable}-annotated bean is constructed and no bean factory * has been configured for the current thread, there is no default set either, then no configuration is performed * and a debug message is logged (to logger {@code org.dellroad.stuff.spring.ThreadConfigurableAspect}); this consistent * with the behavior of Spring's {@link org.springframework.beans.factory.annotation.Configurable @Configurable}. * </p> * * @see ThreadLocalBeanFactory */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Inherited public @interface ThreadConfigurable { /** * Configuration bean definition template name, if any. */ String value() default ""; /** * Whether and how to automatically autowire dependencies. */ Autowire autowire() default Autowire.NO; /** * Whether to enable dependency checking. */ boolean dependencyCheck() default false; /** * Whether to inject dependencies prior to constructor execution. */ boolean preConstruction() default false; }
package org.jivesoftware.messenger.launcher; import org.jdesktop.jdic.tray.SystemTray; import org.jdesktop.jdic.tray.TrayIcon; import org.jivesoftware.messenger.JiveGlobals; import org.jivesoftware.util.XMLProperties; import org.jivesoftware.util.WebManager; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.UIManager; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; /** * Graphical launcher for Jive Messenger. * * @author Matt Tucker */ public class Launcher { private Process messengerd; private String configFile = JiveGlobals.getMessengerHome() + File.separator + "conf" + File.separator + "jive-messenger.xml"; private JPanel toolbar = new JPanel(); private ImageIcon offIcon; private ImageIcon onIcon; private TrayIcon trayIcon; private JFrame frame; /** * Creates a new Launcher object. */ public Launcher() { // Initialize the SystemTray now (to avoid a bug!) final SystemTray tray = SystemTray.getDefaultSystemTray(); // Use the native look and feel. try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } String title = "Jive Messenger"; frame = new DroppableFrame() { public void fileDropped(File file) { String fileName = file.getName(); if (fileName.endsWith("*.jar")) { installPlugin(file); } } }; frame.setTitle(title); ImageIcon splash = null; JLabel splashLabel = null; // Set the icon. try { splash = new ImageIcon(getClass().getClassLoader().getResource("splash.gif")); splashLabel = new JLabel("", splash, JLabel.LEFT); onIcon = new ImageIcon(getClass().getClassLoader().getResource("messenger_on-16x16.gif")); offIcon = new ImageIcon(getClass().getClassLoader().getResource("messenger_off-16x16.gif")); frame.setIconImage(offIcon.getImage()); } catch (Exception e) { } JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); // Add buttons final JButton startButton = new JButton("Start"); startButton.setActionCommand("Start"); final JButton stopButton = new JButton("Stop"); stopButton.setActionCommand("Stop"); final JButton browserButton = new JButton("Launch Admin"); browserButton.setActionCommand("Launch Admin"); final JButton quitButton = new JButton("Quit"); quitButton.setActionCommand("Quit"); toolbar.setLayout(new GridBagLayout()); toolbar.add(startButton, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); toolbar.add(stopButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); toolbar.add(browserButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); toolbar.add(quitButton, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); if (splashLabel != null) { mainPanel.add(splashLabel, BorderLayout.CENTER); } mainPanel.add(toolbar, BorderLayout.SOUTH); // create the main menu of the system tray icon JPopupMenu menu = new JPopupMenu("Messenger Menu"); final JMenuItem showMenuItem = new JMenuItem("Hide"); showMenuItem.setActionCommand("Hide/Show"); menu.add(showMenuItem); final JMenuItem startMenuItem = new JMenuItem("Start"); startMenuItem.setActionCommand("Start"); menu.add(startMenuItem); final JMenuItem stopMenuItem = new JMenuItem("Stop"); stopMenuItem.setActionCommand("Stop"); menu.add(stopMenuItem); final JMenuItem browserMenuItem = new JMenuItem("Launch Admin"); browserMenuItem.setActionCommand("Launch Admin"); menu.add(browserMenuItem); menu.addSeparator(); final JMenuItem quitMenuItem = new JMenuItem("Quit"); quitMenuItem.setActionCommand("Quit"); menu.add(quitMenuItem); browserButton.setEnabled(false); stopButton.setEnabled(false); browserMenuItem.setEnabled(false); stopMenuItem.setEnabled(false); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { if ("Start".equals(e.getActionCommand())) { frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Adjust button and menu items. startApplication(); startButton.setEnabled(false); stopButton.setEnabled(true); startMenuItem.setEnabled(false); stopMenuItem.setEnabled(true); // Change to the "on" icon. frame.setIconImage(onIcon.getImage()); trayIcon.setIcon(onIcon); // Start a thread to enable the admin button after 8 seconds. Thread thread = new Thread() { public void run() { try { sleep(8000); } catch (Exception e) { } // Enable the Launch Admin button/menu item only if the // server has started. if (stopButton.isEnabled()) { browserButton.setEnabled(true); browserMenuItem.setEnabled(true); frame.setCursor(Cursor.getDefaultCursor()); } } }; thread.start(); } else if ("Stop".equals(e.getActionCommand())) { stopApplication(); // Change to the "off" button. frame.setIconImage(offIcon.getImage()); trayIcon.setIcon(offIcon); // Adjust buttons and menu items. frame.setCursor(Cursor.getDefaultCursor()); browserButton.setEnabled(false); startButton.setEnabled(true); stopButton.setEnabled(false); browserMenuItem.setEnabled(false); startMenuItem.setEnabled(true); stopMenuItem.setEnabled(false); } else if ("Launch Admin".equals(e.getActionCommand())) { launchBrowser(); } else if ("Quit".equals(e.getActionCommand())) { stopApplication(); System.exit(0); } else if ("Hide/Show".equals(e.getActionCommand()) || "PressAction".equals(e.getActionCommand())) { // Hide/Unhide the window if the user clicked in the system tray icon or // selected the menu option if (frame.isVisible()) { frame.setVisible(false); frame.setState(Frame.ICONIFIED); showMenuItem.setText("Show"); } else { frame.setVisible(true); frame.setState(Frame.NORMAL); showMenuItem.setText("Hide"); } } } }; // Register a listener for the radio buttons. startButton.addActionListener(actionListener); stopButton.addActionListener(actionListener); browserButton.addActionListener(actionListener); quitButton.addActionListener(actionListener); // Register a listener for the menu items. quitMenuItem.addActionListener(actionListener); browserMenuItem.addActionListener(actionListener); stopMenuItem.addActionListener(actionListener); startMenuItem.addActionListener(actionListener); showMenuItem.addActionListener(actionListener); // Set the system tray icon with the menu trayIcon = new TrayIcon(offIcon, "Jive Messenger", menu); trayIcon.setIconAutoSize(true); trayIcon.addActionListener(actionListener); tray.addTrayIcon(trayIcon); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { stopApplication(); System.exit(0); } public void windowIconified(WindowEvent e) { // Make the window disappear when minimized frame.setVisible(false); showMenuItem.setText("Show"); } }); frame.getContentPane().add(mainPanel); frame.pack(); // frame.setSize(539,418); frame.setResizable(false); GraphicUtils.centerWindowOnScreen(frame); frame.setVisible(true); // Start the app. startButton.doClick(); } /** * Creates a new GUI launcher instance. */ public static void main(String[] args) { new Launcher(); } private synchronized void startApplication() { if (messengerd == null) { try { File windowsExe = new File(new File("").getAbsoluteFile(), "messengerd.exe"); File unixExe = new File(new File("").getAbsoluteFile(), "messengerd"); if (windowsExe.exists()) { messengerd = Runtime.getRuntime().exec(new String[]{windowsExe.toString()}); } else if (unixExe.exists()) { messengerd = Runtime.getRuntime().exec(new String[]{unixExe.toString()}); } else { throw new FileNotFoundException(); } } catch (Exception e) { // Try one more time using the jar and hope java is on the path try { File libDir = new File("../lib").getAbsoluteFile(); messengerd = Runtime.getRuntime().exec(new String[]{ "java", "-jar", new File(libDir, "startup.jar").toString() }); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Launcher could not start,\nJive Messenger", "File not found", JOptionPane.ERROR_MESSAGE); } } } } private synchronized void stopApplication() { if (messengerd != null) { try { messengerd.destroy(); messengerd.waitFor(); } catch (Exception e) { e.printStackTrace(); } } messengerd = null; } private synchronized void launchBrowser() { try { XMLProperties props = new XMLProperties(configFile); String port = props.getProperty("adminConsole.port"); BrowserLauncher.openURL("http://127.0.0.1:" + port + "/index.html"); } catch (Exception e) { JOptionPane.showMessageDialog(new JFrame(), configFile + " " + e.getMessage()); } } private void installPlugin(final File plugin) { final JDialog dialog = new JDialog(frame, "Installing Plugin", true); dialog.getContentPane().setLayout(new BorderLayout()); JProgressBar bar = new JProgressBar(); bar.setIndeterminate(true); bar.setString("Installing Plugin. Please wait..."); bar.setStringPainted(true); dialog.getContentPane().add(bar, BorderLayout.CENTER); dialog.pack(); dialog.setSize(225, 55); final SwingWorker installerThread = new SwingWorker() { public Object construct() { File pluginsDir = new File(JiveGlobals.getMessengerHome(), "plugins"); String tempName = plugin.getName() + ".part"; File tempPluginsFile = new File(pluginsDir, tempName); File realPluginsFile = new File(pluginsDir, plugin.getName()); // Copy Plugin into Dir. try { WebManager.copy(plugin.toURL(), tempPluginsFile); // If successfull, rename to real plugin name. tempPluginsFile.renameTo(realPluginsFile); } catch (IOException e) { e.printStackTrace(); } return realPluginsFile; } public void finished() { dialog.setVisible(false); } }; // Start installation installerThread.start(); } }
package org.jivesoftware.wildfire.group; import org.jivesoftware.util.*; import org.jivesoftware.wildfire.XMPPServer; import org.jivesoftware.wildfire.event.GroupEventDispatcher; import org.jivesoftware.wildfire.event.GroupEventListener; import org.jivesoftware.wildfire.user.User; import org.jivesoftware.wildfire.user.UserManager; import org.jivesoftware.wildfire.user.UserNotFoundException; import org.xmpp.packet.JID; import java.util.Collection; import java.util.Collections; import java.util.Map; /** * Manages groups. * * @see Group * @author Matt Tucker */ public class GroupManager { Cache<String, Group> groupCache; Cache<String, Object> groupMetaCache; private GroupProvider provider; private static GroupManager instance = new GroupManager(); private static final String GROUP_COUNT_KEY = "GROUP_COUNT"; private static final String SHARED_GROUPS_KEY = "SHARED_GROUPS"; private static final String GROUP_NAMES_KEY = "GROUP_NAMES"; /** * Returns a singleton instance of GroupManager. * * @return a GroupManager instance. */ public static GroupManager getInstance() { return instance; } private GroupManager() { // Initialize caches. groupCache = CacheManager.initializeCache("Group", "group", 1024 * 1024, JiveConstants.MINUTE*15); // A cache for meta-data around groups: count, group names, groups associated with // a particular user groupMetaCache = CacheManager.initializeCache("Group Metadata Cache", "groupMeta", 512 * 1024, JiveConstants.MINUTE*15); // Load a group provider. String className = JiveGlobals.getXMLProperty("provider.group.className", "org.jivesoftware.wildfire.group.DefaultGroupProvider"); try { Class c = ClassUtils.forName(className); provider = (GroupProvider) c.newInstance(); } catch (Exception e) { Log.error("Error loading group provider: " + className, e); provider = new DefaultGroupProvider(); } GroupEventDispatcher.addListener(new GroupEventListener() { public void groupCreated(Group group, Map params) { groupMetaCache.clear(); } public void groupDeleting(Group group, Map params) { groupMetaCache.clear(); } public void groupModified(Group group, Map params) { String type = (String)params.get("type"); // If shared group settings changed, expire the cache. if (type != null && (type.equals("propertyModified") || type.equals("propertyDeleted") || type.equals("propertyAdded"))) { if (params.get("propertyKey") != null && params.get("propertyKey").equals("sharedRoster.showInRoster")) { groupMetaCache.clear(); } } } public void memberAdded(Group group, Map params) { groupMetaCache.clear(); } public void memberRemoved(Group group, Map params) { groupMetaCache.clear(); } public void adminAdded(Group group, Map params) { groupMetaCache.clear(); } public void adminRemoved(Group group, Map params) { groupMetaCache.clear(); } }); // Pre-load shared groups. This will provide a faster response // time to the first client that logs in. // TODO: use a task engine instead of creating a thread directly. Runnable task = new Runnable() { public void run() { Collection<Group> groups = getSharedGroups(); // Load each group into cache. for (Group group : groups) { // Load each user in the group into cache. for (JID jid : group.getMembers()) { try { if (XMPPServer.getInstance().isLocal(jid)) { UserManager.getInstance().getUser(jid.getNode()); } } catch (UserNotFoundException unfe) { // Ignore. } } } } }; Thread thread = new Thread(task); thread.setDaemon(true); thread.start(); } /** * Factory method for creating a new Group. A unique name is the only required field. * * @param name the new and unique name for the group. * @return a new Group. * @throws GroupAlreadyExistsException if the group name already exists in the system. */ public Group createGroup(String name) throws GroupAlreadyExistsException { synchronized (name.intern()) { Group newGroup; try { getGroup(name); // The group already exists since now exception, so: throw new GroupAlreadyExistsException(); } catch (GroupNotFoundException unfe) { // The group doesn't already exist so we can create a new group newGroup = provider.createGroup(name); // Update caches. groupCache.put(name, newGroup); // Fire event. GroupEventDispatcher.dispatchEvent(newGroup, GroupEventDispatcher.EventType.group_created, Collections.emptyMap()); } return newGroup; } } /** * Returns a Group by name. * * @param name The name of the group to retrieve * @return The group corresponding to that name * @throws GroupNotFoundException if the group does not exist. */ public Group getGroup(String name) throws GroupNotFoundException { Group group = groupCache.get(name); // If ID wan't found in cache, load it up and put it there. if (group == null) { synchronized (name.intern()) { group = groupCache.get(name); // If group wan't found in cache, load it up and put it there. if (group == null) { group = provider.getGroup(name); groupCache.put(name, group); } } } return group; } /** * Deletes a group from the system. * * @param group the group to delete. */ public void deleteGroup(Group group) { // Fire event. GroupEventDispatcher.dispatchEvent(group, GroupEventDispatcher.EventType.group_deleting, Collections.emptyMap()); // Delete the group. provider.deleteGroup(group.getName()); // Expire cache. groupCache.remove(group.getName()); } /** * Deletes a user from all the groups where he/she belongs. The most probable cause * for this request is that the user has been deleted from the system. * * TODO: remove this method and use events instead. * * @param user the deleted user from the system. */ public void deleteUser(User user) { JID userJID = XMPPServer.getInstance().createJID(user.getUsername(), null); for (Group group : getGroups(userJID)) { if (group.getAdmins().contains(userJID)) { if (group.getAdmins().remove(userJID)) { // Remove the group from cache. groupCache.remove(group.getName()); } } else { if (group.getMembers().remove(userJID)) { // Remove the group from cache. groupCache.remove(group.getName()); } } } } /** * Returns the total number of groups in the system. * * @return the total number of groups. */ public int getGroupCount() { Integer count = (Integer)groupMetaCache.get(GROUP_COUNT_KEY); if (count == null) { synchronized(GROUP_COUNT_KEY.intern()) { count = (Integer)groupMetaCache.get(GROUP_COUNT_KEY); if (count == null) { count = provider.getGroupCount(); groupMetaCache.put(GROUP_COUNT_KEY, count); } } } return count; } /** * Returns an unmodifiable Collection of all groups in the system. * * @return an unmodifiable Collection of all groups. */ public Collection<Group> getGroups() { Collection<String> groupNames = (Collection<String>)groupMetaCache.get(GROUP_NAMES_KEY); if (groupNames == null) { synchronized(GROUP_NAMES_KEY.intern()) { groupNames = (Collection<String>)groupMetaCache.get(GROUP_NAMES_KEY); if (groupNames == null) { groupNames = provider.getGroupNames(); groupMetaCache.put(GROUP_NAMES_KEY, groupNames); } } } return new GroupCollection(groupNames); } /** * Returns an unmodifiable Collection of all shared groups in the system. * * @return an unmodifiable Collection of all shared groups. */ public Collection<Group> getSharedGroups() { Collection<String> groupNames = (Collection<String>)groupMetaCache.get(SHARED_GROUPS_KEY); if (groupNames == null) { synchronized(SHARED_GROUPS_KEY.intern()) { groupNames = (Collection<String>)groupMetaCache.get(SHARED_GROUPS_KEY); if (groupNames == null) { groupNames = Group.getSharedGroupsNames(); groupMetaCache.put(SHARED_GROUPS_KEY, groupNames); } } } return new GroupCollection(groupNames); } /** * Returns all groups given a start index and desired number of results. This is * useful to support pagination in a GUI where you may only want to display a certain * number of results per page. It is possible that the number of results returned will * be less than that specified by numResults if numResults is greater than the number * of records left in the system to display. * * @param startIndex start index in results. * @param numResults number of results to return. * @return an Iterator for all groups in the specified range. */ public Collection<Group> getGroups(int startIndex, int numResults) { String key = GROUP_NAMES_KEY + startIndex + "," + numResults; Collection<String> groupNames = (Collection<String>)groupMetaCache.get(key); if (groupNames == null) { synchronized(key.intern()) { groupNames = (Collection<String>)groupMetaCache.get(key); if (groupNames == null) { groupNames = provider.getGroupNames(startIndex, numResults); groupMetaCache.put(key, groupNames); } } } return new GroupCollection(groupNames); } /** * Returns an iterator for all groups that the User is a member of. * * @param user the user. * @return all groups the user belongs to. */ public Collection<Group> getGroups(User user) { return getGroups(XMPPServer.getInstance().createJID(user.getUsername(), null)); } /** * Returns an iterator for all groups that the entity with the specified JID is a member of. * * @param user the JID of the entity to get a list of groups for. * @return all groups that an entity belongs to. */ public Collection<Group> getGroups(JID user) { String key = user.toBareJID(); Collection<String> groupNames = (Collection<String>)groupMetaCache.get(key); if (groupNames == null) { synchronized(key.intern()) { groupNames = (Collection<String>)groupMetaCache.get(key); if (groupNames == null) { groupNames = provider.getGroupNames(user); groupMetaCache.put(key, groupNames); } } } return new GroupCollection(groupNames); } /** * Returns true if groups are read-only. * * @return true if groups are read-only. */ public boolean isReadOnly() { return provider.isReadOnly(); } /** * Returns true if searching for groups is supported. * * @return true if searching for groups are supported. */ public boolean isSearchSupported() { return provider.isSearchSupported(); } /** * Returns the groups that match the search. The search is over group names and * implicitly uses wildcard matching (although the exact search semantics are left * up to each provider implementation). For example, a search for "HR" should match * the groups "HR", "HR Department", and "The HR People".<p> * * Before searching or showing a search UI, use the {@link #isSearchSupported} method * to ensure that searching is supported. * * @param query the search string for group names. * @return all groups that match the search. */ public Collection<Group> search(String query) { Collection<String> groupNames = provider.search(query); return new GroupCollection(groupNames); } /** * Returns the groups that match the search given a start index and desired number * of results. The search is over group names and implicitly uses wildcard matching * (although the exact search semantics are left up to each provider implementation). * For example, a search for "HR" should match the groups "HR", "HR Department", and * "The HR People".<p> * * Before searching or showing a search UI, use the {@link #isSearchSupported} method * to ensure that searching is supported. * * @param query the search string for group names. * @return all groups that match the search. */ public Collection<Group> search(String query, int startIndex, int numResults) { Collection<String> groupNames = provider.search(query, startIndex, numResults); return new GroupCollection(groupNames); } /** * Returns the configured group provider. Note that this method has special access * privileges since only a few certain classes need to access the provider directly. * * @return the group provider. */ public GroupProvider getProvider() { return provider; } }
package ru.pro.iterator; import org.junit.Test; import java.util.Arrays; import java.util.Iterator; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class TestConvertIt { /** * Method is whenSetIterator. */ @Test public void whenSetIterator() { Iterator<Integer> it1 = Arrays.asList(1, 2).iterator(); Iterator<Integer> it2 = Arrays.asList(3, 4).iterator(); Iterator<Iterator<Integer>> it = Arrays.asList(it1, it2).iterator(); Iterator<Integer> convertresult = new ConvertIt().convert(it); Iterator<Integer> expect = Arrays.asList(1, 2, 3, 4).iterator(); if (convertresult.hasNext()) { assertThat(convertresult.next(), is(expect.next())); } } /** * Method is whenSetIterator2. */ @Test public void whenSetIterator2() { Iterator<Integer> it1 = Arrays.asList(4, 2, 0, 4, 6, 4, 9).iterator(); Iterator<Integer> it2 = Arrays.asList(0, 9, 8, 7, 5).iterator(); Iterator<Integer> it3 = Arrays.asList(1, 3, 5, 6, 7, 0, 9, 8, 4).iterator(); Iterator<Iterator<Integer>> it = Arrays.asList(it1, it2, it3).iterator(); Iterator<Integer> testData = Arrays.asList(4, 2, 0, 4, 6, 4, 9, 0, 9, 8, 7, 5, 1, 3, 5, 6, 7, 0, 9, 8, 4).iterator(); ConvertIt iter = new ConvertIt(); Iterator<Integer> result = iter.convert(it); if (result.hasNext()) { assertThat(result.next(), is(testData.next())); } } }
// File: $Id$ import ibis.ipl.*; import java.util.Properties; import java.util.Random; import java.io.IOException; interface OpenConfig { static final boolean slowStart = true; static final boolean tracePortCreation = false; static final boolean traceCommunication = false; static final boolean showProgress = true; static final boolean showBoard = false; static final boolean traceClusterResizing = true; static final int DEFAULTBOARDSIZE = 3000; static final int GENERATIONS = 1000; static final int SHOWNBOARDWIDTH = 60; static final int SHOWNBOARDHEIGHT = 30; } class RszHandler implements OpenConfig, ResizeHandler { private int members = 0; private IbisIdentifier prev = null; public void join( IbisIdentifier id ) { if( traceClusterResizing ){ System.out.println( "Machine " + id.name() + " joins the computation" ); } if( id.equals( OpenCell1D.ibis.identifier() ) ){ // Hey! That's me. Now I know my member number and my left // neighbour. OpenCell1D.me = members; OpenCell1D.leftNeighbour = prev; if( traceClusterResizing ){ String who = "no"; if( OpenCell1D.leftNeighbour != null ){ who = OpenCell1D.leftNeighbour.name() + " as"; } System.out.println( "P" + OpenCell1D.me + ": that's me! I have " + who + " left neighbour" ); } } else if( prev != null && prev.equals( OpenCell1D.ibis.identifier() ) ){ // The next one after me. Now I know my right neighbour. OpenCell1D.rightNeighbour = id; if( traceClusterResizing ){ System.out.println( "P" + OpenCell1D.me + ": that's my right neighbour" ); } } members++; prev = id; } public void leave( IbisIdentifier id ) { if( traceClusterResizing ){ System.out.println( "Leave of " + id.name() ); } members } public void delete( IbisIdentifier id ) { if( traceClusterResizing ){ System.out.println( "Delete of " + id ); } members } public void reconfigure() { if( traceClusterResizing ){ System.out.println( "Reconfigure" ); } } public synchronized int getMemberCount() { return members; } } class OpenCell1D implements OpenConfig { static Ibis ibis; static Registry registry; static IbisIdentifier leftNeighbour; static IbisIdentifier rightNeighbour; static IbisIdentifier myName; static int me = -1; static SendPort leftSendPort; static SendPort rightSendPort; static ReceivePort leftReceivePort; static ReceivePort rightReceivePort; static int generation; /** The first column that is my responsibility. */ static int firstColumn = -1; /** The first column that is no longer my responsibility. */ static int firstNoColumn = -1; private static void usage() { System.out.println( "Usage: OpenCell1D [-size <int>] [count]" ); System.exit( 0 ); } /** * Creates an update send port that connected to the specified neighbour. * @param updatePort The type of the port to construct. * @param dest The destination processor. * @param prefix The prefix of the port names. */ private static SendPort createNeighbourSendPort( PortType updatePort, IbisIdentifier dest, String prefix ) throws java.io.IOException { String sendportname = prefix + "Send" + myName.name(); String receiveportname = prefix + "Receive" + dest.name(); SendPort res = updatePort.createSendPort( sendportname ); if( tracePortCreation ){ System.out.println( myName.name() + ": created send port " + sendportname ); } ReceivePortIdentifier id = registry.lookup( receiveportname ); res.connect( id ); if( tracePortCreation ){ System.out.println( myName.name() + ": connected " + sendportname + " to " + receiveportname ); } return res; } /** * Creates an update receive port. * @param updatePort The type of the port to construct. * @param prefix The prefix of the port names. */ private static ReceivePort createNeighbourReceivePort( PortType updatePort, String prefix ) throws java.io.IOException { String receiveportname = prefix + "Receive" + myName.name(); ReceivePort res = updatePort.createReceivePort( receiveportname ); if( tracePortCreation ){ System.out.println( myName.name() + ": created receive port " + receiveportname ); } res.enableConnections(); return res; } private static byte horTwister[][] = { { 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0 }, }; private static byte vertTwister[][] = { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 1, 0 }, { 0, 1, 0 }, { 0, 0, 0 }, }; private static byte horTril[][] = { { 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0 }, { 0, 1, 0, 0, 1, 0 }, { 0, 0, 1, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, }; private static byte vertTril[][] = { { 0, 0, 0, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0 }, }; private static byte glider[][] = { { 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0 }, }; /** * Puts the given pattern at the given coordinates. * Since we want the pattern to be readable, we take the first * row of the pattern to be the at the top. */ static protected void putPattern( byte board[][], int px, int py, byte pat[][] ) { for( int y=pat.length-1; y>=0; y byte paty[] = pat[y]; for( int x=0; x<paty.length; x++ ){ board[px+x][py+y] = paty[x]; } } } /** * Returns true iff the given pattern occurs at the given * coordinates. */ static protected boolean hasPattern( byte board[][], int px, int py, byte pat[][ ] ) { for( int y=pat.length-1; y>=0; y byte paty[] = pat[y]; for( int x=0; x<paty.length; x++ ){ if( board[px+x][py+y] != paty[x] ){ return false; } } } return true; } // Put a twister (a bar of 3 cells) at the given center cell. static protected void putTwister( byte board[][], int x, int y ) { putPattern( board, x-2, y-1, horTwister ); } // Given a position, return true iff there is a twister in hor or // vertical position at that point. static protected boolean hasTwister( byte board[][], int x, int y ) { return hasPattern( board, x-2, y-1, horTwister ) || hasPattern( board, x-1, y-2, vertTwister ); } private static void send( SendPort p, byte data[] ) throws java.io.IOException { if( traceCommunication ){ System.out.println( myName.name() + ": sending from port " + p ); } WriteMessage m = p.newMessage(); m.writeInt( OpenCell1D.generation ); m.writeInt( firstColumn ); m.writeInt( firstNoColumn ); m.writeInt( 0 ); // # of shipped columns m.writeArray( data ); m.send(); m.finish(); } private static void receive( ReceivePort p, byte data[] ) throws java.io.IOException { if( traceCommunication ){ System.out.println( myName.name() + ": receiving on port " + p ); } ReadMessage m = p.receive(); int gen = m.readInt(); int firstCol = m.readInt(); int lastCol = m.readInt(); int shippedCol = m.readInt(); m.readArray( data ); m.finish(); } public static void main( String [] args ) { int count = GENERATIONS; int boardsize = DEFAULTBOARDSIZE; int rank = 0; int remoteRank = 1; boolean noneSer = false; RszHandler rszHandler = new RszHandler(); int knownMembers = 0; /* Parse commandline parameters. */ for( int i=0; i<args.length; i++ ){ if( args[i].equals( "-size" ) ){ i++; boardsize = Integer.parseInt( args[i] ); } else { if( count == -1 ){ count = Integer.parseInt( args[i] ); } else { usage(); } } } try { myName = ibis.identifier(); StaticProperties s = new StaticProperties(); s.add( "serialization", "data" ); s.add( "communication", "OneToOne, Reliable, AutoUpcalls, ExplicitReceipt" ); s.add( "worldmodel", "open" ); ibis = Ibis.createIbis( s, rszHandler ); ibis.openWorld(); registry = ibis.registry(); // TODO: be more precise about the properties for the two // port types. PortType updatePort = ibis.createPortType( "neighbour update", s ); PortType loadbalancePort = ibis.createPortType( "loadbalance", s ); leftSendPort = null; rightSendPort = null; leftReceivePort = null; rightReceivePort = null; // Wait until I know my processor number (and also // my left neighbour). // TODO: use a more subtle approach than this. while( me<0 ){ Thread.sleep( 10 ); } if( leftNeighbour != null ){ leftReceivePort = createNeighbourReceivePort( updatePort, "upstream" ); } if( rightNeighbour != null ){ rightReceivePort = createNeighbourReceivePort( updatePort, "downstream" ); } if( leftNeighbour != null ){ leftSendPort = createNeighbourSendPort( updatePort, leftNeighbour, "downstream" ); } if( rightNeighbour != null ){ rightSendPort = createNeighbourSendPort( updatePort, rightNeighbour, "upstream" ); } int myColumns = 0; if( leftNeighbour == null ){ // I'm the leftmost node, I start with the entire board. // Workstealing will spread the load to other processors later // TODO: do something smarter at startup. myColumns = boardsize; firstColumn = 0; firstNoColumn = boardsize; } // The Life board. byte board[][] = new byte[myColumns+2][boardsize+2]; // We need two extra column arrays to temporarily store the update // of a column. These arrays will be circulated with the columns of // the board. byte updatecol[] = new byte[boardsize+2]; byte nextupdatecol[] = new byte[boardsize+2]; putTwister( board, 100, 3 ); putPattern( board, 4, 4, glider ); if( me == 0 ){ System.out.println( "Started" ); } long startTime = System.currentTimeMillis(); for( generation=0; generation<count; generation++ ){ byte prev[]; byte curr[] = board[0]; byte next[] = board[1]; if( showBoard && leftNeighbour == null ){ System.out.println( "Generation " + generation ); for( int y=1; y<SHOWNBOARDHEIGHT; y++ ){ for( int x=1; x<SHOWNBOARDWIDTH; x++ ){ System.out.print( board[x][y] ); } System.out.println(); } } for( int i=1; i<=myColumns; i++ ){ prev = curr; curr = next; next = board[i+1]; for( int j=1; j<=boardsize; j++ ){ int neighbours = prev[j-1] + prev[j] + prev[j+1] + curr[j-1] + curr[j+1] + next[j-1] + next[j] + next[j+1]; boolean alive = (neighbours == 3) || ((neighbours == 2) && (board[i][j]==1)); updatecol[j] = alive?(byte) 1:(byte) 0; } byte tmp[] = board[i]; board[i] = updatecol; updatecol = nextupdatecol; nextupdatecol = tmp; } if( (me % 2) == 0 ){ if( leftSendPort != null ){ send( leftSendPort, board[1] ); } if( rightSendPort != null ){ send( rightSendPort, board[myColumns] ); } if( leftReceivePort != null ){ receive( leftReceivePort, board[0] ); } if( rightReceivePort != null ){ receive( rightReceivePort, board[myColumns+1] ); } } else { if( rightReceivePort != null ){ receive( rightReceivePort, board[myColumns+1] ); } if( leftReceivePort != null ){ receive( leftReceivePort, board[0] ); } if( rightSendPort != null ){ send( rightSendPort, board[myColumns] ); } if( leftSendPort != null ){ send( leftSendPort, board[1] ); } } if( showProgress ){ if( leftNeighbour == null ){ System.out.print( '.' ); } } } if( showProgress ){ if( leftNeighbour == null ){ System.out.println(); } } if( !hasTwister( board, 100, 3 ) ){ System.out.println( "Twister has gone missing" ); } if( leftNeighbour == null ){ long endTime = System.currentTimeMillis(); double time = ((double) (endTime - startTime))/1000.0; long updates = boardsize*boardsize*(long) count; System.out.println( "ExecutionTime: " + time ); System.out.println( "Did " + updates + " updates" ); } ibis.end(); } catch( Exception e ) { System.out.println( "Got exception " + e ); System.out.println( "StackTrace:" ); e.printStackTrace(); } } }
package at.ac.tuwien.inso.view.pdf; import com.lowagie.text.BadElementException; import com.lowagie.text.Cell; import com.lowagie.text.Chunk; import com.lowagie.text.Document; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.Paragraph; import com.lowagie.text.Table; import com.lowagie.text.pdf.PdfWriter; import org.springframework.web.servlet.view.document.AbstractPdfView; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import at.ac.tuwien.inso.entity.Grade; public class GradePDFView extends AbstractPdfView { private static final Font TITLE_FONT = FontFactory.getFont(FontFactory.HELVETICA, 30); private static final Font SMALL_FONT = FontFactory.getFont(FontFactory.HELVETICA, 8); private static final Paragraph EMPTY_LINE = new Paragraph(" "); @Override protected void buildPdfDocument(Map<String, Object> map, Document document, PdfWriter pdfWriter, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { Grade grade = (Grade) map.get("grade"); String validationLink = (String) map.get("validationLink"); document.add(generateTitle()); document.add(EMPTY_LINE); document.add(generateContent(grade)); document.add(EMPTY_LINE); document.add(generateValidation(validationLink)); } private Paragraph generateTitle() { Paragraph title = new Paragraph(new Chunk(generateTitleString(), TITLE_FONT)); title.setAlignment(Element.ALIGN_CENTER); return title; } private String generateTitleString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Grade certificate"); return stringBuilder.toString(); } private Paragraph generateContent(Grade grade) throws BadElementException { Paragraph content = new Paragraph(); Table table = createTable(grade); content.add(table); return content; } private Table createTable(Grade grade) throws BadElementException { Table table = new Table(3); table = setTableOptions(table); Cell name = new Cell(); name.setColspan(3); name.add(new Paragraph("Name: ", SMALL_FONT)); name.add(new Paragraph(grade.getStudent().getName())); Cell course = new Cell(); course.setColspan(3); course.add(new Paragraph("Course: ", SMALL_FONT)); course.add(new Paragraph(grade.getCourse().getSubject().getName())); Cell semester = new Cell(); semester.add(new Paragraph("Semester: ", SMALL_FONT)); semester.add(new Paragraph(grade.getCourse().getSemester().getLabel())); Cell ects = new Cell(); ects.add(new Paragraph("ECTS-Credits", SMALL_FONT)); ects.add(new Paragraph(grade.getCourse().getSubject().getEcts().toPlainString())); Cell note = new Cell(); note.add(new Paragraph("Note: ", SMALL_FONT)); note.add(new Paragraph(grade.getMark().getMark() + "")); Cell lecturer = new Cell(); lecturer.setColspan(3); lecturer.add(new Paragraph("Lecturer: ", SMALL_FONT)); lecturer.add(new Paragraph(grade.getLecturer().getName())); table.addCell(name); table.addCell(course); table.addCell(semester); table.addCell(ects); table.addCell(note); table.addCell(lecturer); return table; } private Table setTableOptions(Table table) { table.setTableFitsPage(true); table.setCellsFitPage(true); table.setPadding(4); return table; } private Paragraph generateValidation(String validationLink) { Paragraph validation = new Paragraph(generateValidationString(validationLink), SMALL_FONT); return validation; } private String generateValidationString(String validationLink) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("This is an automatically generated document. "); stringBuilder.append("The document is valid without a signature. "); stringBuilder.append("To validate the document, please go to: "); stringBuilder.append(validationLink); return stringBuilder.toString(); } }
package be.isach.samaritan.command; import net.dv8tion.jda.entities.MessageChannel; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; class CommandTweet extends Command { /** * Command Constructor. * * @param messageChannel The text Channel where command is called. * @param commandData The Command Data, providing the Guild, the executor and the Samaritan instance. * @param args The args provided when command was called. */ CommandTweet(MessageChannel messageChannel, CommandData commandData, String[] args) { super(messageChannel, commandData, args); } /** * Called when command is executed. * * @param args Arguments provided by user. */ @Override void onExecute(String[] args) { Twitter twitter = TwitterFactory.getSingleton(); try { Status status = twitter.updateStatus(buildStringFromArgs()); String url = "https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId(); getMessageChannel().sendMessage("I tweeted:\n`" + buildStringFromArgs() + "`\nsuccessfully on the account: @" + twitter.getScreenName() + "\n\nTweet Link: " + url); } catch (TwitterException e) { getMessageChannel().sendMessage("Oh, something went wrong. (" + e.getMessage()); } } }
package br.gov.mj.sislegis.app.model; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.collections.CollectionUtils; import br.gov.mj.sislegis.app.enumerated.Origem; import br.gov.mj.sislegis.app.model.pautacomissao.ProposicaoPautaComissao; import br.gov.mj.sislegis.app.rest.serializers.CompactSetProposicaoSerializer; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @Entity //@formatter:off @NamedNativeQueries({ @NamedNativeQuery( name = "getAllProposicoesSeguidas", query = "SELECT * " + "FROM Proposicao a where a.id in (select distinct proposicoesSeguidas_id from Usuario_ProposicaoSeguida)", resultClass=Proposicao.class ), @NamedNativeQuery( name = "listFromReuniao", query="SELECT * FROM Proposicao p where p.id in (select proposicao_id from reuniaoproposicao r where r.reuniao_id=:rid)", resultClass=Proposicao.class ) }) @NamedQueries({ @NamedQuery( name = "findByUniques", query = "select p from Proposicao p where p.idProposicao=:idProposicao and p.origem=:origem") }) //@formatter:on @XmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class Proposicao extends AbstractEntity { private static final long serialVersionUID = 7949894944142814382L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(nullable = false, unique = true) private Integer idProposicao; @Column private String tipo; @Column private String ano; @Column private String numero; @Column private String situacao; @Column private String autor; @Enumerated(EnumType.STRING) @Column private Origem origem; @Column(length = 2000) private String resultadoASPAR; @Column(name = "ultima_comissao") private String comissao; @Transient private Integer seqOrdemPauta; @Transient private String sigla; @Column(length = 2000) private String ementa; @Column private String linkProposicao; @Transient private String linkPauta; @Transient private Posicionamento posicionamento; @Transient private Boolean posicionamentoPreliminar; @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.MERGE) private Usuario responsavel; @OneToMany(fetch = FetchType.EAGER, mappedBy = "proposicao") @OrderBy("pautaReuniaoComissao") private SortedSet<ProposicaoPautaComissao> pautasComissoes = new TreeSet<ProposicaoPautaComissao>(); @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE) @JoinTable(name = "tagproposicao", joinColumns = { @JoinColumn(name = "proposicao_id", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "tag_id", referencedColumnName = "id") }) private List<Tag> tags; @Transient private List<Comentario> listaComentario = new ArrayList<>(); @Transient private Set<EncaminhamentoProposicao> listaEncaminhamentoProposicao = new HashSet<>(); @Transient private List<ProposicaoPautaComissao> listaPautasComissao = new ArrayList<>(); @Column(nullable = false) private boolean isFavorita; @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }, mappedBy = "proposicao") @OrderBy("data ASC") private SortedSet<AlteracaoProposicao> alteracoesProposicao = new TreeSet<AlteracaoProposicao>(); @Transient private Integer totalComentarios = 0; @Transient private Integer totalEncaminhamentos = 0; @Transient private Integer totalPautasComissao = 0; @ManyToMany(fetch = FetchType.EAGER, mappedBy = "proposicoesFilha") private Set<Proposicao> proposicoesPai; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "proposicao_proposicao", joinColumns = { @JoinColumn(name = "proposicao_id") }, inverseJoinColumns = { @JoinColumn(name = "proposicao_id_filha") }) private Set<Proposicao> proposicoesFilha; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "proposicao_elaboracao_normativa", joinColumns = { @JoinColumn(name = "proposicao_id") }, inverseJoinColumns = { @JoinColumn(name = "elaboracao_normativa_id") }) private Set<ElaboracaoNormativa> elaboracoesNormativas; public String getSigla() { if (Objects.isNull(sigla)) sigla = getTipo() + " " + getNumero() + "/" + getAno(); return sigla; } public void setSigla(String sigla) { this.sigla = sigla; } public Long getId() { return this.id; } public void setId(final Long id) { this.id = id; } public Integer getIdProposicao() { return idProposicao; } public void setIdProposicao(Integer idProposicao) { this.idProposicao = idProposicao; } public String getTipo() { if (tipo != null && !tipo.isEmpty()) { tipo = tipo.trim(); } return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public String getAno() { return ano; } public void setAno(String ano) { this.ano = ano; } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } public String getEmenta() { return ementa; } public void setEmenta(String ementa) { this.ementa = ementa; } public String getAutor() { return autor; } public void setAutor(String autor) { this.autor = autor; } public String getComissao() { if (comissao == null || comissao.length() == 0) { if (!pautasComissoes.isEmpty()) { // para algumas proposicoes da camara o campo com dados da // por exemplo: return pautasComissoes.first().getPautaReuniaoComissao().getComissao(); } } return comissao; } public void setComissao(String comissao) { this.comissao = comissao; } public Integer getSeqOrdemPauta() { return seqOrdemPauta; } public void setSeqOrdemPauta(Integer seqOrdemPauta) { this.seqOrdemPauta = seqOrdemPauta; } public Origem getOrigem() { return origem; } public void setOrigem(Origem origem) { this.origem = origem; } public String getLinkProposicao() { if (origem == null) { return null; } switch (origem) { case CAMARA: return "http://www2.camara.leg.br/proposicoesWeb/fichadetramitacao?idProposicao=" + getIdProposicao(); case SENADO: return "http: default: break; } return linkProposicao; } public void setLinkProposicao(String linkProposicao) { this.linkProposicao = linkProposicao; } public String getLinkPauta() { return linkPauta; } public void setLinkPauta(String linkPauta) { this.linkPauta = linkPauta; } public Posicionamento getPosicionamento() { return posicionamento; } public void setPosicionamento(Posicionamento posicionamento) { this.posicionamento = posicionamento; } public Boolean isPosicionamentoPreliminar() { return posicionamentoPreliminar; } public void setPosicionamentoPreliminar(Boolean posicionamentoPreliminar) { this.posicionamentoPreliminar = posicionamentoPreliminar; } public List<Comentario> getListaComentario() { return this.listaComentario; } public void setListaComentario(final List<Comentario> listaComentario) { this.listaComentario = listaComentario; } public Set<EncaminhamentoProposicao> getListaEncaminhamentoProposicao() { return listaEncaminhamentoProposicao; } public void setListaEncaminhamentoProposicao(Set<EncaminhamentoProposicao> listaEncaminhamentoProposicao) { this.listaEncaminhamentoProposicao = listaEncaminhamentoProposicao; } public List<Tag> getTags() { return tags; } public void setTags(List<Tag> tags) { this.tags = tags; } public List<ProposicaoPautaComissao> getListaPautasComissao() { return listaPautasComissao; } public void setListaPautasComissao(List<ProposicaoPautaComissao> listaPautasComissao) { this.listaPautasComissao = listaPautasComissao; } public Usuario getResponsavel() { return responsavel; } public void setResponsavel(Usuario responsavel) { this.responsavel = responsavel; } public String getResultadoASPAR() { return resultadoASPAR; } public void setResultadoASPAR(String resultadoASPAR) { this.resultadoASPAR = resultadoASPAR; } public boolean isFavorita() { return isFavorita; } public void setFavorita(boolean isFavorita) { this.isFavorita = isFavorita; } public Integer getTotalComentarios() { if (CollectionUtils.isNotEmpty(listaComentario)) { totalComentarios = listaComentario.size(); } return totalComentarios; } public void setTotalComentarios(Integer totalComentarios) { this.totalComentarios = totalComentarios; } public Integer getTotalEncaminhamentos() { if (CollectionUtils.isNotEmpty(listaEncaminhamentoProposicao)) { totalEncaminhamentos = listaEncaminhamentoProposicao.size(); } return totalEncaminhamentos; } public void setTotalEncaminhamentos(Integer totalEncaminhamentos) { this.totalEncaminhamentos = totalEncaminhamentos; } public Integer getTotalPautasComissao() { if (CollectionUtils.isNotEmpty(listaPautasComissao)) { totalPautasComissao = listaPautasComissao.size(); } return totalPautasComissao; } public void setTotalPautasComissao(Integer totalPautasComissao) { this.totalPautasComissao = totalPautasComissao; } @JsonSerialize(using = CompactSetProposicaoSerializer.class) public Set<Proposicao> getProposicoesPai() { return proposicoesPai; } @JsonSerialize(using = CompactSetProposicaoSerializer.class) public Set<Proposicao> getProposicoesFilha() { return proposicoesFilha; } public void setProposicoesPai(Set<Proposicao> proposicoesPai) { this.proposicoesPai = proposicoesPai; } public void setProposicoesFilha(Set<Proposicao> proposicoesFilha) { this.proposicoesFilha = proposicoesFilha; } public Set<ElaboracaoNormativa> getElaboracoesNormativas() { return elaboracoesNormativas; } public void setElaboracoesNormativas(Set<ElaboracaoNormativa> elaboracoesNormativas) { this.elaboracoesNormativas = elaboracoesNormativas; } @JsonIgnore public Set<AlteracaoProposicao> getAlteracoesProposicao() { return alteracoesProposicao; } @JsonIgnore public AlteracaoProposicao getLastAlteracoesProposicao() { return alteracoesProposicao.last(); } @Override public String toString() { String result = getClass().getSimpleName() + " "; result += "idProposicao: " + idProposicao; result += ", tipo: " + tipo; result += ", ano: " + ano; result += ", numero: " + numero; if (autor != null && !autor.trim().isEmpty()) result += ", autor: " + autor; if (comissao != null && !comissao.trim().isEmpty()) result += ", comissao: " + comissao; if (seqOrdemPauta != null) result += ", seqOrdemPauta: " + seqOrdemPauta; if (situacao != null) result += ", situacao: " + situacao; return result; } public void addAlteracao(AlteracaoProposicao altera) { altera.setProposicao(this); alteracoesProposicao.add(altera); } public String getSituacao() { return situacao; } public void setSituacao(String siglaSituacao) { this.situacao = siglaSituacao; } @JsonIgnore public SortedSet<ProposicaoPautaComissao> getPautasComissoes() { return pautasComissoes; } public ProposicaoPautaComissao getPautaComissaoAtual() { // TODO isto pode ficar melhor. ProposicaoPautaComissao mostRecent = null; for (Iterator<ProposicaoPautaComissao> iterator = pautasComissoes.iterator(); iterator.hasNext();) { ProposicaoPautaComissao ppc = (ProposicaoPautaComissao) iterator.next(); if (mostRecent == null || mostRecent.getPautaReuniaoComissao().getData().before(ppc.getPautaReuniaoComissao().getData())) { mostRecent = ppc; } } return mostRecent; } }
package org.jetel.data.parser; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.io.SAXContentHandler; import org.jetel.component.RecordTransform; import org.jetel.data.DataField; import org.jetel.data.DataRecord; import org.jetel.data.StringDataField; import org.jetel.data.sequence.Sequence; import org.jetel.data.xml.mapping.XMLMappingConstants; import org.jetel.data.xml.mapping.XMLMappingContext; import org.jetel.data.xml.mapping.parser.XMLMappingDefinitionParseException; import org.jetel.data.xml.mapping.parser.XMLMappingDefinitionParser; import org.jetel.data.xml.mapping.parser.XMLMappingDefinitionParser.XMLMappingParseResult; import org.jetel.data.xml.mapping.runtime.XMLElementRuntimeMappingModel; import org.jetel.data.xml.mapping.runtime.XMLElementRuntimeMappingModel.AncestorFieldMapping; import org.jetel.data.xml.mapping.runtime.factory.RuntimeMappingModelFactory; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.JetelException; import org.jetel.exception.JetelRuntimeException; import org.jetel.exception.TransformException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.OutputPort; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldMetadata; import org.jetel.util.AutoFilling; import org.jetel.util.ExceptionUtils; import org.jetel.util.XmlUtils; import org.jetel.util.file.FileUtils; import org.jetel.util.formatter.DateFormatter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.helpers.DefaultHandler; public class XmlSaxParser { private static final String FEATURES_DELIMETER = ";"; private static final String FEATURES_ASSIGN = ":="; public static final String XML_USE_PARENT_RECORD = "useParentRecord"; public static final String XML_IMPLICIT = "implicit"; public static final String XML_ELEMENT = "element"; public static final String XML_OUTPORT = "outPort"; public static final String XML_PARENTKEY = "parentKey"; public static final String XML_GENERATEDKEY = "generatedKey"; public static final String XML_XMLFIELDS = "xmlFields"; public static final String XML_INPUTFIELDS = "inputFields"; public static final String XML_INPUTFIELD = "inputField"; public static final String XML_OUTPUTFIELD = "outputField"; public static final String XML_CLOVERFIELDS = "cloverFields"; public static final String XML_SEQUENCEFIELD = "sequenceField"; public static final String XML_SEQUENCEID = "sequenceId"; public static final String XML_TEMPLATE_ID = "templateId"; public static final String XML_TEMPLATE_REF = "templateRef"; public static final String XML_TEMPLATE_DEPTH = "nestedDepth"; private static final Log logger = LogFactory.getLog(XmlSaxParser.class); protected TransformationGraph graph; protected Node parentComponent; protected String mapping; protected String mappingURL = null; private boolean useNestedNodes = true; private boolean trim = true; private boolean validate; private String xmlFeatures; // Map of elementName => output port protected Map<String, XMLElementRuntimeMappingModel> m_elementPortMap = new HashMap<String, XMLElementRuntimeMappingModel>(); // protected TreeMap<String, XmlElementMapping> declaredTemplates = new TreeMap<String, XmlElementMapping>(); private DataRecord inputRecord; /** * Namespace bindings relate namespace prefix used in Mapping specification and the namespace URI used by the * namespace declaration in processed XML document */ private HashMap<String, String> namespaceBindings = new HashMap<String, String>(); // global skip and numRecords private int skipRows = 0; // do not skip rows by default private int numRecords = -1; private AutoFilling autoFilling = new AutoFilling(); protected SAXParser parser; protected SAXHandler saxHandler; private NodeList mappingNodes; public XmlSaxParser(TransformationGraph graph, Node parentComponent) { this(graph, parentComponent,(String)null); } public XmlSaxParser(TransformationGraph graph, Node parentComponent, String mapping) { this.graph = graph; this.parentComponent = parentComponent; this.mapping = mapping; } public XmlSaxParser(TransformationGraph graph, Node parentComponent, SAXParser saxParser){ this(graph, parentComponent,(String)null); this.parser = saxParser; } public void init() throws ComponentNotReadyException { augmentNamespaceURIs(); URL projectURL = graph != null ? graph.getRuntimeContext().getContextURL() : null; // prepare mapping if (mappingURL != null) { try { ReadableByteChannel ch = FileUtils.getReadableChannel(projectURL, mappingURL); Document doc = XmlUtils.createDocumentFromChannel(ch); Element rootElement = doc.getDocumentElement(); mappingNodes = rootElement.getChildNodes(); } catch (Exception e) { throw new ComponentNotReadyException(e); } } else if (mapping != null) { Document doc; try { doc = XmlUtils.createDocumentFromString(mapping); } catch (JetelException e) { throw new ComponentNotReadyException(e); } Element rootElement = doc.getDocumentElement(); mappingNodes = rootElement.getChildNodes(); } // iterate over 'Mapping' elements // declaredTemplates.clear(); String errorPrefix = parentComponent.getId() + ": Mapping error - "; for (int i = 0; i < mappingNodes.getLength(); i++) { org.w3c.dom.Node node = mappingNodes.item(i); List<String> errors = processMappings(graph, node); for (String error : errors) { logger.warn(errorPrefix + error); } } if (m_elementPortMap.size() < 1) { throw new ComponentNotReadyException(parentComponent.getId() + ": At least one mapping has to be defined. Absence of mapping can be caused by invalid mapping definition. Check for warnings in log above. Mapping example: <Mapping element=\"elementToMatch\" outPort=\"123\" [parentKey=\"key in parent\" generatedKey=\"new foreign key in target\"]/>"); } // create new sax factory & parser (if not already passed in) if (parser == null) { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(validate); initXmlFeatures(factory, xmlFeatures); // TODO: try { parser = factory.newSAXParser(); } catch (Exception ex) { throw new ComponentNotReadyException(ex); } } saxHandler = new SAXHandler(getXmlElementMappingValues()); try { // this is required to handle events for CDATA sections, processing instructions and entities parser.setProperty("http://xml.org/sax/properties/lexical-handler", saxHandler); } catch (SAXNotRecognizedException e) { throw new ComponentNotReadyException("Lexical Handler not supported", e); } catch (SAXNotSupportedException e) { throw new ComponentNotReadyException("Lexical Handler not supported", e); } } public void reset() { } /** * Set external SAX parser to be used for parsing XML data instead of the defaul one. * * @param parser a SAX parser */ public void setParser(SAXParser parser){ this.parser=parser; } public void parse(InputSource inputSource) throws JetelException, SAXException { try { parser.parse(inputSource, saxHandler); } catch (IOException e) { // reasonable error reporting - get record number on which parsing. This should likely be implemented on // Node level! throw new JetelException(getParseErrorMessage(), e); } catch (SAXException e) { // reasonable error reporting - get record number on which parsing. This should likely be implemented on // Node level! logger.error(getParseErrorMessage()); throw e; } } private String getParseErrorMessage() { String message = "Unexpected XML parsing exception"; InputPort inputPort = parentComponent.getInputPort(0); if (inputPort != null) { message += " on record #" + inputPort.getInputRecordCounter(); } return message; } protected OutputPort getOutputPort(int outPortIndex) { return parentComponent.getOutputPort(outPortIndex); } protected XMLMappingContext createMappingContext() { XMLMappingContext context = new XMLMappingContext(); context.setAutoFilling(autoFilling); context.setGraph(graph); context.setParentComponent(parentComponent); context.setNamespaceBindings(namespaceBindings); return context; } /** * Parses a mapping definition and creates a runtime mapping model. * * @param graph * - graph to be used as a mapping context * @param nodeXML * - XML to be parsed * @return list of error messages */ public List<String> processMappings(TransformationGraph graph, org.w3c.dom.Node nodeXML) { if (nodeXML.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { XMLMappingContext context = createMappingContext(); context.setGraph(graph); // parse the mapping definition XMLMappingDefinitionParser mappingParser = new XMLMappingDefinitionParser(context); mappingParser.init(); XMLMappingParseResult<?> mappingResult; try { mappingResult = mappingParser.parseMapping(nodeXML); } catch (XMLMappingDefinitionParseException e) { return Collections.singletonList(ExceptionUtils.getMessage(e)); } if (!mappingResult.isSuccessful()) { return mappingResult.getErrors(); } RuntimeMappingModelFactory factory = new RuntimeMappingModelFactory(context); // build runtime mapping model addMapping(factory.createRuntimeMappingModel(mappingResult.getMapping())); } return Collections.emptyList(); } private static int performMapping(RecordTransform transformation, DataRecord inRecord, DataRecord outRecord, String errMessage) { try { return transformation.transform(new DataRecord[] { inRecord }, new DataRecord[] { outRecord }); } catch (Exception exception) { try { return transformation.transformOnError(exception, new DataRecord[] { inRecord }, new DataRecord[] { outRecord }); } catch (TransformException e) { throw new JetelRuntimeException(errMessage, e); } } } public void applyInputFieldTransformation(RecordTransform transformation, DataRecord record) { // no input available if (inputRecord == null) { return; } performMapping(transformation, inputRecord, record, "Input field transformation failed"); } public void setMapping(String mapping) { this.mapping = mapping; } public void setMappingURL(String mappingURL) { this.mappingURL = mappingURL; } public boolean isTrim() { return trim; } public void setTrim(boolean trim) { this.trim = trim; } public void setGraph(TransformationGraph graph) { this.graph = graph; } public boolean isUseNestedNodes() { return useNestedNodes; } public void setUseNestedNodes(boolean useNestedNodes) { this.useNestedNodes = useNestedNodes; } /** * Sets skipRows - how many elements to skip. * * @param skipRows */ public void setSkipRows(int skipRows) { this.skipRows = skipRows; } /** * Sets numRecords - how many elements to process. * * @param numRecords */ public void setNumRecords(int numRecords) { this.numRecords = Math.max(numRecords, 0); } /** * Accessor to add a mapping programatically. */ public void addMapping(XMLElementRuntimeMappingModel mapping) { m_elementPortMap.put(mapping.getElementName(), mapping); } /** * SAX Handler that will dispatch the elements to the different ports. */ protected class SAXHandler extends SAXContentHandler { private String CHARS_CDATA_START = "<!CDATA["; private String CHARS_CDATA_END = "]]>"; // depth of the element, used to determine when we hit the matching // close element private int m_level = 0; // flag set if we saw characters, otherwise don't save the column (used // to set null values) private boolean m_hasCharacters = false; // flag to skip text value immediately after end xml tag, for instance // <root> // <subtag>text</subtag> // another text // </root> // "another text" will be ignored private boolean m_grabCharacters = true; // buffer for node value private StringBuilder m_characters = new StringBuilder(); private List<CharacterBufferMarker> m_elementContentStartIndexStack = new ArrayList<CharacterBufferMarker>(); // the active mapping private XMLElementRuntimeMappingModel m_activeMapping = null; private Set<String> cloverAttributes; /** * This is needed to know whether to escape entities in output characters or not. Entities in CDATA should not * be escaped while entities in attribute values or characters should be escaped. */ private boolean in_cdata = false; /** * Status flag to know whether the subtree should be concatenated into m_characters. It is also used to identify * when to generate output. */ private boolean m_element_as_text = false; /** * @param cloverAttributes */ public SAXHandler(Set<String> cloverAttributes) { super(); this.cloverAttributes = cloverAttributes; } /** * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, * org.xml.sax.Attributes) */ @Override public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes attributes) throws SAXException { m_level++; m_grabCharacters = true; // store value of parent of currently starting element (if appropriate) if (m_activeMapping != null && m_hasCharacters && m_level == m_activeMapping.getLevel() + 1) { if (m_activeMapping.getDescendantReferences().containsKey(XMLMappingConstants.ELEMENT_VALUE_REFERENCE)) { m_activeMapping.getDescendantReferences().put(XMLMappingConstants.ELEMENT_VALUE_REFERENCE, getCurrentValue()); } if (!m_activeMapping.isCharactersProcessed()) { processCharacters(null, null, true); m_activeMapping.setCharactersProcessed(true); //clear all character markers - all should be processed or we do not need them for(int i=this.m_elementContentStartIndexStack.size()-1;i>=0; i if(this.m_elementContentStartIndexStack.get(i).type == CharacterBufferMarkerType.CHARACTERS_START || this.m_elementContentStartIndexStack.get(i).type == CharacterBufferMarkerType.CHARACTERS_END) { m_elementContentStartIndexStack.remove(i); } } } } final String universalName = augmentURI(namespaceURI) + localName; XMLElementRuntimeMappingModel mapping = null; if (m_activeMapping == null) { mapping = (XMLElementRuntimeMappingModel) m_elementPortMap.get(universalName); // CL-2053 - backward compatibility (part 1/2) if (mapping == null) { mapping = (XMLElementRuntimeMappingModel) m_elementPortMap.get("{}" + localName); } } else if (useNestedNodes || m_activeMapping.getLevel() == m_level - 1) { mapping = (XMLElementRuntimeMappingModel) m_activeMapping.getChildMapping(universalName); // CL-2053 - backward compatibility (part 2/2) if (mapping == null) { mapping = (XMLElementRuntimeMappingModel) m_activeMapping.getChildMapping("{}" + localName); } } if (mapping != null) { // We have a match, start converting all child nodes into // the DataRecord structure m_activeMapping = mapping; m_activeMapping.setLevel(m_level); m_activeMapping.setCharactersProcessed(false); // clear cached values of xml fields referenced by descendants (there may be values from previously read // element of this m_activemapping) for (Entry<String, String> e : m_activeMapping.getDescendantReferences().entrySet()) { e.setValue(null); } if (mapping.getOutputRecord() != null) { if (mapping.getFieldTransformation() != null) { applyInputFieldTransformation(mapping.getFieldTransformation(), mapping.getOutputRecord()); } // sequence fields initialization String sequenceFieldName = m_activeMapping.getSequenceField(); if (sequenceFieldName != null && m_activeMapping.getOutputRecord().hasField(sequenceFieldName)) { Sequence sequence = m_activeMapping.getSequence(); DataField sequenceField = m_activeMapping.getOutputRecord().getField(sequenceFieldName); if (sequenceField.getType() == DataFieldMetadata.INTEGER_FIELD) { sequenceField.setValue(sequence.nextValueInt()); } else if (sequenceField.getType() == DataFieldMetadata.LONG_FIELD || sequenceField.getType() == DataFieldMetadata.DECIMAL_FIELD || sequenceField.getType() == DataFieldMetadata.NUMERIC_FIELD) { sequenceField.setValue(sequence.nextValueLong()); } else { sequenceField.fromString(sequence.nextValueString()); } } m_activeMapping.prepareDoMap(); m_activeMapping.incCurrentRecord4Mapping(); // This is the closing element of the matched element that // triggered the processing // That should be the end of this record so send it off to the // next Node if (parentComponent.runIt()) { try { DataRecord outRecord = m_activeMapping.getOutputRecord(); String[] generatedKey = m_activeMapping.getGeneratedKeyFields(); String[] parentKey = m_activeMapping.getParentKeyFields(); if (parentKey != null) { // if generatedKey is a single array, all parent keys are concatenated into generatedKey // field // I know it is ugly code... if (generatedKey.length != parentKey.length && generatedKey.length != 1) { logger.warn(parentComponent.getId() + ": XML Extract Mapping's generatedKey and parentKey attribute has different number of field."); m_activeMapping.setGeneratedKeyFields(null); m_activeMapping.setParentKeyFields(null); } else { XMLElementRuntimeMappingModel parentKeyFieldsMapping = m_activeMapping.getParent(); while (parentKeyFieldsMapping != null && parentKeyFieldsMapping.getOutputRecord() == null) { parentKeyFieldsMapping = parentKeyFieldsMapping.getParent(); } for (int i = 0; i < parentKey.length; i++) { boolean existGeneratedKeyField = (outRecord != null) && (generatedKey.length == 1 ? outRecord.hasField(generatedKey[0]) : outRecord.hasField(generatedKey[i])); boolean existParentKeyField = parentKeyFieldsMapping != null && parentKeyFieldsMapping.getOutputRecord().hasField(parentKey[i]); if (!existGeneratedKeyField) { logger.warn(parentComponent.getId() + ": XML Extract Mapping's generatedKey field was not found. generatedKey: " + (generatedKey.length == 1 ? generatedKey[0] : generatedKey[i]) + " of element " + m_activeMapping.getElementName() + ", outPort: " + m_activeMapping.getOutputPortNumber()); m_activeMapping.setGeneratedKeyFields(null); m_activeMapping.setParentKeyFields(null); } else if (!existParentKeyField) { logger.warn(parentComponent.getId() + ": XML Extract Mapping's parentKey field was not found. parentKey: " + parentKey[i] + " of element " + m_activeMapping.getElementName() + ", outPort: " + m_activeMapping.getOutputPortNumber()); m_activeMapping.setGeneratedKeyFields(null); m_activeMapping.setParentKeyFields(null); } else { // both outRecord and m_activeMapping.getParrent().getOutRecord are not null // here, because of if-else if-else chain DataField generatedKeyField = generatedKey.length == 1 ? outRecord.getField(generatedKey[0]) : outRecord.getField(generatedKey[i]); DataField parentKeyField = parentKeyFieldsMapping.getOutputRecord().getField(parentKey[i]); if (generatedKey.length != parentKey.length) { if (generatedKeyField.getType() != DataFieldMetadata.STRING_FIELD) { logger.warn(parentComponent.getId() + ": XML Extract Mapping's generatedKey field has to be String type (keys are concatened to this field)."); m_activeMapping.setGeneratedKeyFields(null); m_activeMapping.setParentKeyFields(null); } else { ((StringDataField) generatedKeyField).append(parentKeyField.toString()); } } else { generatedKeyField.setValue(parentKeyField.getValue()); } } } } } } catch (Exception ex) { String portNumber = "" + m_activeMapping.getOutputPortNumber(); if(m_activeMapping.isUsingParentRecord()) { portNumber = "" + m_activeMapping.getProducingParent().getOutputPortNumber(); } throw new SAXException(" for output port number '" + portNumber + "' element '"+m_activeMapping.getElementName()+"'. Check also parent mapping. ", ex); } // Fill fields from parent record (if any mapped) if (m_activeMapping.hasFieldsFromAncestor()) { for (AncestorFieldMapping afm : m_activeMapping.getFieldsFromAncestor()) { if (m_activeMapping.getOutputRecord().hasField(afm.getCurrentField()) && afm.getAncestor() != null) { m_activeMapping.getOutputRecord().getField(afm.getCurrentField()).fromString(afm.getAncestor().getDescendantReferences().get(afm.getAncestorField())); } } } } else { throw new SAXException("Stop Signaled"); } } } boolean grabElement = false; // Extract Element As Text - append element name; only when whole element should be extracted (including // tags) or when we are already within the element if ((m_element_as_text && (m_activeMapping==null || m_level >= m_activeMapping.getLevel())) || (m_activeMapping!=null && m_activeMapping.getFieldsMap().containsKey(XMLMappingConstants.ELEMENT_AS_TEXT) && m_level == m_activeMapping.getLevel())) { //logger.trace("startElement(" + qualifiedName + "): storing element name; m_element_as_text"); // Starting new subtree mapping if (m_activeMapping!=null && m_activeMapping.getFieldsMap().containsKey(XMLMappingConstants.ELEMENT_AS_TEXT) && m_level == m_activeMapping.getLevel()) { this.m_elementContentStartIndexStack.add(new CharacterBufferMarker(CharacterBufferMarkerType.SUBTREE_WITH_TAG_START, m_characters.length(), m_level)); }; m_characters.append("<").append(localName); grabElement = true; } // Extract Element As Text - start mapping of the subtree as a text // may be not in the right place - fix if (m_activeMapping != null && (m_activeMapping.getFieldsMap().containsKey(XMLMappingConstants.ELEMENT_CONTENTS_AS_TEXT) || m_activeMapping.getFieldsMap().containsKey(XMLMappingConstants.ELEMENT_AS_TEXT))) { m_element_as_text = true; m_hasCharacters = true; } else if (!m_element_as_text) { // Regardless of starting element type, reset the length of the buffer and flag // logger.trace("startElement(" + qualifiedName + "): cleaning m_characters; !m_element_as_text"); m_characters.setLength(0); this.m_elementContentStartIndexStack.clear(); m_hasCharacters = false; } if (m_activeMapping != null // used only if we right now recognize new mapping element or if we want to use // nested unmapped nodes as a source of data && (useNestedNodes || mapping != null)) { // In a matched element (i.e. we are creating a DataRecord) // Store all attributes as columns (this hasn't been // used/tested) for (int i = 0; i < attributes.getLength(); i++) { final String attributeLocalName = attributes.getLocalName(i); String attrName = augmentURI(attributes.getURI(i)) + attributeLocalName; if (m_activeMapping.getDescendantReferences().containsKey(attrName)) { String val = attributes.getValue(i); m_activeMapping.getDescendantReferences().put(attrName, trim ? val.trim() : val); } // use fields mapping final Map<String, String> xmlCloverMap = m_activeMapping.getFieldsMap(); String fieldName = null; if (xmlCloverMap != null) { if (xmlCloverMap.containsKey(attrName)) { fieldName = xmlCloverMap.get(attrName); } else if (m_activeMapping.getExplicitCloverFields().contains(attrName)) { continue; // don't do implicit mapping if clover field is used in an explicit mapping } else if (m_activeMapping.getSequenceField()!=null && (m_activeMapping.getSequenceField().equals(attributeLocalName)||m_activeMapping.getSequenceField().equals(attrName))) { continue; //don't do implicit mapping for fields mapped to sequence } } if (fieldName == null && !m_activeMapping.isImplicit()) { continue; } if (fieldName == null) { // we could not find mapping using the universal name -> try implicit mapping using local name fieldName = attributeLocalName; } // TODO Labels replace: if (m_activeMapping.getOutputRecord() != null && m_activeMapping.getOutputRecord().hasField(fieldName)) { String val = attributes.getValue(i); m_activeMapping.getOutputRecord().getField(fieldName).fromString(trim ? val.trim() : val); } } } // Extract Element As Text - append all attributes and terminate the start tag; only when whole element // should be extracted (including tags) or when we are already within the element if (grabElement) { for (int i = 0; i < attributes.getLength(); i++) { m_characters.append(" ").append(attributes.getLocalName(i)).append("=\"").append(escapeXmlEntity(attributes.getValue(i))).append("\""); } m_characters.append(">"); } if (m_element_as_text && m_activeMapping.getFieldsMap().containsKey(XMLMappingConstants.ELEMENT_CONTENTS_AS_TEXT) && m_level == m_activeMapping.getLevel()) { this.m_elementContentStartIndexStack.add(new CharacterBufferMarker(CharacterBufferMarkerType.SUBTREE_START, m_characters.length(), m_level)); } } /** * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ @Override public void characters(char[] data, int offset, int length) throws SAXException { // Save the characters into the buffer, endElement will store it into the field //logger.trace("characters '" + new String(data, offset, length) + "'"); if (m_activeMapping != null && m_grabCharacters) { if(m_element_as_text) { if (m_elementContentStartIndexStack.size() > 0 && m_elementContentStartIndexStack.get(m_elementContentStartIndexStack.size() - 1).type == CharacterBufferMarkerType.CHARACTERS_END && m_elementContentStartIndexStack.get(m_elementContentStartIndexStack.size() - 1).index == m_characters.length()) { m_elementContentStartIndexStack.remove(m_elementContentStartIndexStack.size() - 1); } else { m_elementContentStartIndexStack.add(new CharacterBufferMarker(CharacterBufferMarkerType.CHARACTERS_START, m_characters.length(), m_level)); } } if (m_element_as_text && !in_cdata) { // perform entity escaping only when extracting element as text since the output should still be // valid XML. m_characters.append(escapeXmlEntity(new String(data, offset, length))); } else { m_characters.append(data, offset, length); } if(m_element_as_text) { m_elementContentStartIndexStack.add(new CharacterBufferMarker(CharacterBufferMarkerType.CHARACTERS_END, m_characters.length(), m_level)); } m_hasCharacters = true; } } private String escapeXmlEntity(String entity) { return entity.replace("&", "&amp;").replace("\"", "&quot").replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;"); } /** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException { if (m_activeMapping != null) { String fullName = "{" + namespaceURI + "}" + localName; // cache characters value if the xml field is referenced by descendant if (m_level - 1 <= m_activeMapping.getLevel() && m_activeMapping.getDescendantReferences().containsKey(fullName)) { m_activeMapping.getDescendantReferences().put(fullName, getCurrentValue()); } if (m_element_as_text && m_activeMapping.getFieldsMap().containsKey(XMLMappingConstants.ELEMENT_CONTENTS_AS_TEXT) && m_level == m_activeMapping.getLevel()) { this.m_elementContentStartIndexStack.add(new CharacterBufferMarker(CharacterBufferMarkerType.SUBTREE_END, m_characters.length(), m_level)); } // Extract Element As Text - append element's end tag; only when whole element should be extracted // (including tags) or when we are already within the element if (m_element_as_text && (m_activeMapping.getFieldsMap().containsKey(XMLMappingConstants.ELEMENT_AS_TEXT) || m_level >= m_activeMapping.getLevel())) { //logger.trace("endElement(" + qualifiedName + "): storing element name; m_element_as_text"); m_characters.append("</").append(localName).append(">"); } // if we are finishing the mapping, check for the mapping on this element through parent if (m_activeMapping != null && m_level == m_activeMapping.getLevel()) { if (m_activeMapping.hasFieldsFromAncestor()) { for (AncestorFieldMapping afm : m_activeMapping.getFieldsFromAncestor()) { if (afm.getAncestor() == m_activeMapping.getParent() && m_activeMapping.getOutputRecord() != null && m_activeMapping.getOutputRecord().hasField(afm.getCurrentField()) && afm.getAncestor() != null && afm.getAncestorField().equals(fullName)) { m_activeMapping.getOutputRecord().getField(afm.getCurrentField()).fromString(getCurrentValue()); } } } } processCharacters(namespaceURI, localName, m_level == m_activeMapping.getLevel()); if (m_element_as_text) { boolean clearMarkers = true; for (CharacterBufferMarker marker : this.m_elementContentStartIndexStack) { if (marker.level < m_level) { clearMarkers = false; } } if (clearMarkers) { this.m_elementContentStartIndexStack.clear(); } } // Extract Element As Text - clean-up buffers when value is stored to output if (this.m_elementContentStartIndexStack.size() == 0 && m_activeMapping != null && m_activeMapping.getLevel() == m_level && (m_activeMapping.getFieldsMap().containsKey(XMLMappingConstants.ELEMENT_CONTENTS_AS_TEXT) || m_activeMapping.getFieldsMap().containsKey(XMLMappingConstants.ELEMENT_AS_TEXT))) { m_element_as_text = false; m_hasCharacters = false; m_grabCharacters = true; m_characters.setLength(0); //logger.trace("endElement(" + qualifiedName + "): cleaning m_characters; end of m_element_as_text"); } else if (!m_element_as_text && this.m_elementContentStartIndexStack.size() == 0) { // Regardless of whether this was saved, reset the length of the // buffer and flag //logger.trace("endElement(" + qualifiedName + "): cleaning m_characters; !m_element_as_text"); m_characters.setLength(0); m_hasCharacters = false; } } if (m_activeMapping != null && m_level == m_activeMapping.getLevel()) { // This is the closing element of the matched element that // triggered the processing // That should be the end of this record so send it off to the // next Node if (parentComponent.runIt()) { try { OutputPort outPort = getOutputPort(m_activeMapping.getOutputPortNumber()); if (outPort != null) { // we just ignore creating output, if port is empty (without metadata) or not specified DataRecord outRecord = m_activeMapping.getOutputRecord(); // skip or process row if (skipRows > 0) { if (m_activeMapping.getParent() == null) skipRows } else { // check for index of last returned record if (!(numRecords >= 0 && numRecords == autoFilling.getGlobalCounter())) { // set autofilling autoFilling.setAutoFillingFields(outRecord); // can I do the map? it depends on skip and numRecords. if (m_activeMapping.doMap() && !m_activeMapping.isUsingParentRecord()) { // send off record outPort.writeRecord(outRecord); } // if (m_activeMapping.getParent() == null) autoFilling.incGlobalCounter(); } } // resets all child's mappings for skip and numRecords m_activeMapping.resetCurrentRecord4ChildMapping(); m_activeMapping.setCharactersProcessed(false); // reset record outRecord.reset(); } m_activeMapping = m_activeMapping.getParent(); } catch (Exception ex) { throw new SAXException(ex); } } else { throw new SAXException("Stop Signaled"); } } // text value immediately after end tag element should not be stored if (!m_element_as_text) { m_grabCharacters = false; } // ended an element so decrease our depth m_level } @Override public void endCDATA() throws SAXException { // super.endCDATA(); in_cdata = false; //logger.trace("Leaving CDATA"); if (m_element_as_text) { m_elementContentStartIndexStack.add(new CharacterBufferMarker(CharacterBufferMarkerType.CDATA_END, m_characters.length(), m_level)); m_characters.append(CHARS_CDATA_END); m_hasCharacters = true; } } @Override public void startCDATA() throws SAXException { super.startCDATA(); //logger.trace("Entering CDATA"); in_cdata = true; if (m_element_as_text) { m_elementContentStartIndexStack.add(new CharacterBufferMarker(CharacterBufferMarkerType.CDATA_START, m_characters.length(), m_level)); m_characters.append(CHARS_CDATA_START); m_hasCharacters = true; } } @Override public void processingInstruction(String target, String data) throws SAXException { super.processingInstruction(target, data); //logger.trace("Processing instruction " + target); if (m_element_as_text) { m_characters.append("<?").append(target).append(" ").append(data).append("?>"); } m_hasCharacters = true; } /** * @return */ private String getCurrentValue() { return trim ? m_characters.toString().trim() : m_characters.toString(); } private String getCurrentValue(int startIndex, int endIndex, boolean excludeCDataTag) { if (startIndex < 0) { return this.getCurrentValue(); } String value = null; int excludeStart = -1; int excludeEnd = -1; int storedEndIndex = endIndex; if (excludeCDataTag) { for (int i = 0; i < this.m_elementContentStartIndexStack.size(); i++) { if (this.m_elementContentStartIndexStack.get(i).index > startIndex && this.m_elementContentStartIndexStack.get(i).index < endIndex) { if (this.m_elementContentStartIndexStack.get(i).type == CharacterBufferMarkerType.CDATA_START) { excludeStart = this.m_elementContentStartIndexStack.get(i).index; excludeEnd = excludeStart + CHARS_CDATA_START.length(); endIndex = excludeStart; } else if (this.m_elementContentStartIndexStack.get(i).type == CharacterBufferMarkerType.CDATA_END) { excludeStart = this.m_elementContentStartIndexStack.get(i).index; excludeEnd = excludeStart + CHARS_CDATA_END.length(); endIndex = excludeStart; } } } } if (endIndex < 0) { value = m_characters.substring(startIndex); } else { value = m_characters.substring(startIndex, endIndex); } if (excludeStart > 0 && excludeEnd > 0) { value += getCurrentValue(excludeEnd, storedEndIndex, excludeCDataTag); } return (trim && value != null) ? value.trim() : value; } private int firstIndexWithType(Set<CharacterBufferMarkerType> types, int startFrom) { for (int i = startFrom; i < this.m_elementContentStartIndexStack.size(); i++) { if (types.contains(this.m_elementContentStartIndexStack.get(i).type)) { return i; } } return -1; } private int lastIndexWithType(CharacterBufferMarkerType type) { for (int i = this.m_elementContentStartIndexStack.size() - 1; i >= 0; i if (this.m_elementContentStartIndexStack.get(i).type == type) { return i; } } return -1; } /** * Store the characters processed by the characters() call back only if we have corresponding output field and * we are on the right level or we want to use data from nested unmapped nodes */ private void processCharacters(String namespaceURI, String localName, boolean elementValue) { // Create universal name String universalName = null; if (localName != null) { universalName = augmentURIAndLocalName(namespaceURI, localName); } String fieldName = null; // use fields mapping Map<String, String> xml2clover = m_activeMapping.getFieldsMap(); if (xml2clover != null /*&& xml2clover.keySet().size() > 0*/) { Set<String> keys = xml2clover.keySet(); for (int counter=0; counter<m_activeMapping.getSubtreeKeys().length+1; counter++) { //three times check special values (text content, ...). Fourth time - element mapped by name. String key = universalName; if(counter<m_activeMapping.getSubtreeKeys().length) { key = m_activeMapping.getSubtreeKeys()[counter]; } if(key==null) { continue; } int startIndex = -1; int endIndex = -1; boolean excludeCDataTag = false; if (elementValue && key.equals(XMLMappingConstants.ELEMENT_VALUE_REFERENCE)) { int startIndexPosition = this.lastIndexWithType(CharacterBufferMarkerType.CHARACTERS_START); if (startIndexPosition >= 0) { int endIndexPosition = this.firstIndexWithType(new HashSet<CharacterBufferMarkerType>(Arrays.asList(CharacterBufferMarkerType.SUBTREE_WITH_TAG_START, CharacterBufferMarkerType.SUBTREE_WITH_TAG_END, CharacterBufferMarkerType.SUBTREE_END, CharacterBufferMarkerType.SUBTREE_START)), startIndexPosition); endIndexPosition--; // we need one marker before found if (endIndexPosition < 0 && startIndexPosition >= 0) { endIndexPosition = this.lastIndexWithType(CharacterBufferMarkerType.CHARACTERS_END); } if (endIndexPosition > 0) { endIndex = this.m_elementContentStartIndexStack.get(endIndexPosition).index; // now remove all characters marker between startIndexPosition and endIndexPosition for (int i = endIndexPosition - 1; i > startIndexPosition; i CharacterBufferMarkerType type = this.m_elementContentStartIndexStack.get(i).type; if (type == CharacterBufferMarkerType.CHARACTERS_END || type == CharacterBufferMarkerType.CHARACTERS_START) { this.m_elementContentStartIndexStack.remove(i); } } this.m_elementContentStartIndexStack.get(endIndexPosition); } startIndex = this.m_elementContentStartIndexStack.get(startIndexPosition).index; if(startIndexPosition>=0 && endIndexPosition>startIndexPosition) { for(int i=endIndexPosition; i>=startIndexPosition; i this.m_elementContentStartIndexStack.remove(i); } } } excludeCDataTag = true; fieldName = xml2clover.get(XMLMappingConstants.ELEMENT_VALUE_REFERENCE); } else if (m_hasCharacters && key.equals(XMLMappingConstants.ELEMENT_CONTENTS_AS_TEXT) && m_activeMapping.getLevel() == m_level) { fieldName = xml2clover.get(XMLMappingConstants.ELEMENT_CONTENTS_AS_TEXT); int endIndexPosition = this.lastIndexWithType(CharacterBufferMarkerType.SUBTREE_END); if (endIndexPosition >= 0) { endIndex = this.m_elementContentStartIndexStack.get(endIndexPosition).index; } int startIndexPosition = this.lastIndexWithType(CharacterBufferMarkerType.SUBTREE_START); if (startIndexPosition >= 0) { startIndex = this.m_elementContentStartIndexStack.get(startIndexPosition).index; } if(startIndexPosition>=0 && endIndexPosition>startIndexPosition) { for(int i=endIndexPosition; i>=startIndexPosition; i this.m_elementContentStartIndexStack.remove(i); } } // logger.trace("processCharacters: getting field name for (" + localName + "); " + fieldName + "; xml2clover=" + xml2clover + ", cloverAttributes=" + cloverAttributes); } else if (m_hasCharacters && key.equals(XMLMappingConstants.ELEMENT_AS_TEXT) && m_activeMapping.getLevel() == m_level) { fieldName = xml2clover.get(XMLMappingConstants.ELEMENT_AS_TEXT); int startIndexPosition = this.lastIndexWithType(CharacterBufferMarkerType.SUBTREE_WITH_TAG_START); if (startIndexPosition >= 0) { startIndex = this.m_elementContentStartIndexStack.get(startIndexPosition).index; for(int i=this.m_elementContentStartIndexStack.size()-1; i>=startIndexPosition; i this.m_elementContentStartIndexStack.remove(i); } } // logger.trace("processCharacters: getting field name for (" + localName + "); " + fieldName + "; xml2clover=" + xml2clover + ", cloverAttributes=" + cloverAttributes); } else if (key.equals(universalName)) { fieldName = xml2clover.get(universalName); if(m_element_as_text) { int startIndexPosition = this.lastIndexWithType(CharacterBufferMarkerType.CHARACTERS_START); if (startIndexPosition >= 0) { int endIndexPosition = this.firstIndexWithType(new HashSet<CharacterBufferMarkerType>(Arrays.asList(CharacterBufferMarkerType.SUBTREE_WITH_TAG_START, CharacterBufferMarkerType.SUBTREE_WITH_TAG_END, CharacterBufferMarkerType.SUBTREE_END, CharacterBufferMarkerType.SUBTREE_START)), startIndexPosition); endIndexPosition--; // we need one marker before found if (endIndexPosition < 0 && startIndexPosition >= 0) { endIndexPosition = this.lastIndexWithType(CharacterBufferMarkerType.CHARACTERS_END); } if (endIndexPosition > 0) { endIndex = this.m_elementContentStartIndexStack.get(endIndexPosition).index; // now remove all characters marker between startIndexPosition and endIndexPosition for (int i = endIndexPosition - 1; i > startIndexPosition; i CharacterBufferMarkerType type = this.m_elementContentStartIndexStack.get(i).type; if (type == CharacterBufferMarkerType.CHARACTERS_END || type == CharacterBufferMarkerType.CHARACTERS_START) { this.m_elementContentStartIndexStack.remove(i); } } this.m_elementContentStartIndexStack.get(endIndexPosition); } startIndex = this.m_elementContentStartIndexStack.get(startIndexPosition).index; if(startIndexPosition>=0 && endIndexPosition>startIndexPosition) { for(int i=endIndexPosition; i>=startIndexPosition; i this.m_elementContentStartIndexStack.remove(i); } } } } } else if (m_activeMapping.getExplicitCloverFields().contains(localName) || keys.contains(localName) || keys.contains(universalName)) { //if local name is mentioned in explicit mapping, we will not let code do implicit mapping for this field continue; } else if (m_activeMapping.getSequenceField()!=null && (m_activeMapping.getSequenceField().equals(localName) || m_activeMapping.getSequenceField().equals(universalName) ) ) { continue; //don't do implicit mapping for fields mapped to sequence } if (fieldName == null && m_activeMapping.isImplicit()) { /* * As we could not find match using qualified name try mapping the xml element/attribute without * the namespace prefix */ fieldName = localName; } // XXX what if fieldName == null ??? // TODO Labels replace: if (m_activeMapping.getOutputRecord() != null && (useNestedNodes || m_level - 1 <= m_activeMapping.getLevel())) { int position = m_activeMapping.getOutputRecord().getMetadata().getFieldPosition(fieldName); if(position>=0) { DataField field = m_activeMapping.getOutputRecord().getField(position); // If field is nullable and there's no character data set it to null if (m_hasCharacters) { //logger.trace("processCharacters: storing (" + localName + "); into field " + fieldName + "; xml2clover=" + xml2clover + ", cloverAttributes=" + cloverAttributes); try { if (field.getValue() != null && cloverAttributes.contains(fieldName)) { // XXX WTF? field.fromString(trim ? field.getValue().toString().trim() : field.getValue().toString()); } else { //logger.trace("processCharacters: storing a new value (" + localName + "); into field " + fieldName + "; xml2clover=" + xml2clover + ", cloverAttributes=" + cloverAttributes); field.fromString(getCurrentValue(startIndex, endIndex, excludeCDataTag)); } } catch (BadDataFormatException ex) { // This is a bit hacky here SOOO let me explain... if (field.getType() == DataFieldMetadata.DATE_FIELD) { // XML dateTime format is not supported by the // DateFormat oject that clover uses... // so timezones are unparsable // i.e. XML wants -5:00 but DateFormat wants // -500 // Attempt to munge and retry... (there has to // be a better way) try { // Chop off the ":" in the timezone (it HAS // to be at the end) String dateTime = m_characters.substring(0, m_characters.lastIndexOf(":")) + m_characters.substring(m_characters.lastIndexOf(":") + 1); DateFormatter formatter = field.getMetadata().createDateFormatter(); field.setValue(formatter.parseDate(trim ? dateTime.trim() : dateTime)); } catch (Exception ex2) { // Oh well we tried, throw the originating // exception throw ex; } } else { throw ex; } } } else if (field.getType() == DataFieldMetadata.STRING_FIELD // and value wasn't already stored (from characters) && (field.getValue() == null || field.getValue().equals(field.getMetadata().getDefaultValueStr()))) { field.setValue(""); } } } } } else { fieldName = localName; // TODO Labels replace: if (m_activeMapping.getOutputRecord() != null && m_activeMapping.getOutputRecord().hasField(fieldName) && (useNestedNodes || m_level - 1 <= m_activeMapping.getLevel())) { DataField field = m_activeMapping.getOutputRecord().getField(fieldName); // If field is nullable and there's no character data set it to null if (m_hasCharacters) { //logger.trace("processCharacters: storing (" + localName + "); into field " + fieldName + "; xml2clover=" + xml2clover + ", cloverAttributes=" + cloverAttributes); try { if (field.getValue() != null && cloverAttributes.contains(fieldName)) { // XXX WTF? field.fromString(trim ? field.getValue().toString().trim() : field.getValue().toString()); } else { //logger.trace("processCharacters: storing a new value (" + localName + "); into field " + fieldName + "; xml2clover=" + xml2clover + ", cloverAttributes=" + cloverAttributes); field.fromString(getCurrentValue()); } } catch (BadDataFormatException ex) { // This is a bit hacky here SOOO let me explain... if (field.getType() == DataFieldMetadata.DATE_FIELD) { // XML dateTime format is not supported by the // DateFormat oject that clover uses... // so timezones are unparsable // i.e. XML wants -5:00 but DateFormat wants // -500 // Attempt to munge and retry... (there has to // be a better way) try { // Chop off the ":" in the timezone (it HAS // to be at the end) String dateTime = m_characters.substring(0, m_characters.lastIndexOf(":")) + m_characters.substring(m_characters.lastIndexOf(":") + 1); DateFormatter formatter = field.getMetadata().createDateFormatter(); field.setValue(formatter.parseDate(trim ? dateTime.trim() : dateTime)); } catch (Exception ex2) { // Oh well we tried, throw the originating // exception throw ex; } } else { throw ex; } } } else if (field.getType() == DataFieldMetadata.STRING_FIELD // and value wasn't already stored (from characters) && (field.getValue() == null || field.getValue().equals(field.getMetadata().getDefaultValueStr()))) { field.setValue(""); } } } } } protected void augmentNamespaceURIs() { for (String prefix : namespaceBindings.keySet()) { String uri = namespaceBindings.get(prefix); namespaceBindings.put(prefix, augmentURI(uri)); } } private String augmentURIAndLocalName(String uri, String localName) { if (uri == null) { return null; } return "{" + uri + "}" + localName; } private String augmentURI(String uri) { if (uri == null) { return null; } return "{" + uri + "}"; } public static class MyHandler extends DefaultHandler { // Handler used at checkConfig to parse XML mapping and retrieve attributes names private Set<String> attributeNames = new HashSet<String>(); private Set<String> cloverAttributes = new HashSet<String>(); @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { int length = atts.getLength(); for (int i = 0; i < length; i++) { String xmlField = atts.getQName(i); attributeNames.add(xmlField); if (xmlField.equals("cloverFields")) { cloverAttributes.add(atts.getValue(i)); } } } public Set<String> getAttributeNames() { return attributeNames; } public Set<String> getCloverAttributes() { return cloverAttributes; } } // /** // * @return the declaredTemplates // */ // public TreeMap<String, XmlElementMapping> getDeclaredTemplates() { // return declaredTemplates; /** * Xml features initialization. * * @throws JetelException */ private void initXmlFeatures(SAXParserFactory factory, String xmlFeatures) throws ComponentNotReadyException { if (xmlFeatures == null) { return; } String[] aXmlFeatures = xmlFeatures.split(FEATURES_DELIMETER); String[] aOneFeature; try { for (String oneFeature : aXmlFeatures) { aOneFeature = oneFeature.split(FEATURES_ASSIGN); if (aOneFeature.length != 2) throw new JetelException("The xml feature '" + oneFeature + "' has wrong format"); factory.setFeature(aOneFeature[0], Boolean.parseBoolean(aOneFeature[1])); } } catch (Exception e) { throw new ComponentNotReadyException(e); } } private Set<String> getXmlElementMappingValues() { try { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); DefaultHandler handler = new MyHandler(); InputStream is = null; if (this.mappingURL != null) { String filePath = FileUtils.getFile(graph.getRuntimeContext().getContextURL(), mappingURL); is = new FileInputStream(new File(filePath)); } else if (this.mapping != null) { is = new ByteArrayInputStream(mapping.getBytes("UTF-8")); } if (is != null) { saxParser.parse(is, handler); return ((MyHandler) handler).getCloverAttributes(); } } catch (Exception e) { return new HashSet<String>(); } return new HashSet<String>(); } /** * Sets namespace bindings to allow processing that relate namespace prefix used in Mapping and namespace URI used * in processed XML document * * @param namespaceBindings * the namespaceBindings to set */ public void setNamespaceBindings(HashMap<String, String> namespaceBindings) { this.namespaceBindings = new HashMap<String, String>(namespaceBindings); // Fix of CL-2510 -- // augmentNamespaceURIs() was run // twice on the same // namespaceBindings instance } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public String getXmlFeatures() { return xmlFeatures; } public void setXmlFeatures(String xmlFeatures) { this.xmlFeatures = xmlFeatures; } public void setMappingNodes(NodeList mappingNodes) { this.mappingNodes = mappingNodes; } public DataRecord getInputRecord() { return inputRecord; } public void setInputRecord(DataRecord inputRecord) { this.inputRecord = inputRecord; } public AutoFilling getAutoFilling() { return autoFilling; } } enum CharacterBufferMarkerType { CHARACTERS_START, SUBTREE_START, SUBTREE_WITH_TAG_START, CDATA_START, CHARACTERS_END, SUBTREE_END, SUBTREE_WITH_TAG_END, CDATA_END } class CharacterBufferMarker { public CharacterBufferMarkerType type; public int index; public int level; public CharacterBufferMarker(CharacterBufferMarkerType type, int index, int level) { this.type = type; this.index = index; this.level = level; } @Override public String toString() { return "("+(type != null ? type.name() : "[NO TYPE]") + ":" + this.index+":"+this.level+")"; } }
package org.jdesktop.swingx; import java.applet.Applet; import java.awt.Component; import java.awt.Cursor; import java.awt.KeyboardFocusManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.Method; import java.util.Hashtable; import java.util.Vector; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterPipeline; import org.jdesktop.swingx.tree.DefaultXTreeCellEditor; /** * JXTree. * * PENDING: support filtering/sorting. * * @author Ramesh Gupta * @author Jeanette Winzenburg */ public class JXTree extends JTree { private static final Logger LOG = Logger.getLogger(JXTree.class.getName()); private Method conversionMethod = null; private final static Class[] methodSignature = new Class[] {Object.class}; private final static Object[] methodArgs = new Object[] {null}; private static final int[] EMPTY_INT_ARRAY = new int[0]; private static final TreePath[] EMPTY_TREEPATH_ARRAY = new TreePath[0]; protected FilterPipeline filters; protected HighlighterPipeline highlighters; private ChangeListener highlighterChangeListener; private DelegatingRenderer delegatingRenderer; /** * Mouse/Motion/Listener keeping track of mouse moved in * cell coordinates. */ private RolloverProducer rolloverProducer; /** * RolloverController: listens to cell over events and * repaints entered/exited rows. */ private TreeRolloverController linkController; private boolean overwriteIcons; private Searchable searchable; private CellEditorRemover editorRemover; /** * Constructs a <code>JXTree</code> with a sample model. The default model * used by this tree defines a leaf node as any node without children. */ public JXTree() { init(); } /** * Constructs a <code>JXTree</code> with each element of the specified array * as the child of a new root node which is not displayed. By default, this * tree defines a leaf node as any node without children. * * This version of the constructor simply invokes the super class version * with the same arguments. * * @param value an array of objects that are children of the root. */ public JXTree(Object[] value) { super(value); init(); } /** * Constructs a <code>JXTree</code> with each element of the specified * Vector as the child of a new root node which is not displayed. * By default, this tree defines a leaf node as any node without children. * * This version of the constructor simply invokes the super class version * with the same arguments. * * @param value an Vector of objects that are children of the root. */ public JXTree(Vector value) { super(value); init(); } /** * Constructs a <code>JXTree</code> created from a Hashtable which does not * display with root. Each value-half of the key/value pairs in the HashTable * becomes a child of the new root node. By default, the tree defines a leaf * node as any node without children. * * This version of the constructor simply invokes the super class version * with the same arguments. * * @param value a Hashtable containing objects that are children of the root. */ public JXTree(Hashtable value) { super(value); init(); } /** * Constructs a <code>JXTree</code> with the specified TreeNode as its root, * which displays the root node. By default, the tree defines a leaf node as * any node without children. * * This version of the constructor simply invokes the super class version * with the same arguments. * * @param root root node of this tree */ public JXTree(TreeNode root) { super(root, false); init(); } /** * Constructs a <code>JXTree</code> with the specified TreeNode as its root, * which displays the root node and which decides whether a node is a leaf * node in the specified manner. * * This version of the constructor simply invokes the super class version * with the same arguments. * * @param root root node of this tree * @param asksAllowsChildren if true, only nodes that do not allow children * are leaf nodes; otherwise, any node without children is a leaf node; * @see javax.swing.tree.DefaultTreeModel#asksAllowsChildren */ public JXTree(TreeNode root, boolean asksAllowsChildren) { super(root, asksAllowsChildren); init(); } /** * Constructs an instance of <code>JXTree</code> which displays the root * node -- the tree is created using the specified data model. * * This version of the constructor simply invokes the super class version * with the same arguments. * * @param newModel * the <code>TreeModel</code> to use as the data model */ public JXTree(TreeModel newModel) { super(newModel); init(); } @Override public void setModel(TreeModel newModel) { // To support delegation of convertValueToText() to the model... // JW: method needs to be set before calling super // otherwise there are size caching problems conversionMethod = getValueConversionMethod(newModel); super.setModel(newModel); } protected Method getValueConversionMethod(TreeModel model) { try { return model == null ? null : model.getClass().getMethod( "convertValueToText", methodSignature); } catch (NoSuchMethodException ex) { LOG.finer("ex " + ex); LOG.finer("no conversionMethod in " + model.getClass()); } return null; } @Override public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { // Delegate to model, if possible. Otherwise fall back to superclass... if (value != null) { if (conversionMethod == null) { return value.toString(); } else { try { methodArgs[0] = value; return (String) conversionMethod.invoke(getModel(), methodArgs); } catch (Exception ex) { LOG.finer("ex " + ex); LOG.finer("can't invoke " + conversionMethod); } } } return ""; } private void init() { // To support delegation of convertValueToText() to the model... // JW: need to set again (is done in setModel, but at call // in super constructor the field is not yet valid) conversionMethod = getValueConversionMethod(getModel()); // Issue #233-swingx: default editor not bidi-compliant // manually install an enhanced TreeCellEditor which // behaves slightly better in RtoL orientation. // Issue #231-swingx: icons lost // Anyway, need to install the editor manually because // the default install in BasicTreeUI doesn't know about // the DelegatingRenderer and therefore can't see // the DefaultTreeCellRenderer type to delegate to. // As a consequence, the icons are lost in the default // setup. // JW PENDING need to mimic ui-delegate default re-set? // JW PENDING alternatively, cleanup and use DefaultXXTreeCellEditor in incubator TreeCellRenderer xRenderer = getCellRenderer(); if (xRenderer instanceof JXTree.DelegatingRenderer) { TreeCellRenderer delegate = ((JXTree.DelegatingRenderer) xRenderer).getDelegateRenderer(); if (delegate instanceof DefaultTreeCellRenderer) { setCellEditor(new DefaultXTreeCellEditor(this, (DefaultTreeCellRenderer) delegate)); } } // Register the actions that this class can handle. ActionMap map = getActionMap(); map.put("expand-all", new Actions("expand-all")); map.put("collapse-all", new Actions("collapse-all")); map.put("find", createFindAction()); KeyStroke findStroke = SearchFactory.getInstance().getSearchAccelerator(); getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(findStroke, "find"); } /** * A small class which dispatches actions. * TODO: Is there a way that we can make this static? */ private class Actions extends UIAction { Actions(String name) { super(name); } public void actionPerformed(ActionEvent evt) { if ("expand-all".equals(getName())) { expandAll(); } else if ("collapse-all".equals(getName())) { collapseAll(); } } } private Action createFindAction() { Action findAction = new UIAction("find") { public void actionPerformed(ActionEvent e) { doFind(); } }; return findAction; } protected void doFind() { SearchFactory.getInstance().showFindInput(this, getSearchable()); } /** * * @return a not-null Searchable for this editor. */ public Searchable getSearchable() { if (searchable == null) { searchable = new TreeSearchable(); } return searchable; } /** * sets the Searchable for this editor. If null, a default * searchable will be used. * * @param searchable */ public void setSearchable(Searchable searchable) { this.searchable = searchable; } /** * A searchable targetting the visible rows of a JXTree. * * PENDING: value to string conversion should behave as nextMatch (?) which * uses the convertValueToString(). * */ public class TreeSearchable extends AbstractSearchable { protected void findMatchAndUpdateState(Pattern pattern, int startRow, boolean backwards) { SearchResult searchResult = null; if (backwards) { for (int index = startRow; index >= 0 && searchResult == null; index searchResult = findMatchAt(pattern, index); } } else { for (int index = startRow; index < getSize() && searchResult == null; index++) { searchResult = findMatchAt(pattern, index); } } updateState(searchResult); } protected SearchResult findExtendedMatch(Pattern pattern, int row) { return findMatchAt(pattern, row); } /** * Matches the cell content at row/col against the given Pattern. * Returns an appropriate SearchResult if matching or null if no * matching * * @param pattern * @param row * a valid row index in view coordinates * a valid column index in view coordinates * @return an appropriate <code>SearchResult</code> if matching or * null if no matching */ protected SearchResult findMatchAt(Pattern pattern, int row) { TreePath path = getPathForRow(row); Object value = null; if (path != null) { value = path.getLastPathComponent(); } if (value != null) { Matcher matcher = pattern.matcher(value.toString()); if (matcher.find()) { return createSearchResult(matcher, row, -1); } } return null; } protected int getSize() { return getRowCount(); } protected void moveMatchMarker() { int row = lastSearchResult.foundRow; setSelectionRow(row); if (row >= 0) { scrollRowToVisible(row); } } } /** * Collapses all nodes in the tree table. */ public void collapseAll() { for (int i = getRowCount() - 1; i >= 0 ; i collapseRow(i); } } /** * Expands all nodes in the tree table. */ public void expandAll() { if (getRowCount() == 0) { expandRoot(); } for (int i = 0; i < getRowCount(); i++) { expandRow(i); } } /** * Expands the root path, assuming the current TreeModel has been set. */ private void expandRoot() { TreeModel model = getModel(); if(model != null && model.getRoot() != null) { expandPath(new TreePath(model.getRoot())); } } /** * overridden to always return a not-null array * (following SwingX convention). */ @Override public int[] getSelectionRows() { int[] rows = super.getSelectionRows(); return rows != null ? rows : EMPTY_INT_ARRAY; } /** * overridden to always return a not-null array * (following SwingX convention). */ @Override public TreePath[] getSelectionPaths() { // TODO Auto-generated method stub TreePath[] paths = super.getSelectionPaths(); return paths != null ? paths : EMPTY_TREEPATH_ARRAY; } /** * Returns the HighlighterPipeline assigned to the table, null if none. * * @return the HighlighterPipeline assigned to the table. * @see #setHighlighters(HighlighterPipeline) */ public HighlighterPipeline getHighlighters() { return highlighters; } /** * Assigns a HighlighterPipeline to the table, maybe null to remove all * Highlighters.<p> * * The default value is <code>null</code>. * * @param pipeline the HighlighterPipeline to use for renderer decoration. * @see #getHighlighters() * @see #addHighlighter(Highlighter) * @see #removeHighlighter(Highlighter) * */ public void setHighlighters(HighlighterPipeline pipeline) { HighlighterPipeline old = getHighlighters(); if (old != null) { old.removeChangeListener(getHighlighterChangeListener()); } highlighters = pipeline; if (highlighters != null) { highlighters.addChangeListener(getHighlighterChangeListener()); } firePropertyChange("highlighters", old, getHighlighters()); } /** * Sets the <code>Highlighter</code>s to the tree, replacing any old settings. * Maybe null to remove all highlighters.<p> * * * @param highlighters the highlighters to use for renderer decoration. * @see #getHighlighters() * @see #addHighlighter(Highlighter) * @see #removeHighlighter(Highlighter) * */ public void setHighlighters(Highlighter... highlighters) { HighlighterPipeline pipeline = null; if ((highlighters != null) && (highlighters.length > 0) && (highlighters[0] != null)) { pipeline = new HighlighterPipeline(highlighters); } setHighlighters(pipeline); } /** * Adds a Highlighter. * <p> * * If the <code>HighlighterPipeline</code> returned from getHighlighters() * is null, creates and sets a new pipeline containing the given * <code>Highlighter</code>. Else, appends the <code>Highlighter</code> * to the end of the pipeline. * * @param highlighter the <code>Highlighter</code> to add. * @throws NullPointerException if <code>Highlighter</code> is null. * @see #removeHighlighter(Highlighter) * @see #setHighlighters(HighlighterPipeline) */ public void addHighlighter(Highlighter highlighter) { HighlighterPipeline pipeline = getHighlighters(); if (pipeline == null) { setHighlighters(new HighlighterPipeline(new Highlighter[] {highlighter})); } else { pipeline.addHighlighter(highlighter); } } /** * Removes the Highlighter. <p> * * Does nothing if the HighlighterPipeline is null or does not contain * the given Highlighter. * * @param highlighter the highlighter to remove. * @see #addHighlighter(Highlighter) * @see #setHighlighters(HighlighterPipeline) */ public void removeHighlighter(Highlighter highlighter) { if ((getHighlighters() == null)) return; getHighlighters().removeHighlighter(highlighter); } private ChangeListener getHighlighterChangeListener() { if (highlighterChangeListener == null) { highlighterChangeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { repaint(); } }; } return highlighterChangeListener; } /** * Property to enable/disable rollover support. This can be enabled * to show "live" rollover behaviour, f.i. the cursor over LinkModel cells. * Default is disabled. * @param rolloverEnabled */ public void setRolloverEnabled(boolean rolloverEnabled) { boolean old = isRolloverEnabled(); if (rolloverEnabled == old) return; if (rolloverEnabled) { rolloverProducer = createRolloverProducer(); addMouseListener(rolloverProducer); addMouseMotionListener(rolloverProducer); getLinkController().install(this); } else { removeMouseListener(rolloverProducer); removeMouseMotionListener(rolloverProducer); rolloverProducer = null; getLinkController().release(); } firePropertyChange("rolloverEnabled", old, isRolloverEnabled()); } protected TreeRolloverController getLinkController() { if (linkController == null) { linkController = createLinkController(); } return linkController; } protected TreeRolloverController createLinkController() { return new TreeRolloverController(); } /** * creates and returns the RolloverProducer to use with this tree. * A "hit" for rollover is covering the total width of the tree. * Additionally, a pressed to the right (but outside of the label bounds) * is re-dispatched as a pressed just inside the label bounds. This * is a first go for #166-swingx. * * @return <code>RolloverProducer</code> to use with this tree */ protected RolloverProducer createRolloverProducer() { RolloverProducer r = new RolloverProducer() { @Override public void mousePressed(MouseEvent e) { JXTree tree = (JXTree) e.getComponent(); Point mousePoint = e.getPoint(); int labelRow = tree.getRowForLocation(mousePoint.x, mousePoint.y); // default selection if (labelRow >= 0) return; int row = tree.getClosestRowForLocation(mousePoint.x, mousePoint.y); Rectangle bounds = tree.getRowBounds(row); if (bounds == null) { row = -1; } else { if ((bounds.y + bounds.height < mousePoint.y) || bounds.x > mousePoint.x) { row = -1; } } // no hit if (row < 0) return; tree.dispatchEvent(new MouseEvent(tree, e.getID(), e.getWhen(), e.getModifiers(), bounds.x + bounds.width - 2, mousePoint.y, e.getClickCount(), e.isPopupTrigger(), e.getButton())); } protected void updateRolloverPoint(JComponent component, Point mousePoint) { JXTree tree = (JXTree) component; int row = tree.getClosestRowForLocation(mousePoint.x, mousePoint.y); Rectangle bounds = tree.getRowBounds(row); if (bounds == null) { row = -1; } else { if ((bounds.y + bounds.height < mousePoint.y) || bounds.x > mousePoint.x) { row = -1; } } int col = row < 0 ? -1 : 0; rollover.x = col; rollover.y = row; } }; return r; } /** * returns the rolloverEnabled property. * * TODO: Why doesn't this just return rolloverEnabled??? * * @return if rollober is enabled. */ public boolean isRolloverEnabled() { return rolloverProducer != null; } /** * listens to rollover properties. * Repaints effected component regions. * Updates link cursor. * * @author Jeanette Winzenburg */ public class TreeRolloverController<T extends JTree> extends RolloverController<T> { private Cursor oldCursor; protected void rollover(Point oldLocation, Point newLocation) { setRolloverCursor(newLocation); //setLinkCursor(list, newLocation); // JW: conditional repaint not working? component.repaint(); // if (oldLocation != null) { // Rectangle r = tree.getRowBounds(oldLocation.y); //// r.x = 0; //// r.width = table.getWidth(); // if (r != null) // tree.repaint(r); // if (newLocation != null) { // Rectangle r = tree.getRowBounds(newLocation.y); //// r.x = 0; //// r.width = table.getWidth(); // if (r != null) // tree.repaint(r); } private void setRolloverCursor(Point location) { if (hasRollover(location)) { if (oldCursor == null) { oldCursor = component.getCursor(); component.setCursor(Cursor .getPredefinedCursor(Cursor.HAND_CURSOR)); } } else { if (oldCursor != null) { component.setCursor(oldCursor); oldCursor = null; } } } protected RolloverRenderer getRolloverRenderer(Point location, boolean prepare) { TreeCellRenderer renderer = component.getCellRenderer(); RolloverRenderer rollover = renderer instanceof RolloverRenderer ? (RolloverRenderer) renderer : null; if ((rollover != null) && !rollover.isEnabled()) { rollover = null; } if ((rollover != null) && prepare) { TreePath path = component.getPathForRow(location.y); Object element = path != null ? path.getLastPathComponent() : null; renderer.getTreeCellRendererComponent(component, element, false, false, false, location.y, false); } return rollover; } protected Point getFocusedCell() { // TODO Auto-generated method stub return null; } } private DelegatingRenderer getDelegatingRenderer() { if (delegatingRenderer == null) { // only called once... to get hold of the default? delegatingRenderer = new DelegatingRenderer(); delegatingRenderer.setDelegateRenderer(super.getCellRenderer()); } return delegatingRenderer; } public TreeCellRenderer getCellRenderer() { return getDelegatingRenderer(); } public void setCellRenderer(TreeCellRenderer renderer) { // PENDING: do something against recursive setting // == multiple delegation... getDelegatingRenderer().setDelegateRenderer(renderer); super.setCellRenderer(delegatingRenderer); } /** * sets the icon for the handle of an expanded node. * * Note: this will only succeed if the current ui delegate is * a BasicTreeUI otherwise it will do nothing. * * @param expanded */ public void setExpandedIcon(Icon expanded) { if (getUI() instanceof BasicTreeUI) { ((BasicTreeUI) getUI()).setExpandedIcon(expanded); } } /** * sets the icon for the handel of a collapsed node. * * Note: this will only succeed if the current ui delegate is * a BasicTreeUI otherwise it will do nothing. * * @param collapsed */ public void setCollapsedIcon(Icon collapsed) { if (getUI() instanceof BasicTreeUI) { ((BasicTreeUI) getUI()).setCollapsedIcon(collapsed); } } /** * set the icon for a leaf node. * * Note: this will only succeed if current renderer is a * DefaultTreeCellRenderer. * * @param leafIcon */ public void setLeafIcon(Icon leafIcon) { getDelegatingRenderer().setLeafIcon(leafIcon); } /** * set the icon for a open non-leaf node. * * Note: this will only succeed if current renderer is a * DefaultTreeCellRenderer. * * @param openIcon */ public void setOpenIcon(Icon openIcon) { getDelegatingRenderer().setOpenIcon(openIcon); } /** * set the icon for a closed non-leaf node. * * Note: this will only succeed if current renderer is a * DefaultTreeCellRenderer. * * @param closedIcon */ public void setClosedIcon(Icon closedIcon) { getDelegatingRenderer().setClosedIcon(closedIcon); } /** * Property to control whether per-tree icons should be * copied to the renderer on setCellRenderer. * * the default is false for backward compatibility. * * PENDING: should update the current renderer's icons when * setting to true? * * @param overwrite */ public void setOverwriteRendererIcons(boolean overwrite) { if (overwriteIcons == overwrite) return; boolean old = overwriteIcons; this.overwriteIcons = overwrite; firePropertyChange("overwriteRendererIcons", old, overwrite); } public boolean isOverwriteRendererIcons() { return overwriteIcons; } public class DelegatingRenderer implements TreeCellRenderer, RolloverRenderer { private Icon closedIcon = null; private Icon openIcon = null; private Icon leafIcon = null; private TreeCellRenderer delegate; public DelegatingRenderer() { initIcons(new DefaultTreeCellRenderer()); } /** * initially sets the icons to the defaults as given * by a DefaultTreeCellRenderer. * * @param renderer */ private void initIcons(DefaultTreeCellRenderer renderer) { closedIcon = renderer.getDefaultClosedIcon(); openIcon = renderer.getDefaultOpenIcon(); leafIcon = renderer.getDefaultLeafIcon(); } /** * Set the delegate renderer. * Updates the folder/leaf icons. * * THINK: how to update? always override with this.icons, only * if renderer's icons are null, update this icons if they are not, * update all if only one is != null.... ?? * * @param delegate */ public void setDelegateRenderer(TreeCellRenderer delegate) { if (delegate == null) { delegate = new DefaultTreeCellRenderer(); } this.delegate = delegate; updateIcons(); } /** * tries to set the renderers icons. Can succeed only if the * delegate is a DefaultTreeCellRenderer. * THINK: how to update? always override with this.icons, only * if renderer's icons are null, update this icons if they are not, * update all if only one is != null.... ?? * */ private void updateIcons() { if (!isOverwriteRendererIcons()) return; setClosedIcon(closedIcon); setOpenIcon(openIcon); setLeafIcon(leafIcon); } public void setClosedIcon(Icon closedIcon) { if (delegate instanceof DefaultTreeCellRenderer) { ((DefaultTreeCellRenderer) delegate).setClosedIcon(closedIcon); } this.closedIcon = closedIcon; } public void setOpenIcon(Icon openIcon) { if (delegate instanceof DefaultTreeCellRenderer) { ((DefaultTreeCellRenderer) delegate).setOpenIcon(openIcon); } this.openIcon = openIcon; } public void setLeafIcon(Icon leafIcon) { if (delegate instanceof DefaultTreeCellRenderer) { ((DefaultTreeCellRenderer) delegate).setLeafIcon(leafIcon); } this.leafIcon = leafIcon; } public TreeCellRenderer getDelegateRenderer() { return delegate; } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component result = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); if (highlighters != null) { getComponentAdapter().row = row; result = highlighters.apply(result, getComponentAdapter()); } return result; } public boolean isEnabled() { return (delegate instanceof RolloverRenderer) && ((RolloverRenderer) delegate).isEnabled(); } public void doClick() { if (isEnabled()) { ((RolloverRenderer) delegate).doClick(); } } } /** * Overridden to terminate edits on focusLost. * This method updates the internal CellEditorRemover. * * @see #updateEditorRemover() */ @Override public void startEditingAtPath(TreePath path) { super.startEditingAtPath(path); if (isEditing()) { updateEditorRemover(); } } /** * Overridden to release the CellEditorRemover, if any. */ @Override public void removeNotify() { if (editorRemover != null) { editorRemover.release(); editorRemover = null; } super.removeNotify(); } /** * Lazily creates and updates the internal CellEditorRemover. * * */ private void updateEditorRemover() { if (editorRemover == null) { editorRemover = new CellEditorRemover(); } editorRemover.updateKeyboardFocusManager(); } /** This class tracks changes in the keyboard focus state. It is used * when the JXTree is editing to determine when to terminate the edit. * If focus switches to a component outside of the JXTree, but in the * same window, this will terminate editing. The exact terminate * behaviour is controlled by the invokeStopEditing property. * * @see javax.swing.JTree#setInvokesStopCellEditing(boolean) * */ public class CellEditorRemover implements PropertyChangeListener { /** the focusManager this is listening to. */ KeyboardFocusManager focusManager; public CellEditorRemover() { updateKeyboardFocusManager(); } /** * Updates itself to listen to the current KeyboardFocusManager. * */ public void updateKeyboardFocusManager() { KeyboardFocusManager current = KeyboardFocusManager.getCurrentKeyboardFocusManager(); setKeyboardFocusManager(current); } /** * stops listening. * */ public void release() { setKeyboardFocusManager(null); } /** * Sets the focusManager this is listening to. * Unregisters/registers itself from/to the old/new manager, * respectively. * * @param current the KeyboardFocusManager to listen too. */ private void setKeyboardFocusManager(KeyboardFocusManager current) { if (focusManager == current) return; KeyboardFocusManager old = focusManager; if (old != null) { old.removePropertyChangeListener("permanentFocusOwner", this); } focusManager = current; if (focusManager != null) { focusManager.addPropertyChangeListener("permanentFocusOwner", this); } } public void propertyChange(PropertyChangeEvent ev) { if (!isEditing()) { return; } Component c = focusManager.getPermanentFocusOwner(); while (c != null) { JXTree tree = JXTree.this; if (c == tree) { // focus remains inside the table return; } else if ((c instanceof Window) || (c instanceof Applet && c.getParent() == null)) { if (c == SwingUtilities.getRoot(tree)) { if (tree.getInvokesStopCellEditing()) { tree.stopEditing(); } if (tree.isEditing()) { tree.cancelEditing(); } } break; } c = c.getParent(); } } } protected ComponentAdapter getComponentAdapter() { return dataAdapter; } private final ComponentAdapter dataAdapter = new TreeAdapter(this); protected static class TreeAdapter extends ComponentAdapter { private final JXTree tree; /** * Constructs a <code>TableCellRenderContext</code> for the specified * target component. * * @param component the target component */ public TreeAdapter(JXTree component) { super(component); tree = component; } public JXTree getTree() { return tree; } public boolean hasFocus() { return tree.isFocusOwner() && (tree.getLeadSelectionRow() == row); } public Object getValueAt(int row, int column) { TreePath path = tree.getPathForRow(row); return path.getLastPathComponent(); } public Object getFilteredValueAt(int row, int column) { /** TODO: Implement filtering */ return getValueAt(row, column); } public boolean isSelected() { return tree.isRowSelected(row); } @Override public boolean isExpanded() { return tree.isExpanded(row); } @Override public boolean isLeaf() { return tree.getModel().isLeaf(getValue()); } public boolean isCellEditable(int row, int column) { return false; /** TODO: */ } public void setValueAt(Object aValue, int row, int column) { /** TODO: */ } public String getColumnName(int columnIndex) { return "Column_" + columnIndex; } public String getColumnIdentifier(int columnIndex) { return null; } } }
package org.gluu.oxauth.service; import org.gluu.oxauth.ciba.CIBAPingCallbackProxy; import org.gluu.oxauth.ciba.CIBAPushErrorProxy; import org.gluu.oxauth.model.ciba.PushErrorResponseType; import org.gluu.oxauth.model.common.*; import org.gluu.oxauth.model.configuration.AppConfiguration; import org.gluu.service.cdi.async.Asynchronous; import org.gluu.service.cdi.event.CibaRequestsProcessorEvent; import org.gluu.service.cdi.event.Scheduled; import org.gluu.service.timer.event.TimerEvent; import org.gluu.service.timer.schedule.TimerSchedule; import org.slf4j.Logger; import javax.ejb.DependsOn; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.inject.Inject; import javax.inject.Named; import java.util.Date; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; /** * @author Milton BO * @version May 20, 2020 */ @ApplicationScoped @DependsOn("appInitializer") @Named public class CibaRequestsProcessorJob { @Inject private Logger log; @Inject private AppConfiguration appConfiguration; @Inject private Event<TimerEvent> processorEvent; @Inject private CIBAPushErrorProxy cibaPushErrorProxy; @Inject private CIBAPingCallbackProxy cibaPingCallbackProxy; @Inject private AuthorizationGrantList authorizationGrantList; @Inject private GrantService grantService; private long lastFinishedTime; private AtomicBoolean isActive; private ExecutorService executorService; /** * Method invoked from the appInitializer to start processing every some time. */ public void initTimer() { log.debug("Initializing CIBA requests processor"); this.isActive = new AtomicBoolean(false); int intervalSec = appConfiguration.getBackchannelRequestsProcessorJobIntervalSec(); // Schedule to start processor every N seconds processorEvent.fire(new TimerEvent(new TimerSchedule(intervalSec, intervalSec), new CibaRequestsProcessorEvent(), Scheduled.Literal.INSTANCE)); this.lastFinishedTime = System.currentTimeMillis(); int threadPoolSize = Runtime.getRuntime().availableProcessors() * 2; this.executorService = Executors.newFixedThreadPool(threadPoolSize); } @Asynchronous public void process(@Observes @Scheduled CibaRequestsProcessorEvent cibaRequestsProcessorEvent) { if (this.isActive.get()) { return; } if (!this.isActive.compareAndSet(false, true)) { return; } try { if (jobIsFree()) { processImpl(); this.lastFinishedTime = System.currentTimeMillis(); } else { log.trace("Starting conditions aren't reached for CIBA requestes processor"); } } finally { this.isActive.set(false); } } /** * Defines whether the job is still in process or it is free according to the time interval defined. * @return True in case it is free to start a new process. */ private boolean jobIsFree() { int interval = appConfiguration.getBackchannelRequestsProcessorJobIntervalSec(); if (interval < 0) { log.info("CIBA Requests processor timer is disabled."); log.warn("CIBA Requests processor timer Interval (cleanServiceInterval in oxauth configuration) is negative which turns OFF internal clean up by the server. Please set it to positive value if you wish internal CIBA Requests processor up timer run."); return false; } long timeDiffrence = System.currentTimeMillis() - this.lastFinishedTime; return timeDiffrence >= interval * 1000; } /** * Main process that process CIBA requests in cache. */ public void processImpl() { try { CIBACacheAuthReqIds cibaCacheAuthReqIds = grantService.getCacheCibaAuthReqIds(); for (Map.Entry<String, Long> entry : cibaCacheAuthReqIds.getAuthReqIds().entrySet()) { Date now = new Date(); if (entry.getValue() < now.getTime()) { CIBAGrant cibaGrant = authorizationGrantList.getCIBAGrant(entry.getKey()); if (cibaGrant != null) { executorService.execute(() -> processExpiredRequest(cibaGrant) ); } authorizationGrantList.removeCibaGrantFromProcessorCache(entry.getKey()); } } } catch (Exception e) { log.error("Failed to process CIBA request from cache.", e); } } /** * Method responsible to process expired CIBA grants, set them as expired in cache * and send callbacks to the client * @param cibaGrant Object containing data related to the CIBA grant. */ private void processExpiredRequest(CIBAGrant cibaGrant) { if (cibaGrant.getUserAuthorization() != CIBAGrantUserAuthorization.AUTHORIZATION_PENDING && cibaGrant.getUserAuthorization() != CIBAGrantUserAuthorization.AUTHORIZATION_EXPIRED) { return; } log.info("Authentication request id {} has expired", cibaGrant.getCIBAAuthenticationRequestId()); cibaGrant.setUserAuthorization(CIBAGrantUserAuthorization.AUTHORIZATION_EXPIRED); cibaGrant.setTokensDelivered(false); cibaGrant.save(); if (cibaGrant.getClient().getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PUSH) { cibaPushErrorProxy.pushError(cibaGrant.getCIBAAuthenticationRequestId().getCode(), cibaGrant.getClient().getBackchannelClientNotificationEndpoint(), cibaGrant.getClientNotificationToken(), PushErrorResponseType.EXPIRED_TOKEN, "Request has expired and there was no answer from the end user."); } else if (cibaGrant.getClient().getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PING) { cibaPingCallbackProxy.pingCallback( cibaGrant.getCIBAAuthenticationRequestId().getCode(), cibaGrant.getClient().getBackchannelClientNotificationEndpoint(), cibaGrant.getClientNotificationToken() ); } } }
package ch.tkuhn.nanopub.server; import java.io.InputStream; import net.trustyuri.TrustyUriUtils; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.nanopub.NanopubImpl; import org.openrdf.rio.RDFFormat; public class CollectNanopubs implements Runnable { private static NanopubDb db = NanopubDb.get(); private String serverUri; private String artifactCodeStart; public CollectNanopubs(String serverUri, String artifactCodeStart) { this.serverUri = serverUri; this.artifactCodeStart = artifactCodeStart; } @Override public void run() { try { ServerInfo si = ServerInfo.load(serverUri); for (String nanopubUri : Utils.loadNanopubUriList(si, artifactCodeStart)) { if ("...".equals(nanopubUri)) { processDeeperLevel(); break; } String ac = TrustyUriUtils.getArtifactCode(nanopubUri); if (ac != null && !db.hasNanopub(ac)) { HttpGet get = new HttpGet(serverUri + ac); get.setHeader("Content-Type", "application/trig"); InputStream in = HttpClientBuilder.create().build().execute(get).getEntity().getContent(); db.loadNanopub(new NanopubImpl(in, RDFFormat.TRIG)); } } } catch (Exception ex) { ex.printStackTrace(); } } private void processDeeperLevel() { if (artifactCodeStart.length() > 44) { throw new RuntimeException("Unexcepted search depth: something went wrong"); } for (char ch : Utils.base64Alphabet.toCharArray()) { CollectNanopubs obj = new CollectNanopubs(serverUri, artifactCodeStart + ch); obj.run(); } } }
package br.com.blackhubos.eventozero.factory; import java.util.Map.Entry; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.ThrownPotion; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.material.MaterialData; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import br.com.blackhubos.eventozero.util.Framework; public final class ItemFactory { private static final Pattern pattern_name = Pattern.compile("(?:nome|name|nm|nme)\\s*(?:\\{)\\s*'+([^']+)'+\\s*(?:\\})", Pattern.CASE_INSENSITIVE); private static final Pattern pattern_item = Pattern.compile("(?:item|id|material)\\s*(?:\\{)\\s*([0-9]+)\\s*(?::\\s*([0-9]+))*\\s*(?:\\})", Pattern.CASE_INSENSITIVE); private static final Pattern pattern_encantos_outside = Pattern.compile("(?:encantos|enchants|enchantments)\\s*(?:\\{)\\s*([a-zA-Z0-9\\s\\,_-]+)\\s*(?:\\})", Pattern.CASE_INSENSITIVE); private static final Pattern pattern_encantos_inside = Pattern.compile("([a-zA-Z_-]+)\\s*(?:,|-)\\s*([0-9]+)", Pattern.CASE_INSENSITIVE); private static final Pattern pattern_desc_outside = Pattern.compile("(?:desc|description|descricao|descrição|lore)\\s*(?:\\{)\\s*([^\\)]+)\\}", Pattern.CASE_INSENSITIVE); private static final Pattern pattern_desc_inside = Pattern.compile("'+\\s*([^']+)\\s*'+", Pattern.CASE_INSENSITIVE); private static final Pattern pattern_amount = Pattern.compile("(?:quantia|amount|total|qnt)\\s*(?:\\{)\\s*([0-9]+)\\}", Pattern.CASE_INSENSITIVE); private static final Pattern pattern_dur = Pattern.compile("(?:durabilidade|dur|durability|desgaste)\\s*(?:\\{)\\s*([0-9]+)\\}", Pattern.CASE_INSENSITIVE); private static final Pattern pattern_skull = Pattern.compile("(?:skull|head|cabeça|cabeca|cbc)\\s*(?:\\{)\\s*([a-zA-Z0-9_-]+)\\}", Pattern.CASE_INSENSITIVE); private static final Pattern pattern_pots = Pattern.compile("(?:pots|poções|poção|potion|pot)\\s*(?:\\{)\\s*([a-zA-Z0-9_-\\,\\s]+)\\}", Pattern.CASE_INSENSITIVE); /** * Processa parte interna do potion ('speed,2,60 strength,2,60') ignore as aspas. */ private static final Pattern pattern_pots_inside = Pattern.compile("\\s*([a-zA-Z_-]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*"); private static final Pattern pattern_book_outside = Pattern.compile("(?:book|livro)\\s*(?:\\{)\\s*([^\\}]+)\\s*\\}"); private static final Pattern pattern_book_inside_p1 = Pattern.compile("\\(\\s*'([^']+)\\s*'\\s*,\\s*'\\s*([^']+)\\s*'\\s*\\)\\s*([^\\}]+)\\s*\\}"); private static final Pattern pattern_book_inside_p2 = Pattern.compile("\\s*\\(\\s*'\\s*(.+)\\s*'\\s*\\)\\s*"); private static final Pattern pattern_book_inside_p3 = Pattern.compile("\\s*'\\s*([^']+)\\s*'"); private ItemStack item; private String serial; public ItemFactory(final ItemStack is) { final StringBuffer buffer = new StringBuffer(); buffer.append("item{" + is.getTypeId() + ":" + is.getData().getData() + "}"); buffer.append(" "); buffer.append("nome{'" + ChatColor.translateAlternateColorCodes('&', is.getItemMeta().getDisplayName()) + "'}"); buffer.append(" "); buffer.append("amount{" + is.getAmount() + "}"); buffer.append(" "); buffer.append("dur{" + is.getDurability() + "}"); buffer.append(" "); if (is.getType() == Material.WRITTEN_BOOK) { final BookMeta meta = (BookMeta) is.getItemMeta(); buffer.append("book{"); buffer.append("('" + meta.getAuthor() + "','" + meta.getTitle() + "')"); buffer.append(" "); buffer.append("("); boolean first = true; for (String page : meta.getPages()) { if (!first) { buffer.append(","); } buffer.append("'"); if (page.contains("'")) { page = page.replaceAll("'", "${1}:"); } buffer.append(page); buffer.append("'"); first = false; } buffer.append(")"); buffer.append("}"); buffer.append(" "); } if (is.getType() == Material.POTION) { buffer.append("pots{"); boolean first = true; final ThrownPotion pot = (ThrownPotion) is; for (final PotionEffect effect : pot.getEffects()) { if (!first) { buffer.append(" "); } final String line = effect.getType().getName() + "," + effect.getAmplifier() + "," + effect.getDuration(); buffer.append(line); first = false; } buffer.append("}"); buffer.append(" "); } if (is.getType() == Material.SKULL_ITEM) { buffer.append("skull{"); final SkullMeta meta = (SkullMeta) is.getItemMeta(); buffer.append(meta.getOwner()); buffer.append("}"); buffer.append(" "); } if (!is.getItemMeta().getLore().isEmpty()) { buffer.append("desc{"); boolean first = true; for (String line : is.getItemMeta().getLore()) { if (!first) { buffer.append(", "); } line = ChatColor.translateAlternateColorCodes('&', line); buffer.append("'" + line + "'"); first = false; } buffer.append("}"); buffer.append(" "); } if (!is.getEnchantments().isEmpty()) { buffer.append("encantos{"); boolean first = true; for (final Entry<Enchantment, Integer> encantos : is.getEnchantments().entrySet()) { if (!first) { buffer.append(" "); } final String e = Framework.reverseEnchantment(encantos.getKey()); final int level = encantos.getValue(); buffer.append(e + "," + level); first = false; } buffer.append("}"); buffer.append(" "); } this.serial = buffer.toString(); this.item = is; } public ItemFactory(final String script, ConcurrentHashMap<String, String> replaces) { if (replaces == null) { replaces = new ConcurrentHashMap<String, String>(); } this.serial = script; final Matcher item = ItemFactory.pattern_item.matcher(script); if (!item.find()) { return; } final int id = Integer.parseInt(item.group(1)); byte data = 0; if (item.group(2) != null) { data = (byte) Integer.parseInt(item.group(2)); } final ItemStack is = new ItemStack(id); final MaterialData isdata = is.getData(); final ItemMeta meta = is.getItemMeta(); isdata.setData(data); is.setData(isdata); final Matcher name = ItemFactory.pattern_name.matcher(script); if (name.find()) { final String isname = name.group(1); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', this.replaces(isname, replaces))); } final Matcher desc = ItemFactory.pattern_desc_outside.matcher(script); if (desc.find()) { final Matcher desc2 = ItemFactory.pattern_desc_inside.matcher(desc.group(1)); final Vector<String> lore = new Vector<String>(); while (desc2.find()) { String text = desc2.group(1); text = this.replaces(text, replaces); text = ChatColor.translateAlternateColorCodes('&', text); lore.add(text); } meta.setLore(lore); } final Matcher dur = ItemFactory.pattern_dur.matcher(script); if (dur.find()) { final short s = Short.parseShort(dur.group(1)); is.setDurability(s); } final Matcher ench = ItemFactory.pattern_encantos_outside.matcher(script); if (ench.find()) { final Matcher enchs = ItemFactory.pattern_encantos_inside.matcher(ench.group(1)); while (enchs.find()) { final String encanto = enchs.group(1); final int level = Integer.parseInt(enchs.group(2)); final Enchantment e = Framework.checkEnchantment(encanto); if (e != null) { is.addUnsafeEnchantment(e, level); } } } final Matcher qnt = ItemFactory.pattern_amount.matcher(script); if (qnt.find()) { final int quantia = Integer.parseInt(qnt.group(1)); if (quantia > 0) { is.setAmount(quantia); } } is.setItemMeta(meta); final Matcher pot = ItemFactory.pattern_pots.matcher(script); if (pot.find()) { final PotionMeta pm = (PotionMeta) is.getItemMeta(); final String efeitos = pot.group(1); final Matcher eff = ItemFactory.pattern_pots_inside.matcher(efeitos); while (eff.find()) { final String efeito = eff.group(1); final int level = Integer.parseInt(eff.group(2)); final int tempo = Integer.parseInt(eff.group(3)); pm.getCustomEffects().add(new PotionEffect(PotionEffectType.getByName(efeito), tempo, level)); } is.setItemMeta(pm); } final Matcher skull = ItemFactory.pattern_skull.matcher(script); if (skull.find()) { final String owner = skull.group(1); final SkullMeta sm = (SkullMeta) is.getItemMeta(); sm.setOwner(owner); is.setItemMeta(sm); } final Matcher book = ItemFactory.pattern_book_outside.matcher(script); if (book.find()) { final String content = book.group(1); final Matcher p1 = ItemFactory.pattern_book_inside_p1.matcher(content); if (p1.find()) { final String titulo = p1.group(1); final String autor = p1.group(2); final BookMeta bm = (BookMeta) is.getItemMeta(); bm.setAuthor(this.replaces(autor, replaces)); bm.setTitle(this.replaces(titulo, replaces)); final String unco = p1.group(3); final Matcher mpgs = ItemFactory.pattern_book_inside_p2.matcher(unco); while (mpgs.find()) { final Vector<String> array = new Vector<String>(); final Matcher pages = ItemFactory.pattern_book_inside_p3.matcher(mpgs.group(1)); while (pages.find()) { array.add(this.replaces(pages.group(1), replaces).replace("${1}:", "'")); } final String[] local = array.toArray(new String[array.size()]); bm.addPage(local); } } } this.item = is; } @Nonnull public String getSerial() { return this.serial; } @Nullable public ItemStack getPreparedItem() { return this.item; } private String replaces(String old, final ConcurrentHashMap<String, String> replaces) { if (replaces != null) { for (final Entry<String, String> kv : replaces.entrySet()) { old = old.replaceAll("(?i)\\{\\s*" + kv.getKey() + "\\}", kv.getValue()); } } return old; } }
package org.jetel.metadata; import java.io.BufferedInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.sql.SQLException; import org.jetel.graph.TransformationGraph; import org.w3c.dom.DOMException; /** * @author dpavlis * @since 19.10.2004 * * Helper class for instantiating metadata from various * sources. Not really a factory - merely set of metadata creation * methods. */ public class MetadataFactory { public static DataRecordMetadata fromFile(TransformationGraph graph, String fileURL) throws IOException { URL url; try{ url = new URL(fileURL); }catch(MalformedURLException e){ // try to patch the url try { url=new URL("file:"+fileURL); }catch(MalformedURLException ex){ throw new RuntimeException("Wrong URL of file specified: "+ex.getMessage()); } } DataRecordMetadata recordMetadata; DataRecordMetadataXMLReaderWriter metadataXMLRW = new DataRecordMetadataXMLReaderWriter(graph); try{ recordMetadata=metadataXMLRW.read( new BufferedInputStream(url.openStream())); if (recordMetadata==null){ throw new RuntimeException("Can't parse metadata definition file: "+fileURL); } }catch(IOException ex){ throw new IOException("Can't read metadata definition file: "+ex.getMessage()); }catch(Exception ex){ throw new RuntimeException("Can't get metadata file "+fileURL+" - "+ex.getClass().getName()+" : "+ex.getMessage()); } return recordMetadata; } /** * Generates DataRecordMetadata based on IConnection and its parameters.<br> * The sql query is executed against * database and metadata of result set is obtained. This metadata is translated * to corresponding Clover metadata. * * @param dbConnection database connection to use * @param sqlQuery sql query to use. * @return * @throws Exception * @throws SQLException */ public static DataRecordMetadata fromStub(DataRecordMetadataStub metadataStub) throws Exception { return metadataStub.createMetadata(); } /** * Generates DataRecordMetadata based on XML definition * * @param node * @return */ public static DataRecordMetadata fromXML(TransformationGraph graph, org.w3c.dom.Node node)throws DOMException{ DataRecordMetadataXMLReaderWriter parser=new DataRecordMetadataXMLReaderWriter(graph); return parser.parseRecordMetadata(node); } }
package club.magicfun.aquila.job; import java.io.File; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import club.magicfun.aquila.util.StringUtility; import club.magicfun.aquila.util.WebDriverUtility; public class TestWebDriver4 { private static final Logger logger = LoggerFactory.getLogger(TestWebDriver4.class); private static final String PRODUCT_CATEGORY_URL_TEMPLATE = "http://item.taobao.com/item.htm?id={PRODUCTID}"; private static final String SHOP_TYPE_TMALL = "tmall"; private static final String SHOP_TYPE_TAOBAO = "taobao"; public static final int MAX_EXTRACT_PAGE_COUNT = 1000; public static final long SLEEP_TIME = 1000l; public static void main(String[] args) { String dir = System.getProperty("user.dir"); String osName = System.getProperty("os.name"); // load the appropriate chrome drivers according to the OS type if (osName.toLowerCase().indexOf("windows") > -1) { System.setProperty("webdriver.chrome.driver", dir + File.separator + "drivers" + File.separator + "win" + File.separator + "chromedriver.exe"); } else if (osName.toLowerCase().indexOf("mac") > -1) { System.setProperty("webdriver.chrome.driver", dir + File.separator + "drivers" + File.separator + "mac" + File.separator + "chromedriver"); } // variables String shopType = null; //Long productId = 522818128551l; //taobao Long productId = 17382419997l; //tmall WebDriver webDriver = new ChromeDriver(); try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } webDriver.manage().window().maximize(); try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); String url = PRODUCT_CATEGORY_URL_TEMPLATE.replaceFirst("\\{PRODUCTID\\}", productId.toString()); webDriver.get(url); try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Current URL: " + webDriver.getCurrentUrl()); if (StringUtility.containsAny(webDriver.getCurrentUrl(), "detail.tmall.com")) { shopType = SHOP_TYPE_TMALL; } else if (StringUtility.containsAny(webDriver.getCurrentUrl(), "item.taobao.com")) { shopType = SHOP_TYPE_TAOBAO; } logger.info("shop type = " + shopType); if (SHOP_TYPE_TAOBAO.equalsIgnoreCase(shopType)) { WebElement dealCountButton = webDriver.findElement(By.xpath("//a[@shortcut-label='']")); dealCountButton.click(); int targetPageIndex = 1; int currentPageIndex = 1; while (targetPageIndex <= MAX_EXTRACT_PAGE_COUNT) { logger.info("targetPageIndex: " + targetPageIndex); if (targetPageIndex > 1) { WebElement nextPageLink = null; try { nextPageLink = webDriver.findElement(By.xpath("//div[@id='deal-record']/div[@class='tb-pagination']//a[@class='J_TAjaxTrigger page-next']")); nextPageLink.click(); try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } catch (NoSuchElementException ex) { } } currentPageIndex = Integer.parseInt(webDriver.findElement(By.xpath("//div[@id='deal-record']/div[@class='tb-pagination']//span[@class='page-cur']")).getAttribute("page")); logger.info("currentPageIndex: " + currentPageIndex); if (currentPageIndex < targetPageIndex) { logger.info("break the while block because currentPageIndex (" + currentPageIndex + ") < targetPageIndex (" + targetPageIndex + "). "); break; } List<WebElement> dealRecordElements = webDriver.findElements(By.xpath("//div[@id='deal-record']/table/tbody/tr[not(@class='tb-change-info')]")); for (WebElement dealRecord : dealRecordElements) { String dealDateTime = dealRecord.findElement(By.xpath("td[@class='tb-start']")).getText().trim(); String dealAmount = dealRecord.findElement(By.xpath("td[@class='tb-amount']")).getText().trim(); String dealSku = dealRecord.findElement(By.xpath("td[@class='tb-sku']")).getText().replaceAll(":", ""); logger.info(">>> " + dealDateTime + "|" + dealAmount + "|" + dealSku); } targetPageIndex++; } } else if (SHOP_TYPE_TMALL.equalsIgnoreCase(shopType)) { WebElement dealCountButton = webDriver.findElement(By.xpath("//div[@id='J_TabBarBox']//a[@href='#J_DealRecord']")); logger.info("dealCountButton location: " + dealCountButton.getLocation()); dealCountButton.click(); WebDriverUtility.hideElement(webDriver, "//div[@id='J_MUIMallbar']"); int targetPageIndex = 1; int currentPageIndex = 1; while (targetPageIndex <= MAX_EXTRACT_PAGE_COUNT) { logger.info("targetPageIndex: " + targetPageIndex); if (targetPageIndex > 1) { WebElement nextPageLink = null; try { nextPageLink = webDriver.findElement(By.xpath("//div[@id='J_showBuyerList']/div[@class='pagination']//a[@class='J_TAjaxTrigger page-next'][last()]")); logger.info("nextPageLink location: " + nextPageLink.getLocation()); logger.info("nextPageLink text: " + nextPageLink.getText()); nextPageLink.click(); try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } catch (NoSuchElementException ex) { // do nothing } catch (StaleElementReferenceException sre) { // do nothing } } currentPageIndex = Integer.parseInt(webDriver.findElement(By.xpath("//div[@id='J_showBuyerList']/div[@class='pagination']//span[@class='page-cur']")).getText()); logger.info("currentPageIndex: " + currentPageIndex); if (currentPageIndex < targetPageIndex) { logger.info("break the while block because currentPageIndex (" + currentPageIndex + ") < targetPageIndex (" + targetPageIndex + "). "); break; } List<WebElement> dealRecordElements = webDriver.findElements(By.xpath("//div[@id='J_showBuyerList']/table/tbody/tr[not(@class='tb-change-info') and position()>1]")); for (WebElement dealRecord : dealRecordElements) { String dealDateTime = dealRecord.findElement(By.xpath("td[@class='dealtime']")).getText().trim().replaceAll("\n", " "); String dealAmount = dealRecord.findElement(By.xpath("td[@class='quantity']")).getText().trim(); String dealSku = dealRecord.findElement(By.xpath("td[@class='cell-align-l style']")).getText().replaceAll(" :", ""); logger.info(">>> " + dealDateTime + "|" + dealAmount + "|" + dealSku); } targetPageIndex++; } } webDriver.close(); webDriver.quit(); } }
package br.com.juliocnsouza.ocpjp.tests; /** * StringProcessing.java -> Job: * <p> * @since 23/02/2015 * @version 1.0 * @author Julio Cesar Nunes de Souza (julio.souza@mobilitasistemas.com.br) */ public class StringProcessing { static void q1() { int i = 200; double d = 100.00; try { System.console().format( "%d * %1.1f" , i , d ); } catch ( NullPointerException npe ) { System.out.println( "Não há console pela IDE" ); } } public static void main( String[] args ) { q1(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.mypackage.hello; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoException; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * * @author uko */ public class Worker { private String data; public Worker() { data=""; // String user = "crawler"; // char[] pass = "J7vVBYCiGTjcnhN6Qe".toCharArray(); try { // Mongo m = new Mongo("localhost"); // DB db = m.getDB("npss"); // boolean auth = db.authenticate(user, pass); // if (auth) // data+="<br />good"; // else // data+="<br />bad"; // m.close(); Map<String, Double> testMap = new HashMap<String, Double>(); testMap.put("x", 123.124); testMap.put("y", 124.4632); testMap.put("z", 412.235); PMP mongodbAnt = new PMP(); String taskName = "firstTestTask"; String factoryName = "firstTestFactory"; data += "<br/>mongodbAnt: setting data..."; mongodbAnt.setValue(taskName, factoryName, testMap, 100.500); data += "<br/>mongodbAnt: data was set"; data += "<br/>mongodbAnt: getting data..."; Double value = mongodbAnt.getValue(taskName, factoryName, testMap); data += "<br/>mongodbAnt: data was extracted from MongoDB"; data += "<br/>Task: " + taskName; data += "<br/>Factory: " + factoryName; data += "<br/>Parameters: x => " + testMap.get("x"); data += " y => " + testMap.get("y"); data += " z => " + testMap.get("z"); data += "<br/>Value: " + value; // DBCollection coll = db.getCollection("testCollection"); // Set<String> colls = db.getCollectionNames(); // for (String s : colls) // data+="<br />"+s; // BasicDBObject doc = new BasicDBObject(); // doc.put("name", "MongoDB"); // doc.put("type", "database"); // doc.put("count", 1); // BasicDBObject info = new BasicDBObject(); // info.put("x", 203); // info.put("y", 102); // doc.put("info", info); // coll.insert(doc); // for (int i = 0; i < 100; i++) // coll.insert(new BasicDBObject().append("i", i)); // data+="<br />"+coll.getCount(); // DBCursor cur = coll.find(); // while(cur.hasNext()) { // DBObject one=cur.next(); // data+="<br />"+one; } catch (UnknownHostException ex) { System.out.print("UnknownHOST"); } catch (MongoException ex) { System.out.print("MongoError"); } catch(Exception e) { data += "<br/>Exception was handled: " + e.getMessage(); } } /** * @return the name */ public String getData() { return data; } /** * @param name the name to set */ // public void setData(String data) // this.data = data; }